fc572c25e61d51dd146f465f3b5c6921421d059b
[redakcja.git] / apps / catalogue / views.py
1 from collections import defaultdict
2 from datetime import datetime, date, timedelta
3 import logging
4 import os
5 from StringIO import StringIO
6 from urllib import unquote
7 from urlparse import urlsplit, urlunsplit
8
9 from django.conf import settings
10 from django.contrib import auth
11 from django.contrib.auth.models import User
12 from django.contrib.auth.decorators import login_required, permission_required
13 from django.core.urlresolvers import reverse
14 from django.db.models import Count, Q
15 from django.db import transaction
16 from django import http
17 from django.http import Http404, HttpResponse, HttpResponseForbidden
18 from django.http.response import HttpResponseRedirect
19 from django.shortcuts import get_object_or_404, render
20 from django.utils.encoding import iri_to_uri
21 from django.utils.http import urlquote_plus
22 from django.utils.translation import ugettext_lazy as _
23 from django.views.decorators.http import require_POST
24 from django_cas.decorators import user_passes_test
25
26 from apiclient import NotAuthorizedError
27 from catalogue import forms
28 from catalogue import helpers
29 from catalogue.forms import MarkFinalForm
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_string()
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_string() 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):
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     pdf_file = doc.as_pdf(cover=True, ilustr_path=book.gallery_path())
276     from catalogue.ebook_utils import serve_file
277     return serve_file(pdf_file.get_filename(),
278                 book.slug + '.pdf', 'application/pdf')
279
280
281 @never_cache
282 def book_epub(request, slug):
283     book = get_object_or_404(Book, slug=slug)
284     if not book.accessible(request):
285         return HttpResponseForbidden("Not authorized.")
286
287     # TODO: move to celery
288     doc = book.wldocument()
289     # TODO: error handling
290     epub = doc.as_epub(ilustr_path=book.gallery_path()).get_string()
291     response = HttpResponse(content_type='application/epub+zip')
292     response['Content-Disposition'] = 'attachment; filename=%s' % book.slug + '.epub'
293     response.write(epub)
294     return response
295
296
297 @never_cache
298 def book_mobi(request, slug):
299     book = get_object_or_404(Book, slug=slug)
300     if not book.accessible(request):
301         return HttpResponseForbidden("Not authorized.")
302
303     # TODO: move to celery
304     doc = book.wldocument()
305     # TODO: error handling
306     mobi = doc.as_mobi(ilustr_path=book.gallery_path()).get_string()
307     response = HttpResponse(content_type='application/x-mobipocket-ebook')
308     response['Content-Disposition'] = 'attachment; filename=%s' % book.slug + '.mobi'
309     response.write(mobi)
310     return response
311
312
313 @never_cache
314 def revision(request, slug, chunk=None):
315     try:
316         doc = Chunk.get(slug, chunk)
317     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
318         raise Http404
319     if not doc.book.accessible(request):
320         return HttpResponseForbidden("Not authorized.")
321     return http.HttpResponse(str(doc.revision()))
322
323
324 def book(request, slug):
325     book = get_object_or_404(Book, slug=slug)
326     if not book.accessible(request):
327         return HttpResponseForbidden("Not authorized.")
328
329     if request.user.has_perm('catalogue.change_book'):
330         if request.method == "POST":
331             form = forms.BookForm(request.POST, instance=book)
332             if form.is_valid():
333                 form.save()
334                 return http.HttpResponseRedirect(book.get_absolute_url())
335         else:
336             form = forms.BookForm(instance=book)
337         editable = True
338     else:
339         form = forms.ReadonlyBookForm(instance=book)
340         editable = False
341
342     publish_error = book.publishable_error()
343     publishable = publish_error is None
344
345     return render(request, "catalogue/book_detail.html", {
346         "book": book,
347         "publishable": publishable,
348         "publishable_error": publish_error,
349         "form": form,
350         "editable": editable,
351     })
352
353
354 def image(request, slug):
355     image = get_object_or_404(Image, slug=slug)
356     if not image.accessible(request):
357         return HttpResponseForbidden("Not authorized.")
358
359     if request.user.has_perm('catalogue.change_image'):
360         if request.method == "POST":
361             form = forms.ImageForm(request.POST, instance=image)
362             if form.is_valid():
363                 form.save()
364                 return http.HttpResponseRedirect(image.get_absolute_url())
365         else:
366             form = forms.ImageForm(instance=image)
367         editable = True
368     else:
369         form = forms.ReadonlyImageForm(instance=image)
370         editable = False
371
372     publish_error = image.publishable_error()
373     publishable = publish_error is None
374
375     return render(request, "catalogue/image_detail.html", {
376         "object": image,
377         "publishable": publishable,
378         "publishable_error": publish_error,
379         "form": form,
380         "editable": editable,
381     })
382
383
384 @permission_required('catalogue.add_chunk')
385 def chunk_add(request, slug, chunk):
386     try:
387         doc = Chunk.get(slug, chunk)
388     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
389         raise Http404
390     if not doc.book.accessible(request):
391         return HttpResponseForbidden("Not authorized.")
392
393     if request.method == "POST":
394         form = forms.ChunkAddForm(request.POST, instance=doc)
395         if form.is_valid():
396             if request.user.is_authenticated():
397                 creator = request.user
398             else:
399                 creator = None
400             doc.split(creator=creator,
401                 slug=form.cleaned_data['slug'],
402                 title=form.cleaned_data['title'],
403                 gallery_start=form.cleaned_data['gallery_start'],
404                 user=form.cleaned_data['user'],
405                 stage=form.cleaned_data['stage']
406             )
407
408             return http.HttpResponseRedirect(doc.book.get_absolute_url())
409     else:
410         form = forms.ChunkAddForm(initial={
411                 "slug": str(doc.number + 1),
412                 "title": "cz. %d" % (doc.number + 1, ),
413         })
414
415     return render(request, "catalogue/chunk_add.html", {
416         "chunk": doc,
417         "form": form,
418     })
419
420
421 @login_required
422 def chunk_edit(request, slug, chunk):
423     try:
424         doc = Chunk.get(slug, chunk)
425     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
426         raise Http404
427     if not doc.book.accessible(request):
428         return HttpResponseForbidden("Not authorized.")
429
430     if request.method == "POST":
431         form = forms.ChunkForm(request.POST, instance=doc)
432         if form.is_valid():
433             form.save()
434             go_next = request.GET.get('next', None)
435             if go_next:
436                 go_next = urlquote_plus(unquote(iri_to_uri(go_next)), safe='/?=&')
437             else:
438                 go_next = doc.book.get_absolute_url()
439             return http.HttpResponseRedirect(go_next)
440     else:
441         form = forms.ChunkForm(instance=doc)
442
443     referer = request.META.get('HTTP_REFERER')
444     if referer:
445         parts = urlsplit(referer)
446         parts = ['', ''] + list(parts[2:])
447         go_next = urlquote_plus(urlunsplit(parts))
448     else:
449         go_next = ''
450
451     return render(request, "catalogue/chunk_edit.html", {
452         "chunk": doc,
453         "form": form,
454         "go_next": go_next,
455     })
456
457
458 @transaction.atomic
459 @login_required
460 @require_POST
461 def chunk_mass_edit(request):
462     ids = map(int, filter(lambda i: i.strip()!='', request.POST.get('ids').split(',')))
463     chunks = map(lambda i: Chunk.objects.get(id=i), ids)
464     
465     stage = request.POST.get('stage')
466     if stage:
467         try:
468             stage = Chunk.tag_model.objects.get(slug=stage)
469         except Chunk.DoesNotExist, e:
470             stage = None
471        
472         for c in chunks: c.stage = stage
473
474     username = request.POST.get('user')
475     logger.info("username: %s" % username)
476     logger.info(request.POST)
477     if username:
478         try:
479             user = User.objects.get(username=username)
480         except User.DoesNotExist, e:
481             user = None
482             
483         for c in chunks: c.user = user
484
485     project_id = request.POST.get('project')
486     if project_id:
487         try:
488             project = Project.objects.get(pk=int(project_id))
489         except (Project.DoesNotExist, ValueError), e:
490             project = None
491         for c in chunks:
492             book = c.book
493             book.project = project
494             book.save()
495
496     for c in chunks: c.save()
497
498     return HttpResponse("", content_type="text/plain")
499
500
501 @transaction.atomic
502 @login_required
503 @require_POST
504 def image_mass_edit(request):
505     ids = map(int, filter(lambda i: i.strip()!='', request.POST.get('ids').split(',')))
506     images = map(lambda i: Image.objects.get(id=i), ids)
507     
508     stage = request.POST.get('stage')
509     if stage:
510         try:
511             stage = Image.tag_model.objects.get(slug=stage)
512         except Image.DoesNotExist, e:
513             stage = None
514        
515         for c in images: c.stage = stage
516
517     username = request.POST.get('user')
518     logger.info("username: %s" % username)
519     logger.info(request.POST)
520     if username:
521         try:
522             user = User.objects.get(username=username)
523         except User.DoesNotExist, e:
524             user = None
525             
526         for c in images: c.user = user
527
528     project_id = request.POST.get('project')
529     if project_id:
530         try:
531             project = Project.objects.get(pk=int(project_id))
532         except (Project.DoesNotExist, ValueError), e:
533             project = None
534         for c in images:
535             c.project = project
536
537     for c in images: c.save()
538
539     return HttpResponse("", content_type="text/plain")
540
541
542 @permission_required('catalogue.change_book')
543 def book_append(request, slug):
544     book = get_object_or_404(Book, slug=slug)
545     if not book.accessible(request):
546         return HttpResponseForbidden("Not authorized.")
547
548     if request.method == "POST":
549         form = forms.BookAppendForm(book, request.POST)
550         if form.is_valid():
551             append_to = form.cleaned_data['append_to']
552             append_to.append(book)
553             return http.HttpResponseRedirect(append_to.get_absolute_url())
554     else:
555         form = forms.BookAppendForm(book)
556     return render(request, "catalogue/book_append_to.html", {
557         "book": book,
558         "form": form,
559
560         "logout_to": '/',
561     })
562
563
564 @require_POST
565 @login_required
566 def publish(request, slug):
567     book = get_object_or_404(Book, slug=slug)
568     if not book.accessible(request):
569         return HttpResponseForbidden("Not authorized.")
570
571     try:
572         protocol = 'https://' if request.is_secure() else 'http://'
573         book.publish(request.user, host=protocol + request.get_host())
574     except NotAuthorizedError:
575         return http.HttpResponseRedirect(reverse('apiclient_oauth'))
576     except BaseException, e:
577         return http.HttpResponse(repr(e))
578     else:
579         return http.HttpResponseRedirect(book.get_absolute_url())
580
581
582 @require_POST
583 @login_required
584 def publish_image(request, slug):
585     image = get_object_or_404(Image, slug=slug)
586     if not image.accessible(request):
587         return HttpResponseForbidden("Not authorized.")
588
589     try:
590         image.publish(request.user)
591     except NotAuthorizedError:
592         return http.HttpResponseRedirect(reverse('apiclient_oauth'))
593     except BaseException, e:
594         return http.HttpResponse(e)
595     else:
596         return http.HttpResponseRedirect(image.get_absolute_url())
597
598
599 class GalleryView(UploadView):
600     def get_object(self, request, slug):
601         book = get_object_or_404(Book, slug=slug)
602         if not book.gallery:
603             raise Http404
604         return book
605
606     def breadcrumbs(self):
607         return [
608             (_('books'), reverse('catalogue_document_list')),
609             (self.object.title, self.object.get_absolute_url()),
610             (_('scan gallery'),),
611         ]
612
613     def get_directory(self):
614         return "%s%s/" % (settings.IMAGE_DIR, self.object.gallery)
615
616
617 def active_users_list(request):
618     since = date(date.today().year, 1, 1)
619     by_user = defaultdict(lambda: 0)
620     by_email = defaultdict(lambda: 0)
621     names_by_email = defaultdict(set)
622     for change_model in (Chunk.change_model, Image.change_model):
623         for c in change_model.objects.filter(
624                 created_at__gte=since).order_by(
625                 'author', 'author_email', 'author_name').values(
626                 'author', 'author_name', 'author_email').annotate(
627                 c=Count('author'), ce=Count('author_email')).distinct():
628             if c['author']:
629                 by_user[c['author']] += c['c']
630             else:
631                 by_email[c['author_email']] += c['ce']
632                 if c['author_name'].strip():
633                     names_by_email[c['author_email']].add(c['author_name'])
634     for user in User.objects.filter(pk__in=by_user):
635         by_email[user.email] += by_user[user.pk]
636         names_by_email[user.email].add("%s %s" % (user.first_name, user.last_name))
637
638     active_users = []
639     for email, count in by_email.items():
640         active_users.append((email, names_by_email[email], count))
641     active_users.sort(key=lambda x: -x[2])
642     return render(request, 'catalogue/active_users_list.html', {
643         'users': active_users,
644         'since': since,
645     })
646
647
648 @user_passes_test(lambda u: u.is_superuser)
649 def mark_final(request):
650     if request.method == 'POST':
651         form = MarkFinalForm(data=request.POST)
652         if form.is_valid():
653             form.save()
654             return HttpResponseRedirect(reverse('mark_final_completed'))
655     else:
656         form = MarkFinalForm()
657     return render(request, 'catalogue/mark_final.html', {'form': form})
658
659
660 def mark_final_completed(request):
661     return render(request, 'catalogue/mark_final_completed.html')