87236855b5365cd7dcda67d9a09b90672abb3dfb
[redakcja.git] / apps / catalogue / views.py
1 from datetime import datetime, date, timedelta
2 import logging
3 import os
4 from StringIO import StringIO
5 from urllib import unquote
6 from urlparse import urlsplit, urlunsplit
7
8 from django.contrib import auth
9 from django.contrib.auth.models import User
10 from django.contrib.auth.decorators import login_required, permission_required
11 from django.core.urlresolvers import reverse
12 from django.db.models import Count, Q
13 from django import http
14 from django.http import Http404, HttpResponse, HttpResponseForbidden
15 from django.shortcuts import get_object_or_404, render
16 from django.utils.encoding import iri_to_uri
17 from django.utils.http import urlquote_plus
18 from django.utils.translation import ugettext_lazy as _
19 from django.views.decorators.http import require_POST
20 from django.views.generic.simple import direct_to_template
21
22 from apiclient import NotAuthorizedError
23 from catalogue import forms
24 from catalogue import helpers
25 from catalogue.helpers import active_tab
26 from catalogue.models import Book, Chunk, BookPublishRecord, ChunkPublishRecord
27 from catalogue.tasks import publishable_error
28
29 #
30 # Quick hack around caching problems, TODO: use ETags
31 #
32 from django.views.decorators.cache import never_cache
33
34 logger = logging.getLogger("fnp.catalogue")
35
36
37 @active_tab('all')
38 @never_cache
39 def document_list(request):
40     return render(request, 'catalogue/document_list.html')
41
42
43 @never_cache
44 def user(request, username):
45     user = get_object_or_404(User, username=username)
46     return render(request, 'catalogue/user_page.html', {"viewed_user": user})
47
48
49 @login_required
50 @active_tab('my')
51 @never_cache
52 def my(request):
53     return render(request, 'catalogue/my_page.html', {
54         'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
55                         key=lambda x: x[1]['time'], reverse=True),
56
57         "logout_to": '/',
58         })
59
60
61 @active_tab('users')
62 def users(request):
63     return direct_to_template(request, 'catalogue/user_list.html', extra_context={
64         'users': User.objects.all().annotate(count=Count('chunk')).order_by(
65             '-count', 'last_name', 'first_name'),
66     })
67
68
69 @active_tab('activity')
70 def activity(request, isodate=None):
71     today = date.today()
72     try:
73         day = helpers.parse_isodate(isodate)
74     except ValueError:
75         day = today
76
77     if day > today:
78         raise Http404
79     if day != today:
80         next_day = day + timedelta(1)
81     prev_day = day - timedelta(1)
82
83     return render(request, 'catalogue/activity.html', locals())
84
85
86 @never_cache
87 def logout_then_redirect(request):
88     auth.logout(request)
89     return http.HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
90
91
92 @permission_required('catalogue.add_book')
93 @active_tab('create')
94 def create_missing(request, slug=None):
95     if slug is None:
96         slug = ''
97     slug = slug.replace(' ', '-')
98
99     if request.method == "POST":
100         form = forms.DocumentCreateForm(request.POST, request.FILES)
101         if form.is_valid():
102             
103             if request.user.is_authenticated():
104                 creator = request.user
105             else:
106                 creator = None
107             book = Book.create(
108                 text=form.cleaned_data['text'],
109                 creator=creator,
110                 slug=form.cleaned_data['slug'],
111                 title=form.cleaned_data['title'],
112                 gallery=form.cleaned_data['gallery'],
113             )
114
115             return http.HttpResponseRedirect(reverse("catalogue_book", args=[book.slug]))
116     else:
117         form = forms.DocumentCreateForm(initial={
118                 "slug": slug,
119                 "title": slug.replace('-', ' ').title(),
120                 "gallery": slug,
121         })
122
123     return direct_to_template(request, "catalogue/document_create_missing.html", extra_context={
124         "slug": slug,
125         "form": form,
126
127         "logout_to": '/',
128     })
129
130
131 @permission_required('catalogue.add_book')
132 @active_tab('upload')
133 def upload(request):
134     if request.method == "POST":
135         form = forms.DocumentsUploadForm(request.POST, request.FILES)
136         if form.is_valid():
137             import slughifi
138
139             if request.user.is_authenticated():
140                 creator = request.user
141             else:
142                 creator = None
143
144             zip = form.cleaned_data['zip']
145             skipped_list = []
146             ok_list = []
147             error_list = []
148             slugs = {}
149             existing = [book.slug for book in Book.objects.all()]
150             for filename in zip.namelist():
151                 if filename[-1] == '/':
152                     continue
153                 title = os.path.basename(filename)[:-4]
154                 slug = slughifi(title)
155                 if not (slug and filename.endswith('.xml')):
156                     skipped_list.append(filename)
157                 elif slug in slugs:
158                     error_list.append((filename, slug, _('Slug already used for %s' % slugs[slug])))
159                 elif slug in existing:
160                     error_list.append((filename, slug, _('Slug already used in repository.')))
161                 else:
162                     try:
163                         zip.read(filename).decode('utf-8') # test read
164                         ok_list.append((filename, slug, title))
165                     except UnicodeDecodeError:
166                         error_list.append((filename, title, _('File should be UTF-8 encoded.')))
167                     slugs[slug] = filename
168
169             if not error_list:
170                 for filename, slug, title in ok_list:
171                     book = Book.create(
172                         text=zip.read(filename).decode('utf-8'),
173                         creator=creator,
174                         slug=slug,
175                         title=title,
176                     )
177
178             return direct_to_template(request, "catalogue/document_upload.html", extra_context={
179                 "form": form,
180                 "ok_list": ok_list,
181                 "skipped_list": skipped_list,
182                 "error_list": error_list,
183
184                 "logout_to": '/',
185             })
186     else:
187         form = forms.DocumentsUploadForm()
188
189     return direct_to_template(request, "catalogue/document_upload.html", extra_context={
190         "form": form,
191
192         "logout_to": '/',
193     })
194
195
196 @never_cache
197 def book_xml(request, slug):
198     book = get_object_or_404(Book, slug=slug)
199     if not book.accessible(request):
200         return HttpResponseForbidden("Not authorized.")
201     xml = book.materialize()
202
203     response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
204     response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
205     return response
206
207
208 @never_cache
209 def book_txt(request, slug):
210     book = get_object_or_404(Book, slug=slug)
211     if not book.accessible(request):
212         return HttpResponseForbidden("Not authorized.")
213     xml = book.materialize()
214     output = StringIO()
215     # errors?
216
217     import librarian.text
218     librarian.text.transform(StringIO(xml), output)
219     text = output.getvalue()
220     response = http.HttpResponse(text, content_type='text/plain', mimetype='text/plain')
221     response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
222     return response
223
224
225 @never_cache
226 def book_html(request, slug):
227     book = get_object_or_404(Book, slug=slug)
228     if not book.accessible(request):
229         return HttpResponseForbidden("Not authorized.")
230     xml = book.materialize()
231     output = StringIO()
232     # errors?
233
234     import librarian.html
235     librarian.html.transform(StringIO(xml), output, parse_dublincore=False,
236                              flags=['full-page'])
237     html = output.getvalue()
238     response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
239     return response
240
241
242 @never_cache
243 def book_pdf(request, slug):
244     book = get_object_or_404(Book, slug=slug)
245     if not book.accessible(request):
246         return HttpResponseForbidden("Not authorized.")
247
248     from tempfile import NamedTemporaryFile
249     from os import unlink
250     from librarian import pdf
251     from catalogue.ebook_utils import RedakcjaDocProvider, serve_file
252
253     xml = book.materialize()
254     xml_file = NamedTemporaryFile()
255     xml_file.write(xml.encode('utf-8'))
256     xml_file.flush()
257
258     try:
259         pdf_file = NamedTemporaryFile(delete=False)
260         pdf.transform(RedakcjaDocProvider(),
261                   file_path=xml_file.name,
262                   output_file=pdf_file,
263                   )
264         return serve_file(pdf_file.name, book.slug + '.pdf', 'application/pdf')
265     finally:
266         unlink(pdf_file.name)
267
268
269 @never_cache
270 def book_epub(request, slug):
271     book = get_object_or_404(Book, slug=slug)
272     if not book.accessible(request):
273         return HttpResponseForbidden("Not authorized.")
274
275     from StringIO import StringIO
276     from tempfile import NamedTemporaryFile
277     from librarian import epub
278     from catalogue.ebook_utils import RedakcjaDocProvider
279
280     xml = book.materialize()
281     xml_file = NamedTemporaryFile()
282     xml_file.write(xml.encode('utf-8'))
283     xml_file.flush()
284
285     epub_file = StringIO()
286     epub.transform(RedakcjaDocProvider(), file_path=xml_file.name,
287             output_file=epub_file)
288     response = HttpResponse(mimetype='application/epub+zip')
289     response['Content-Disposition'] = 'attachment; filename=%s' % book.slug + '.epub'
290     response.write(epub_file.getvalue())
291     return response
292
293
294 @never_cache
295 def revision(request, slug, chunk=None):
296     try:
297         doc = Chunk.get(slug, chunk)
298     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
299         raise Http404
300     if not doc.book.accessible(request):
301         return HttpResponseForbidden("Not authorized.")
302     return http.HttpResponse(str(doc.revision()))
303
304
305 def book(request, slug):
306     book = get_object_or_404(Book, slug=slug)
307     if not book.accessible(request):
308         return HttpResponseForbidden("Not authorized.")
309
310     if request.user.has_perm('catalogue.change_book'):
311         if request.method == "POST":
312             form = forms.BookForm(request.POST, instance=book)
313             if form.is_valid():
314                 form.save()
315                 return http.HttpResponseRedirect(book.get_absolute_url())
316         else:
317             form = forms.BookForm(instance=book)
318             editable = True
319     else:
320         form = forms.ReadonlyBookForm(instance=book)
321         editable = False
322
323     publish_error = publishable_error(book)
324     publishable = publish_error is None
325
326     return direct_to_template(request, "catalogue/book_detail.html", extra_context={
327         "book": book,
328         "publishable": publishable,
329         "publishable_error": publish_error,
330         "form": form,
331         "editable": editable,
332     })
333
334
335 @permission_required('catalogue.add_chunk')
336 def chunk_add(request, slug, chunk):
337     try:
338         doc = Chunk.get(slug, chunk)
339     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
340         raise Http404
341     if not doc.book.accessible(request):
342         return HttpResponseForbidden("Not authorized.")
343
344     if request.method == "POST":
345         form = forms.ChunkAddForm(request.POST, instance=doc)
346         if form.is_valid():
347             if request.user.is_authenticated():
348                 creator = request.user
349             else:
350                 creator = None
351             doc.split(creator=creator,
352                 slug=form.cleaned_data['slug'],
353                 title=form.cleaned_data['title'],
354                 gallery_start=form.cleaned_data['gallery_start'],
355                 user=form.cleaned_data['user'],
356                 stage=form.cleaned_data['stage']
357             )
358
359             return http.HttpResponseRedirect(doc.book.get_absolute_url())
360     else:
361         form = forms.ChunkAddForm(initial={
362                 "slug": str(doc.number + 1),
363                 "title": "cz. %d" % (doc.number + 1, ),
364         })
365
366     return direct_to_template(request, "catalogue/chunk_add.html", extra_context={
367         "chunk": doc,
368         "form": form,
369     })
370
371
372 def chunk_edit(request, slug, chunk):
373     try:
374         doc = Chunk.get(slug, chunk)
375     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
376         raise Http404
377     if not doc.book.accessible(request):
378         return HttpResponseForbidden("Not authorized.")
379
380     if request.method == "POST":
381         form = forms.ChunkForm(request.POST, instance=doc)
382         if form.is_valid():
383             form.save()
384             go_next = request.GET.get('next', None)
385             if go_next:
386                 go_next = urlquote_plus(unquote(iri_to_uri(go_next)), safe='/?=&')
387             else:
388                 go_next = doc.book.get_absolute_url()
389             return http.HttpResponseRedirect(go_next)
390     else:
391         form = forms.ChunkForm(instance=doc)
392
393     referer = request.META.get('HTTP_REFERER')
394     if referer:
395         parts = urlsplit(referer)
396         parts = ['', ''] + list(parts[2:])
397         go_next = urlquote_plus(urlunsplit(parts))
398     else:
399         go_next = ''
400
401     return direct_to_template(request, "catalogue/chunk_edit.html", extra_context={
402         "chunk": doc,
403         "form": form,
404         "go_next": go_next,
405     })
406
407
408 @permission_required('catalogue.change_book')
409 def book_append(request, slug):
410     book = get_object_or_404(Book, slug=slug)
411     if not book.accessible(request):
412         return HttpResponseForbidden("Not authorized.")
413
414     if request.method == "POST":
415         form = forms.BookAppendForm(book, request.POST)
416         if form.is_valid():
417             append_to = form.cleaned_data['append_to']
418             append_to.append(book)
419             return http.HttpResponseRedirect(append_to.get_absolute_url())
420     else:
421         form = forms.BookAppendForm(book)
422     return direct_to_template(request, "catalogue/book_append_to.html", extra_context={
423         "book": book,
424         "form": form,
425
426         "logout_to": '/',
427     })
428
429
430 @require_POST
431 @login_required
432 def publish(request, slug):
433     book = get_object_or_404(Book, slug=slug)
434     if not book.accessible(request):
435         return HttpResponseForbidden("Not authorized.")
436
437     try:
438         book.publish(request.user)
439     except NotAuthorizedError:
440         return http.HttpResponseRedirect(reverse('apiclient_oauth'))
441     except BaseException, e:
442         return http.HttpResponse(e)
443     else:
444         return http.HttpResponseRedirect(book.get_absolute_url())