1 # -*- coding: utf-8 -*-
2 from collections import defaultdict
3 from datetime import datetime, date, timedelta
6 from urllib.parse import unquote, urlsplit, urlunsplit
8 from django.conf import settings
9 from django.contrib import auth
10 from django.contrib.auth.models import User
11 from django.contrib.auth.decorators import login_required, permission_required
12 from django.core.urlresolvers import reverse
13 from django.db.models import Count, Q
14 from django.db import transaction
15 from django import http
16 from django.http import Http404, HttpResponse, HttpResponseForbidden
17 from django.http.response import HttpResponseRedirect
18 from django.shortcuts import get_object_or_404, render
19 from django.utils.encoding import iri_to_uri
20 from django.utils.http import urlquote_plus
21 from django.utils.translation import ugettext_lazy as _
22 from django.views.decorators.http import require_POST
23 from django_cas_ng.decorators import user_passes_test
25 from apiclient import NotAuthorizedError
26 from catalogue import forms
27 from catalogue import helpers
28 from catalogue.helpers import active_tab
29 from catalogue.models import (Book, Chunk, Image, BookPublishRecord,
30 ChunkPublishRecord, ImagePublishRecord, Project)
31 from fileupload.views import UploadView
34 # Quick hack around caching problems, TODO: use ETags
36 from django.views.decorators.cache import never_cache
38 logger = logging.getLogger("fnp.catalogue")
43 def document_list(request):
44 return render(request, 'catalogue/document_list.html')
49 def image_list(request, user=None):
50 return render(request, 'catalogue/image_list.html')
54 def user(request, username):
55 user = get_object_or_404(User, username=username)
56 return render(request, 'catalogue/user_page.html', {"viewed_user": user})
63 last_books = sorted(request.session.get("wiki_last_books", {}).items(),
64 key=lambda x: x[1]['time'], reverse=True)
65 for k, v in last_books:
66 v['time'] = datetime.fromtimestamp(v['time'])
67 return render(request, 'catalogue/my_page.html', {
68 'last_books': last_books,
75 return render(request, 'catalogue/user_list.html', {
76 'users': User.objects.all().annotate(count=Count('chunk')).order_by(
77 '-count', 'last_name', 'first_name'),
81 @active_tab('activity')
82 def activity(request, isodate=None):
85 day = helpers.parse_isodate(isodate)
92 next_day = day + timedelta(1)
93 prev_day = day - timedelta(1)
95 return render(request, 'catalogue/activity.html', locals())
99 def logout_then_redirect(request):
101 return http.HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
104 @permission_required('catalogue.add_book')
105 @active_tab('create')
106 def create_missing(request, slug=None):
109 slug = slug.replace(' ', '-')
111 if request.method == "POST":
112 form = forms.DocumentCreateForm(request.POST, request.FILES)
115 if request.user.is_authenticated():
116 creator = request.user
120 text=form.cleaned_data['text'],
122 slug=form.cleaned_data['slug'],
123 title=form.cleaned_data['title'],
124 gallery=form.cleaned_data['gallery'],
127 return http.HttpResponseRedirect(reverse("catalogue_book", args=[book.slug]))
129 form = forms.DocumentCreateForm(initial={
131 "title": slug.replace('-', ' ').title(),
135 return render(request, "catalogue/document_create_missing.html", {
143 @permission_required('catalogue.add_book')
144 @active_tab('upload')
146 if request.method == "POST":
147 form = forms.DocumentsUploadForm(request.POST, request.FILES)
149 from slugify import slugify
151 if request.user.is_authenticated():
152 creator = request.user
156 zip = form.cleaned_data['zip']
161 existing = [book.slug for book in Book.objects.all()]
162 for filename in zip.namelist():
163 if filename[-1] == '/':
165 title = os.path.basename(filename)[:-4]
166 slug = slugify(title)
167 if not (slug and filename.endswith('.xml')):
168 skipped_list.append(filename)
170 error_list.append((filename, slug, _('Slug already used for %s' % slugs[slug])))
171 elif slug in existing:
172 error_list.append((filename, slug, _('Slug already used in repository.')))
175 zip.read(filename).decode('utf-8') # test read
176 ok_list.append((filename, slug, title))
177 except UnicodeDecodeError:
178 error_list.append((filename, title, _('File should be UTF-8 encoded.')))
179 slugs[slug] = filename
182 for filename, slug, title in ok_list:
184 text=zip.read(filename).decode('utf-8'),
190 return render(request, "catalogue/document_upload.html", {
193 "skipped_list": skipped_list,
194 "error_list": error_list,
199 form = forms.DocumentsUploadForm()
201 return render(request, "catalogue/document_upload.html", {
208 def serve_xml(request, book, slug):
209 if not book.accessible(request):
210 return HttpResponseForbidden("Not authorized.")
211 xml = book.materialize(publishable=True)
212 response = http.HttpResponse(xml, content_type='application/xml')
213 response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
218 def book_xml(request, slug):
219 book = get_object_or_404(Book, slug=slug)
220 return serve_xml(request, book, slug)
224 def book_xml_dc(request, slug):
225 book = get_object_or_404(Book, dc_slug=slug)
226 return serve_xml(request, book, slug)
230 def book_txt(request, slug):
231 book = get_object_or_404(Book, slug=slug)
232 if not book.accessible(request):
233 return HttpResponseForbidden("Not authorized.")
235 doc = book.wldocument()
236 text = doc.as_text().get_bytes()
237 response = http.HttpResponse(text, content_type='text/plain')
238 response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
243 def book_html(request, slug):
244 book = get_object_or_404(Book, slug=slug)
245 if not book.accessible(request):
246 return HttpResponseForbidden("Not authorized.")
248 doc = book.wldocument(parse_dublincore=False)
249 html = doc.as_html(options={'gallery': "'%s'" % book.gallery_url()})
251 html = html.get_bytes() if html is not None else ''
252 # response = http.HttpResponse(html, content_type='text/html')
255 # for fragment in book.fragments.all().iterator():
256 # for theme in fragment.tags.filter(category='theme').iterator():
257 # book_themes.setdefault(theme, []).append(fragment)
259 # book_themes = book_themes.items()
260 # book_themes.sort(key=lambda s: s[0].sort_key)
261 return render(request, 'catalogue/book_text.html', locals())
265 def book_pdf(request, slug, mobile=False):
266 book = get_object_or_404(Book, slug=slug)
267 if not book.accessible(request):
268 return HttpResponseForbidden("Not authorized.")
270 # TODO: move to celery
271 doc = book.wldocument()
272 # TODO: error handling
273 customizations = ['26pt', 'nothemes', 'nomargins', 'notoc'] if mobile else None
274 pdf_file = doc.as_pdf(cover=True, ilustr_path=book.gallery_path(), customizations=customizations)
275 from catalogue.ebook_utils import serve_file
276 return serve_file(pdf_file.get_filename(),
277 book.slug + '.pdf', 'application/pdf')
281 def book_epub(request, slug):
282 book = get_object_or_404(Book, slug=slug)
283 if not book.accessible(request):
284 return HttpResponseForbidden("Not authorized.")
286 # TODO: move to celery
287 doc = book.wldocument()
288 # TODO: error handling
289 epub = doc.as_epub(ilustr_path=book.gallery_path()).get_bytes()
290 response = HttpResponse(content_type='application/epub+zip')
291 response['Content-Disposition'] = 'attachment; filename=%s' % book.slug + '.epub'
297 def book_mobi(request, slug):
298 book = get_object_or_404(Book, slug=slug)
299 if not book.accessible(request):
300 return HttpResponseForbidden("Not authorized.")
302 # TODO: move to celery
303 doc = book.wldocument()
304 # TODO: error handling
305 mobi = doc.as_mobi(ilustr_path=book.gallery_path()).get_bytes()
306 response = HttpResponse(content_type='application/x-mobipocket-ebook')
307 response['Content-Disposition'] = 'attachment; filename=%s' % book.slug + '.mobi'
313 def revision(request, slug, chunk=None):
315 doc = Chunk.get(slug, chunk)
316 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
318 if not doc.book.accessible(request):
319 return HttpResponseForbidden("Not authorized.")
320 return http.HttpResponse(str(doc.revision()))
323 def book(request, slug):
324 book = get_object_or_404(Book, slug=slug)
325 if not book.accessible(request):
326 return HttpResponseForbidden("Not authorized.")
328 if request.user.has_perm('catalogue.change_book'):
329 if request.method == "POST":
330 form = forms.BookForm(request.POST, instance=book)
333 return http.HttpResponseRedirect(book.get_absolute_url())
335 form = forms.BookForm(instance=book)
336 publish_options_form = forms.PublishOptionsForm()
339 form = forms.ReadonlyBookForm(instance=book)
340 publish_options_form = forms.PublishOptionsForm()
343 publish_error = book.publishable_error()
344 publishable = publish_error is None
346 return render(request, "catalogue/book_detail.html", {
348 "publishable": publishable,
349 "publishable_error": publish_error,
351 "publish_options_form": publish_options_form,
352 "editable": editable,
356 def image(request, slug):
357 image = get_object_or_404(Image, slug=slug)
358 if not image.accessible(request):
359 return HttpResponseForbidden("Not authorized.")
361 if request.user.has_perm('catalogue.change_image'):
362 if request.method == "POST":
363 form = forms.ImageForm(request.POST, instance=image)
366 return http.HttpResponseRedirect(image.get_absolute_url())
368 form = forms.ImageForm(instance=image)
371 form = forms.ReadonlyImageForm(instance=image)
374 publish_error = image.publishable_error()
375 publishable = publish_error is None
377 return render(request, "catalogue/image_detail.html", {
379 "publishable": publishable,
380 "publishable_error": publish_error,
382 "editable": editable,
386 @permission_required('catalogue.add_chunk')
387 def chunk_add(request, slug, chunk):
389 doc = Chunk.get(slug, chunk)
390 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
392 if not doc.book.accessible(request):
393 return HttpResponseForbidden("Not authorized.")
395 if request.method == "POST":
396 form = forms.ChunkAddForm(request.POST, instance=doc)
398 if request.user.is_authenticated():
399 creator = request.user
402 doc.split(creator=creator,
403 slug=form.cleaned_data['slug'],
404 title=form.cleaned_data['title'],
405 gallery_start=form.cleaned_data['gallery_start'],
406 user=form.cleaned_data['user'],
407 stage=form.cleaned_data['stage']
410 return http.HttpResponseRedirect(doc.book.get_absolute_url())
412 form = forms.ChunkAddForm(initial={
413 "slug": str(doc.number + 1),
414 "title": "cz. %d" % (doc.number + 1, ),
417 return render(request, "catalogue/chunk_add.html", {
424 def chunk_edit(request, slug, chunk):
426 doc = Chunk.get(slug, chunk)
427 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
429 if not doc.book.accessible(request):
430 return HttpResponseForbidden("Not authorized.")
432 if request.method == "POST":
433 form = forms.ChunkForm(request.POST, instance=doc)
436 go_next = request.GET.get('next', None)
438 go_next = urlquote_plus(unquote(iri_to_uri(go_next)), safe='/?=&')
440 go_next = doc.book.get_absolute_url()
441 return http.HttpResponseRedirect(go_next)
443 form = forms.ChunkForm(instance=doc)
445 referer = request.META.get('HTTP_REFERER')
447 parts = urlsplit(referer)
448 parts = ['', ''] + list(parts[2:])
449 go_next = urlquote_plus(urlunsplit(parts))
453 return render(request, "catalogue/chunk_edit.html", {
463 def chunk_mass_edit(request):
464 ids = map(int, filter(lambda i: i.strip()!='', request.POST.get('ids').split(',')))
465 chunks = map(lambda i: Chunk.objects.get(id=i), ids)
467 stage = request.POST.get('stage')
470 stage = Chunk.tag_model.objects.get(slug=stage)
471 except Chunk.DoesNotExist as e:
474 for c in chunks: c.stage = stage
476 username = request.POST.get('user')
477 logger.info("username: %s" % username)
478 logger.info(request.POST)
481 user = User.objects.get(username=username)
482 except User.DoesNotExist as e:
485 for c in chunks: c.user = user
487 project_id = request.POST.get('project')
490 project = Project.objects.get(pk=int(project_id))
491 except (Project.DoesNotExist, ValueError) as e:
495 book.project = project
498 for c in chunks: c.save()
500 return HttpResponse("", content_type="text/plain")
506 def image_mass_edit(request):
507 ids = map(int, filter(lambda i: i.strip()!='', request.POST.get('ids').split(',')))
508 images = map(lambda i: Image.objects.get(id=i), ids)
510 stage = request.POST.get('stage')
513 stage = Image.tag_model.objects.get(slug=stage)
514 except Image.DoesNotExist as e:
517 for c in images: c.stage = stage
519 username = request.POST.get('user')
520 logger.info("username: %s" % username)
521 logger.info(request.POST)
524 user = User.objects.get(username=username)
525 except User.DoesNotExist as e:
528 for c in images: c.user = user
530 project_id = request.POST.get('project')
533 project = Project.objects.get(pk=int(project_id))
534 except (Project.DoesNotExist, ValueError) as e:
539 for c in images: c.save()
541 return HttpResponse("", content_type="text/plain")
544 @permission_required('catalogue.change_book')
545 def book_append(request, slug):
546 book = get_object_or_404(Book, slug=slug)
547 if not book.accessible(request):
548 return HttpResponseForbidden("Not authorized.")
550 if request.method == "POST":
551 form = forms.BookAppendForm(book, request.POST)
553 append_to = form.cleaned_data['append_to']
554 append_to.append(book)
555 return http.HttpResponseRedirect(append_to.get_absolute_url())
557 form = forms.BookAppendForm(book)
558 return render(request, "catalogue/book_append_to.html", {
568 def publish(request, slug):
569 form = forms.PublishOptionsForm(request.POST)
571 days = form.cleaned_data['days']
572 beta = form.cleaned_data['beta']
576 book = get_object_or_404(Book, slug=slug)
577 if not book.accessible(request):
578 return HttpResponseForbidden("Not authorized.")
581 protocol = 'https://' if request.is_secure() else 'http://'
582 book.publish(request.user, host=protocol + request.get_host(), days=days, beta=beta)
583 except NotAuthorizedError:
584 return http.HttpResponseRedirect(reverse('apiclient_oauth' if not beta else 'apiclient_beta_oauth'))
585 except BaseException as e:
586 return http.HttpResponse(repr(e))
588 return http.HttpResponseRedirect(book.get_absolute_url())
593 def publish_image(request, slug):
594 image = get_object_or_404(Image, slug=slug)
595 if not image.accessible(request):
596 return HttpResponseForbidden("Not authorized.")
599 image.publish(request.user)
600 except NotAuthorizedError:
601 return http.HttpResponseRedirect(reverse('apiclient_oauth'))
602 except BaseException as e:
603 return http.HttpResponse(e)
605 return http.HttpResponseRedirect(image.get_absolute_url())
608 class GalleryView(UploadView):
609 def get_object(self, request, slug):
610 book = get_object_or_404(Book, slug=slug)
615 def breadcrumbs(self):
617 (_('books'), reverse('catalogue_document_list')),
618 (self.object.title, self.object.get_absolute_url()),
619 (_('scan gallery'),),
622 def get_directory(self):
623 return "%s%s/" % (settings.IMAGE_DIR, self.object.gallery)
626 def active_users_list(request):
627 since = date(date.today().year, 1, 1)
628 by_user = defaultdict(lambda: 0)
629 by_email = defaultdict(lambda: 0)
630 names_by_email = defaultdict(set)
631 for change_model in (Chunk.change_model, Image.change_model):
632 for c in change_model.objects.filter(
633 created_at__gte=since).order_by(
634 'author', 'author_email', 'author_name').values(
635 'author', 'author_name', 'author_email').annotate(
636 c=Count('author'), ce=Count('author_email')).distinct():
638 by_user[c['author']] += c['c']
640 by_email[c['author_email']] += c['ce']
641 if c['author_name'].strip():
642 names_by_email[c['author_email']].add(c['author_name'])
643 for user in User.objects.filter(pk__in=by_user):
644 by_email[user.email] += by_user[user.pk]
645 names_by_email[user.email].add("%s %s" % (user.first_name, user.last_name))
648 for email, count in by_email.items():
649 active_users.append((email, names_by_email[email], count))
650 active_users.sort(key=lambda x: -x[2])
651 return render(request, 'catalogue/active_users_list.html', {
652 'users': active_users,
657 @user_passes_test(lambda u: u.is_superuser)
658 def mark_final(request):
659 if request.method == 'POST':
660 form = forms.MarkFinalForm(data=request.POST)
663 return HttpResponseRedirect(reverse('mark_final_completed'))
665 form = forms.MarkFinalForm()
666 return render(request, 'catalogue/mark_final.html', {'form': form})
669 def mark_final_completed(request):
670 return render(request, 'catalogue/mark_final_completed.html')