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