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