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.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 import http
14 from django.http import Http404, HttpResponse, HttpResponseForbidden
15 from django.shortcuts import get_object_or_404, render, render_to_response
16 from django.utils.encoding import iri_to_uri
17 from django.utils.http import urlquote_plus
18 from django.utils.translation import ugettext_lazy as _
19 from django.views.decorators.http import require_POST
20 from django.views.generic.simple import direct_to_template
21 from django.template import RequestContext
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, BookPublishRecord, ChunkPublishRecord
28 from catalogue.tasks import publishable_error
31 # Quick hack around caching problems, TODO: use ETags
33 from django.views.decorators.cache import never_cache
35 logger = logging.getLogger("fnp.catalogue")
40 def document_list(request):
41 return render(request, 'catalogue/document_list.html')
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})
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),
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'),
70 @active_tab('activity')
71 def activity(request, isodate=None):
74 day = helpers.parse_isodate(isodate)
81 next_day = day + timedelta(1)
82 prev_day = day - timedelta(1)
84 return render(request, 'catalogue/activity.html', locals())
88 def logout_then_redirect(request):
90 return http.HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
93 @permission_required('catalogue.add_book')
95 def create_missing(request, slug=None):
98 slug = slug.replace(' ', '-')
100 if request.method == "POST":
101 form = forms.DocumentCreateForm(request.POST, request.FILES)
104 if request.user.is_authenticated():
105 creator = request.user
109 text=form.cleaned_data['text'],
111 slug=form.cleaned_data['slug'],
112 title=form.cleaned_data['title'],
113 gallery=form.cleaned_data['gallery'],
116 return http.HttpResponseRedirect(reverse("catalogue_book", args=[book.slug]))
118 form = forms.DocumentCreateForm(initial={
120 "title": slug.replace('-', ' ').title(),
124 return direct_to_template(request, "catalogue/document_create_missing.html", extra_context={
132 @permission_required('catalogue.add_book')
133 @active_tab('upload')
135 if request.method == "POST":
136 form = forms.DocumentsUploadForm(request.POST, request.FILES)
140 if request.user.is_authenticated():
141 creator = request.user
145 zip = form.cleaned_data['zip']
150 existing = [book.slug for book in Book.objects.all()]
151 for filename in zip.namelist():
152 if filename[-1] == '/':
154 title = os.path.basename(filename)[:-4]
155 slug = slughifi(title)
156 if not (slug and filename.endswith('.xml')):
157 skipped_list.append(filename)
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.')))
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
171 for filename, slug, title in ok_list:
173 text=zip.read(filename).decode('utf-8'),
179 return direct_to_template(request, "catalogue/document_upload.html", extra_context={
182 "skipped_list": skipped_list,
183 "error_list": error_list,
188 form = forms.DocumentsUploadForm()
190 return direct_to_template(request, "catalogue/document_upload.html", extra_context={
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()
204 response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
205 response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
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.")
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
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.")
228 doc = book.wldocument(parse_dublincore=False)
231 html = html.get_string() if html is not None else ''
232 # response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
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)
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))
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.")
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')
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.")
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'
277 def revision(request, slug, chunk=None):
279 doc = Chunk.get(slug, chunk)
280 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
282 if not doc.book.accessible(request):
283 return HttpResponseForbidden("Not authorized.")
284 return http.HttpResponse(str(doc.revision()))
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.")
292 if request.user.has_perm('catalogue.change_book'):
293 if request.method == "POST":
294 form = forms.BookForm(request.POST, instance=book)
297 return http.HttpResponseRedirect(book.get_absolute_url())
299 form = forms.BookForm(instance=book)
302 form = forms.ReadonlyBookForm(instance=book)
305 publish_error = publishable_error(book)
306 publishable = publish_error is None
308 return direct_to_template(request, "catalogue/book_detail.html", extra_context={
310 "publishable": publishable,
311 "publishable_error": publish_error,
313 "editable": editable,
317 @permission_required('catalogue.add_chunk')
318 def chunk_add(request, slug, chunk):
320 doc = Chunk.get(slug, chunk)
321 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
323 if not doc.book.accessible(request):
324 return HttpResponseForbidden("Not authorized.")
326 if request.method == "POST":
327 form = forms.ChunkAddForm(request.POST, instance=doc)
329 if request.user.is_authenticated():
330 creator = request.user
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']
341 return http.HttpResponseRedirect(doc.book.get_absolute_url())
343 form = forms.ChunkAddForm(initial={
344 "slug": str(doc.number + 1),
345 "title": "cz. %d" % (doc.number + 1, ),
348 return direct_to_template(request, "catalogue/chunk_add.html", extra_context={
354 def chunk_edit(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.ChunkForm(request.POST, instance=doc)
366 go_next = request.GET.get('next', None)
368 go_next = urlquote_plus(unquote(iri_to_uri(go_next)), safe='/?=&')
370 go_next = doc.book.get_absolute_url()
371 return http.HttpResponseRedirect(go_next)
373 form = forms.ChunkForm(instance=doc)
375 referer = request.META.get('HTTP_REFERER')
377 parts = urlsplit(referer)
378 parts = ['', ''] + list(parts[2:])
379 go_next = urlquote_plus(urlunsplit(parts))
383 return direct_to_template(request, "catalogue/chunk_edit.html", extra_context={
390 @permission_required('catalogue.change_book')
391 def book_append(request, slug):
392 book = get_object_or_404(Book, slug=slug)
393 if not book.accessible(request):
394 return HttpResponseForbidden("Not authorized.")
396 if request.method == "POST":
397 form = forms.BookAppendForm(book, request.POST)
399 append_to = form.cleaned_data['append_to']
400 append_to.append(book)
401 return http.HttpResponseRedirect(append_to.get_absolute_url())
403 form = forms.BookAppendForm(book)
404 return direct_to_template(request, "catalogue/book_append_to.html", extra_context={
414 def publish(request, slug):
415 book = get_object_or_404(Book, slug=slug)
416 if not book.accessible(request):
417 return HttpResponseForbidden("Not authorized.")
420 book.publish(request.user)
421 except NotAuthorizedError:
422 return http.HttpResponseRedirect(reverse('apiclient_oauth'))
423 except BaseException, e:
424 return http.HttpResponse(e)
426 return http.HttpResponseRedirect(book.get_absolute_url())