moviewyrm/bookwyrm/views.py

838 lines
25 KiB
Python
Raw Normal View History

2020-02-22 22:02:03 +00:00
''' views for pages you can go to in the application '''
2020-05-04 04:13:43 +00:00
import re
2020-10-01 19:59:38 +00:00
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.postgres.search import TrigramSimilarity
2020-11-11 18:35:34 +00:00
from django.core.paginator import Paginator
from django.db.models import Avg, Q, Max
from django.db.models.functions import Greatest
from django.http import HttpResponseNotFound, JsonResponse
from django.core.exceptions import PermissionDenied
from django.shortcuts import get_object_or_404, redirect
2020-01-25 23:25:19 +00:00
from django.template.response import TemplateResponse
2020-03-14 00:57:36 +00:00
from django.views.decorators.csrf import csrf_exempt
2020-11-28 16:22:25 +00:00
from django.views.decorators.http import require_GET
2020-01-25 06:32:41 +00:00
from bookwyrm import outgoing
2021-01-02 16:14:28 +00:00
from bookwyrm import forms, models
from bookwyrm.activitypub import ActivitypubResponse
from bookwyrm.connectors import connector_manager
2020-11-11 18:35:34 +00:00
from bookwyrm.settings import PAGE_LENGTH
from bookwyrm.tasks import app
2020-11-01 18:42:48 +00:00
from bookwyrm.utils import regex
2020-01-28 19:45:27 +00:00
2021-01-02 16:14:28 +00:00
def get_edition(book_id):
''' look up a book in the db and return an edition '''
book = models.Book.objects.select_subclasses().get(id=book_id)
if isinstance(book, models.Work):
2021-01-02 16:38:27 +00:00
book = book.get_default_edition()
2021-01-02 16:14:28 +00:00
return book
2020-02-22 22:02:03 +00:00
def get_user_from_username(username):
''' helper function to resolve a localname or a username to a user '''
# raises DoesNotExist if user is now found
2020-02-22 22:02:03 +00:00
try:
return models.User.objects.get(localname=username)
2020-02-22 22:02:03 +00:00
except models.User.DoesNotExist:
return models.User.objects.get(username=username)
2020-02-22 22:02:03 +00:00
2020-03-14 00:57:36 +00:00
def is_api_request(request):
''' check whether a request is asking for html or data '''
return 'json' in request.headers.get('Accept') or \
request.path[-5:] == '.json'
def is_bookworm_request(request):
''' check if the request is coming from another bookworm instance '''
user_agent = request.headers.get('User-Agent')
2021-01-03 16:17:00 +00:00
if user_agent is None or \
re.search(regex.bookwyrm_user_agent, user_agent) is None:
return False
return True
2020-03-14 00:57:36 +00:00
def server_error_page(request):
''' 500 errors '''
return TemplateResponse(
request, 'error.html', {'title': 'Oops!'}, status=500)
def not_found_page(request, _):
''' 404s '''
return TemplateResponse(
request, 'notfound.html', {'title': 'Not found'}, status=404)
2020-11-28 16:22:25 +00:00
@require_GET
2020-01-25 23:25:19 +00:00
def home(request):
''' this is the same as the feed on the home tab '''
if request.user.is_authenticated:
return home_tab(request, 'home')
return discover_page(request)
@login_required
2020-11-28 16:22:25 +00:00
@require_GET
def home_tab(request, tab):
2020-01-28 19:45:27 +00:00
''' user's homepage with activity feed '''
2020-04-01 22:36:35 +00:00
try:
page = int(request.GET.get('page', 1))
except ValueError:
page = 1
suggested_books = get_suggested_books(request.user)
2020-02-07 23:29:11 +00:00
if tab == 'home':
activities = get_activity_feed(
request.user, ['public', 'unlisted', 'followers'],
following_only=True)
elif tab == 'local':
activities = get_activity_feed(
request.user, ['public', 'followers'], local_only=True)
else:
activities = get_activity_feed(
request.user, ['public', 'followers'])
2020-11-11 18:35:34 +00:00
paginated = Paginator(activities, PAGE_LENGTH)
activity_page = paginated.page(page)
prev_page = next_page = None
if activity_page.has_next():
next_page = '/%s/?page=%d#feed' % \
(tab, activity_page.next_page_number())
if activity_page.has_previous():
prev_page = '/%s/?page=%d#feed' % \
(tab, activity_page.previous_page_number())
2020-01-25 23:25:19 +00:00
data = {
2020-11-02 22:25:16 +00:00
'title': 'Updates Feed',
2020-01-25 23:25:19 +00:00
'user': request.user,
2020-11-07 04:36:52 +00:00
'suggested_books': suggested_books,
2020-11-11 18:35:34 +00:00
'activities': activity_page.object_list,
'tab': tab,
2020-11-11 18:35:34 +00:00
'next': next_page,
'prev': prev_page,
2020-01-25 23:25:19 +00:00
}
return TemplateResponse(request, 'feed.html', data)
2020-01-25 06:32:41 +00:00
2020-01-28 02:47:54 +00:00
def get_suggested_books(user, max_books=5):
''' helper to get a user's recent books '''
book_count = 0
preset_shelves = [
('reading', max_books), ('read', 2), ('to-read', max_books)
]
suggested_books = []
for (preset, shelf_max) in preset_shelves:
limit = shelf_max if shelf_max < (max_books - book_count) \
else max_books - book_count
shelf = user.shelf_set.get(identifier=preset)
shelf_books = shelf.shelfbook_set.order_by(
'-updated_date'
).all()[:limit]
if not shelf_books:
continue
shelf_preview = {
'name': shelf.name,
'books': [s.book for s in shelf_books]
}
suggested_books.append(shelf_preview)
book_count += len(shelf_preview['books'])
return suggested_books
2021-01-03 19:10:04 +00:00
@require_GET
def discover_page(request):
''' tiled book activity page '''
books = models.Edition.objects.filter(
review__published_date__isnull=False,
review__user__local=True,
review__privacy__in=['public', 'unlisted'],
).exclude(
2021-01-03 19:10:04 +00:00
cover__exact=''
).annotate(
Max('review__published_date')
).order_by('-review__published_date__max')[:6]
ratings = {}
for book in books:
reviews = models.Review.objects.filter(
book__in=book.parent_work.editions.all()
)
reviews = get_activity_feed(
request.user, ['public', 'unlisted'], queryset=reviews)
ratings[book.id] = reviews.aggregate(Avg('rating'))['rating__avg']
2021-01-03 19:10:04 +00:00
data = {
'title': 'Discover',
'register_form': forms.RegisterForm(),
'books': list(set(books)),
'ratings': ratings
2021-01-03 19:10:04 +00:00
}
return TemplateResponse(request, 'discover.html', data)
2020-12-14 00:16:12 +00:00
@login_required
@require_GET
def direct_messages_page(request, page=1):
''' like a feed but for dms only '''
activities = get_activity_feed(request.user, 'direct')
paginated = Paginator(activities, PAGE_LENGTH)
activity_page = paginated.page(page)
prev_page = next_page = None
if activity_page.has_next():
next_page = '/direct-message/?page=%d#feed' % \
activity_page.next_page_number()
if activity_page.has_previous():
prev_page = '/direct-messages/?page=%d#feed' % \
activity_page.previous_page_number()
data = {
'title': 'Direct Messages',
'user': request.user,
'activities': activity_page.object_list,
'next': next_page,
'prev': prev_page,
}
return TemplateResponse(request, 'direct_messages.html', data)
def get_activity_feed(
user, privacy, local_only=False, following_only=False,
queryset=models.Status.objects):
2020-04-01 23:02:39 +00:00
''' get a filtered queryset of statuses '''
privacy = privacy if isinstance(privacy, list) else [privacy]
# if we're looking at Status, we need this. We don't if it's Comment
if hasattr(queryset, 'select_subclasses'):
queryset = queryset.select_subclasses()
# exclude deleted
queryset = queryset.exclude(deleted=True).order_by('-published_date')
# you can't see followers only or direct messages if you're not logged in
if user.is_anonymous:
privacy = [p for p in privacy if not p in ['followers', 'direct']]
# filter to only privided privacy levels
queryset = queryset.filter(privacy__in=privacy)
# only include statuses the user follows
if following_only:
queryset = queryset.exclude(
~Q(# remove everythign except
Q(user__in=user.following.all()) | # user follwoing
Q(user=user) |# is self
Q(mention_users=user)# mentions user
),
2020-10-29 19:32:37 +00:00
)
# exclude followers-only statuses the user doesn't follow
elif 'followers' in privacy:
queryset = queryset.exclude(
~Q(# user isn't following and it isn't their own status
Q(user__in=user.following.all()) | Q(user=user)
),
privacy='followers' # and the status is followers only
2020-10-27 22:41:53 +00:00
)
# exclude direct messages not intended for the user
if 'direct' in privacy:
queryset = queryset.exclude(
~Q(
Q(user=user) | Q(mention_users=user)
), privacy='direct'
2020-10-27 22:41:53 +00:00
)
2020-04-01 23:02:39 +00:00
# filter for only local status
if local_only:
queryset = queryset.filter(user__local=True)
# remove statuses that have boosts in the same queryset
try:
queryset = queryset.filter(~Q(boosters__in=queryset))
except ValueError:
pass
return queryset
2020-04-01 23:02:39 +00:00
2020-11-28 16:22:25 +00:00
@require_GET
2020-05-04 04:13:43 +00:00
def search(request):
''' that search bar up top '''
query = request.GET.get('q')
min_confidence = request.GET.get('min_confidence', 0.1)
2020-05-04 17:15:41 +00:00
if is_api_request(request):
# only return local book results via json so we don't cause a cascade
book_results = connector_manager.local_search(
query, min_confidence=min_confidence)
2020-12-30 19:37:26 +00:00
return JsonResponse([r.json() for r in book_results], safe=False)
2020-05-04 04:13:43 +00:00
# use webfinger for mastodon style account@domain.com username
2021-01-07 00:01:13 +00:00
if re.match(r'\B%s' % regex.full_username, query):
outgoing.handle_remote_webfinger(query)
# do a local user search
user_results = models.User.objects.annotate(
similarity=Greatest(
TrigramSimilarity('username', query),
TrigramSimilarity('localname', query),
)
).filter(
similarity__gt=0.5,
).order_by('-similarity')[:10]
book_results = connector_manager.search(
query, min_confidence=min_confidence)
data = {
2020-11-02 22:25:16 +00:00
'title': 'Search Results',
'book_results': book_results,
'user_results': user_results,
'query': query,
}
return TemplateResponse(request, 'search_results.html', data)
2020-05-04 04:13:43 +00:00
2020-03-23 16:40:09 +00:00
@login_required
2020-11-28 16:22:25 +00:00
@require_GET
2020-03-23 16:40:09 +00:00
def import_page(request):
''' import history from goodreads '''
return TemplateResponse(request, 'import.html', {
2020-11-02 22:25:16 +00:00
'title': 'Import Books',
2020-03-23 16:40:09 +00:00
'import_form': forms.ImportForm(),
'jobs': models.ImportJob.
objects.filter(user=request.user).order_by('-created_date'),
2020-03-23 16:40:09 +00:00
})
@login_required
2020-11-28 16:22:25 +00:00
@require_GET
def import_status(request, job_id):
''' status of an import job '''
job = models.ImportJob.objects.get(id=job_id)
if job.user != request.user:
raise PermissionDenied
task = app.AsyncResult(job.task_id)
2020-11-12 21:52:57 +00:00
items = job.items.order_by('index').all()
failed_items = [i for i in items if i.fail_reason]
items = [i for i in items if not i.fail_reason]
return TemplateResponse(request, 'import_status.html', {
2020-11-02 22:25:16 +00:00
'title': 'Import Status',
'job': job,
2020-11-12 21:52:57 +00:00
'items': items,
'failed_items': failed_items,
'task': task
})
2020-03-17 00:45:34 +00:00
2020-11-28 16:22:25 +00:00
@require_GET
2020-03-15 21:15:36 +00:00
def login_page(request):
2020-01-25 23:25:19 +00:00
''' authentication '''
2020-10-01 03:47:26 +00:00
if request.user.is_authenticated:
return redirect('/')
2020-01-25 23:25:19 +00:00
# send user to the login page
2020-03-15 21:15:36 +00:00
data = {
2020-11-02 22:25:16 +00:00
'title': 'Login',
2020-03-15 21:15:36 +00:00
'login_form': forms.LoginForm(),
'register_form': forms.RegisterForm(),
}
return TemplateResponse(request, 'login.html', data)
2020-01-29 03:05:59 +00:00
2020-11-28 16:22:25 +00:00
@require_GET
def about_page(request):
''' more information about the instance '''
data = {
2020-11-02 22:25:16 +00:00
'title': 'About',
}
return TemplateResponse(request, 'about.html', data)
2020-11-28 16:22:25 +00:00
@require_GET
2020-10-02 20:32:19 +00:00
def password_reset_request(request):
''' invite management page '''
2020-11-06 00:48:15 +00:00
return TemplateResponse(
request,
'password_reset_request.html',
{'title': 'Reset Password'}
)
2020-10-02 20:32:19 +00:00
2020-11-28 16:22:25 +00:00
@require_GET
2020-10-02 20:32:19 +00:00
def password_reset(request, code):
''' endpoint for sending invites '''
if request.user.is_authenticated:
return redirect('/')
try:
reset_code = models.PasswordReset.objects.get(code=code)
if not reset_code.valid():
raise PermissionDenied
except models.PasswordReset.DoesNotExist:
raise PermissionDenied
return TemplateResponse(
request,
'password_reset.html',
2020-11-02 22:25:16 +00:00
{'title': 'Reset Password', 'code': reset_code.code}
2020-10-02 20:32:19 +00:00
)
2020-11-28 16:22:25 +00:00
@require_GET
def invite_page(request, code):
''' endpoint for sending invites '''
2020-10-01 03:47:26 +00:00
if request.user.is_authenticated:
return redirect('/')
invite = get_object_or_404(models.SiteInvite, code=code)
data = {
2020-11-02 22:25:16 +00:00
'title': 'Join',
'register_form': forms.RegisterForm(),
'invite': invite,
'valid': invite.valid() if invite else True,
}
return TemplateResponse(request, 'invite.html', data)
2020-06-03 16:38:30 +00:00
@login_required
2020-10-01 19:59:38 +00:00
@permission_required('bookwyrm.create_invites', raise_exception=True)
2020-11-28 16:22:25 +00:00
@require_GET
2020-06-03 16:38:30 +00:00
def manage_invites(request):
''' invite management page '''
2020-06-03 16:38:30 +00:00
data = {
2020-11-02 22:25:16 +00:00
'title': 'Invitations',
2021-01-05 19:37:48 +00:00
'invites': models.SiteInvite.objects.filter(
user=request.user).order_by('-created_date'),
2020-06-03 16:38:30 +00:00
'form': forms.CreateInviteForm(),
}
return TemplateResponse(request, 'manage_invites.html', data)
2020-03-10 20:31:57 +00:00
@login_required
2020-11-28 16:22:25 +00:00
@require_GET
2020-03-07 22:50:29 +00:00
def notifications_page(request):
''' list notitications '''
notifications = request.user.notification_set.all() \
.order_by('-created_date')
2020-03-10 20:31:57 +00:00
unread = [n.id for n in notifications.filter(read=False)]
2020-03-07 22:50:29 +00:00
data = {
2020-11-02 22:25:16 +00:00
'title': 'Notifications',
'notifications': notifications,
2020-03-10 20:31:57 +00:00
'unread': unread,
2020-03-07 22:50:29 +00:00
}
notifications.update(read=True)
2020-03-07 22:50:29 +00:00
return TemplateResponse(request, 'notifications.html', data)
2020-11-10 22:07:12 +00:00
2020-03-14 00:57:36 +00:00
@csrf_exempt
2020-11-28 16:22:25 +00:00
@require_GET
2020-11-10 22:07:12 +00:00
def user_page(request, username):
2020-01-26 20:14:27 +00:00
''' profile page for a user '''
2020-01-28 06:49:56 +00:00
try:
2020-02-22 00:03:05 +00:00
user = get_user_from_username(username)
2020-01-28 06:49:56 +00:00
except models.User.DoesNotExist:
2020-02-22 00:03:05 +00:00
return HttpResponseNotFound()
2020-01-28 06:49:56 +00:00
2020-03-14 00:57:36 +00:00
if is_api_request(request):
# we have a json request
return ActivitypubResponse(user.to_activity())
2020-03-14 00:57:36 +00:00
# otherwise we're at a UI view
2020-11-11 18:43:47 +00:00
try:
page = int(request.GET.get('page', 1))
except ValueError:
page = 1
shelf_preview = []
# only show other shelves that should be visible
shelves = user.shelf_set
is_self = request.user.id == user.id
if not is_self:
follower = user.followers.filter(id=request.user.id).exists()
if follower:
shelves = shelves.filter(privacy__in=['public', 'followers'])
else:
shelves = shelves.filter(privacy='public')
for user_shelf in shelves.all():
2020-10-30 21:01:43 +00:00
if not user_shelf.books.count():
2020-09-30 02:44:00 +00:00
continue
shelf_preview.append({
2020-10-30 21:01:43 +00:00
'name': user_shelf.name,
2020-12-31 01:36:35 +00:00
'local_path': user_shelf.local_path,
2020-10-30 21:01:43 +00:00
'books': user_shelf.books.all()[:3],
'size': user_shelf.books.count(),
2020-09-30 02:44:00 +00:00
})
if len(shelf_preview) > 2:
2020-09-30 02:44:00 +00:00
break
2020-11-11 18:43:47 +00:00
# user's posts
activities = get_activity_feed(
request.user,
['public', 'unlisted', 'followers'],
queryset=models.Status.objects.filter(user=user)
)
2020-11-11 18:43:47 +00:00
paginated = Paginator(activities, PAGE_LENGTH)
activity_page = paginated.page(page)
prev_page = next_page = None
if activity_page.has_next():
next_page = '/user/%s/?page=%d' % \
(username, activity_page.next_page_number())
if activity_page.has_previous():
prev_page = '/user/%s/?page=%d' % \
(username, activity_page.previous_page_number())
data = {
'title': user.name,
'user': user,
'is_self': is_self,
'shelves': shelf_preview,
'shelf_count': shelves.count(),
2020-11-11 18:43:47 +00:00
'activities': activity_page.object_list,
'next': next_page,
'prev': prev_page,
}
2020-04-22 13:53:22 +00:00
return TemplateResponse(request, 'user.html', data)
2020-01-26 20:14:27 +00:00
2020-03-14 00:57:36 +00:00
@csrf_exempt
2020-11-28 16:22:25 +00:00
@require_GET
2020-03-14 00:57:36 +00:00
def followers_page(request, username):
''' list of followers '''
try:
user = get_user_from_username(username)
except models.User.DoesNotExist:
return HttpResponseNotFound()
if is_api_request(request):
return ActivitypubResponse(user.to_followers_activity(**request.GET))
2020-03-14 00:57:36 +00:00
2020-11-10 22:07:12 +00:00
data = {
'title': '%s: followers' % user.name,
'user': user,
'is_self': request.user.id == user.id,
'followers': user.followers.all(),
}
return TemplateResponse(request, 'followers.html', data)
2020-03-14 00:57:36 +00:00
@csrf_exempt
2020-11-28 16:22:25 +00:00
@require_GET
2020-03-14 00:57:36 +00:00
def following_page(request, username):
''' list of followers '''
try:
user = get_user_from_username(username)
except models.User.DoesNotExist:
return HttpResponseNotFound()
if is_api_request(request):
return ActivitypubResponse(user.to_following_activity(**request.GET))
2020-03-14 00:57:36 +00:00
2020-11-10 22:07:12 +00:00
data = {
'title': '%s: following' % user.name,
'user': user,
'is_self': request.user.id == user.id,
'following': user.following.all(),
}
return TemplateResponse(request, 'following.html', data)
2020-03-14 00:57:36 +00:00
@csrf_exempt
2020-11-28 16:22:25 +00:00
@require_GET
2020-03-07 23:28:11 +00:00
def status_page(request, username, status_id):
''' display a particular status (and replies, etc) '''
try:
user = get_user_from_username(username)
2020-03-07 23:28:11 +00:00
status = models.Status.objects.select_subclasses().get(id=status_id)
except ValueError:
return HttpResponseNotFound()
2020-10-27 22:41:53 +00:00
# the url should have the poster's username in it
2020-03-07 23:28:11 +00:00
if user != status.user:
return HttpResponseNotFound()
2020-10-27 22:41:53 +00:00
# make sure the user is authorized to see the status
if not status_visible_to_user(request.user, status):
return HttpResponseNotFound()
2020-03-14 00:57:36 +00:00
if is_api_request(request):
2021-01-03 16:17:00 +00:00
return ActivitypubResponse(
status.to_activity(pure=not is_bookworm_request(request)))
2020-03-14 00:57:36 +00:00
2020-03-07 23:28:11 +00:00
data = {
'title': 'Status by %s' % user.username,
2020-03-07 23:28:11 +00:00
'status': status,
}
return TemplateResponse(request, 'status.html', data)
2020-10-27 22:41:53 +00:00
def status_visible_to_user(viewer, status):
''' is a user authorized to view a status? '''
if viewer == status.user or status.privacy in ['public', 'unlisted']:
return True
if status.privacy == 'followers' and \
status.user.followers.filter(id=viewer.id).first():
return True
if status.privacy == 'direct' and \
status.mention_users.filter(id=viewer.id).first():
return True
return False
2020-03-14 00:57:36 +00:00
@csrf_exempt
2020-11-28 16:22:25 +00:00
@require_GET
2020-03-14 00:57:36 +00:00
def replies_page(request, username, status_id):
''' ordered collection of replies to a status '''
if not is_api_request(request):
return status_page(request, username, status_id)
status = models.Status.objects.get(id=status_id)
if status.user.localname != username:
return HttpResponseNotFound()
return ActivitypubResponse(status.to_replies(**request.GET))
2020-03-14 00:57:36 +00:00
2020-01-28 06:49:56 +00:00
@login_required
2020-11-28 16:22:25 +00:00
@require_GET
def edit_profile_page(request):
2020-01-28 06:49:56 +00:00
''' profile page for a user '''
user = request.user
2020-01-28 06:49:56 +00:00
2020-01-29 20:24:50 +00:00
form = forms.EditUserForm(instance=request.user)
2020-01-28 06:49:56 +00:00
data = {
2020-11-02 22:25:16 +00:00
'title': 'Edit profile',
2020-01-29 07:23:05 +00:00
'form': form,
2020-01-28 06:49:56 +00:00
'user': user,
}
return TemplateResponse(request, 'edit_user.html', data)
2020-11-28 16:22:25 +00:00
@require_GET
def book_page(request, book_id):
2020-01-28 02:47:54 +00:00
''' info about a book '''
2020-11-11 18:50:51 +00:00
try:
page = int(request.GET.get('page', 1))
except ValueError:
page = 1
2020-11-12 19:40:20 +00:00
try:
book = models.Book.objects.select_subclasses().get(id=book_id)
except models.Book.DoesNotExist:
return HttpResponseNotFound()
2020-03-28 02:52:05 +00:00
if is_api_request(request):
return ActivitypubResponse(book.to_activity())
2020-03-28 02:52:05 +00:00
2020-03-07 06:56:44 +00:00
if isinstance(book, models.Work):
2020-11-29 01:41:57 +00:00
book = book.get_default_edition()
if not book:
return HttpResponseNotFound()
2020-03-30 22:03:21 +00:00
work = book.parent_work
2020-04-04 20:12:15 +00:00
if not work:
return HttpResponseNotFound()
reviews = models.Review.objects.filter(
book__in=work.editions.all(),
2020-10-29 19:32:37 +00:00
)
2020-11-11 18:50:51 +00:00
# all reviews for the book
reviews = get_activity_feed(
request.user,
['public', 'unlisted', 'followers', 'direct'],
queryset=reviews
)
2020-03-07 06:56:44 +00:00
2020-11-11 18:50:51 +00:00
# the reviews to show
paginated = Paginator(reviews.exclude(
Q(content__isnull=True) | Q(content='')
), PAGE_LENGTH)
2020-11-11 18:50:51 +00:00
reviews_page = paginated.page(page)
prev_page = next_page = None
if reviews_page.has_next():
next_page = '/book/%d/?page=%d' % \
(book_id, reviews_page.next_page_number())
if reviews_page.has_previous():
prev_page = '/book/%s/?page=%d' % \
(book_id, reviews_page.previous_page_number())
user_tags = readthroughs = user_shelves = other_edition_shelves = []
if request.user.is_authenticated:
user_tags = models.UserTag.objects.filter(
book=book, user=request.user
).values_list('tag__identifier', flat=True)
2020-10-29 19:32:37 +00:00
readthroughs = models.ReadThrough.objects.filter(
user=request.user,
book=book,
2020-10-29 19:32:37 +00:00
).order_by('start_date')
user_shelves = models.ShelfBook.objects.filter(
added_by=request.user, book=book
)
other_edition_shelves = models.ShelfBook.objects.filter(
~Q(book=book),
added_by=request.user,
book__parent_work=book.parent_work,
)
2020-01-28 02:47:54 +00:00
data = {
2020-11-02 22:25:16 +00:00
'title': book.title,
2020-01-28 02:47:54 +00:00
'book': book,
2020-11-11 18:50:51 +00:00
'reviews': reviews_page,
2021-01-05 01:59:46 +00:00
'review_count': reviews.count(),
'ratings': reviews.filter(Q(content__isnull=True) | Q(content='')),
2020-12-20 02:54:56 +00:00
'rating': reviews.aggregate(Avg('rating'))['rating__avg'],
'tags': models.UserTag.objects.filter(book=book),
2020-02-21 06:19:19 +00:00
'user_tags': user_tags,
'user_shelves': user_shelves,
'other_edition_shelves': other_edition_shelves,
2020-10-30 05:38:01 +00:00
'readthroughs': readthroughs,
2020-05-04 00:53:14 +00:00
'path': '/book/%s' % book_id,
2020-11-11 18:50:51 +00:00
'next': next_page,
'prev': prev_page,
2020-01-28 02:47:54 +00:00
}
return TemplateResponse(request, 'book.html', data)
2020-03-28 22:06:16 +00:00
@login_required
2020-10-01 19:59:38 +00:00
@permission_required('bookwyrm.edit_book', raise_exception=True)
2020-11-28 16:22:25 +00:00
@require_GET
2020-05-04 00:53:14 +00:00
def edit_book_page(request, book_id):
2020-03-28 22:06:16 +00:00
''' info about a book '''
2021-01-02 16:14:28 +00:00
book = get_edition(book_id)
if not book.description:
book.description = book.parent_work.description
2020-03-28 22:06:16 +00:00
data = {
2020-11-02 22:25:16 +00:00
'title': 'Edit Book',
2020-03-28 22:06:16 +00:00
'book': book,
2020-04-02 15:44:53 +00:00
'form': forms.EditionForm(instance=book)
2020-03-28 22:06:16 +00:00
}
return TemplateResponse(request, 'edit_book.html', data)
@login_required
@permission_required('bookwyrm.edit_book', raise_exception=True)
@require_GET
def edit_author_page(request, author_id):
''' info about a book '''
author = get_object_or_404(models.Author, id=author_id)
data = {
'title': 'Edit Author',
'author': author,
'form': forms.AuthorForm(instance=author)
}
return TemplateResponse(request, 'edit_author.html', data)
2020-11-28 16:22:25 +00:00
@require_GET
2020-11-04 20:55:00 +00:00
def editions_page(request, book_id):
2020-03-30 22:03:21 +00:00
''' list of editions of a book '''
work = get_object_or_404(models.Work, id=book_id)
2020-11-04 20:55:00 +00:00
if is_api_request(request):
return ActivitypubResponse(work.to_edition_list(**request.GET))
2020-11-04 20:55:00 +00:00
2020-03-30 22:03:21 +00:00
data = {
2020-11-02 22:25:16 +00:00
'title': 'Editions of %s' % work.title,
2021-01-11 18:25:34 +00:00
'editions': work.editions.order_by('-edition_rank').all(),
2020-03-30 22:03:21 +00:00
'work': work,
}
return TemplateResponse(request, 'editions.html', data)
2020-11-28 16:22:25 +00:00
@require_GET
2020-05-04 00:53:14 +00:00
def author_page(request, author_id):
2020-02-11 06:32:03 +00:00
''' landing page for an author '''
author = get_object_or_404(models.Author, id=author_id)
2020-02-11 06:32:03 +00:00
if is_api_request(request):
return ActivitypubResponse(author.to_activity())
books = models.Work.objects.filter(
Q(authors=author) | Q(editions__authors=author)).distinct()
2020-02-11 06:32:03 +00:00
data = {
2020-11-02 22:25:16 +00:00
'title': author.name,
2020-02-11 06:32:03 +00:00
'author': author,
2020-11-29 01:41:57 +00:00
'books': [b.get_default_edition() for b in books],
2020-02-11 06:32:03 +00:00
}
return TemplateResponse(request, 'author.html', data)
2020-11-28 16:22:25 +00:00
@require_GET
2020-02-21 17:10:27 +00:00
def tag_page(request, tag_id):
''' books related to a tag '''
2020-02-21 17:15:20 +00:00
tag_obj = models.Tag.objects.filter(identifier=tag_id).first()
if not tag_obj:
return HttpResponseNotFound()
if is_api_request(request):
return ActivitypubResponse(tag_obj.to_activity(**request.GET))
books = models.Edition.objects.filter(
usertag__tag__identifier=tag_id
).distinct()
2020-02-21 17:10:27 +00:00
data = {
2020-11-02 22:25:16 +00:00
'title': tag_obj.name,
2020-02-21 17:10:27 +00:00
'books': books,
2020-02-21 17:15:20 +00:00
'tag': tag_obj,
2020-02-21 17:10:27 +00:00
}
return TemplateResponse(request, 'tag.html', data)
@csrf_exempt
2020-11-28 16:22:25 +00:00
@require_GET
def user_shelves_page(request, username):
''' list of followers '''
return shelf_page(request, username, None)
2020-11-28 16:22:25 +00:00
@require_GET
2020-02-22 00:03:05 +00:00
def shelf_page(request, username, shelf_identifier):
''' display a shelf '''
try:
user = get_user_from_username(username)
except models.User.DoesNotExist:
return HttpResponseNotFound()
2020-11-10 22:52:04 +00:00
if shelf_identifier:
shelf = user.shelf_set.get(identifier=shelf_identifier)
else:
shelf = user.shelf_set.first()
is_self = request.user == user
shelves = user.shelf_set
if not is_self:
follower = user.followers.filter(id=request.user.id).exists()
# make sure the user has permission to view the shelf
if shelf.privacy == 'direct' or \
(shelf.privacy == 'followers' and not follower):
return HttpResponseNotFound()
# only show other shelves that should be visible
if follower:
shelves = shelves.filter(privacy__in=['public', 'followers'])
else:
shelves = shelves.filter(privacy='public')
2020-03-28 02:52:05 +00:00
if is_api_request(request):
return ActivitypubResponse(shelf.to_activity(**request.GET))
2020-03-28 02:52:05 +00:00
2020-12-31 00:07:29 +00:00
books = models.ShelfBook.objects.filter(
added_by=user, shelf=shelf
).order_by('-updated_date').all()
2020-11-10 22:07:12 +00:00
data = {
2020-12-20 02:54:56 +00:00
'title': '%s\'s %s shelf' % (user.display_name, shelf.name),
2020-11-10 22:07:12 +00:00
'user': user,
'is_self': is_self,
'shelves': shelves.all(),
2020-11-10 22:52:04 +00:00
'shelf': shelf,
2020-12-31 00:07:29 +00:00
'books': [b.book for b in books],
2020-11-10 22:07:12 +00:00
}
return TemplateResponse(request, 'shelf.html', data)