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