Django 1.7, working version.
[wolnelektury.git] / apps / social / views.py
1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 from django.shortcuts import render, get_object_or_404, redirect
6 from django.http import HttpResponseForbidden, JsonResponse
7 from django.contrib.auth.decorators import login_required
8 from django.views.decorators.http import require_POST
9
10 from ajaxable.utils import AjaxableFormView
11
12 from catalogue.models import Book
13 from social import forms
14 from social.utils import get_set, likes, set_sets
15
16
17 # ====================
18 # = Shelf management =
19 # ====================
20
21
22 @require_POST
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)
27     if not likes(request.user, book):
28         tag = get_set(request.user, '')
29         set_sets(request.user, book, [tag])
30
31     if request.is_ajax():
32         return JsonResponse({"success": True, "msg": "ok", "like": True})
33     else:
34         return redirect(book)
35
36
37 @login_required
38 def my_shelf(request):
39     books = Book.tagged.with_any(request.user.tag_set.all())
40     return render(request, 'social/my_shelf.html', locals())
41
42
43 class ObjectSetsFormView(AjaxableFormView):
44     form_class = forms.ObjectSetsForm
45     placeholdize = True
46     template = 'social/sets_form.html'
47     ajax_redirect = True
48     POST_login = True
49
50     def get_object(self, request, slug):
51         return get_object_or_404(Book, slug=slug)
52
53     def context_description(self, request, obj):
54         return obj.pretty_title()
55
56     def form_args(self, request, obj):
57         return (obj, request.user), {}
58
59
60 @require_POST
61 def unlike_book(request, slug):
62     if not request.user.is_authenticated():
63         return HttpResponseForbidden('Login required.')
64     book = get_object_or_404(Book, slug=slug)
65     if likes(request.user, book):
66         set_sets(request.user, book, [])
67
68     if request.is_ajax():
69         return JsonResponse({"success": True, "msg": "ok", "like": False})
70     else:
71         return redirect(book)