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