cac1bd2b1e4979ced593638773828861194b4e34
[redakcja.git] / apps / catalogue / views.py
1 from datetime import datetime
2 import logging
3 import os
4 from StringIO import StringIO
5 from urllib import unquote
6 from urlparse import urlsplit, urlunsplit
7
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
21
22 import librarian.html
23 import librarian.text
24
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
31
32 #
33 # Quick hack around caching problems, TODO: use ETags
34 #
35 from django.views.decorators.cache import never_cache
36
37 logger = logging.getLogger("fnp.catalogue")
38
39
40 @active_tab('all')
41 @never_cache
42 def document_list(request):
43     return render(request, 'catalogue/document_list.html')
44
45
46 @never_cache
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})
50
51
52 @login_required
53 @active_tab('my')
54 @never_cache
55 def my(request):
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),
59         })
60
61
62 @active_tab('users')
63 def users(request):
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'),
67     })
68
69
70 @active_tab('activity')
71 def activity(request):
72     return render(request, 'catalogue/activity.html')
73
74
75 @never_cache
76 def logout_then_redirect(request):
77     auth.logout(request)
78     return http.HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
79
80
81 @permission_required('catalogue.add_book')
82 @active_tab('create')
83 def create_missing(request, slug=None):
84     if slug is None:
85         slug = ''
86     slug = slug.replace(' ', '-')
87
88     if request.method == "POST":
89         form = forms.DocumentCreateForm(request.POST, request.FILES)
90         if form.is_valid():
91             
92             if request.user.is_authenticated():
93                 creator = request.user
94             else:
95                 creator = None
96             book = Book.create(
97                 text=form.cleaned_data['text'],
98                 creator=creator,
99                 slug=form.cleaned_data['slug'],
100                 title=form.cleaned_data['title'],
101             )
102
103             return http.HttpResponseRedirect(reverse("wiki_editor", args=[book.slug]))
104     else:
105         form = forms.DocumentCreateForm(initial={
106                 "slug": slug,
107                 "title": slug.replace('-', ' ').title(),
108         })
109
110     return direct_to_template(request, "catalogue/document_create_missing.html", extra_context={
111         "slug": slug,
112         "form": form,
113     })
114
115
116 @permission_required('catalogue.add_book')
117 @active_tab('upload')
118 def upload(request):
119     if request.method == "POST":
120         form = forms.DocumentsUploadForm(request.POST, request.FILES)
121         if form.is_valid():
122             import slughifi
123
124             if request.user.is_authenticated():
125                 creator = request.user
126             else:
127                 creator = None
128
129             zip = form.cleaned_data['zip']
130             skipped_list = []
131             ok_list = []
132             error_list = []
133             slugs = {}
134             existing = [book.slug for book in Book.objects.all()]
135             for filename in zip.namelist():
136                 if filename[-1] == '/':
137                     continue
138                 title = os.path.basename(filename)[:-4]
139                 slug = slughifi(title)
140                 if not (slug and filename.endswith('.xml')):
141                     skipped_list.append(filename)
142                 elif slug in slugs:
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.')))
146                 else:
147                     try:
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
153
154             if not error_list:
155                 for filename, slug, title in ok_list:
156                     book = Book.create(
157                         text=zip.read(filename).decode('utf-8'),
158                         creator=creator,
159                         slug=slug,
160                         title=title,
161                     )
162
163             return direct_to_template(request, "catalogue/document_upload.html", extra_context={
164                 "form": form,
165                 "ok_list": ok_list,
166                 "skipped_list": skipped_list,
167                 "error_list": error_list,
168             })
169     else:
170         form = forms.DocumentsUploadForm()
171
172     return direct_to_template(request, "catalogue/document_upload.html", extra_context={
173         "form": form,
174     })
175
176
177 @never_cache
178 def book_xml(request, slug):
179     xml = get_object_or_404(Book, slug=slug).materialize()
180
181     response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
182     response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
183     return response
184
185
186 @never_cache
187 def book_txt(request, slug):
188     xml = get_object_or_404(Book, slug=slug).materialize()
189     output = StringIO()
190     # errors?
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
195     return response
196
197
198 @never_cache
199 def book_html(request, slug):
200     xml = get_object_or_404(Book, slug=slug).materialize()
201     output = StringIO()
202     # errors?
203     librarian.html.transform(StringIO(xml), output, parse_dublincore=False,
204                              flags=['full-page'])
205     html = output.getvalue()
206     response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
207     return response
208
209
210 @never_cache
211 def revision(request, slug, chunk=None):
212     try:
213         doc = Chunk.get(slug, chunk)
214     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
215         raise Http404
216     return http.HttpResponse(str(doc.revision()))
217
218
219 def book(request, slug):
220     book = get_object_or_404(Book, slug=slug)
221
222     # TODO: most of this should go somewhere else
223
224     # do we need some automation?
225     first_master = None
226     chunks = []
227     need_fixing = False
228     choose_master = False
229
230     length = book.chunk_set.count()
231     for i, chunk in enumerate(book):
232         chunk_dict = {
233             "chunk": chunk,
234             "fix": [],
235             "grade": ""
236             }
237         graded = xml_tools.GradedText(chunk.materialize())
238         if graded.is_wl():
239             master = graded.master()
240             if first_master is None:
241                 first_master = master
242             elif master != first_master:
243                 chunk_dict['fix'].append('bad-master')
244
245             if i > 0 and not graded.has_trim_begin():
246                 chunk_dict['fix'].append('trim-begin')
247             if i < length - 1 and not graded.has_trim_end():
248                 chunk_dict['fix'].append('trim-end')
249
250             if chunk_dict['fix']:
251                 chunk_dict['grade'] = 'wl-fix'
252             else:
253                 chunk_dict['grade'] = 'wl'
254
255         elif graded.is_broken_wl():
256             chunk_dict['grade'] = 'wl-broken'
257         elif graded.is_xml():
258             chunk_dict['grade'] = 'xml'
259         else:
260             chunk_dict['grade'] = 'plain'
261             chunk_dict['fix'].append('wl')
262             choose_master = True
263
264         if chunk_dict['fix']:
265             need_fixing = True
266         chunks.append(chunk_dict)
267
268     if first_master or not need_fixing:
269         choose_master = False
270
271     if request.method == "POST":
272         form = forms.ChooseMasterForm(request.POST)
273         if not choose_master or form.is_valid():
274             if choose_master:
275                 first_master = form.cleaned_data['master']
276
277             # do the actual fixing
278             for c in chunks:
279                 if not c['fix']:
280                     continue
281
282                 text = c['chunk'].materialize()
283                 for fix in c['fix']:
284                     if fix == 'bad-master':
285                         text = xml_tools.change_master(text, first_master)
286                     elif fix == 'trim-begin':
287                         text = xml_tools.add_trim_begin(text)
288                     elif fix == 'trim-end':
289                         text = xml_tools.add_trim_end(text)
290                     elif fix == 'wl':
291                         text = xml_tools.basic_structure(text, first_master)
292                 author = request.user if request.user.is_authenticated() else None
293                 description = "auto-fix: " + ", ".join(c['fix'])
294                 c['chunk'].commit(text=text, author=author, 
295                     description=description)
296
297             return http.HttpResponseRedirect(book.get_absolute_url())
298     elif choose_master:
299         form = forms.ChooseMasterForm()
300     else:
301         form = None
302
303     try:
304         book.assert_publishable()
305     except AssertionError, e:
306         publishable = False
307         publishable_error = e
308     else:
309         publishable = True
310         publishable_error = None
311
312     return direct_to_template(request, "catalogue/book_detail.html", extra_context={
313         "book": book,
314         "publishable": publishable,
315         "publishable_error": publishable_error,
316         "chunks": chunks,
317         "need_fixing": need_fixing,
318         "choose_master": choose_master,
319         "first_master": first_master,
320         "form": form,
321     })
322
323
324 @permission_required('catalogue.add_chunk')
325 def chunk_add(request, slug, chunk):
326     try:
327         doc = Chunk.get(slug, chunk)
328     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
329         raise Http404
330
331     if request.method == "POST":
332         form = forms.ChunkAddForm(request.POST, instance=doc)
333         if form.is_valid():
334             if request.user.is_authenticated():
335                 creator = request.user
336             else:
337                 creator = None
338             doc.split(creator=creator,
339                 slug=form.cleaned_data['slug'],
340                 title=form.cleaned_data['title'],
341             )
342
343             return http.HttpResponseRedirect(doc.book.get_absolute_url())
344     else:
345         form = forms.ChunkAddForm(initial={
346                 "slug": str(doc.number + 1),
347                 "title": "cz. %d" % (doc.number + 1, ),
348         })
349
350     return direct_to_template(request, "catalogue/chunk_add.html", extra_context={
351         "chunk": doc,
352         "form": form,
353     })
354
355
356 def chunk_edit(request, slug, chunk):
357     try:
358         doc = Chunk.get(slug, chunk)
359     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
360         raise Http404
361     if request.method == "POST":
362         form = forms.ChunkForm(request.POST, instance=doc)
363         if form.is_valid():
364             form.save()
365             go_next = request.GET.get('next', None)
366             if go_next:
367                 go_next = urlquote_plus(unquote(iri_to_uri(go_next)), safe='/?=&')
368             else:
369                 go_next = doc.book.get_absolute_url()
370             return http.HttpResponseRedirect(go_next)
371     else:
372         form = forms.ChunkForm(instance=doc)
373
374     parts = urlsplit(request.META['HTTP_REFERER'])
375     parts = ['', ''] + list(parts[2:])
376     go_next = urlquote_plus(urlunsplit(parts))
377
378     return direct_to_template(request, "catalogue/chunk_edit.html", extra_context={
379         "chunk": doc,
380         "form": form,
381         "go_next": go_next,
382     })
383
384
385 @permission_required('catalogue.change_book')
386 def book_append(request, slug):
387     book = get_object_or_404(Book, slug=slug)
388     if request.method == "POST":
389         form = forms.BookAppendForm(book, request.POST)
390         if form.is_valid():
391             append_to = form.cleaned_data['append_to']
392             append_to.append(book)
393             return http.HttpResponseRedirect(append_to.get_absolute_url())
394     else:
395         form = forms.BookAppendForm(book)
396     return direct_to_template(request, "catalogue/book_append_to.html", extra_context={
397         "book": book,
398         "form": form,
399     })
400
401
402 @permission_required('catalogue.change_book')
403 def book_edit(request, slug):
404     book = get_object_or_404(Book, slug=slug)
405     if request.method == "POST":
406         form = forms.BookForm(request.POST, instance=book)
407         if form.is_valid():
408             form.save()
409             return http.HttpResponseRedirect(book.get_absolute_url())
410     else:
411         form = forms.BookForm(instance=book)
412     return direct_to_template(request, "catalogue/book_edit.html", extra_context={
413         "book": book,
414         "form": form,
415     })
416
417
418 @require_POST
419 @login_required
420 def publish(request, slug):
421     book = get_object_or_404(Book, slug=slug)
422     try:
423         book.publish(request.user)
424     except NotAuthorizedError:
425         return http.HttpResponseRedirect(reverse('apiclient_oauth'))
426     except BaseException, e:
427         return http.HttpResponse(e)
428     else:
429         return http.HttpResponseRedirect(book.get_absolute_url())