bookwyrm/bookwyrm/views/status.py

271 lines
8.9 KiB
Python
Raw Normal View History

2021-03-08 16:49:10 +00:00
""" what are we here for if not for posting """
2021-01-12 21:47:00 +00:00
import re
2022-05-26 17:58:11 +00:00
import logging
2021-08-30 16:47:19 +00:00
from urllib.parse import urlparse
2021-01-12 21:47:00 +00:00
from django.contrib.auth.decorators import login_required
2021-08-30 16:12:05 +00:00
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError
from django.http import HttpResponse, HttpResponseBadRequest, Http404
2021-01-12 21:47:00 +00:00
from django.shortcuts import get_object_or_404, redirect
2021-04-03 19:30:18 +00:00
from django.template.response import TemplateResponse
from django.utils import timezone
2021-01-12 21:47:00 +00:00
from django.utils.decorators import method_decorator
from django.views import View
2021-09-29 17:59:36 +00:00
from django.views.decorators.http import require_POST
2021-08-30 16:12:05 +00:00
2021-08-30 16:47:19 +00:00
from markdown import markdown
2021-01-12 21:47:00 +00:00
from bookwyrm import forms, models
from bookwyrm.settings import DOMAIN
2022-07-04 20:14:22 +00:00
from bookwyrm.utils import regex, sanitizer
from .helpers import handle_remote_webfinger, is_api_request
from .helpers import load_date_in_user_tz_as_utc
2021-01-12 21:47:00 +00:00
2022-05-26 17:58:11 +00:00
logger = logging.getLogger(__name__)
2021-01-12 21:47:00 +00:00
2021-10-14 23:30:27 +00:00
# pylint: disable= no-self-use
@method_decorator(login_required, name="dispatch")
class EditStatus(View):
"""the view for *posting*"""
def get(self, request, status_id): # pylint: disable=unused-argument
"""load the edit panel"""
2021-10-14 23:57:58 +00:00
status = get_object_or_404(
models.Status.objects.select_subclasses(), id=status_id
)
2021-10-14 23:30:27 +00:00
status.raise_not_editable(request.user)
2021-10-15 02:14:47 +00:00
status_type = "reply" if status.reply_parent else status.status_type.lower()
2021-10-14 23:30:27 +00:00
data = {
2021-10-15 02:14:47 +00:00
"type": status_type,
"book": getattr(status, "book", None),
"draft": status,
2021-10-14 23:30:27 +00:00
}
return TemplateResponse(request, "compose.html", data)
2021-01-12 21:47:00 +00:00
# pylint: disable= no-self-use
2021-03-08 16:49:10 +00:00
@method_decorator(login_required, name="dispatch")
2021-01-12 21:47:00 +00:00
class CreateStatus(View):
2021-04-26 16:15:42 +00:00
"""the view for *posting*"""
2021-03-08 16:49:10 +00:00
def get(self, request, status_type): # pylint: disable=unused-argument
2021-10-14 23:30:27 +00:00
"""compose view (...not used?)"""
2021-04-03 21:32:34 +00:00
book = get_object_or_404(models.Edition, id=request.GET.get("book"))
data = {"book": book}
return TemplateResponse(request, "compose.html", data)
2021-11-20 08:19:51 +00:00
# pylint: disable=too-many-branches
2021-10-15 00:13:54 +00:00
def post(self, request, status_type, existing_status_id=None):
2021-10-13 20:12:56 +00:00
"""create status of whatever type"""
2021-10-15 15:15:48 +00:00
created = not existing_status_id
2021-10-15 00:32:38 +00:00
existing_status = None
2021-10-15 00:13:54 +00:00
if existing_status_id:
existing_status = get_object_or_404(
2021-10-15 00:23:54 +00:00
models.Status.objects.select_subclasses(), id=existing_status_id
2021-10-15 00:13:54 +00:00
)
existing_status.raise_not_editable(request.user)
existing_status.edited_date = timezone.now()
2021-10-15 00:13:54 +00:00
2021-01-12 22:02:38 +00:00
status_type = status_type[0].upper() + status_type[1:]
2021-01-18 17:57:44 +00:00
2021-01-12 22:02:38 +00:00
try:
2021-10-15 00:13:54 +00:00
form = getattr(forms, f"{status_type}Form")(
request.POST, instance=existing_status
)
2022-05-26 17:58:11 +00:00
except AttributeError as err:
logger.exception(err)
2021-01-12 21:47:00 +00:00
return HttpResponseBadRequest()
2022-05-26 17:58:11 +00:00
2021-01-12 21:47:00 +00:00
if not form.is_valid():
if is_api_request(request):
2022-05-26 17:58:11 +00:00
logger.exception(form.errors)
return HttpResponseBadRequest()
2021-03-08 16:49:10 +00:00
return redirect(request.headers.get("Referer", "/"))
2021-01-12 21:47:00 +00:00
status = form.save(commit=False)
2021-10-15 01:34:26 +00:00
# save the plain, unformatted version of the status for future editing
status.raw_content = status.content
if hasattr(status, "quote"):
status.raw_quote = status.quote
status.sensitive = status.content_warning not in [None, ""]
status.save(broadcast=False)
2021-01-12 21:47:00 +00:00
# inspect the text for user tags
content = status.content
for (mention_text, mention_user) in find_mentions(content):
# add them to status mentions fk
status.mention_users.add(mention_user)
# turn the mention into a link
content = re.sub(
2021-09-18 18:32:00 +00:00
rf"{mention_text}([^@]|$)",
rf'<a href="{mention_user.remote_id}">{mention_text}</a>\g<1>',
2021-03-08 16:49:10 +00:00
content,
)
2021-02-10 22:13:36 +00:00
# add reply parent to mentions
2021-01-12 21:47:00 +00:00
if status.reply_parent:
status.mention_users.add(status.reply_parent.user)
# deduplicate mentions
status.mention_users.set(set(status.mention_users.all()))
# don't apply formatting to generated notes
if not isinstance(status, models.GeneratedNote) and content:
2021-01-12 21:47:00 +00:00
status.content = to_markdown(content)
# do apply formatting to quotes
2021-03-08 16:49:10 +00:00
if hasattr(status, "quote"):
2021-01-12 21:47:00 +00:00
status.quote = to_markdown(status.quote)
2021-10-15 15:15:48 +00:00
status.save(created=created)
2021-03-21 00:34:58 +00:00
# update a readthrough, if needed
if bool(request.POST.get("id")):
try:
edit_readthrough(request)
except Http404:
pass
2021-03-21 00:34:58 +00:00
if is_api_request(request):
return HttpResponse()
2021-04-03 22:47:47 +00:00
return redirect("/")
2021-01-12 21:47:00 +00:00
2021-04-03 19:30:18 +00:00
@method_decorator(login_required, name="dispatch")
2021-01-12 21:47:00 +00:00
class DeleteStatus(View):
2021-04-26 16:15:42 +00:00
"""tombstone that bad boy"""
2021-03-08 16:49:10 +00:00
2021-01-12 21:47:00 +00:00
def post(self, request, status_id):
2021-04-26 16:15:42 +00:00
"""delete and tombstone a status"""
2021-01-12 21:47:00 +00:00
status = get_object_or_404(models.Status, id=status_id)
# don't let people delete other people's statuses
2021-09-27 21:03:17 +00:00
status.raise_not_deletable(request.user)
2021-01-12 21:47:00 +00:00
# perform deletion
2021-04-03 19:30:18 +00:00
status.delete()
2021-03-08 16:49:10 +00:00
return redirect(request.headers.get("Referer", "/"))
2021-01-12 21:47:00 +00:00
2021-09-29 17:59:36 +00:00
@login_required
@require_POST
def update_progress(request, book_id): # pylint: disable=unused-argument
2021-09-29 17:59:36 +00:00
"""Either it's just a progress update, or it's a comment with a progress update"""
if request.POST.get("post-status"):
return CreateStatus.as_view()(request, "comment")
return edit_readthrough(request)
@login_required
@require_POST
def edit_readthrough(request):
"""can't use the form because the dates are too finnicky"""
2022-01-11 18:40:32 +00:00
# TODO: remove this, it duplicates the code in the ReadThrough view
readthrough = get_object_or_404(models.ReadThrough, id=request.POST.get("id"))
readthrough.raise_not_editable(request.user)
readthrough.start_date = load_date_in_user_tz_as_utc(
request.POST.get("start_date"), request.user
)
readthrough.finish_date = load_date_in_user_tz_as_utc(
request.POST.get("finish_date"), request.user
)
progress = request.POST.get("progress")
try:
progress = int(progress)
readthrough.progress = progress
except (ValueError, TypeError):
pass
progress_mode = request.POST.get("progress_mode")
try:
progress_mode = models.ProgressMode(progress_mode)
readthrough.progress_mode = progress_mode
except ValueError:
pass
readthrough.save()
# record the progress update individually
# use default now for date field
readthrough.create_update()
if is_api_request(request):
return HttpResponse()
return redirect(request.headers.get("Referer", "/"))
2021-01-12 21:47:00 +00:00
def find_mentions(content):
2021-04-26 16:15:42 +00:00
"""detect @mentions in raw status content"""
if not content:
return
2021-06-18 21:29:24 +00:00
for match in re.finditer(regex.STRICT_USERNAME, content):
2021-03-08 16:49:10 +00:00
username = match.group().strip().split("@")[1:]
2021-01-12 21:47:00 +00:00
if len(username) == 1:
# this looks like a local user (@user), fill in the domain
username.append(DOMAIN)
2021-03-08 16:49:10 +00:00
username = "@".join(username)
2021-01-12 21:47:00 +00:00
mention_user = handle_remote_webfinger(username)
if not mention_user:
# we can ignore users we don't know about
continue
yield (match.group(), mention_user)
def format_links(content):
2021-04-26 16:15:42 +00:00
"""detect and format links"""
validator = URLValidator()
2021-08-30 16:12:05 +00:00
formatted_content = ""
split_content = re.split(r"(\s+)", content)
for potential_link in split_content:
if not potential_link:
continue
2021-08-30 16:12:05 +00:00
wrapped = _wrapped(potential_link)
if wrapped:
wrapper_close = potential_link[-1]
2021-08-30 16:38:00 +00:00
formatted_content += potential_link[0]
2021-08-30 16:12:05 +00:00
potential_link = potential_link[1:-1]
try:
# raises an error on anything that's not a valid link
validator(potential_link)
# use everything but the scheme in the presentation of the link
url = urlparse(potential_link)
link = url.netloc + url.path + url.params
if url.query != "":
link += "?" + url.query
if url.fragment != "":
link += "#" + url.fragment
2021-09-18 18:32:00 +00:00
formatted_content += f'<a href="{potential_link}">{link}</a>'
except (ValidationError, UnicodeError):
formatted_content += potential_link
2021-08-30 16:12:05 +00:00
if wrapped:
2021-08-30 16:38:00 +00:00
formatted_content += wrapper_close
2021-08-30 16:12:05 +00:00
return formatted_content
2021-08-30 16:38:00 +00:00
2021-08-30 16:12:05 +00:00
def _wrapped(text):
2021-08-30 16:51:42 +00:00
"""check if a line of text is wrapped"""
2021-08-30 16:38:00 +00:00
wrappers = [("(", ")"), ("[", "]"), ("{", "}")]
2021-08-30 16:47:19 +00:00
for wrapper in wrappers:
if text[0] == wrapper[0] and text[-1] == wrapper[-1]:
2021-08-30 16:38:00 +00:00
return True
2021-08-30 16:12:05 +00:00
return False
2021-01-12 21:47:00 +00:00
2021-08-30 16:38:00 +00:00
2021-01-12 21:47:00 +00:00
def to_markdown(content):
2021-04-26 16:15:42 +00:00
"""catch links and convert to markdown"""
content = format_links(content)
content = markdown(content)
2021-01-12 21:47:00 +00:00
# sanitize resulting html
2022-07-04 20:14:22 +00:00
return sanitizer.clean(content)