74036f0dbe95049a3bed596beef1ca1c5282cbe0
[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.contrib import auth
9 from django.contrib.auth.models import User
10 from django.contrib.auth.decorators import login_required, permission_required
11 from django.core.urlresolvers import reverse
12 from django.db.models import Count, Q
13 from django.db import transaction
14 from django import http
15 from django.http import Http404, HttpResponse, HttpResponseForbidden
16 from django.shortcuts import get_object_or_404, render, render_to_response
17 from django.utils.encoding import iri_to_uri
18 from django.utils.http import urlquote_plus
19 from django.utils.translation import ugettext_lazy as _
20 from django.views.decorators.http import require_POST
21 from django.views.generic.simple import direct_to_template
22 from django.template import RequestContext
23
24 from apiclient import NotAuthorizedError
25 from catalogue import forms
26 from catalogue import helpers
27 from catalogue.helpers import active_tab
28 from catalogue.models import Book, Chunk, BookPublishRecord, ChunkPublishRecord
29
30 #
31 # Quick hack around caching problems, TODO: use ETags
32 #
33 from django.views.decorators.cache import never_cache
34
35 logger = logging.getLogger("fnp.catalogue")
36
37
38 @active_tab('all')
39 @never_cache
40 def document_list(request):
41     return render(request, 'catalogue/document_list.html')
42
43
44 @never_cache
45 def user(request, username):
46     user = get_object_or_404(User, username=username)
47     return render(request, 'catalogue/user_page.html', {"viewed_user": user})
48
49
50 @login_required
51 @active_tab('my')
52 @never_cache
53 def my(request):
54     return render(request, 'catalogue/my_page.html', {
55         'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
56                         key=lambda x: x[1]['time'], reverse=True),
57
58         "logout_to": '/',
59         })
60
61
62 @active_tab('users')
63 def users(request):
64     return direct_to_template(request, 'catalogue/user_list.html', extra_context={
65         'users': User.objects.all().annotate(count=Count('chunk')).order_by(
66             '-count', 'last_name', 'first_name'),
67     })
68
69
70 @active_tab('activity')
71 def activity(request, isodate=None):
72     today = date.today()
73     try:
74         day = helpers.parse_isodate(isodate)
75     except ValueError:
76         day = today
77
78     if day > today:
79         raise Http404
80     if day != today:
81         next_day = day + timedelta(1)
82     prev_day = day - timedelta(1)
83
84     return render(request, 'catalogue/activity.html', locals())
85
86
87 @never_cache
88 def logout_then_redirect(request):
89     auth.logout(request)
90     return http.HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
91
92
93 @permission_required('catalogue.add_book')
94 @active_tab('create')
95 def create_missing(request, slug=None):
96     if slug is None:
97         slug = ''
98     slug = slug.replace(' ', '-')
99
100     if request.method == "POST":
101         form = forms.DocumentCreateForm(request.POST, request.FILES)
102         if form.is_valid():
103             
104             if request.user.is_authenticated():
105                 creator = request.user
106             else:
107                 creator = None
108             book = Book.create(
109                 text=form.cleaned_data['text'],
110                 creator=creator,
111                 slug=form.cleaned_data['slug'],
112                 title=form.cleaned_data['title'],
113                 gallery=form.cleaned_data['gallery'],
114             )
115
116             return http.HttpResponseRedirect(reverse("catalogue_book", args=[book.slug]))
117     else:
118         form = forms.DocumentCreateForm(initial={
119                 "slug": slug,
120                 "title": slug.replace('-', ' ').title(),
121                 "gallery": slug,
122         })
123
124     return direct_to_template(request, "catalogue/document_create_missing.html", extra_context={
125         "slug": slug,
126         "form": form,
127
128         "logout_to": '/',
129     })
130
131
132 @permission_required('catalogue.add_book')
133 @active_tab('upload')
134 def upload(request):
135     if request.method == "POST":
136         form = forms.DocumentsUploadForm(request.POST, request.FILES)
137         if form.is_valid():
138             import slughifi
139
140             if request.user.is_authenticated():
141                 creator = request.user
142             else:
143                 creator = None
144
145             zip = form.cleaned_data['zip']
146             skipped_list = []
147             ok_list = []
148             error_list = []
149             slugs = {}
150             existing = [book.slug for book in Book.objects.all()]
151             for filename in zip.namelist():
152                 if filename[-1] == '/':
153                     continue
154                 title = os.path.basename(filename)[:-4]
155                 slug = slughifi(title)
156                 if not (slug and filename.endswith('.xml')):
157                     skipped_list.append(filename)
158                 elif slug in slugs:
159                     error_list.append((filename, slug, _('Slug already used for %s' % slugs[slug])))
160                 elif slug in existing:
161                     error_list.append((filename, slug, _('Slug already used in repository.')))
162                 else:
163                     try:
164                         zip.read(filename).decode('utf-8') # test read
165                         ok_list.append((filename, slug, title))
166                     except UnicodeDecodeError:
167                         error_list.append((filename, title, _('File should be UTF-8 encoded.')))
168                     slugs[slug] = filename
169
170             if not error_list:
171                 for filename, slug, title in ok_list:
172                     book = Book.create(
173                         text=zip.read(filename).decode('utf-8'),
174                         creator=creator,
175                         slug=slug,
176                         title=title,
177                     )
178
179             return direct_to_template(request, "catalogue/document_upload.html", extra_context={
180                 "form": form,
181                 "ok_list": ok_list,
182                 "skipped_list": skipped_list,
183                 "error_list": error_list,
184
185                 "logout_to": '/',
186             })
187     else:
188         form = forms.DocumentsUploadForm()
189
190     return direct_to_template(request, "catalogue/document_upload.html", extra_context={
191         "form": form,
192
193         "logout_to": '/',
194     })
195
196
197 @never_cache
198 def book_xml(request, slug):
199     book = get_object_or_404(Book, slug=slug)
200     if not book.accessible(request):
201         return HttpResponseForbidden("Not authorized.")
202     xml = book.materialize()
203
204     response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
205     response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
206     return response
207
208
209 @never_cache
210 def book_txt(request, slug):
211     book = get_object_or_404(Book, slug=slug)
212     if not book.accessible(request):
213         return HttpResponseForbidden("Not authorized.")
214
215     doc = book.wldocument()
216     text = doc.as_text().get_string()
217     response = http.HttpResponse(text, content_type='text/plain', mimetype='text/plain')
218     response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
219     return response
220
221
222 @never_cache
223 def book_html(request, slug):
224     book = get_object_or_404(Book, slug=slug)
225     if not book.accessible(request):
226         return HttpResponseForbidden("Not authorized.")
227
228     doc = book.wldocument(parse_dublincore=False)
229     html = doc.as_html()
230
231     html = html.get_string() if html is not None else ''
232     # response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
233     # return response
234     # book_themes = {}
235     # for fragment in book.fragments.all().iterator():
236     #     for theme in fragment.tags.filter(category='theme').iterator():
237     #         book_themes.setdefault(theme, []).append(fragment)
238
239     # book_themes = book_themes.items()
240     # book_themes.sort(key=lambda s: s[0].sort_key)
241     return render_to_response('catalogue/book_text.html', locals(),
242         context_instance=RequestContext(request))
243
244
245 @never_cache
246 def book_pdf(request, slug):
247     book = get_object_or_404(Book, slug=slug)
248     if not book.accessible(request):
249         return HttpResponseForbidden("Not authorized.")
250
251     # TODO: move to celery
252     doc = book.wldocument()
253     # TODO: error handling
254     pdf_file = doc.as_pdf()
255     from catalogue.ebook_utils import serve_file
256     return serve_file(pdf_file.get_filename(),
257                 book.slug + '.pdf', 'application/pdf')
258
259
260 @never_cache
261 def book_epub(request, slug):
262     book = get_object_or_404(Book, slug=slug)
263     if not book.accessible(request):
264         return HttpResponseForbidden("Not authorized.")
265
266     # TODO: move to celery
267     doc = book.wldocument()
268     # TODO: error handling
269     epub = doc.as_epub().get_string()
270     response = HttpResponse(mimetype='application/epub+zip')
271     response['Content-Disposition'] = 'attachment; filename=%s' % book.slug + '.epub'
272     response.write(epub)
273     return response
274
275
276 @never_cache
277 def revision(request, slug, chunk=None):
278     try:
279         doc = Chunk.get(slug, chunk)
280     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
281         raise Http404
282     if not doc.book.accessible(request):
283         return HttpResponseForbidden("Not authorized.")
284     return http.HttpResponse(str(doc.revision()))
285
286
287 def book(request, slug):
288     book = get_object_or_404(Book, slug=slug)
289     if not book.accessible(request):
290         return HttpResponseForbidden("Not authorized.")
291
292     if request.user.has_perm('catalogue.change_book'):
293         if request.method == "POST":
294             form = forms.BookForm(request.POST, instance=book)
295             if form.is_valid():
296                 form.save()
297                 return http.HttpResponseRedirect(book.get_absolute_url())
298         else:
299             form = forms.BookForm(instance=book)
300         editable = True
301     else:
302         form = forms.ReadonlyBookForm(instance=book)
303         editable = False
304
305     publish_error = book.publishable_error()
306     publishable = publish_error is None
307
308     return direct_to_template(request, "catalogue/book_detail.html", extra_context={
309         "book": book,
310         "publishable": publishable,
311         "publishable_error": publish_error,
312         "form": form,
313         "editable": editable,
314     })
315
316
317 @permission_required('catalogue.add_chunk')
318 def chunk_add(request, slug, chunk):
319     try:
320         doc = Chunk.get(slug, chunk)
321     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
322         raise Http404
323     if not doc.book.accessible(request):
324         return HttpResponseForbidden("Not authorized.")
325
326     if request.method == "POST":
327         form = forms.ChunkAddForm(request.POST, instance=doc)
328         if form.is_valid():
329             if request.user.is_authenticated():
330                 creator = request.user
331             else:
332                 creator = None
333             doc.split(creator=creator,
334                 slug=form.cleaned_data['slug'],
335                 title=form.cleaned_data['title'],
336                 gallery_start=form.cleaned_data['gallery_start'],
337                 user=form.cleaned_data['user'],
338                 stage=form.cleaned_data['stage']
339             )
340
341             return http.HttpResponseRedirect(doc.book.get_absolute_url())
342     else:
343         form = forms.ChunkAddForm(initial={
344                 "slug": str(doc.number + 1),
345                 "title": "cz. %d" % (doc.number + 1, ),
346         })
347
348     return direct_to_template(request, "catalogue/chunk_add.html", extra_context={
349         "chunk": doc,
350         "form": form,
351     })
352
353
354 def chunk_edit(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.ChunkForm(request.POST, instance=doc)
364         if form.is_valid():
365             form.save()
366             go_next = request.GET.get('next', None)
367             if go_next:
368                 go_next = urlquote_plus(unquote(iri_to_uri(go_next)), safe='/?=&')
369             else:
370                 go_next = doc.book.get_absolute_url()
371             return http.HttpResponseRedirect(go_next)
372     else:
373         form = forms.ChunkForm(instance=doc)
374
375     referer = request.META.get('HTTP_REFERER')
376     if referer:
377         parts = urlsplit(referer)
378         parts = ['', ''] + list(parts[2:])
379         go_next = urlquote_plus(urlunsplit(parts))
380     else:
381         go_next = ''
382
383     return direct_to_template(request, "catalogue/chunk_edit.html", extra_context={
384         "chunk": doc,
385         "form": form,
386         "go_next": go_next,
387     })
388
389
390 @transaction.commit_on_success
391 def chunk_mass_edit(request):
392     if request.method == 'POST':
393         ids = map(int, filter(lambda i: i.strip()!='', request.POST.get('ids').split(',')))
394         chunks = map(lambda i: Chunk.objects.get(id=i), ids)
395         
396         stage = request.POST.get('stage')
397         if stage:
398             try:
399                 stage = Chunk.tag_model.objects.get(slug=stage)
400             except Chunk.DoesNotExist, e:
401                 stage = None
402            
403             for c in chunks: c.stage = stage
404
405         username = request.POST.get('user')
406         logger.info("username: %s" % username)
407         logger.info(request.POST)
408         if username:
409             try:
410                 user = User.objects.get(username=username)
411             except User.DoesNotExist, e:
412                 user = None
413                 
414             for c in chunks: c.user = user
415
416         status = request.POST.get('status')
417         if status:
418             books_affected = set()
419             for c in chunks:
420                 if status == 'publish':
421                     c.head.publishable = True
422                     c.head.save()
423                 elif status == 'unpublish':
424                     c.head.publishable = False
425                     c.head.save()
426                 c.touch()  # cache
427                 books_affected.add(c.book)
428             for b in books_affected:
429                 b.touch()  # cache
430
431         for c in chunks: c.save()
432
433         return HttpResponse("", content_type="text/plain")
434     else:
435         raise Http404
436
437
438 @permission_required('catalogue.change_book')
439 def book_append(request, slug):
440     book = get_object_or_404(Book, slug=slug)
441     if not book.accessible(request):
442         return HttpResponseForbidden("Not authorized.")
443
444     if request.method == "POST":
445         form = forms.BookAppendForm(book, request.POST)
446         if form.is_valid():
447             append_to = form.cleaned_data['append_to']
448             append_to.append(book)
449             return http.HttpResponseRedirect(append_to.get_absolute_url())
450     else:
451         form = forms.BookAppendForm(book)
452     return direct_to_template(request, "catalogue/book_append_to.html", extra_context={
453         "book": book,
454         "form": form,
455
456         "logout_to": '/',
457     })
458
459
460 @require_POST
461 @login_required
462 def publish(request, slug):
463     book = get_object_or_404(Book, slug=slug)
464     if not book.accessible(request):
465         return HttpResponseForbidden("Not authorized.")
466
467     try:
468         book.publish(request.user)
469     except NotAuthorizedError:
470         return http.HttpResponseRedirect(reverse('apiclient_oauth'))
471     except BaseException, e:
472         return http.HttpResponse(e)
473     else:
474         return http.HttpResponseRedirect(book.get_absolute_url())