moviewyrm/bookwyrm/views/status.py

208 lines
6.8 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
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
2021-01-29 18:25:31 +00:00
from django.http import HttpResponseBadRequest
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
2021-01-12 21:47:00 +00:00
from django.utils.decorators import method_decorator
from django.views import View
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.sanitize_html import InputHtmlParser
from bookwyrm.settings import DOMAIN
from bookwyrm.utils import regex
2021-01-29 18:25:31 +00:00
from .helpers import handle_remote_webfinger
2021-03-21 00:34:58 +00:00
from .reading import edit_readthrough
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-04-26 16:15:42 +00:00
"""compose view (used for delete-and-redraft"""
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-01-12 21:47:00 +00:00
def post(self, request, status_type):
2021-04-26 16:15:42 +00:00
"""create status of whatever type"""
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-03-08 16:49:10 +00:00
form = getattr(forms, "%sForm" % status_type)(request.POST)
2021-01-12 22:02:38 +00:00
except AttributeError:
2021-01-12 21:47:00 +00:00
return HttpResponseBadRequest()
if not form.is_valid():
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)
if not status.sensitive and status.content_warning:
# the cw text field remains populated when you click "remove"
status.content_warning = 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-03-08 16:49:10 +00:00
r"%s([^@]|$)" % mention_text,
r'<a href="%s">%s</a>\g<1>' % (mention_user.remote_id, mention_text),
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)
status.save(created=True)
2021-03-21 00:34:58 +00:00
# update a readthorugh, if needed
edit_readthrough(request)
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
if status.user != request.user and not request.user.has_perm("moderate_post"):
2021-01-12 21:47:00 +00:00
return HttpResponseBadRequest()
# 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-04-03 19:30:18 +00:00
@method_decorator(login_required, name="dispatch")
class DeleteAndRedraft(View):
2021-04-26 16:15:42 +00:00
"""delete a status but let the user re-create it"""
2021-04-03 19:30:18 +00:00
def post(self, request, status_id):
2021-04-26 16:15:42 +00:00
"""delete and tombstone a status"""
2021-04-03 22:47:47 +00:00
status = get_object_or_404(
models.Status.objects.select_subclasses(), id=status_id
)
2021-04-04 16:18:52 +00:00
if isinstance(status, (models.GeneratedNote, models.ReviewRating)):
2021-04-03 19:30:18 +00:00
return HttpResponseBadRequest()
2021-04-03 22:47:47 +00:00
# don't let people redraft other people's statuses
if status.user != request.user:
return HttpResponseBadRequest()
2021-04-03 21:55:13 +00:00
2021-04-04 16:18:52 +00:00
status_type = status.status_type.lower()
if status.reply_parent:
2021-04-04 16:24:17 +00:00
status_type = "reply"
2021-04-04 16:18:52 +00:00
2021-04-03 22:47:47 +00:00
data = {
"draft": status,
2021-04-04 16:18:52 +00:00
"type": status_type,
2021-04-03 22:47:47 +00:00
}
2021-04-03 21:32:34 +00:00
if hasattr(status, "book"):
data["book"] = status.book
2021-04-03 22:47:47 +00:00
elif status.mention_books:
data["book"] = status.mention_books.first()
2021-04-03 19:30:18 +00:00
# perform deletion
status.delete()
2021-04-03 21:32:34 +00:00
return TemplateResponse(request, "compose.html", data)
2021-04-03 19:30:18 +00:00
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
formatted_content += '<a href="%s">%s</a>' % (potential_link, link)
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
sanitizer = InputHtmlParser()
sanitizer.feed(content)
return sanitizer.get_output()