localsettings are no longer main settings
[redakcja.git] / apps / catalogue / views.py
1 from datetime import datetime, date, timedelta
2 import logging
3 import os
4 from StringIO import StringIO
5 from urllib import unquote
6 from urlparse import urlsplit, urlunsplit
7
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.shortcuts import get_object_or_404, render
18 from django.utils.encoding import iri_to_uri
19 from django.utils.http import urlquote_plus
20 from django.utils.translation import ugettext_lazy as _
21 from django.views.decorators.http import require_POST
22
23 from apiclient import NotAuthorizedError
24 from catalogue import forms
25 from catalogue import helpers
26 from catalogue.helpers import active_tab
27 from catalogue.models import (Book, Chunk, Image, BookPublishRecord, 
28         ChunkPublishRecord, ImagePublishRecord, Project)
29 from fileupload.views import UploadView
30
31 #
32 # Quick hack around caching problems, TODO: use ETags
33 #
34 from django.views.decorators.cache import never_cache
35
36 logger = logging.getLogger("fnp.catalogue")
37
38
39 @active_tab('all')
40 @never_cache
41 def document_list(request):
42     return render(request, 'catalogue/document_list.html')
43
44
45 @active_tab('images')
46 @never_cache
47 def image_list(request, user=None):
48     return render(request, 'catalogue/image_list.html')
49
50
51 @never_cache
52 def user(request, username):
53     user = get_object_or_404(User, username=username)
54     return render(request, 'catalogue/user_page.html', {"viewed_user": user})
55
56
57 @login_required
58 @active_tab('my')
59 @never_cache
60 def my(request):
61     last_books = sorted(request.session.get("wiki_last_books", {}).items(),
62         key=lambda x: x[1]['time'], reverse=True)
63     for k, v in last_books:
64         v['time'] = datetime.fromtimestamp(v['time'])
65     return render(request, 'catalogue/my_page.html', {
66         'last_books': last_books,
67         "logout_to": '/',
68         })
69
70
71 @active_tab('users')
72 def users(request):
73     return render(request, 'catalogue/user_list.html', {
74         'users': User.objects.all().annotate(count=Count('chunk')).order_by(
75             '-count', 'last_name', 'first_name'),
76     })
77
78
79 @active_tab('activity')
80 def activity(request, isodate=None):
81     today = date.today()
82     try:
83         day = helpers.parse_isodate(isodate)
84     except ValueError:
85         day = today
86
87     if day > today:
88         raise Http404
89     if day != today:
90         next_day = day + timedelta(1)
91     prev_day = day - timedelta(1)
92
93     return render(request, 'catalogue/activity.html', locals())
94
95
96 @never_cache
97 def logout_then_redirect(request):
98     auth.logout(request)
99     return http.HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
100
101
102 @permission_required('catalogue.add_book')
103 @active_tab('create')
104 def create_missing(request, slug=None):
105     if slug is None:
106         slug = ''
107     slug = slug.replace(' ', '-')
108
109     if request.method == "POST":
110         form = forms.DocumentCreateForm(request.POST, request.FILES)
111         if form.is_valid():
112             
113             if request.user.is_authenticated():
114                 creator = request.user
115             else:
116                 creator = None
117             book = Book.create(
118                 text=form.cleaned_data['text'],
119                 creator=creator,
120                 slug=form.cleaned_data['slug'],
121                 title=form.cleaned_data['title'],
122                 gallery=form.cleaned_data['gallery'],
123             )
124
125             return http.HttpResponseRedirect(reverse("catalogue_book", args=[book.slug]))
126     else:
127         form = forms.DocumentCreateForm(initial={
128                 "slug": slug,
129                 "title": slug.replace('-', ' ').title(),
130                 "gallery": slug,
131         })
132
133     return render(request, "catalogue/document_create_missing.html", {
134         "slug": slug,
135         "form": form,
136
137         "logout_to": '/',
138     })
139
140
141 @permission_required('catalogue.add_book')
142 @active_tab('upload')
143 def upload(request):
144     if request.method == "POST":
145         form = forms.DocumentsUploadForm(request.POST, request.FILES)
146         if form.is_valid():
147             from slugify import slugify
148
149             if request.user.is_authenticated():
150                 creator = request.user
151             else:
152                 creator = None
153
154             zip = form.cleaned_data['zip']
155             skipped_list = []
156             ok_list = []
157             error_list = []
158             slugs = {}
159             existing = [book.slug for book in Book.objects.all()]
160             for filename in zip.namelist():
161                 if filename[-1] == '/':
162                     continue
163                 title = os.path.basename(filename)[:-4]
164                 slug = slugify(title)
165                 if not (slug and filename.endswith('.xml')):
166                     skipped_list.append(filename)
167                 elif slug in slugs:
168                     error_list.append((filename, slug, _('Slug already used for %s' % slugs[slug])))
169                 elif slug in existing:
170                     error_list.append((filename, slug, _('Slug already used in repository.')))
171                 else:
172                     try:
173                         zip.read(filename).decode('utf-8') # test read
174                         ok_list.append((filename, slug, title))
175                     except UnicodeDecodeError:
176                         error_list.append((filename, title, _('File should be UTF-8 encoded.')))
177                     slugs[slug] = filename
178
179             if not error_list:
180                 for filename, slug, title in ok_list:
181                     book = Book.create(
182                         text=zip.read(filename).decode('utf-8'),
183                         creator=creator,
184                         slug=slug,
185                         title=title,
186                     )
187
188             return render(request, "catalogue/document_upload.html", {
189                 "form": form,
190                 "ok_list": ok_list,
191                 "skipped_list": skipped_list,
192                 "error_list": error_list,
193
194                 "logout_to": '/',
195             })
196     else:
197         form = forms.DocumentsUploadForm()
198
199     return render(request, "catalogue/document_upload.html", {
200         "form": form,
201
202         "logout_to": '/',
203     })
204
205
206 @never_cache
207 def book_xml(request, slug):
208     book = get_object_or_404(Book, slug=slug)
209     if not book.accessible(request):
210         return HttpResponseForbidden("Not authorized.")
211     xml = book.materialize()
212
213     response = http.HttpResponse(xml, content_type='application/xml')
214     response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
215     return response
216
217
218 @never_cache
219 def book_txt(request, slug):
220     book = get_object_or_404(Book, slug=slug)
221     if not book.accessible(request):
222         return HttpResponseForbidden("Not authorized.")
223
224     doc = book.wldocument()
225     text = doc.as_text().get_string()
226     response = http.HttpResponse(text, content_type='text/plain')
227     response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
228     return response
229
230
231 @never_cache
232 def book_html(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(parse_dublincore=False)
238     html = doc.as_html()
239
240     html = html.get_string() if html is not None else ''
241     # response = http.HttpResponse(html, content_type='text/html')
242     # return response
243     # book_themes = {}
244     # for fragment in book.fragments.all().iterator():
245     #     for theme in fragment.tags.filter(category='theme').iterator():
246     #         book_themes.setdefault(theme, []).append(fragment)
247
248     # book_themes = book_themes.items()
249     # book_themes.sort(key=lambda s: s[0].sort_key)
250     return render(request, 'catalogue/book_text.html', locals())
251
252
253 @never_cache
254 def book_pdf(request, slug):
255     book = get_object_or_404(Book, slug=slug)
256     if not book.accessible(request):
257         return HttpResponseForbidden("Not authorized.")
258
259     # TODO: move to celery
260     doc = book.wldocument()
261     # TODO: error handling
262     pdf_file = doc.as_pdf()
263     from catalogue.ebook_utils import serve_file
264     return serve_file(pdf_file.get_filename(),
265                 book.slug + '.pdf', 'application/pdf')
266
267
268 @never_cache
269 def book_epub(request, slug):
270     book = get_object_or_404(Book, slug=slug)
271     if not book.accessible(request):
272         return HttpResponseForbidden("Not authorized.")
273
274     # TODO: move to celery
275     doc = book.wldocument()
276     # TODO: error handling
277     epub = doc.as_epub().get_string()
278     response = HttpResponse(content_type='application/epub+zip')
279     response['Content-Disposition'] = 'attachment; filename=%s' % book.slug + '.epub'
280     response.write(epub)
281     return response
282
283
284 @never_cache
285 def revision(request, slug, chunk=None):
286     try:
287         doc = Chunk.get(slug, chunk)
288     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
289         raise Http404
290     if not doc.book.accessible(request):
291         return HttpResponseForbidden("Not authorized.")
292     return http.HttpResponse(str(doc.revision()))
293
294
295 def book(request, slug):
296     book = get_object_or_404(Book, slug=slug)
297     if not book.accessible(request):
298         return HttpResponseForbidden("Not authorized.")
299
300     if request.user.has_perm('catalogue.change_book'):
301         if request.method == "POST":
302             form = forms.BookForm(request.POST, instance=book)
303             if form.is_valid():
304                 form.save()
305                 return http.HttpResponseRedirect(book.get_absolute_url())
306         else:
307             form = forms.BookForm(instance=book)
308         editable = True
309     else:
310         form = forms.ReadonlyBookForm(instance=book)
311         editable = False
312
313     publish_error = book.publishable_error()
314     publishable = publish_error is None
315
316     return render(request, "catalogue/book_detail.html", {
317         "book": book,
318         "publishable": publishable,
319         "publishable_error": publish_error,
320         "form": form,
321         "editable": editable,
322     })
323
324
325 def image(request, slug):
326     image = get_object_or_404(Image, slug=slug)
327     if not image.accessible(request):
328         return HttpResponseForbidden("Not authorized.")
329
330     if request.user.has_perm('catalogue.change_image'):
331         if request.method == "POST":
332             form = forms.ImageForm(request.POST, instance=image)
333             if form.is_valid():
334                 form.save()
335                 return http.HttpResponseRedirect(image.get_absolute_url())
336         else:
337             form = forms.ImageForm(instance=image)
338         editable = True
339     else:
340         form = forms.ReadonlyImageForm(instance=image)
341         editable = False
342
343     publish_error = image.publishable_error()
344     publishable = publish_error is None
345
346     return render(request, "catalogue/image_detail.html", {
347         "object": image,
348         "publishable": publishable,
349         "publishable_error": publish_error,
350         "form": form,
351         "editable": editable,
352     })
353
354
355 @permission_required('catalogue.add_chunk')
356 def chunk_add(request, slug, chunk):
357     try:
358         doc = Chunk.get(slug, chunk)
359     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
360         raise Http404
361     if not doc.book.accessible(request):
362         return HttpResponseForbidden("Not authorized.")
363
364     if request.method == "POST":
365         form = forms.ChunkAddForm(request.POST, instance=doc)
366         if form.is_valid():
367             if request.user.is_authenticated():
368                 creator = request.user
369             else:
370                 creator = None
371             doc.split(creator=creator,
372                 slug=form.cleaned_data['slug'],
373                 title=form.cleaned_data['title'],
374                 gallery_start=form.cleaned_data['gallery_start'],
375                 user=form.cleaned_data['user'],
376                 stage=form.cleaned_data['stage']
377             )
378
379             return http.HttpResponseRedirect(doc.book.get_absolute_url())
380     else:
381         form = forms.ChunkAddForm(initial={
382                 "slug": str(doc.number + 1),
383                 "title": "cz. %d" % (doc.number + 1, ),
384         })
385
386     return render(request, "catalogue/chunk_add.html", {
387         "chunk": doc,
388         "form": form,
389     })
390
391
392 @login_required
393 def chunk_edit(request, slug, chunk):
394     try:
395         doc = Chunk.get(slug, chunk)
396     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
397         raise Http404
398     if not doc.book.accessible(request):
399         return HttpResponseForbidden("Not authorized.")
400
401     if request.method == "POST":
402         form = forms.ChunkForm(request.POST, instance=doc)
403         if form.is_valid():
404             form.save()
405             go_next = request.GET.get('next', None)
406             if go_next:
407                 go_next = urlquote_plus(unquote(iri_to_uri(go_next)), safe='/?=&')
408             else:
409                 go_next = doc.book.get_absolute_url()
410             return http.HttpResponseRedirect(go_next)
411     else:
412         form = forms.ChunkForm(instance=doc)
413
414     referer = request.META.get('HTTP_REFERER')
415     if referer:
416         parts = urlsplit(referer)
417         parts = ['', ''] + list(parts[2:])
418         go_next = urlquote_plus(urlunsplit(parts))
419     else:
420         go_next = ''
421
422     return render(request, "catalogue/chunk_edit.html", {
423         "chunk": doc,
424         "form": form,
425         "go_next": go_next,
426     })
427
428
429 @transaction.atomic
430 @login_required
431 @require_POST
432 def chunk_mass_edit(request):
433     ids = map(int, filter(lambda i: i.strip()!='', request.POST.get('ids').split(',')))
434     chunks = map(lambda i: Chunk.objects.get(id=i), ids)
435     
436     stage = request.POST.get('stage')
437     if stage:
438         try:
439             stage = Chunk.tag_model.objects.get(slug=stage)
440         except Chunk.DoesNotExist, e:
441             stage = None
442        
443         for c in chunks: c.stage = stage
444
445     username = request.POST.get('user')
446     logger.info("username: %s" % username)
447     logger.info(request.POST)
448     if username:
449         try:
450             user = User.objects.get(username=username)
451         except User.DoesNotExist, e:
452             user = None
453             
454         for c in chunks: c.user = user
455
456     project_id = request.POST.get('project')
457     if project_id:
458         try:
459             project = Project.objects.get(pk=int(project_id))
460         except (Project.DoesNotExist, ValueError), e:
461             project = None
462         for c in chunks:
463             book = c.book
464             book.project = project
465             book.save()
466
467     for c in chunks: c.save()
468
469     return HttpResponse("", content_type="text/plain")
470
471
472 @transaction.atomic
473 @login_required
474 @require_POST
475 def image_mass_edit(request):
476     ids = map(int, filter(lambda i: i.strip()!='', request.POST.get('ids').split(',')))
477     images = map(lambda i: Image.objects.get(id=i), ids)
478     
479     stage = request.POST.get('stage')
480     if stage:
481         try:
482             stage = Image.tag_model.objects.get(slug=stage)
483         except Image.DoesNotExist, e:
484             stage = None
485        
486         for c in images: c.stage = stage
487
488     username = request.POST.get('user')
489     logger.info("username: %s" % username)
490     logger.info(request.POST)
491     if username:
492         try:
493             user = User.objects.get(username=username)
494         except User.DoesNotExist, e:
495             user = None
496             
497         for c in images: c.user = user
498
499     project_id = request.POST.get('project')
500     if project_id:
501         try:
502             project = Project.objects.get(pk=int(project_id))
503         except (Project.DoesNotExist, ValueError), e:
504             project = None
505         for c in images:
506             c.project = project
507
508     for c in images: c.save()
509
510     return HttpResponse("", content_type="text/plain")
511
512
513 @permission_required('catalogue.change_book')
514 def book_append(request, slug):
515     book = get_object_or_404(Book, slug=slug)
516     if not book.accessible(request):
517         return HttpResponseForbidden("Not authorized.")
518
519     if request.method == "POST":
520         form = forms.BookAppendForm(book, request.POST)
521         if form.is_valid():
522             append_to = form.cleaned_data['append_to']
523             append_to.append(book)
524             return http.HttpResponseRedirect(append_to.get_absolute_url())
525     else:
526         form = forms.BookAppendForm(book)
527     return render(request, "catalogue/book_append_to.html", {
528         "book": book,
529         "form": form,
530
531         "logout_to": '/',
532     })
533
534
535 @require_POST
536 @login_required
537 def publish(request, slug):
538     book = get_object_or_404(Book, slug=slug)
539     if not book.accessible(request):
540         return HttpResponseForbidden("Not authorized.")
541
542     try:
543         book.publish(request.user)
544     except NotAuthorizedError:
545         return http.HttpResponseRedirect(reverse('apiclient_oauth'))
546     except BaseException, e:
547         return http.HttpResponse(e)
548     else:
549         return http.HttpResponseRedirect(book.get_absolute_url())
550
551
552 @require_POST
553 @login_required
554 def publish_image(request, slug):
555     image = get_object_or_404(Image, slug=slug)
556     if not image.accessible(request):
557         return HttpResponseForbidden("Not authorized.")
558
559     try:
560         image.publish(request.user)
561     except NotAuthorizedError:
562         return http.HttpResponseRedirect(reverse('apiclient_oauth'))
563     except BaseException, e:
564         return http.HttpResponse(e)
565     else:
566         return http.HttpResponseRedirect(image.get_absolute_url())
567
568
569 class GalleryView(UploadView):
570     def get_object(self, request, slug):
571         book = get_object_or_404(Book, slug=slug)
572         if not book.gallery:
573             raise Http404
574         return book
575
576     def breadcrumbs(self):
577         return [
578             (_('books'), reverse('catalogue_document_list')),
579             (self.object.title, self.object.get_absolute_url()),
580             (_('scan gallery'),),
581         ]
582
583     def get_directory(self):
584         return "%s%s/" % (settings.IMAGE_DIR, self.object.gallery)