1 from datetime import datetime
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
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
25 from apiclient import NotAuthorizedError
26 from catalogue import forms
27 from catalogue import helpers
28 from catalogue.helpers import active_tab
29 from catalogue.models import Book, Chunk, BookPublishRecord, ChunkPublishRecord
30 from catalogue.tasks import publishable_error
31 from catalogue import xml_tools
34 # Quick hack around caching problems, TODO: use ETags
36 from django.views.decorators.cache import never_cache
38 logger = logging.getLogger("fnp.catalogue")
43 def document_list(request):
44 return render(request, 'catalogue/document_list.html')
48 def user(request, username):
49 user = get_object_or_404(User, username=username)
50 return render(request, 'catalogue/user_page.html', {"viewed_user": user})
57 return render(request, 'catalogue/my_page.html', {
58 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
59 key=lambda x: x[1]['time'], reverse=True),
67 return direct_to_template(request, 'catalogue/user_list.html', extra_context={
68 'users': User.objects.all().annotate(count=Count('chunk')).order_by(
69 '-count', 'last_name', 'first_name'),
73 @active_tab('activity')
74 def activity(request):
75 return render(request, 'catalogue/activity.html')
79 def logout_then_redirect(request):
81 return http.HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
84 @permission_required('catalogue.add_book')
86 def create_missing(request, slug=None):
89 slug = slug.replace(' ', '-')
91 if request.method == "POST":
92 form = forms.DocumentCreateForm(request.POST, request.FILES)
95 if request.user.is_authenticated():
96 creator = request.user
100 text=form.cleaned_data['text'],
102 slug=form.cleaned_data['slug'],
103 title=form.cleaned_data['title'],
106 return http.HttpResponseRedirect(reverse("wiki_editor", args=[book.slug]))
108 form = forms.DocumentCreateForm(initial={
110 "title": slug.replace('-', ' ').title(),
113 return direct_to_template(request, "catalogue/document_create_missing.html", extra_context={
121 @permission_required('catalogue.add_book')
122 @active_tab('upload')
124 if request.method == "POST":
125 form = forms.DocumentsUploadForm(request.POST, request.FILES)
129 if request.user.is_authenticated():
130 creator = request.user
134 zip = form.cleaned_data['zip']
139 existing = [book.slug for book in Book.objects.all()]
140 for filename in zip.namelist():
141 if filename[-1] == '/':
143 title = os.path.basename(filename)[:-4]
144 slug = slughifi(title)
145 if not (slug and filename.endswith('.xml')):
146 skipped_list.append(filename)
148 error_list.append((filename, slug, _('Slug already used for %s' % slugs[slug])))
149 elif slug in existing:
150 error_list.append((filename, slug, _('Slug already used in repository.')))
153 zip.read(filename).decode('utf-8') # test read
154 ok_list.append((filename, slug, title))
155 except UnicodeDecodeError:
156 error_list.append((filename, title, _('File should be UTF-8 encoded.')))
157 slugs[slug] = filename
160 for filename, slug, title in ok_list:
162 text=zip.read(filename).decode('utf-8'),
168 return direct_to_template(request, "catalogue/document_upload.html", extra_context={
171 "skipped_list": skipped_list,
172 "error_list": error_list,
177 form = forms.DocumentsUploadForm()
179 return direct_to_template(request, "catalogue/document_upload.html", extra_context={
187 def book_xml(request, slug):
188 xml = get_object_or_404(Book, slug=slug).materialize()
190 response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
191 response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
196 def book_txt(request, slug):
197 xml = get_object_or_404(Book, slug=slug).materialize()
200 librarian.text.transform(StringIO(xml), output)
201 text = output.getvalue()
202 response = http.HttpResponse(text, content_type='text/plain', mimetype='text/plain')
203 response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
208 def book_html(request, slug):
209 xml = get_object_or_404(Book, slug=slug).materialize()
212 librarian.html.transform(StringIO(xml), output, parse_dublincore=False,
214 html = output.getvalue()
215 response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
220 def revision(request, slug, chunk=None):
222 doc = Chunk.get(slug, chunk)
223 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
225 return http.HttpResponse(str(doc.revision()))
228 def book(request, slug):
229 book = get_object_or_404(Book, slug=slug)
231 if request.user.has_perm('catalogue.change_book'):
232 if request.method == "POST":
233 form = forms.BookForm(request.POST, instance=book)
236 return http.HttpResponseRedirect(book.get_absolute_url())
238 form = forms.BookForm(instance=book)
241 form = forms.ReadonlyBookForm(instance=book)
244 task = publishable_error.delay(book)
245 publish_error = task.wait()
246 publishable = publish_error is None
248 return direct_to_template(request, "catalogue/book_detail.html", extra_context={
250 "publishable": publishable,
251 "publishable_error": publish_error,
253 "editable": editable,
257 @permission_required('catalogue.add_chunk')
258 def chunk_add(request, slug, chunk):
260 doc = Chunk.get(slug, chunk)
261 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
264 if request.method == "POST":
265 form = forms.ChunkAddForm(request.POST, instance=doc)
267 if request.user.is_authenticated():
268 creator = request.user
271 doc.split(creator=creator,
272 slug=form.cleaned_data['slug'],
273 title=form.cleaned_data['title'],
276 return http.HttpResponseRedirect(doc.book.get_absolute_url())
278 form = forms.ChunkAddForm(initial={
279 "slug": str(doc.number + 1),
280 "title": "cz. %d" % (doc.number + 1, ),
283 return direct_to_template(request, "catalogue/chunk_add.html", extra_context={
289 def chunk_edit(request, slug, chunk):
291 doc = Chunk.get(slug, chunk)
292 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
294 if request.method == "POST":
295 form = forms.ChunkForm(request.POST, instance=doc)
298 go_next = request.GET.get('next', None)
300 go_next = urlquote_plus(unquote(iri_to_uri(go_next)), safe='/?=&')
302 go_next = doc.book.get_absolute_url()
303 return http.HttpResponseRedirect(go_next)
305 form = forms.ChunkForm(instance=doc)
307 parts = urlsplit(request.META['HTTP_REFERER'])
308 parts = ['', ''] + list(parts[2:])
309 go_next = urlquote_plus(urlunsplit(parts))
311 return direct_to_template(request, "catalogue/chunk_edit.html", extra_context={
318 @permission_required('catalogue.change_book')
319 def book_append(request, slug):
320 book = get_object_or_404(Book, slug=slug)
321 if request.method == "POST":
322 form = forms.BookAppendForm(book, request.POST)
324 append_to = form.cleaned_data['append_to']
325 append_to.append(book)
326 return http.HttpResponseRedirect(append_to.get_absolute_url())
328 form = forms.BookAppendForm(book)
329 return direct_to_template(request, "catalogue/book_append_to.html", extra_context={
339 def publish(request, slug):
340 book = get_object_or_404(Book, slug=slug)
342 book.publish(request.user)
343 except NotAuthorizedError:
344 return http.HttpResponseRedirect(reverse('apiclient_oauth'))
345 except BaseException, e:
346 return http.HttpResponse(e)
348 return http.HttpResponseRedirect(book.get_absolute_url())