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)
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()
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().get_string()
278 response = HttpResponse(content_type='application/epub+zip')
279 response['Content-Disposition'] = 'attachment; filename=%s' % book.slug + '.epub'
285 def revision(request, slug, chunk=None):
287 doc = Chunk.get(slug, chunk)
288 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
290 if not doc.book.accessible(request):
291 return HttpResponseForbidden("Not authorized.")
292 return http.HttpResponse(str(doc.revision()))
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.")
300 if request.user.has_perm('catalogue.change_book'):
301 if request.method == "POST":
302 form = forms.BookForm(request.POST, instance=book)
305 return http.HttpResponseRedirect(book.get_absolute_url())
307 form = forms.BookForm(instance=book)
310 form = forms.ReadonlyBookForm(instance=book)
313 publish_error = book.publishable_error()
314 publishable = publish_error is None
316 return render(request, "catalogue/book_detail.html", {
318 "publishable": publishable,
319 "publishable_error": publish_error,
321 "editable": editable,
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.")
330 if request.user.has_perm('catalogue.change_image'):
331 if request.method == "POST":
332 form = forms.ImageForm(request.POST, instance=image)
335 return http.HttpResponseRedirect(image.get_absolute_url())
337 form = forms.ImageForm(instance=image)
340 form = forms.ReadonlyImageForm(instance=image)
343 publish_error = image.publishable_error()
344 publishable = publish_error is None
346 return render(request, "catalogue/image_detail.html", {
348 "publishable": publishable,
349 "publishable_error": publish_error,
351 "editable": editable,
355 @permission_required('catalogue.add_chunk')
356 def chunk_add(request, slug, chunk):
358 doc = Chunk.get(slug, chunk)
359 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
361 if not doc.book.accessible(request):
362 return HttpResponseForbidden("Not authorized.")
364 if request.method == "POST":
365 form = forms.ChunkAddForm(request.POST, instance=doc)
367 if request.user.is_authenticated():
368 creator = request.user
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']
379 return http.HttpResponseRedirect(doc.book.get_absolute_url())
381 form = forms.ChunkAddForm(initial={
382 "slug": str(doc.number + 1),
383 "title": "cz. %d" % (doc.number + 1, ),
386 return render(request, "catalogue/chunk_add.html", {
393 def chunk_edit(request, slug, chunk):
395 doc = Chunk.get(slug, chunk)
396 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
398 if not doc.book.accessible(request):
399 return HttpResponseForbidden("Not authorized.")
401 if request.method == "POST":
402 form = forms.ChunkForm(request.POST, instance=doc)
405 go_next = request.GET.get('next', None)
407 go_next = urlquote_plus(unquote(iri_to_uri(go_next)), safe='/?=&')
409 go_next = doc.book.get_absolute_url()
410 return http.HttpResponseRedirect(go_next)
412 form = forms.ChunkForm(instance=doc)
414 referer = request.META.get('HTTP_REFERER')
416 parts = urlsplit(referer)
417 parts = ['', ''] + list(parts[2:])
418 go_next = urlquote_plus(urlunsplit(parts))
422 return render(request, "catalogue/chunk_edit.html", {
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)
436 stage = request.POST.get('stage')
439 stage = Chunk.tag_model.objects.get(slug=stage)
440 except Chunk.DoesNotExist, e:
443 for c in chunks: c.stage = stage
445 username = request.POST.get('user')
446 logger.info("username: %s" % username)
447 logger.info(request.POST)
450 user = User.objects.get(username=username)
451 except User.DoesNotExist, e:
454 for c in chunks: c.user = user
456 project_id = request.POST.get('project')
459 project = Project.objects.get(pk=int(project_id))
460 except (Project.DoesNotExist, ValueError), e:
464 book.project = project
467 for c in chunks: c.save()
469 return HttpResponse("", content_type="text/plain")
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)
479 stage = request.POST.get('stage')
482 stage = Image.tag_model.objects.get(slug=stage)
483 except Image.DoesNotExist, e:
486 for c in images: c.stage = stage
488 username = request.POST.get('user')
489 logger.info("username: %s" % username)
490 logger.info(request.POST)
493 user = User.objects.get(username=username)
494 except User.DoesNotExist, e:
497 for c in images: c.user = user
499 project_id = request.POST.get('project')
502 project = Project.objects.get(pk=int(project_id))
503 except (Project.DoesNotExist, ValueError), e:
508 for c in images: c.save()
510 return HttpResponse("", content_type="text/plain")
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.")
519 if request.method == "POST":
520 form = forms.BookAppendForm(book, request.POST)
522 append_to = form.cleaned_data['append_to']
523 append_to.append(book)
524 return http.HttpResponseRedirect(append_to.get_absolute_url())
526 form = forms.BookAppendForm(book)
527 return render(request, "catalogue/book_append_to.html", {
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.")
543 book.publish(request.user)
544 except NotAuthorizedError:
545 return http.HttpResponseRedirect(reverse('apiclient_oauth'))
546 except BaseException, e:
547 return http.HttpResponse(e)
549 return http.HttpResponseRedirect(book.get_absolute_url())
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.")
560 image.publish(request.user)
561 except NotAuthorizedError:
562 return http.HttpResponseRedirect(reverse('apiclient_oauth'))
563 except BaseException, e:
564 return http.HttpResponse(e)
566 return http.HttpResponseRedirect(image.get_absolute_url())
569 class GalleryView(UploadView):
570 def get_object(self, request, slug):
571 book = get_object_or_404(Book, slug=slug)
576 def breadcrumbs(self):
578 (_('books'), reverse('catalogue_document_list')),
579 (self.object.title, self.object.get_absolute_url()),
580 (_('scan gallery'),),
583 def get_directory(self):
584 return "%s%s/" % (settings.IMAGE_DIR, self.object.gallery)