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 import xml_tools
33 # Quick hack around caching problems, TODO: use ETags
35 from django.views.decorators.cache import never_cache
37 logger = logging.getLogger("fnp.catalogue")
42 def document_list(request):
43 return render(request, 'catalogue/document_list.html')
47 def user(request, username):
48 user = get_object_or_404(User, username=username)
49 return render(request, 'catalogue/user_page.html', {"viewed_user": user})
56 return render(request, 'catalogue/my_page.html', {
57 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
58 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):
72 return render(request, 'catalogue/activity.html')
76 def logout_then_redirect(request):
78 return http.HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
81 @permission_required('catalogue.add_book')
83 def create_missing(request, slug=None):
86 slug = slug.replace(' ', '-')
88 if request.method == "POST":
89 form = forms.DocumentCreateForm(request.POST, request.FILES)
92 if request.user.is_authenticated():
93 creator = request.user
97 text=form.cleaned_data['text'],
99 slug=form.cleaned_data['slug'],
100 title=form.cleaned_data['title'],
103 return http.HttpResponseRedirect(reverse("wiki_editor", args=[book.slug]))
105 form = forms.DocumentCreateForm(initial={
107 "title": slug.replace('-', ' ').title(),
110 return direct_to_template(request, "catalogue/document_create_missing.html", extra_context={
116 @permission_required('catalogue.add_book')
117 @active_tab('upload')
119 if request.method == "POST":
120 form = forms.DocumentsUploadForm(request.POST, request.FILES)
124 if request.user.is_authenticated():
125 creator = request.user
129 zip = form.cleaned_data['zip']
134 existing = [book.slug for book in Book.objects.all()]
135 for filename in zip.namelist():
136 if filename[-1] == '/':
138 title = os.path.basename(filename)[:-4]
139 slug = slughifi(title)
140 if not (slug and filename.endswith('.xml')):
141 skipped_list.append(filename)
143 error_list.append((filename, slug, _('Slug already used for %s' % slugs[slug])))
144 elif slug in existing:
145 error_list.append((filename, slug, _('Slug already used in repository.')))
148 zip.read(filename).decode('utf-8') # test read
149 ok_list.append((filename, slug, title))
150 except UnicodeDecodeError:
151 error_list.append((filename, title, _('File should be UTF-8 encoded.')))
152 slugs[slug] = filename
155 for filename, slug, title in ok_list:
157 text=zip.read(filename).decode('utf-8'),
163 return direct_to_template(request, "catalogue/document_upload.html", extra_context={
166 "skipped_list": skipped_list,
167 "error_list": error_list,
170 form = forms.DocumentsUploadForm()
172 return direct_to_template(request, "catalogue/document_upload.html", extra_context={
178 def book_xml(request, slug):
179 xml = get_object_or_404(Book, slug=slug).materialize()
181 response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
182 response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
187 def book_txt(request, slug):
188 xml = get_object_or_404(Book, slug=slug).materialize()
191 librarian.text.transform(StringIO(xml), output)
192 text = output.getvalue()
193 response = http.HttpResponse(text, content_type='text/plain', mimetype='text/plain')
194 response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
199 def book_html(request, slug):
200 xml = get_object_or_404(Book, slug=slug).materialize()
203 librarian.html.transform(StringIO(xml), output, parse_dublincore=False,
205 html = output.getvalue()
206 response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
211 def revision(request, slug, chunk=None):
213 doc = Chunk.get(slug, chunk)
214 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
216 return http.HttpResponse(str(doc.revision()))
219 def book(request, slug):
220 book = get_object_or_404(Book, slug=slug)
222 if request.user.has_perm('catalogue.change_book'):
223 if request.method == "POST":
224 form = forms.BookForm(request.POST, instance=book)
227 return http.HttpResponseRedirect(book.get_absolute_url())
229 form = forms.BookForm(instance=book)
232 form = forms.ReadonlyBookForm(instance=book)
237 book.assert_publishable()
238 except AssertionError, e:
240 publishable_error = e
243 publishable_error = None
245 return direct_to_template(request, "catalogue/book_detail.html", extra_context={
247 "publishable": publishable,
248 "publishable_error": publishable_error,
250 "editable": editable,
254 @permission_required('catalogue.add_chunk')
255 def chunk_add(request, slug, chunk):
257 doc = Chunk.get(slug, chunk)
258 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
261 if request.method == "POST":
262 form = forms.ChunkAddForm(request.POST, instance=doc)
264 if request.user.is_authenticated():
265 creator = request.user
268 doc.split(creator=creator,
269 slug=form.cleaned_data['slug'],
270 title=form.cleaned_data['title'],
273 return http.HttpResponseRedirect(doc.book.get_absolute_url())
275 form = forms.ChunkAddForm(initial={
276 "slug": str(doc.number + 1),
277 "title": "cz. %d" % (doc.number + 1, ),
280 return direct_to_template(request, "catalogue/chunk_add.html", extra_context={
286 def chunk_edit(request, slug, chunk):
288 doc = Chunk.get(slug, chunk)
289 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
291 if request.method == "POST":
292 form = forms.ChunkForm(request.POST, instance=doc)
295 go_next = request.GET.get('next', None)
297 go_next = urlquote_plus(unquote(iri_to_uri(go_next)), safe='/?=&')
299 go_next = doc.book.get_absolute_url()
300 return http.HttpResponseRedirect(go_next)
302 form = forms.ChunkForm(instance=doc)
304 parts = urlsplit(request.META['HTTP_REFERER'])
305 parts = ['', ''] + list(parts[2:])
306 go_next = urlquote_plus(urlunsplit(parts))
308 return direct_to_template(request, "catalogue/chunk_edit.html", extra_context={
315 @permission_required('catalogue.change_book')
316 def book_append(request, slug):
317 book = get_object_or_404(Book, slug=slug)
318 if request.method == "POST":
319 form = forms.BookAppendForm(book, request.POST)
321 append_to = form.cleaned_data['append_to']
322 append_to.append(book)
323 return http.HttpResponseRedirect(append_to.get_absolute_url())
325 form = forms.BookAppendForm(book)
326 return direct_to_template(request, "catalogue/book_append_to.html", extra_context={
334 def publish(request, slug):
335 book = get_object_or_404(Book, slug=slug)
337 book.publish(request.user)
338 except NotAuthorizedError:
339 return http.HttpResponseRedirect(reverse('apiclient_oauth'))
340 except BaseException, e:
341 return http.HttpResponse(e)
343 return http.HttpResponseRedirect(book.get_absolute_url())