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