moviewyrm/bookwyrm/views/books/links.py

49 lines
1.8 KiB
Python
Raw Normal View History

2021-12-15 21:15:51 +00:00
""" the good stuff! the books! """
from django.contrib.auth.decorators import login_required, permission_required
from django.db import transaction
from django.shortcuts import get_object_or_404, redirect
from django.template.response import TemplateResponse
from django.views import View
from django.utils.decorators import method_decorator
from bookwyrm import forms, models
2021-12-16 00:23:21 +00:00
from bookwyrm.activitypub import ActivitypubResponse
2021-12-15 21:15:51 +00:00
# pylint: disable=no-self-use
@method_decorator(login_required, name="dispatch")
@method_decorator(
permission_required("bookwyrm.edit_book", raise_exception=True), name="dispatch"
)
class FileLink(View):
"""a book! this is the stuff"""
2021-12-16 00:23:21 +00:00
def get(self, request, book_id=None, link_id=None):
2021-12-15 21:15:51 +00:00
"""info about a book"""
link = get_object_or_404(models.FileLink, id=link_id) if link_id else None
2021-12-16 00:23:21 +00:00
if not book_id:
return ActivitypubResponse(link.to_activity())
book = get_object_or_404(models.Edition, id=book_id)
2021-12-15 21:15:51 +00:00
data = {
"file_link_form": forms.FileLinkForm(instance=link),
"book": book,
}
return TemplateResponse(request, "book/file_link_page.html", data)
@transaction.atomic
2021-12-15 21:20:05 +00:00
def post(self, request, book_id, link_id=None):
2021-12-15 21:15:51 +00:00
"""Add a link to a copy of the book you can read"""
book = get_object_or_404(models.Book.objects.select_subclasses(), id=book_id)
2021-12-15 21:20:05 +00:00
link = get_object_or_404(models.FileLink, id=link_id) if link_id else None
form = forms.FileLinkForm(request.POST, instance=link)
2021-12-15 21:15:51 +00:00
if not form.is_valid():
data = {"file_link_form": form, "book": book}
return TemplateResponse(request, "book/file_link_page.html", data)
link = form.save()
book.file_links.add(link)
book.last_edited_by = request.user
book.save()
return redirect("book", book.id)