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