Fix section counting/targetting from search snippet
[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
7 from django.contrib.auth.decorators import login_required
8 #~ from django.utils.datastructures import SortedDict
9 from django.views.decorators.http import require_POST
10 #~ from django.contrib import auth
11 #~ from django.views.decorators import cache
12 from django.utils.translation import ugettext as _
13
14 from ajaxable.utils import LazyEncoder, JSONResponse, AjaxableFormView
15
16 from catalogue.models import Book, Tag
17 from social import forms
18 from social.utils import get_set, likes, set_sets
19
20
21 # ====================
22 # = Shelf management =
23 # ====================
24
25
26 @require_POST
27 def like_book(request, slug):
28     if not request.user.is_authenticated():
29         return HttpResponseForbidden('Login required.')
30     book = get_object_or_404(Book, slug=slug)
31     if not likes(request.user, book):
32         tag = get_set(request.user, '')
33         set_sets(request.user, book, [tag])
34
35     if request.is_ajax():
36         return JSONResponse({"success": True, "msg": "ok", "like": True})
37     else:
38         return redirect(book)
39
40
41 @login_required
42 def my_shelf(request):
43     books = Book.tagged.with_any(request.user.tag_set.all())
44     return render(request, 'social/my_shelf.html', locals())
45
46
47 class ObjectSetsFormView(AjaxableFormView):
48     form_class = forms.ObjectSetsForm
49     placeholdize = True
50     template = 'social/sets_form.html'
51     ajax_redirect = True
52     POST_login = True
53
54     def form_args(self, request, slug):
55         book = get_object_or_404(Book, slug=slug)
56         return (book, request.user), {}
57
58
59 def unlike_book(request, slug):
60     book = get_object_or_404(Book, slug=slug)
61     if likes(request.user, book):
62         set_sets(request.user, book, [])
63
64     if request.is_ajax():
65         return JSONResponse({"success": True, "msg": "ok", "like": False})
66     else:
67         return redirect(book)
68
69
70 #~ @login_required
71 #~ @cache.never_cache
72 #~ def user_shelves(request):
73     #~ shelves = models.Tag.objects.filter(category='set', user=request.user)
74     #~ new_set_form = forms.NewSetForm()
75     #~ return render_to_response('social/user_shelves.html', locals(),
76             #~ context_instance=RequestContext(request))
77 #~ 
78 #~ @cache.never_cache
79 #~ def book_sets(request, slug):
80     #~ if not request.user.is_authenticated():
81         #~ return HttpResponse(_('<p>To maintain your shelves you need to be logged in.</p>'))
82 #~ 
83     #~ book = get_object_or_404(models.Book, slug=slug)
84 #~ 
85     #~ user_sets = models.Tag.objects.filter(category='set', user=request.user)
86     #~ book_sets = book.tags.filter(category='set', user=request.user)
87 #~ 
88     #~ if request.method == 'POST':
89         #~ form = forms.ObjectSetsForm(book, request.user, request.POST)
90         #~ if form.is_valid():
91             #~ DONE!
92             #~ if request.is_ajax():
93                 #~ return JSONResponse('{"msg":"'+_("<p>Shelves were sucessfully saved.</p>")+'", "after":"close"}')
94             #~ else:
95                 #~ return HttpResponseRedirect('/')
96     #~ else:
97         #~ form = forms.ObjectSetsForm(book, request.user)
98         #~ new_set_form = forms.NewSetForm()
99 #~ 
100     #~ return render_to_response('social/book_sets.html', locals(),
101         #~ context_instance=RequestContext(request))
102 #~ 
103 #~ 
104 #~ @login_required
105 #~ @require_POST
106 #~ @cache.never_cache
107 #~ def remove_from_shelf(request, shelf, slug):
108     #~ book = get_object_or_404(models.Book, slug=slug)
109 #~ 
110     #~ shelf = get_object_or_404(models.Tag, slug=shelf, category='set', user=request.user)
111 #~ 
112     #~ if shelf in book.tags:
113         #~ models.Tag.objects.remove_tag(book, shelf)
114         #~ touch_tag(shelf)
115 #~ 
116         #~ return HttpResponse(_('Book was successfully removed from the shelf'))
117     #~ else:
118         #~ return HttpResponse(_('This book is not on the shelf'))
119 #~ 
120 #~ 
121 #~ def collect_books(books):
122     #~ """
123     #~ Returns all real books in collection.
124     #~ """
125     #~ result = []
126     #~ for book in books:
127         #~ if len(book.children.all()) == 0:
128             #~ result.append(book)
129         #~ else:
130             #~ result += collect_books(book.children.all())
131     #~ return result
132 #~ 
133 #~ 
134 #~ @cache.never_cache
135 #~ def download_shelf(request, slug):
136     #~ """"
137     #~ Create a ZIP archive on disk and transmit it in chunks of 8KB,
138     #~ without loading the whole file into memory. A similar approach can
139     #~ be used for large dynamic PDF files.
140     #~ """
141     #~ from slughifi import slughifi
142     #~ import tempfile
143     #~ import zipfile
144 #~ 
145     #~ shelf = get_object_or_404(models.Tag, slug=slug, category='set')
146 #~ 
147     #~ formats = []
148     #~ form = forms.DownloadFormatsForm(request.GET)
149     #~ if form.is_valid():
150         #~ formats = form.cleaned_data['formats']
151     #~ if len(formats) == 0:
152         #~ formats = models.Book.ebook_formats
153 #~ 
154     #~ # Create a ZIP archive
155     #~ temp = tempfile.TemporaryFile()
156     #~ archive = zipfile.ZipFile(temp, 'w')
157 #~ 
158     #~ for book in collect_books(models.Book.tagged.with_all(shelf)):
159         #~ for ebook_format in models.Book.ebook_formats:
160             #~ if ebook_format in formats and book.has_media(ebook_format):
161                 #~ filename = book.get_media(ebook_format).path
162                 #~ archive.write(filename, str('%s.%s' % (book.slug, ebook_format)))
163     #~ archive.close()
164 #~ 
165     #~ response = HttpResponse(content_type='application/zip', mimetype='application/x-zip-compressed')
166     #~ response['Content-Disposition'] = 'attachment; filename=%s.zip' % slughifi(shelf.name)
167     #~ response['Content-Length'] = temp.tell()
168 #~ 
169     #~ temp.seek(0)
170     #~ response.write(temp.read())
171     #~ return response
172 #~ 
173 #~ 
174 #~ @cache.never_cache
175 #~ def shelf_book_formats(request, shelf):
176     #~ """"
177     #~ Returns a list of formats of books in shelf.
178     #~ """
179     #~ shelf = get_object_or_404(models.Tag, slug=shelf, category='set')
180 #~ 
181     #~ formats = {}
182     #~ for ebook_format in models.Book.ebook_formats:
183         #~ formats[ebook_format] = False
184 #~ 
185     #~ for book in collect_books(models.Book.tagged.with_all(shelf)):
186         #~ for ebook_format in models.Book.ebook_formats:
187             #~ if book.has_media(ebook_format):
188                 #~ formats[ebook_format] = True
189 #~ 
190     #~ return HttpResponse(LazyEncoder().encode(formats))
191 #~ 
192 #~ 
193 #~ @login_required
194 #~ @require_POST
195 #~ @cache.never_cache
196 #~ def new_set(request):
197     #~ new_set_form = forms.NewSetForm(request.POST)
198     #~ if new_set_form.is_valid():
199         #~ new_set = new_set_form.save(request.user)
200 #~ 
201         #~ if request.is_ajax():
202             #~ return JSONResponse('{"id":"%d", "name":"%s", "msg":"<p>Shelf <strong>%s</strong> was successfully created</p>"}' % (new_set.id, new_set.name, new_set))
203         #~ else:
204             #~ return HttpResponseRedirect('/')
205 #~ 
206     #~ return HttpResponseRedirect('/')
207 #~ 
208 #~ 
209 #~ @login_required
210 #~ @require_POST
211 #~ @cache.never_cache
212 #~ def delete_shelf(request, slug):
213     #~ user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
214     #~ user_set.delete()
215 #~ 
216     #~ if request.is_ajax():
217         #~ return HttpResponse(_('<p>Shelf <strong>%s</strong> was successfully removed</p>') % user_set.name)
218     #~ else:
219         #~ return HttpResponseRedirect('/')