1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 from django.shortcuts import render, get_object_or_404, redirect
5 from django.http import HttpResponseForbidden, JsonResponse
6 from django.contrib.auth.decorators import login_required
7 from django.views.decorators.cache import never_cache
8 from django.views.decorators.http import require_POST
9 from django.views.generic.edit import FormView
11 from catalogue.models import Book, Tag
12 import catalogue.models.tag
13 from social import forms
14 from wolnelektury.utils import is_ajax
17 # ====================
18 # = Shelf management =
19 # ====================
23 def like_book(request, slug):
24 if not request.user.is_authenticated:
25 return HttpResponseForbidden('Login required.')
26 book = get_object_or_404(Book, slug=slug)
28 book.like(request.user)
31 return JsonResponse({"success": True, "msg": "ok", "like": True})
36 class AddSetView(FormView):
37 form_class = forms.AddSetForm
38 template_name = 'forms/form_detail.html'
40 def form_valid(self, form):
41 book, tag = form.save(self.request.user)
43 if is_ajax(self.request):
44 return JsonResponse(get_sets_for_book_ids([book.id], self.request.user))
49 class RemoveSetView(AddSetView):
50 form_class = forms.RemoveSetForm
54 def unlike_book(request, slug):
55 if not request.user.is_authenticated:
56 return HttpResponseForbidden('Login required.')
57 book = get_object_or_404(Book, slug=slug)
59 book.unlike(request.user)
62 return JsonResponse({"success": True, "msg": "ok", "like": False})
68 def my_shelf(request):
69 template_name = 'social/2022/my_shelf.html'
70 tags = list(request.user.tag_set.all())
71 suggest = [t for t in tags if t.name]
74 return render(request, template_name, {
76 'books': Book.tagged.with_any(tags),
81 def get_sets_for_book_ids(book_ids, user):
83 tagged = catalogue.models.tag.TagRelation.objects.filter(
85 #content_type= # for books,
86 object_id__in=book_ids
87 ).order_by('tag__sort_key')
90 item = data.setdefault(t.object_id, [])
94 "url": t.tag.get_absolute_url(),
106 def my_liked(request):
107 if not request.user.is_authenticated:
108 return JsonResponse({})
110 ids = [int(x) for x in request.GET.get('ids', '').split(',')]
112 return JsonResponse({})
113 return JsonResponse(get_sets_for_book_ids(ids, request.user))
118 def my_tags(request):
119 term = request.GET.get('term', '')
120 tags = Tag.objects.filter(user=request.user).order_by('sort_key')
122 tags = tags.filter(name__icontains=term)