1 # -*- coding: utf-8 -*-
2 from collections import defaultdict
3 from datetime import datetime, date, timedelta
6 from StringIO import StringIO
7 from urllib import unquote
8 from urlparse import urlsplit, urlunsplit
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
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
36 # Quick hack around caching problems, TODO: use ETags
38 from django.views.decorators.cache import never_cache
40 logger = logging.getLogger("fnp.catalogue")
45 def document_list(request):
46 return render(request, 'catalogue/document_list.html')
51 def image_list(request, user=None):
52 return render(request, 'catalogue/image_list.html')
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})
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,
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'),
83 @active_tab('activity')
84 def activity(request, isodate=None):
87 day = helpers.parse_isodate(isodate)
94 next_day = day + timedelta(1)
95 prev_day = day - timedelta(1)
97 return render(request, 'catalogue/activity.html', locals())
101 def logout_then_redirect(request):
103 return http.HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
106 @permission_required('catalogue.add_book')
107 @active_tab('create')
108 def create_missing(request, slug=None):
111 slug = slug.replace(' ', '-')
113 if request.method == "POST":
114 form = forms.DocumentCreateForm(request.POST, request.FILES)
117 if request.user.is_authenticated():
118 creator = request.user
122 text=form.cleaned_data['text'],
124 slug=form.cleaned_data['slug'],
125 title=form.cleaned_data['title'],
126 gallery=form.cleaned_data['gallery'],
129 return http.HttpResponseRedirect(reverse("catalogue_book", args=[book.slug]))
131 form = forms.DocumentCreateForm(initial={
133 "title": slug.replace('-', ' ').title(),
137 return render(request, "catalogue/document_create_missing.html", {
145 @permission_required('catalogue.add_book')
146 @active_tab('upload')
148 if request.method == "POST":
149 form = forms.DocumentsUploadForm(request.POST, request.FILES)
151 from slugify import slugify
153 if request.user.is_authenticated():
154 creator = request.user
158 zip = form.cleaned_data['zip']
163 existing = [book.slug for book in Book.objects.all()]
164 for filename in zip.namelist():
165 if filename[-1] == '/':
167 title = os.path.basename(filename)[:-4]
168 slug = slugify(title)
169 if not (slug and filename.endswith('.xml')):
170 skipped_list.append(filename)
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.')))
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
184 for filename, slug, title in ok_list:
186 text=zip.read(filename).decode('utf-8'),
192 return render(request, "catalogue/document_upload.html", {
195 "skipped_list": skipped_list,
196 "error_list": error_list,
201 form = forms.DocumentsUploadForm()
203 return render(request, "catalogue/document_upload.html", {
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
220 def book_xml(request, slug):
221 book = get_object_or_404(Book, slug=slug)
222 return serve_xml(request, book, slug)
226 def book_xml_dc(request, slug):
227 book = get_object_or_404(Book, dc_slug=slug)
228 return serve_xml(request, book, slug)
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.")
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
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.")
250 doc = book.wldocument(parse_dublincore=False)
251 html = doc.as_html(options={'gallery': "'%s'" % book.gallery_url()})
253 html = html.get_string() if html is not None else ''
254 # response = http.HttpResponse(html, content_type='text/html')
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)
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())
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.")
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')
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.")
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'
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.")
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'
314 def revision(request, slug, chunk=None):
316 doc = Chunk.get(slug, chunk)
317 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
319 if not doc.book.accessible(request):
320 return HttpResponseForbidden("Not authorized.")
321 return http.HttpResponse(str(doc.revision()))
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.")
329 if request.user.has_perm('catalogue.change_book'):
330 if request.method == "POST":
331 form = forms.BookForm(request.POST, instance=book)
334 return http.HttpResponseRedirect(book.get_absolute_url())
336 form = forms.BookForm(instance=book)
337 publish_options_form = forms.PublishOptionsForm()
340 form = forms.ReadonlyBookForm(instance=book)
341 publish_options_form = forms.PublishOptionsForm()
344 publish_error = book.publishable_error()
345 publishable = publish_error is None
347 return render(request, "catalogue/book_detail.html", {
349 "publishable": publishable,
350 "publishable_error": publish_error,
352 "publish_options_form": publish_options_form,
353 "editable": editable,
357 def image(request, slug):
358 image = get_object_or_404(Image, slug=slug)
359 if not image.accessible(request):
360 return HttpResponseForbidden("Not authorized.")
362 if request.user.has_perm('catalogue.change_image'):
363 if request.method == "POST":
364 form = forms.ImageForm(request.POST, instance=image)
367 return http.HttpResponseRedirect(image.get_absolute_url())
369 form = forms.ImageForm(instance=image)
372 form = forms.ReadonlyImageForm(instance=image)
375 publish_error = image.publishable_error()
376 publishable = publish_error is None
378 return render(request, "catalogue/image_detail.html", {
380 "publishable": publishable,
381 "publishable_error": publish_error,
383 "editable": editable,
387 @permission_required('catalogue.add_chunk')
388 def chunk_add(request, slug, chunk):
390 doc = Chunk.get(slug, chunk)
391 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
393 if not doc.book.accessible(request):
394 return HttpResponseForbidden("Not authorized.")
396 if request.method == "POST":
397 form = forms.ChunkAddForm(request.POST, instance=doc)
399 if request.user.is_authenticated():
400 creator = request.user
403 doc.split(creator=creator,
404 slug=form.cleaned_data['slug'],
405 title=form.cleaned_data['title'],
406 gallery_start=form.cleaned_data['gallery_start'],
407 user=form.cleaned_data['user'],
408 stage=form.cleaned_data['stage']
411 return http.HttpResponseRedirect(doc.book.get_absolute_url())
413 form = forms.ChunkAddForm(initial={
414 "slug": str(doc.number + 1),
415 "title": "cz. %d" % (doc.number + 1, ),
418 return render(request, "catalogue/chunk_add.html", {
425 def chunk_edit(request, slug, chunk):
427 doc = Chunk.get(slug, chunk)
428 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
430 if not doc.book.accessible(request):
431 return HttpResponseForbidden("Not authorized.")
433 if request.method == "POST":
434 form = forms.ChunkForm(request.POST, instance=doc)
437 go_next = request.GET.get('next', None)
439 go_next = urlquote_plus(unquote(iri_to_uri(go_next)), safe='/?=&')
441 go_next = doc.book.get_absolute_url()
442 return http.HttpResponseRedirect(go_next)
444 form = forms.ChunkForm(instance=doc)
446 referer = request.META.get('HTTP_REFERER')
448 parts = urlsplit(referer)
449 parts = ['', ''] + list(parts[2:])
450 go_next = urlquote_plus(urlunsplit(parts))
454 return render(request, "catalogue/chunk_edit.html", {
464 def chunk_mass_edit(request):
465 ids = map(int, filter(lambda i: i.strip()!='', request.POST.get('ids').split(',')))
466 chunks = map(lambda i: Chunk.objects.get(id=i), ids)
468 stage = request.POST.get('stage')
471 stage = Chunk.tag_model.objects.get(slug=stage)
472 except Chunk.DoesNotExist, e:
475 for c in chunks: c.stage = stage
477 username = request.POST.get('user')
478 logger.info("username: %s" % username)
479 logger.info(request.POST)
482 user = User.objects.get(username=username)
483 except User.DoesNotExist, e:
486 for c in chunks: c.user = user
488 project_id = request.POST.get('project')
491 project = Project.objects.get(pk=int(project_id))
492 except (Project.DoesNotExist, ValueError), e:
496 book.project = project
499 for c in chunks: c.save()
501 return HttpResponse("", content_type="text/plain")
507 def image_mass_edit(request):
508 ids = map(int, filter(lambda i: i.strip()!='', request.POST.get('ids').split(',')))
509 images = map(lambda i: Image.objects.get(id=i), ids)
511 stage = request.POST.get('stage')
514 stage = Image.tag_model.objects.get(slug=stage)
515 except Image.DoesNotExist, e:
518 for c in images: c.stage = stage
520 username = request.POST.get('user')
521 logger.info("username: %s" % username)
522 logger.info(request.POST)
525 user = User.objects.get(username=username)
526 except User.DoesNotExist, e:
529 for c in images: c.user = user
531 project_id = request.POST.get('project')
534 project = Project.objects.get(pk=int(project_id))
535 except (Project.DoesNotExist, ValueError), e:
540 for c in images: c.save()
542 return HttpResponse("", content_type="text/plain")
545 @permission_required('catalogue.change_book')
546 def book_append(request, slug):
547 book = get_object_or_404(Book, slug=slug)
548 if not book.accessible(request):
549 return HttpResponseForbidden("Not authorized.")
551 if request.method == "POST":
552 form = forms.BookAppendForm(book, request.POST)
554 append_to = form.cleaned_data['append_to']
555 append_to.append(book)
556 return http.HttpResponseRedirect(append_to.get_absolute_url())
558 form = forms.BookAppendForm(book)
559 return render(request, "catalogue/book_append_to.html", {
569 def publish(request, slug):
570 form = forms.PublishOptionsForm(request.POST)
572 days = form.cleaned_data['days']
573 beta = form.cleaned_data['beta']
577 book = get_object_or_404(Book, slug=slug)
578 if not book.accessible(request):
579 return HttpResponseForbidden("Not authorized.")
582 protocol = 'https://' if request.is_secure() else 'http://'
583 book.publish(request.user, host=protocol + request.get_host(), days=days, beta=beta)
584 except NotAuthorizedError:
585 return http.HttpResponseRedirect(reverse('apiclient_oauth' if not beta else 'apiclient_beta_oauth'))
586 except BaseException, e:
587 return http.HttpResponse(repr(e))
589 return http.HttpResponseRedirect(book.get_absolute_url())
594 def publish_image(request, slug):
595 image = get_object_or_404(Image, slug=slug)
596 if not image.accessible(request):
597 return HttpResponseForbidden("Not authorized.")
600 image.publish(request.user)
601 except NotAuthorizedError:
602 return http.HttpResponseRedirect(reverse('apiclient_oauth'))
603 except BaseException, e:
604 return http.HttpResponse(e)
606 return http.HttpResponseRedirect(image.get_absolute_url())
609 class GalleryView(UploadView):
610 def get_object(self, request, slug):
611 book = get_object_or_404(Book, slug=slug)
616 def breadcrumbs(self):
618 (_('books'), reverse('catalogue_document_list')),
619 (self.object.title, self.object.get_absolute_url()),
620 (_('scan gallery'),),
623 def get_directory(self):
624 return "%s%s/" % (settings.IMAGE_DIR, self.object.gallery)
627 def active_users_list(request):
628 since = date(date.today().year, 1, 1)
629 by_user = defaultdict(lambda: 0)
630 by_email = defaultdict(lambda: 0)
631 names_by_email = defaultdict(set)
632 for change_model in (Chunk.change_model, Image.change_model):
633 for c in change_model.objects.filter(
634 created_at__gte=since).order_by(
635 'author', 'author_email', 'author_name').values(
636 'author', 'author_name', 'author_email').annotate(
637 c=Count('author'), ce=Count('author_email')).distinct():
639 by_user[c['author']] += c['c']
641 by_email[c['author_email']] += c['ce']
642 if c['author_name'].strip():
643 names_by_email[c['author_email']].add(c['author_name'])
644 for user in User.objects.filter(pk__in=by_user):
645 by_email[user.email] += by_user[user.pk]
646 names_by_email[user.email].add("%s %s" % (user.first_name, user.last_name))
649 for email, count in by_email.items():
650 active_users.append((email, names_by_email[email], count))
651 active_users.sort(key=lambda x: -x[2])
652 return render(request, 'catalogue/active_users_list.html', {
653 'users': active_users,
658 @user_passes_test(lambda u: u.is_superuser)
659 def mark_final(request):
660 if request.method == 'POST':
661 form = forms.MarkFinalForm(data=request.POST)
664 return HttpResponseRedirect(reverse('mark_final_completed'))
666 form = forms.MarkFinalForm()
667 return render(request, 'catalogue/mark_final.html', {'form': form})
670 def mark_final_completed(request):
671 return render(request, 'catalogue/mark_final_completed.html')