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
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
22 from apiclient import NotAuthorizedError
23 from catalogue import forms
24 from catalogue import helpers
25 from catalogue.helpers import active_tab
26 from catalogue.models import Book, Chunk, BookPublishRecord, ChunkPublishRecord
27 from catalogue.tasks import publishable_error
30 # Quick hack around caching problems, TODO: use ETags
32 from django.views.decorators.cache import never_cache
34 logger = logging.getLogger("fnp.catalogue")
39 def document_list(request):
40 return render(request, 'catalogue/document_list.html')
44 def user(request, username):
45 user = get_object_or_404(User, username=username)
46 return render(request, 'catalogue/user_page.html', {"viewed_user": user})
53 return render(request, 'catalogue/my_page.html', {
54 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
55 key=lambda x: x[1]['time'], reverse=True),
63 return direct_to_template(request, 'catalogue/user_list.html', extra_context={
64 'users': User.objects.all().annotate(count=Count('chunk')).order_by(
65 '-count', 'last_name', 'first_name'),
69 @active_tab('activity')
70 def activity(request, isodate=None):
73 day = helpers.parse_isodate(isodate)
80 next_day = day + timedelta(1)
81 prev_day = day - timedelta(1)
83 return render(request, 'catalogue/activity.html', locals())
87 def logout_then_redirect(request):
89 return http.HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
92 @permission_required('catalogue.add_book')
94 def create_missing(request, slug=None):
97 slug = slug.replace(' ', '-')
99 if request.method == "POST":
100 form = forms.DocumentCreateForm(request.POST, request.FILES)
103 if request.user.is_authenticated():
104 creator = request.user
108 text=form.cleaned_data['text'],
110 slug=form.cleaned_data['slug'],
111 title=form.cleaned_data['title'],
112 gallery=form.cleaned_data['gallery'],
115 return http.HttpResponseRedirect(reverse("catalogue_book", args=[book.slug]))
117 form = forms.DocumentCreateForm(initial={
119 "title": slug.replace('-', ' ').title(),
123 return direct_to_template(request, "catalogue/document_create_missing.html", extra_context={
131 @permission_required('catalogue.add_book')
132 @active_tab('upload')
134 if request.method == "POST":
135 form = forms.DocumentsUploadForm(request.POST, request.FILES)
139 if request.user.is_authenticated():
140 creator = request.user
144 zip = form.cleaned_data['zip']
149 existing = [book.slug for book in Book.objects.all()]
150 for filename in zip.namelist():
151 if filename[-1] == '/':
153 title = os.path.basename(filename)[:-4]
154 slug = slughifi(title)
155 if not (slug and filename.endswith('.xml')):
156 skipped_list.append(filename)
158 error_list.append((filename, slug, _('Slug already used for %s' % slugs[slug])))
159 elif slug in existing:
160 error_list.append((filename, slug, _('Slug already used in repository.')))
163 zip.read(filename).decode('utf-8') # test read
164 ok_list.append((filename, slug, title))
165 except UnicodeDecodeError:
166 error_list.append((filename, title, _('File should be UTF-8 encoded.')))
167 slugs[slug] = filename
170 for filename, slug, title in ok_list:
172 text=zip.read(filename).decode('utf-8'),
178 return direct_to_template(request, "catalogue/document_upload.html", extra_context={
181 "skipped_list": skipped_list,
182 "error_list": error_list,
187 form = forms.DocumentsUploadForm()
189 return direct_to_template(request, "catalogue/document_upload.html", extra_context={
197 def book_xml(request, slug):
198 book = get_object_or_404(Book, slug=slug)
199 if not book.accessible(request):
200 return HttpResponseForbidden("Not authorized.")
201 xml = book.materialize()
203 response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
204 response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
209 def book_txt(request, slug):
210 book = get_object_or_404(Book, slug=slug)
211 if not book.accessible(request):
212 return HttpResponseForbidden("Not authorized.")
213 xml = book.materialize()
217 import librarian.text
218 librarian.text.transform(StringIO(xml), output)
219 text = output.getvalue()
220 response = http.HttpResponse(text, content_type='text/plain', mimetype='text/plain')
221 response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
226 def book_html(request, slug):
227 book = get_object_or_404(Book, slug=slug)
228 if not book.accessible(request):
229 return HttpResponseForbidden("Not authorized.")
230 xml = book.materialize()
234 import librarian.html
235 librarian.html.transform(StringIO(xml), output, parse_dublincore=False,
237 html = output.getvalue()
238 response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
243 def book_pdf(request, slug):
244 book = get_object_or_404(Book, slug=slug)
245 if not book.accessible(request):
246 return HttpResponseForbidden("Not authorized.")
248 from tempfile import NamedTemporaryFile
249 from os import unlink
250 from librarian import pdf
251 from catalogue.ebook_utils import RedakcjaDocProvider, serve_file
253 xml = book.materialize()
254 xml_file = NamedTemporaryFile()
255 xml_file.write(xml.encode('utf-8'))
259 pdf_file = NamedTemporaryFile(delete=False)
260 pdf.transform(RedakcjaDocProvider(publishable=True),
261 file_path=xml_file.name,
262 output_file=pdf_file,
264 return serve_file(pdf_file.name, book.slug + '.pdf', 'application/pdf')
266 unlink(pdf_file.name)
270 def book_epub(request, slug):
271 book = get_object_or_404(Book, slug=slug)
272 if not book.accessible(request):
273 return HttpResponseForbidden("Not authorized.")
275 from StringIO import StringIO
276 from tempfile import NamedTemporaryFile
277 from librarian import epub
278 from catalogue.ebook_utils import RedakcjaDocProvider
280 xml = book.materialize()
281 xml_file = NamedTemporaryFile()
282 xml_file.write(xml.encode('utf-8'))
285 epub_file = StringIO()
286 epub.transform(RedakcjaDocProvider(publishable=True),
287 file_path=xml_file.name,
288 output_file=epub_file)
289 response = HttpResponse(mimetype='application/epub+zip')
290 response['Content-Disposition'] = 'attachment; filename=%s' % book.slug + '.epub'
291 response.write(epub_file.getvalue())
296 def revision(request, slug, chunk=None):
298 doc = Chunk.get(slug, chunk)
299 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
301 if not doc.book.accessible(request):
302 return HttpResponseForbidden("Not authorized.")
303 return http.HttpResponse(str(doc.revision()))
306 def book(request, slug):
307 book = get_object_or_404(Book, slug=slug)
308 if not book.accessible(request):
309 return HttpResponseForbidden("Not authorized.")
311 if request.user.has_perm('catalogue.change_book'):
312 if request.method == "POST":
313 form = forms.BookForm(request.POST, instance=book)
316 return http.HttpResponseRedirect(book.get_absolute_url())
318 form = forms.BookForm(instance=book)
321 form = forms.ReadonlyBookForm(instance=book)
324 publish_error = publishable_error(book)
325 publishable = publish_error is None
327 return direct_to_template(request, "catalogue/book_detail.html", extra_context={
329 "publishable": publishable,
330 "publishable_error": publish_error,
332 "editable": editable,
336 @permission_required('catalogue.add_chunk')
337 def chunk_add(request, slug, chunk):
339 doc = Chunk.get(slug, chunk)
340 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
342 if not doc.book.accessible(request):
343 return HttpResponseForbidden("Not authorized.")
345 if request.method == "POST":
346 form = forms.ChunkAddForm(request.POST, instance=doc)
348 if request.user.is_authenticated():
349 creator = request.user
352 doc.split(creator=creator,
353 slug=form.cleaned_data['slug'],
354 title=form.cleaned_data['title'],
355 gallery_start=form.cleaned_data['gallery_start'],
356 user=form.cleaned_data['user'],
357 stage=form.cleaned_data['stage']
360 return http.HttpResponseRedirect(doc.book.get_absolute_url())
362 form = forms.ChunkAddForm(initial={
363 "slug": str(doc.number + 1),
364 "title": "cz. %d" % (doc.number + 1, ),
367 return direct_to_template(request, "catalogue/chunk_add.html", extra_context={
373 def chunk_edit(request, slug, chunk):
375 doc = Chunk.get(slug, chunk)
376 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
378 if not doc.book.accessible(request):
379 return HttpResponseForbidden("Not authorized.")
381 if request.method == "POST":
382 form = forms.ChunkForm(request.POST, instance=doc)
385 go_next = request.GET.get('next', None)
387 go_next = urlquote_plus(unquote(iri_to_uri(go_next)), safe='/?=&')
389 go_next = doc.book.get_absolute_url()
390 return http.HttpResponseRedirect(go_next)
392 form = forms.ChunkForm(instance=doc)
394 referer = request.META.get('HTTP_REFERER')
396 parts = urlsplit(referer)
397 parts = ['', ''] + list(parts[2:])
398 go_next = urlquote_plus(urlunsplit(parts))
402 return direct_to_template(request, "catalogue/chunk_edit.html", extra_context={
409 @permission_required('catalogue.change_book')
410 def book_append(request, slug):
411 book = get_object_or_404(Book, slug=slug)
412 if not book.accessible(request):
413 return HttpResponseForbidden("Not authorized.")
415 if request.method == "POST":
416 form = forms.BookAppendForm(book, request.POST)
418 append_to = form.cleaned_data['append_to']
419 append_to.append(book)
420 return http.HttpResponseRedirect(append_to.get_absolute_url())
422 form = forms.BookAppendForm(book)
423 return direct_to_template(request, "catalogue/book_append_to.html", extra_context={
433 def publish(request, slug):
434 book = get_object_or_404(Book, slug=slug)
435 if not book.accessible(request):
436 return HttpResponseForbidden("Not authorized.")
439 book.publish(request.user)
440 except NotAuthorizedError:
441 return http.HttpResponseRedirect(reverse('apiclient_oauth'))
442 except BaseException, e:
443 return http.HttpResponse(e)
445 return http.HttpResponseRedirect(book.get_absolute_url())