1 from datetime import datetime, date, timedelta
4 from StringIO import StringIO
5 from urllib import unquote
6 from urlparse import 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.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
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
32 # Quick hack around caching problems, TODO: use ETags
34 from django.views.decorators.cache import never_cache
36 logger = logging.getLogger("fnp.catalogue")
41 def document_list(request):
42 return render(request, 'catalogue/document_list.html')
47 def image_list(request, user=None):
48 return render(request, 'catalogue/image_list.html')
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})
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),
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'),
77 @active_tab('activity')
78 def activity(request, isodate=None):
81 day = helpers.parse_isodate(isodate)
88 next_day = day + timedelta(1)
89 prev_day = day - timedelta(1)
91 return render(request, 'catalogue/activity.html', locals())
95 def logout_then_redirect(request):
97 return http.HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
100 @permission_required('catalogue.add_book')
101 @active_tab('create')
102 def create_missing(request, slug=None):
105 slug = slug.replace(' ', '-')
107 if request.method == "POST":
108 form = forms.DocumentCreateForm(request.POST, request.FILES)
111 if request.user.is_authenticated():
112 creator = request.user
116 text=form.cleaned_data['text'],
118 slug=form.cleaned_data['slug'],
119 title=form.cleaned_data['title'],
120 gallery=form.cleaned_data['gallery'],
123 return http.HttpResponseRedirect(reverse("catalogue_book", args=[book.slug]))
125 form = forms.DocumentCreateForm(initial={
127 "title": slug.replace('-', ' ').title(),
131 return render(request, "catalogue/document_create_missing.html", {
139 @permission_required('catalogue.add_book')
140 @active_tab('upload')
142 if request.method == "POST":
143 form = forms.DocumentsUploadForm(request.POST, request.FILES)
145 from fnpdjango.utils.text.slughifi import slughifi
147 if request.user.is_authenticated():
148 creator = request.user
152 zip = form.cleaned_data['zip']
157 existing = [book.slug for book in Book.objects.all()]
158 for filename in zip.namelist():
159 if filename[-1] == '/':
161 title = os.path.basename(filename)[:-4]
162 slug = slughifi(title)
163 if not (slug and filename.endswith('.xml')):
164 skipped_list.append(filename)
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.')))
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
178 for filename, slug, title in ok_list:
180 text=zip.read(filename).decode('utf-8'),
186 return render(request, "catalogue/document_upload.html", {
189 "skipped_list": skipped_list,
190 "error_list": error_list,
195 form = forms.DocumentsUploadForm()
197 return render(request, "catalogue/document_upload.html", {
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()
211 response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
212 response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
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.")
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
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.")
235 doc = book.wldocument(parse_dublincore=False)
238 html = html.get_string() if html is not None else ''
239 # response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
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)
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())
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.")
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')
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.")
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'
283 def revision(request, slug, chunk=None):
285 doc = Chunk.get(slug, chunk)
286 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
288 if not doc.book.accessible(request):
289 return HttpResponseForbidden("Not authorized.")
290 return http.HttpResponse(str(doc.revision()))
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.")
298 if request.user.has_perm('catalogue.change_book'):
299 if request.method == "POST":
300 form = forms.BookForm(request.POST, instance=book)
303 return http.HttpResponseRedirect(book.get_absolute_url())
305 form = forms.BookForm(instance=book)
308 form = forms.ReadonlyBookForm(instance=book)
311 publish_error = book.publishable_error()
312 publishable = publish_error is None
314 return render(request, "catalogue/book_detail.html", {
316 "publishable": publishable,
317 "publishable_error": publish_error,
319 "editable": editable,
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.")
328 if request.user.has_perm('catalogue.change_image'):
329 if request.method == "POST":
330 form = forms.ImageForm(request.POST, instance=image)
333 return http.HttpResponseRedirect(image.get_absolute_url())
335 form = forms.ImageForm(instance=image)
338 form = forms.ReadonlyImageForm(instance=image)
341 publish_error = image.publishable_error()
342 publishable = publish_error is None
344 return render(request, "catalogue/image_detail.html", {
346 "publishable": publishable,
347 "publishable_error": publish_error,
349 "editable": editable,
353 @permission_required('catalogue.add_chunk')
354 def chunk_add(request, slug, chunk):
356 doc = Chunk.get(slug, chunk)
357 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
359 if not doc.book.accessible(request):
360 return HttpResponseForbidden("Not authorized.")
362 if request.method == "POST":
363 form = forms.ChunkAddForm(request.POST, instance=doc)
365 if request.user.is_authenticated():
366 creator = request.user
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']
377 return http.HttpResponseRedirect(doc.book.get_absolute_url())
379 form = forms.ChunkAddForm(initial={
380 "slug": str(doc.number + 1),
381 "title": "cz. %d" % (doc.number + 1, ),
384 return render(request, "catalogue/chunk_add.html", {
391 def chunk_edit(request, slug, chunk):
393 doc = Chunk.get(slug, chunk)
394 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
396 if not doc.book.accessible(request):
397 return HttpResponseForbidden("Not authorized.")
399 if request.method == "POST":
400 form = forms.ChunkForm(request.POST, instance=doc)
403 go_next = request.GET.get('next', None)
405 go_next = urlquote_plus(unquote(iri_to_uri(go_next)), safe='/?=&')
407 go_next = doc.book.get_absolute_url()
408 return http.HttpResponseRedirect(go_next)
410 form = forms.ChunkForm(instance=doc)
412 referer = request.META.get('HTTP_REFERER')
414 parts = urlsplit(referer)
415 parts = ['', ''] + list(parts[2:])
416 go_next = urlquote_plus(urlunsplit(parts))
420 return render(request, "catalogue/chunk_edit.html", {
427 @transaction.commit_on_success
430 def chunk_mass_edit(request):
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)
434 stage = request.POST.get('stage')
437 stage = Chunk.tag_model.objects.get(slug=stage)
438 except Chunk.DoesNotExist, e:
441 for c in chunks: c.stage = stage
443 username = request.POST.get('user')
444 logger.info("username: %s" % username)
445 logger.info(request.POST)
448 user = User.objects.get(username=username)
449 except User.DoesNotExist, e:
452 for c in chunks: c.user = user
454 project_id = request.POST.get('project')
457 project = Project.objects.get(pk=int(project_id))
458 except (Project.DoesNotExist, ValueError), e:
462 book.project = project
465 for c in chunks: c.save()
467 return HttpResponse("", content_type="text/plain")
470 @transaction.commit_on_success
473 def image_mass_edit(request):
474 ids = map(int, filter(lambda i: i.strip()!='', request.POST.get('ids').split(',')))
475 images = map(lambda i: Image.objects.get(id=i), ids)
477 stage = request.POST.get('stage')
480 stage = Image.tag_model.objects.get(slug=stage)
481 except Image.DoesNotExist, e:
484 for c in images: c.stage = stage
486 username = request.POST.get('user')
487 logger.info("username: %s" % username)
488 logger.info(request.POST)
491 user = User.objects.get(username=username)
492 except User.DoesNotExist, e:
495 for c in images: c.user = user
497 project_id = request.POST.get('project')
500 project = Project.objects.get(pk=int(project_id))
501 except (Project.DoesNotExist, ValueError), e:
506 for c in images: c.save()
508 return HttpResponse("", content_type="text/plain")
511 @permission_required('catalogue.change_book')
512 def book_append(request, slug):
513 book = get_object_or_404(Book, slug=slug)
514 if not book.accessible(request):
515 return HttpResponseForbidden("Not authorized.")
517 if request.method == "POST":
518 form = forms.BookAppendForm(book, request.POST)
520 append_to = form.cleaned_data['append_to']
521 append_to.append(book)
522 return http.HttpResponseRedirect(append_to.get_absolute_url())
524 form = forms.BookAppendForm(book)
525 return render(request, "catalogue/book_append_to.html", {
535 def publish(request, slug):
536 book = get_object_or_404(Book, slug=slug)
537 if not book.accessible(request):
538 return HttpResponseForbidden("Not authorized.")
541 book.publish(request.user)
542 except NotAuthorizedError:
543 return http.HttpResponseRedirect(reverse('apiclient_oauth'))
544 except BaseException, e:
545 return http.HttpResponse(e)
547 return http.HttpResponseRedirect(book.get_absolute_url())
552 def publish_image(request, slug):
553 image = get_object_or_404(Image, slug=slug)
554 if not image.accessible(request):
555 return HttpResponseForbidden("Not authorized.")
558 image.publish(request.user)
559 except NotAuthorizedError:
560 return http.HttpResponseRedirect(reverse('apiclient_oauth'))
561 except BaseException, e:
562 return http.HttpResponse(e)
564 return http.HttpResponseRedirect(image.get_absolute_url())
567 class GalleryView(UploadView):
568 def get_object(self, request, slug):
569 book = get_object_or_404(Book, slug=slug)
574 def breadcrumbs(self):
576 (_('books'), reverse('catalogue_document_list')),
577 (self.object.title, self.object.get_absolute_url()),
578 (_('scan gallery'),),
581 def get_directory(self):
582 return "%s%s/" % (settings.IMAGE_DIR, self.object.gallery)