f62080562b979c118de8131c587843942b0062fa
[redakcja.git] / src / catalogue / views.py
1 # -*- coding: utf-8 -*-
2 from collections import defaultdict
3 from datetime import datetime, date, timedelta
4 import logging
5 import os
6 from StringIO import StringIO
7 from urllib import unquote
8 from urlparse import urlsplit, urlunsplit
9
10 from django.conf import settings
11 from django.contrib import auth
12 from django.contrib.auth.models import User
13 from django.contrib.auth.decorators import login_required, permission_required
14 from django.core.urlresolvers import reverse
15 from django.db.models import Count, Q
16 from django.db import transaction
17 from django import http
18 from django.http import Http404, HttpResponse, HttpResponseForbidden
19 from django.http.response import HttpResponseRedirect
20 from django.shortcuts import get_object_or_404, render
21 from django.utils.encoding import iri_to_uri
22 from django.utils.http import urlquote_plus
23 from django.utils.translation import ugettext_lazy as _
24 from django.views.decorators.http import require_POST
25 from django_cas.decorators import user_passes_test
26
27 from apiclient import NotAuthorizedError
28 from catalogue import forms
29 from catalogue import helpers
30 from catalogue.helpers import active_tab
31 from catalogue.models import (Book, Chunk, Image, BookPublishRecord, 
32         ChunkPublishRecord, ImagePublishRecord, Project)
33 from fileupload.views import UploadView
34
35 #
36 # Quick hack around caching problems, TODO: use ETags
37 #
38 from django.views.decorators.cache import never_cache
39
40 logger = logging.getLogger("fnp.catalogue")
41
42
43 @active_tab('all')
44 @never_cache
45 def document_list(request):
46     return render(request, 'catalogue/document_list.html')
47
48
49 @active_tab('images')
50 @never_cache
51 def image_list(request, user=None):
52     return render(request, 'catalogue/image_list.html')
53
54
55 @never_cache
56 def user(request, username):
57     user = get_object_or_404(User, username=username)
58     return render(request, 'catalogue/user_page.html', {"viewed_user": user})
59
60
61 @login_required
62 @active_tab('my')
63 @never_cache
64 def my(request):
65     last_books = sorted(request.session.get("wiki_last_books", {}).items(),
66         key=lambda x: x[1]['time'], reverse=True)
67     for k, v in last_books:
68         v['time'] = datetime.fromtimestamp(v['time'])
69     return render(request, 'catalogue/my_page.html', {
70         'last_books': last_books,
71         "logout_to": '/',
72         })
73
74
75 @active_tab('users')
76 def users(request):
77     return render(request, 'catalogue/user_list.html', {
78         'users': User.objects.all().annotate(count=Count('chunk')).order_by(
79             '-count', 'last_name', 'first_name'),
80     })
81
82
83 @active_tab('activity')
84 def activity(request, isodate=None):
85     today = date.today()
86     try:
87         day = helpers.parse_isodate(isodate)
88     except ValueError:
89         day = today
90
91     if day > today:
92         raise Http404
93     if day != today:
94         next_day = day + timedelta(1)
95     prev_day = day - timedelta(1)
96
97     return render(request, 'catalogue/activity.html', locals())
98
99
100 @never_cache
101 def logout_then_redirect(request):
102     auth.logout(request)
103     return http.HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
104
105
106 @permission_required('catalogue.add_book')
107 @active_tab('create')
108 def create_missing(request, slug=None):
109     if slug is None:
110         slug = ''
111     slug = slug.replace(' ', '-')
112
113     if request.method == "POST":
114         form = forms.DocumentCreateForm(request.POST, request.FILES)
115         if form.is_valid():
116             
117             if request.user.is_authenticated():
118                 creator = request.user
119             else:
120                 creator = None
121             book = Book.create(
122                 text=form.cleaned_data['text'],
123                 creator=creator,
124                 slug=form.cleaned_data['slug'],
125                 title=form.cleaned_data['title'],
126                 gallery=form.cleaned_data['gallery'],
127             )
128
129             return http.HttpResponseRedirect(reverse("catalogue_book", args=[book.slug]))
130     else:
131         form = forms.DocumentCreateForm(initial={
132                 "slug": slug,
133                 "title": slug.replace('-', ' ').title(),
134                 "gallery": slug,
135         })
136
137     return render(request, "catalogue/document_create_missing.html", {
138         "slug": slug,
139         "form": form,
140
141         "logout_to": '/',
142     })
143
144
145 @permission_required('catalogue.add_book')
146 @active_tab('upload')
147 def upload(request):
148     if request.method == "POST":
149         form = forms.DocumentsUploadForm(request.POST, request.FILES)
150         if form.is_valid():
151             from slugify import slugify
152
153             if request.user.is_authenticated():
154                 creator = request.user
155             else:
156                 creator = None
157
158             zip = form.cleaned_data['zip']
159             skipped_list = []
160             ok_list = []
161             error_list = []
162             slugs = {}
163             existing = [book.slug for book in Book.objects.all()]
164             for filename in zip.namelist():
165                 if filename[-1] == '/':
166                     continue
167                 title = os.path.basename(filename)[:-4]
168                 slug = slugify(title)
169                 if not (slug and filename.endswith('.xml')):
170                     skipped_list.append(filename)
171                 elif slug in slugs:
172                     error_list.append((filename, slug, _('Slug already used for %s' % slugs[slug])))
173                 elif slug in existing:
174                     error_list.append((filename, slug, _('Slug already used in repository.')))
175                 else:
176                     try:
177                         zip.read(filename).decode('utf-8') # test read
178                         ok_list.append((filename, slug, title))
179                     except UnicodeDecodeError:
180                         error_list.append((filename, title, _('File should be UTF-8 encoded.')))
181                     slugs[slug] = filename
182
183             if not error_list:
184                 for filename, slug, title in ok_list:
185                     book = Book.create(
186                         text=zip.read(filename).decode('utf-8'),
187                         creator=creator,
188                         slug=slug,
189                         title=title,
190                     )
191
192             return render(request, "catalogue/document_upload.html", {
193                 "form": form,
194                 "ok_list": ok_list,
195                 "skipped_list": skipped_list,
196                 "error_list": error_list,
197
198                 "logout_to": '/',
199             })
200     else:
201         form = forms.DocumentsUploadForm()
202
203     return render(request, "catalogue/document_upload.html", {
204         "form": form,
205
206         "logout_to": '/',
207     })
208
209
210 def serve_xml(request, book, slug):
211     if not book.accessible(request):
212         return HttpResponseForbidden("Not authorized.")
213     xml = book.materialize(publishable=True)
214     response = http.HttpResponse(xml, content_type='application/xml')
215     response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
216     return response
217
218
219 @never_cache
220 def book_xml(request, slug):
221     book = get_object_or_404(Book, slug=slug)
222     return serve_xml(request, book, slug)
223
224
225 @never_cache
226 def book_xml_dc(request, slug):
227     book = get_object_or_404(Book, dc_slug=slug)
228     return serve_xml(request, book, slug)
229
230
231 @never_cache
232 def book_txt(request, slug):
233     book = get_object_or_404(Book, slug=slug)
234     if not book.accessible(request):
235         return HttpResponseForbidden("Not authorized.")
236
237     doc = book.wldocument()
238     text = doc.as_text().get_bytes()
239     response = http.HttpResponse(text, content_type='text/plain')
240     response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
241     return response
242
243
244 @never_cache
245 def book_html(request, slug):
246     book = get_object_or_404(Book, slug=slug)
247     if not book.accessible(request):
248         return HttpResponseForbidden("Not authorized.")
249
250     doc = book.wldocument(parse_dublincore=False)
251     html = doc.as_html(options={'gallery': "'%s'" % book.gallery_url()})
252
253     html = html.get_bytes() if html is not None else ''
254     # response = http.HttpResponse(html, content_type='text/html')
255     # return response
256     # book_themes = {}
257     # for fragment in book.fragments.all().iterator():
258     #     for theme in fragment.tags.filter(category='theme').iterator():
259     #         book_themes.setdefault(theme, []).append(fragment)
260
261     # book_themes = book_themes.items()
262     # book_themes.sort(key=lambda s: s[0].sort_key)
263     return render(request, 'catalogue/book_text.html', locals())
264
265
266 @never_cache
267 def book_pdf(request, slug, mobile=False):
268     book = get_object_or_404(Book, slug=slug)
269     if not book.accessible(request):
270         return HttpResponseForbidden("Not authorized.")
271
272     # TODO: move to celery
273     doc = book.wldocument()
274     # TODO: error handling
275     customizations = ['26pt', 'nothemes', 'nomargins', 'notoc'] if mobile else None
276     pdf_file = doc.as_pdf(cover=True, ilustr_path=book.gallery_path(), customizations=customizations)
277     from catalogue.ebook_utils import serve_file
278     return serve_file(pdf_file.get_filename(),
279                 book.slug + '.pdf', 'application/pdf')
280
281
282 @never_cache
283 def book_epub(request, slug):
284     book = get_object_or_404(Book, slug=slug)
285     if not book.accessible(request):
286         return HttpResponseForbidden("Not authorized.")
287
288     # TODO: move to celery
289     doc = book.wldocument()
290     # TODO: error handling
291     epub = doc.as_epub(ilustr_path=book.gallery_path()).get_bytes()
292     response = HttpResponse(content_type='application/epub+zip')
293     response['Content-Disposition'] = 'attachment; filename=%s' % book.slug + '.epub'
294     response.write(epub)
295     return response
296
297
298 @never_cache
299 def book_mobi(request, slug):
300     book = get_object_or_404(Book, slug=slug)
301     if not book.accessible(request):
302         return HttpResponseForbidden("Not authorized.")
303
304     # TODO: move to celery
305     doc = book.wldocument()
306     # TODO: error handling
307     mobi = doc.as_mobi(ilustr_path=book.gallery_path()).get_bytes()
308     response = HttpResponse(content_type='application/x-mobipocket-ebook')
309     response['Content-Disposition'] = 'attachment; filename=%s' % book.slug + '.mobi'
310     response.write(mobi)
311     return response
312
313
314 @never_cache
315 def revision(request, slug, chunk=None):
316     try:
317         doc = Chunk.get(slug, chunk)
318     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
319         raise Http404
320     if not doc.book.accessible(request):
321         return HttpResponseForbidden("Not authorized.")
322     return http.HttpResponse(str(doc.revision()))
323
324
325 def book(request, slug):
326     book = get_object_or_404(Book, slug=slug)
327     if not book.accessible(request):
328         return HttpResponseForbidden("Not authorized.")
329
330     if request.user.has_perm('catalogue.change_book'):
331         if request.method == "POST":
332             form = forms.BookForm(request.POST, instance=book)
333             if form.is_valid():
334                 form.save()
335                 return http.HttpResponseRedirect(book.get_absolute_url())
336         else:
337             form = forms.BookForm(instance=book)
338         publish_options_form = forms.PublishOptionsForm()
339         editable = True
340     else:
341         form = forms.ReadonlyBookForm(instance=book)
342         publish_options_form = forms.PublishOptionsForm()
343         editable = False
344
345     publish_error = book.publishable_error()
346     publishable = publish_error is None
347
348     return render(request, "catalogue/book_detail.html", {
349         "book": book,
350         "publishable": publishable,
351         "publishable_error": publish_error,
352         "form": form,
353         "publish_options_form": publish_options_form,
354         "editable": editable,
355     })
356
357
358 def image(request, slug):
359     image = get_object_or_404(Image, slug=slug)
360     if not image.accessible(request):
361         return HttpResponseForbidden("Not authorized.")
362
363     if request.user.has_perm('catalogue.change_image'):
364         if request.method == "POST":
365             form = forms.ImageForm(request.POST, instance=image)
366             if form.is_valid():
367                 form.save()
368                 return http.HttpResponseRedirect(image.get_absolute_url())
369         else:
370             form = forms.ImageForm(instance=image)
371         editable = True
372     else:
373         form = forms.ReadonlyImageForm(instance=image)
374         editable = False
375
376     publish_error = image.publishable_error()
377     publishable = publish_error is None
378
379     return render(request, "catalogue/image_detail.html", {
380         "object": image,
381         "publishable": publishable,
382         "publishable_error": publish_error,
383         "form": form,
384         "editable": editable,
385     })
386
387
388 @permission_required('catalogue.add_chunk')
389 def chunk_add(request, slug, chunk):
390     try:
391         doc = Chunk.get(slug, chunk)
392     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
393         raise Http404
394     if not doc.book.accessible(request):
395         return HttpResponseForbidden("Not authorized.")
396
397     if request.method == "POST":
398         form = forms.ChunkAddForm(request.POST, instance=doc)
399         if form.is_valid():
400             if request.user.is_authenticated():
401                 creator = request.user
402             else:
403                 creator = None
404             doc.split(creator=creator,
405                 slug=form.cleaned_data['slug'],
406                 title=form.cleaned_data['title'],
407                 gallery_start=form.cleaned_data['gallery_start'],
408                 user=form.cleaned_data['user'],
409                 stage=form.cleaned_data['stage']
410             )
411
412             return http.HttpResponseRedirect(doc.book.get_absolute_url())
413     else:
414         form = forms.ChunkAddForm(initial={
415                 "slug": str(doc.number + 1),
416                 "title": "cz. %d" % (doc.number + 1, ),
417         })
418
419     return render(request, "catalogue/chunk_add.html", {
420         "chunk": doc,
421         "form": form,
422     })
423
424
425 @login_required
426 def chunk_edit(request, slug, chunk):
427     try:
428         doc = Chunk.get(slug, chunk)
429     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
430         raise Http404
431     if not doc.book.accessible(request):
432         return HttpResponseForbidden("Not authorized.")
433
434     if request.method == "POST":
435         form = forms.ChunkForm(request.POST, instance=doc)
436         if form.is_valid():
437             form.save()
438             go_next = request.GET.get('next', None)
439             if go_next:
440                 go_next = urlquote_plus(unquote(iri_to_uri(go_next)), safe='/?=&')
441             else:
442                 go_next = doc.book.get_absolute_url()
443             return http.HttpResponseRedirect(go_next)
444     else:
445         form = forms.ChunkForm(instance=doc)
446
447     referer = request.META.get('HTTP_REFERER')
448     if referer:
449         parts = urlsplit(referer)
450         parts = ['', ''] + list(parts[2:])
451         go_next = urlquote_plus(urlunsplit(parts))
452     else:
453         go_next = ''
454
455     return render(request, "catalogue/chunk_edit.html", {
456         "chunk": doc,
457         "form": form,
458         "go_next": go_next,
459     })
460
461
462 @transaction.atomic
463 @login_required
464 @require_POST
465 def chunk_mass_edit(request):
466     ids = map(int, filter(lambda i: i.strip()!='', request.POST.get('ids').split(',')))
467     chunks = map(lambda i: Chunk.objects.get(id=i), ids)
468     
469     stage = request.POST.get('stage')
470     if stage:
471         try:
472             stage = Chunk.tag_model.objects.get(slug=stage)
473         except Chunk.DoesNotExist, e:
474             stage = None
475        
476         for c in chunks: c.stage = stage
477
478     username = request.POST.get('user')
479     logger.info("username: %s" % username)
480     logger.info(request.POST)
481     if username:
482         try:
483             user = User.objects.get(username=username)
484         except User.DoesNotExist, e:
485             user = None
486             
487         for c in chunks: c.user = user
488
489     project_id = request.POST.get('project')
490     if project_id:
491         try:
492             project = Project.objects.get(pk=int(project_id))
493         except (Project.DoesNotExist, ValueError), e:
494             project = None
495         for c in chunks:
496             book = c.book
497             book.project = project
498             book.save()
499
500     for c in chunks: c.save()
501
502     return HttpResponse("", content_type="text/plain")
503
504
505 @transaction.atomic
506 @login_required
507 @require_POST
508 def image_mass_edit(request):
509     ids = map(int, filter(lambda i: i.strip()!='', request.POST.get('ids').split(',')))
510     images = map(lambda i: Image.objects.get(id=i), ids)
511     
512     stage = request.POST.get('stage')
513     if stage:
514         try:
515             stage = Image.tag_model.objects.get(slug=stage)
516         except Image.DoesNotExist, e:
517             stage = None
518        
519         for c in images: c.stage = stage
520
521     username = request.POST.get('user')
522     logger.info("username: %s" % username)
523     logger.info(request.POST)
524     if username:
525         try:
526             user = User.objects.get(username=username)
527         except User.DoesNotExist, e:
528             user = None
529             
530         for c in images: c.user = user
531
532     project_id = request.POST.get('project')
533     if project_id:
534         try:
535             project = Project.objects.get(pk=int(project_id))
536         except (Project.DoesNotExist, ValueError), e:
537             project = None
538         for c in images:
539             c.project = project
540
541     for c in images: c.save()
542
543     return HttpResponse("", content_type="text/plain")
544
545
546 @permission_required('catalogue.change_book')
547 def book_append(request, slug):
548     book = get_object_or_404(Book, slug=slug)
549     if not book.accessible(request):
550         return HttpResponseForbidden("Not authorized.")
551
552     if request.method == "POST":
553         form = forms.BookAppendForm(book, request.POST)
554         if form.is_valid():
555             append_to = form.cleaned_data['append_to']
556             append_to.append(book)
557             return http.HttpResponseRedirect(append_to.get_absolute_url())
558     else:
559         form = forms.BookAppendForm(book)
560     return render(request, "catalogue/book_append_to.html", {
561         "book": book,
562         "form": form,
563
564         "logout_to": '/',
565     })
566
567
568 @require_POST
569 @login_required
570 def publish(request, slug):
571     form = forms.PublishOptionsForm(request.POST)
572     if form.is_valid():
573         days = form.cleaned_data['days']
574         beta = form.cleaned_data['beta']
575     else:
576         days = 0
577         beta = False
578     book = get_object_or_404(Book, slug=slug)
579     if not book.accessible(request):
580         return HttpResponseForbidden("Not authorized.")
581
582     try:
583         protocol = 'https://' if request.is_secure() else 'http://'
584         book.publish(request.user, host=protocol + request.get_host(), days=days, beta=beta)
585     except NotAuthorizedError:
586         return http.HttpResponseRedirect(reverse('apiclient_oauth' if not beta else 'apiclient_beta_oauth'))
587     except BaseException, e:
588         return http.HttpResponse(repr(e))
589     else:
590         return http.HttpResponseRedirect(book.get_absolute_url())
591
592
593 @require_POST
594 @login_required
595 def publish_image(request, slug):
596     image = get_object_or_404(Image, slug=slug)
597     if not image.accessible(request):
598         return HttpResponseForbidden("Not authorized.")
599
600     try:
601         image.publish(request.user)
602     except NotAuthorizedError:
603         return http.HttpResponseRedirect(reverse('apiclient_oauth'))
604     except BaseException, e:
605         return http.HttpResponse(e)
606     else:
607         return http.HttpResponseRedirect(image.get_absolute_url())
608
609
610 class GalleryView(UploadView):
611     def get_object(self, request, slug):
612         book = get_object_or_404(Book, slug=slug)
613         if not book.gallery:
614             raise Http404
615         return book
616
617     def breadcrumbs(self):
618         return [
619             (_('books'), reverse('catalogue_document_list')),
620             (self.object.title, self.object.get_absolute_url()),
621             (_('scan gallery'),),
622         ]
623
624     def get_directory(self):
625         return "%s%s/" % (settings.IMAGE_DIR, self.object.gallery)
626
627
628 def active_users_list(request):
629     since = date(date.today().year, 1, 1)
630     by_user = defaultdict(lambda: 0)
631     by_email = defaultdict(lambda: 0)
632     names_by_email = defaultdict(set)
633     for change_model in (Chunk.change_model, Image.change_model):
634         for c in change_model.objects.filter(
635                 created_at__gte=since).order_by(
636                 'author', 'author_email', 'author_name').values(
637                 'author', 'author_name', 'author_email').annotate(
638                 c=Count('author'), ce=Count('author_email')).distinct():
639             if c['author']:
640                 by_user[c['author']] += c['c']
641             else:
642                 by_email[c['author_email']] += c['ce']
643                 if c['author_name'].strip():
644                     names_by_email[c['author_email']].add(c['author_name'])
645     for user in User.objects.filter(pk__in=by_user):
646         by_email[user.email] += by_user[user.pk]
647         names_by_email[user.email].add("%s %s" % (user.first_name, user.last_name))
648
649     active_users = []
650     for email, count in by_email.items():
651         active_users.append((email, names_by_email[email], count))
652     active_users.sort(key=lambda x: -x[2])
653     return render(request, 'catalogue/active_users_list.html', {
654         'users': active_users,
655         'since': since,
656     })
657
658
659 @user_passes_test(lambda u: u.is_superuser)
660 def mark_final(request):
661     if request.method == 'POST':
662         form = forms.MarkFinalForm(data=request.POST)
663         if form.is_valid():
664             form.save()
665             return HttpResponseRedirect(reverse('mark_final_completed'))
666     else:
667         form = forms.MarkFinalForm()
668     return render(request, 'catalogue/mark_final.html', {'form': form})
669
670
671 def mark_final_completed(request):
672     return render(request, 'catalogue/mark_final_completed.html')