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