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 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,
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'),
79 @active_tab('activity')
80 def activity(request, isodate=None):
83 day = helpers.parse_isodate(isodate)
90 next_day = day + timedelta(1)
91 prev_day = day - timedelta(1)
93 return render(request, 'catalogue/activity.html', locals())
97 def logout_then_redirect(request):
99 return http.HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
102 @permission_required('catalogue.add_book')
103 @active_tab('create')
104 def create_missing(request, slug=None):
107 slug = slug.replace(' ', '-')
109 if request.method == "POST":
110 form = forms.DocumentCreateForm(request.POST, request.FILES)
113 if request.user.is_authenticated():
114 creator = request.user
118 text=form.cleaned_data['text'],
120 slug=form.cleaned_data['slug'],
121 title=form.cleaned_data['title'],
122 gallery=form.cleaned_data['gallery'],
125 return http.HttpResponseRedirect(reverse("catalogue_book", args=[book.slug]))
127 form = forms.DocumentCreateForm(initial={
129 "title": slug.replace('-', ' ').title(),
133 return render(request, "catalogue/document_create_missing.html", {
141 @permission_required('catalogue.add_book')
142 @active_tab('upload')
144 if request.method == "POST":
145 form = forms.DocumentsUploadForm(request.POST, request.FILES)
147 from slugify import slugify
149 if request.user.is_authenticated():
150 creator = request.user
154 zip = form.cleaned_data['zip']
159 existing = [book.slug for book in Book.objects.all()]
160 for filename in zip.namelist():
161 if filename[-1] == '/':
163 title = os.path.basename(filename)[:-4]
164 slug = slugify(title)
165 if not (slug and filename.endswith('.xml')):
166 skipped_list.append(filename)
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.')))
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
180 for filename, slug, title in ok_list:
182 text=zip.read(filename).decode('utf-8'),
188 return render(request, "catalogue/document_upload.html", {
191 "skipped_list": skipped_list,
192 "error_list": error_list,
197 form = forms.DocumentsUploadForm()
199 return render(request, "catalogue/document_upload.html", {
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()
213 response = http.HttpResponse(xml, content_type='application/xml')
214 response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
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.")
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
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.")
237 doc = book.wldocument(parse_dublincore=False)
238 html = doc.as_html(options={'gallery': "'%s'" % book.gallery_url()})
240 html = html.get_string() if html is not None else ''
241 # response = http.HttpResponse(html, content_type='text/html')
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)
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())
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.")
259 # TODO: move to celery
260 doc = book.wldocument()
261 # TODO: error handling
262 pdf_file = doc.as_pdf(cover=True, ilustr_path=book.gallery_path())
263 from catalogue.ebook_utils import serve_file
264 return serve_file(pdf_file.get_filename(),
265 book.slug + '.pdf', 'application/pdf')
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.")
274 # TODO: move to celery
275 doc = book.wldocument()
276 # TODO: error handling
277 epub = doc.as_epub(ilustr_path=book.gallery_path()).get_string()
278 response = HttpResponse(content_type='application/epub+zip')
279 response['Content-Disposition'] = 'attachment; filename=%s' % book.slug + '.epub'
285 def book_mobi(request, slug):
286 book = get_object_or_404(Book, slug=slug)
287 if not book.accessible(request):
288 return HttpResponseForbidden("Not authorized.")
290 # TODO: move to celery
291 doc = book.wldocument()
292 # TODO: error handling
293 mobi = doc.as_mobi(ilustr_path=book.gallery_path()).get_string()
294 response = HttpResponse(content_type='application/x-mobipocket-ebook')
295 response['Content-Disposition'] = 'attachment; filename=%s' % book.slug + '.mobi'
301 def revision(request, slug, chunk=None):
303 doc = Chunk.get(slug, chunk)
304 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
306 if not doc.book.accessible(request):
307 return HttpResponseForbidden("Not authorized.")
308 return http.HttpResponse(str(doc.revision()))
311 def book(request, slug):
312 book = get_object_or_404(Book, slug=slug)
313 if not book.accessible(request):
314 return HttpResponseForbidden("Not authorized.")
316 if request.user.has_perm('catalogue.change_book'):
317 if request.method == "POST":
318 form = forms.BookForm(request.POST, instance=book)
321 return http.HttpResponseRedirect(book.get_absolute_url())
323 form = forms.BookForm(instance=book)
326 form = forms.ReadonlyBookForm(instance=book)
329 publish_error = book.publishable_error()
330 publishable = publish_error is None
332 return render(request, "catalogue/book_detail.html", {
334 "publishable": publishable,
335 "publishable_error": publish_error,
337 "editable": editable,
341 def image(request, slug):
342 image = get_object_or_404(Image, slug=slug)
343 if not image.accessible(request):
344 return HttpResponseForbidden("Not authorized.")
346 if request.user.has_perm('catalogue.change_image'):
347 if request.method == "POST":
348 form = forms.ImageForm(request.POST, instance=image)
351 return http.HttpResponseRedirect(image.get_absolute_url())
353 form = forms.ImageForm(instance=image)
356 form = forms.ReadonlyImageForm(instance=image)
359 publish_error = image.publishable_error()
360 publishable = publish_error is None
362 return render(request, "catalogue/image_detail.html", {
364 "publishable": publishable,
365 "publishable_error": publish_error,
367 "editable": editable,
371 @permission_required('catalogue.add_chunk')
372 def chunk_add(request, slug, chunk):
374 doc = Chunk.get(slug, chunk)
375 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
377 if not doc.book.accessible(request):
378 return HttpResponseForbidden("Not authorized.")
380 if request.method == "POST":
381 form = forms.ChunkAddForm(request.POST, instance=doc)
383 if request.user.is_authenticated():
384 creator = request.user
387 doc.split(creator=creator,
388 slug=form.cleaned_data['slug'],
389 title=form.cleaned_data['title'],
390 gallery_start=form.cleaned_data['gallery_start'],
391 user=form.cleaned_data['user'],
392 stage=form.cleaned_data['stage']
395 return http.HttpResponseRedirect(doc.book.get_absolute_url())
397 form = forms.ChunkAddForm(initial={
398 "slug": str(doc.number + 1),
399 "title": "cz. %d" % (doc.number + 1, ),
402 return render(request, "catalogue/chunk_add.html", {
409 def chunk_edit(request, slug, chunk):
411 doc = Chunk.get(slug, chunk)
412 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
414 if not doc.book.accessible(request):
415 return HttpResponseForbidden("Not authorized.")
417 if request.method == "POST":
418 form = forms.ChunkForm(request.POST, instance=doc)
421 go_next = request.GET.get('next', None)
423 go_next = urlquote_plus(unquote(iri_to_uri(go_next)), safe='/?=&')
425 go_next = doc.book.get_absolute_url()
426 return http.HttpResponseRedirect(go_next)
428 form = forms.ChunkForm(instance=doc)
430 referer = request.META.get('HTTP_REFERER')
432 parts = urlsplit(referer)
433 parts = ['', ''] + list(parts[2:])
434 go_next = urlquote_plus(urlunsplit(parts))
438 return render(request, "catalogue/chunk_edit.html", {
448 def chunk_mass_edit(request):
449 ids = map(int, filter(lambda i: i.strip()!='', request.POST.get('ids').split(',')))
450 chunks = map(lambda i: Chunk.objects.get(id=i), ids)
452 stage = request.POST.get('stage')
455 stage = Chunk.tag_model.objects.get(slug=stage)
456 except Chunk.DoesNotExist, e:
459 for c in chunks: c.stage = stage
461 username = request.POST.get('user')
462 logger.info("username: %s" % username)
463 logger.info(request.POST)
466 user = User.objects.get(username=username)
467 except User.DoesNotExist, e:
470 for c in chunks: c.user = user
472 project_id = request.POST.get('project')
475 project = Project.objects.get(pk=int(project_id))
476 except (Project.DoesNotExist, ValueError), e:
480 book.project = project
483 for c in chunks: c.save()
485 return HttpResponse("", content_type="text/plain")
491 def image_mass_edit(request):
492 ids = map(int, filter(lambda i: i.strip()!='', request.POST.get('ids').split(',')))
493 images = map(lambda i: Image.objects.get(id=i), ids)
495 stage = request.POST.get('stage')
498 stage = Image.tag_model.objects.get(slug=stage)
499 except Image.DoesNotExist, e:
502 for c in images: c.stage = stage
504 username = request.POST.get('user')
505 logger.info("username: %s" % username)
506 logger.info(request.POST)
509 user = User.objects.get(username=username)
510 except User.DoesNotExist, e:
513 for c in images: c.user = user
515 project_id = request.POST.get('project')
518 project = Project.objects.get(pk=int(project_id))
519 except (Project.DoesNotExist, ValueError), e:
524 for c in images: c.save()
526 return HttpResponse("", content_type="text/plain")
529 @permission_required('catalogue.change_book')
530 def book_append(request, slug):
531 book = get_object_or_404(Book, slug=slug)
532 if not book.accessible(request):
533 return HttpResponseForbidden("Not authorized.")
535 if request.method == "POST":
536 form = forms.BookAppendForm(book, request.POST)
538 append_to = form.cleaned_data['append_to']
539 append_to.append(book)
540 return http.HttpResponseRedirect(append_to.get_absolute_url())
542 form = forms.BookAppendForm(book)
543 return render(request, "catalogue/book_append_to.html", {
553 def publish(request, slug):
554 book = get_object_or_404(Book, slug=slug)
555 if not book.accessible(request):
556 return HttpResponseForbidden("Not authorized.")
559 protocol = 'https://' if request.is_secure() else 'http://'
560 book.publish(request.user, host=protocol + request.get_host())
561 except NotAuthorizedError:
562 return http.HttpResponseRedirect(reverse('apiclient_oauth'))
563 except BaseException, e:
564 return http.HttpResponse(e)
566 return http.HttpResponseRedirect(book.get_absolute_url())
571 def publish_image(request, slug):
572 image = get_object_or_404(Image, slug=slug)
573 if not image.accessible(request):
574 return HttpResponseForbidden("Not authorized.")
577 image.publish(request.user)
578 except NotAuthorizedError:
579 return http.HttpResponseRedirect(reverse('apiclient_oauth'))
580 except BaseException, e:
581 return http.HttpResponse(e)
583 return http.HttpResponseRedirect(image.get_absolute_url())
586 class GalleryView(UploadView):
587 def get_object(self, request, slug):
588 book = get_object_or_404(Book, slug=slug)
593 def breadcrumbs(self):
595 (_('books'), reverse('catalogue_document_list')),
596 (self.object.title, self.object.get_absolute_url()),
597 (_('scan gallery'),),
600 def get_directory(self):
601 return "%s%s/" % (settings.IMAGE_DIR, self.object.gallery)