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