filebrowser csrf issues fix
[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.create(
92                 text=form.cleaned_data['text'],
93                 creator=creator,
94                 slug=form.cleaned_data['slug'],
95                 title=form.cleaned_data['title'],
96             )
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 = Book.create(
151                         text=zip.read(filename).decode('utf-8'),
152                         creator=creator,
153                         slug=slug,
154                         title=title,
155                     )
156
157             return direct_to_template(request, "catalogue/document_upload.html", extra_context={
158                 "form": form,
159                 "ok_list": ok_list,
160                 "skipped_list": skipped_list,
161                 "error_list": error_list,
162             })
163     else:
164         form = forms.DocumentsUploadForm()
165
166     return direct_to_template(request, "catalogue/document_upload.html", extra_context={
167         "form": form,
168     })
169
170
171 @never_cache
172 def book_xml(request, slug):
173     xml = get_object_or_404(Book, slug=slug).materialize()
174
175     response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
176     response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
177     return response
178
179
180 @never_cache
181 def book_txt(request, slug):
182     xml = get_object_or_404(Book, slug=slug).materialize()
183     output = StringIO()
184     # errors?
185     librarian.text.transform(StringIO(xml), output)
186     text = output.getvalue()
187     response = http.HttpResponse(text, content_type='text/plain', mimetype='text/plain')
188     response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
189     return response
190
191
192 @never_cache
193 def book_html(request, slug):
194     xml = get_object_or_404(Book, slug=slug).materialize()
195     output = StringIO()
196     # errors?
197     librarian.html.transform(StringIO(xml), output, parse_dublincore=False,
198                              flags=['full-page'])
199     html = output.getvalue()
200     response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
201     return response
202
203
204 @never_cache
205 def revision(request, slug, chunk=None):
206     try:
207         doc = Chunk.get(slug, chunk)
208     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
209         raise Http404
210     return http.HttpResponse(str(doc.revision()))
211
212
213 def book(request, slug):
214     book = get_object_or_404(Book, slug=slug)
215
216     # TODO: most of this should go somewhere else
217
218     # do we need some automation?
219     first_master = None
220     chunks = []
221     need_fixing = False
222     choose_master = False
223
224     length = book.chunk_set.count()
225     for i, chunk in enumerate(book):
226         chunk_dict = {
227             "chunk": chunk,
228             "fix": [],
229             "grade": ""
230             }
231         graded = xml_tools.GradedText(chunk.materialize())
232         if graded.is_wl():
233             master = graded.master()
234             if first_master is None:
235                 first_master = master
236             elif master != first_master:
237                 chunk_dict['fix'].append('bad-master')
238
239             if i > 0 and not graded.has_trim_begin():
240                 chunk_dict['fix'].append('trim-begin')
241             if i < length - 1 and not graded.has_trim_end():
242                 chunk_dict['fix'].append('trim-end')
243
244             if chunk_dict['fix']:
245                 chunk_dict['grade'] = 'wl-fix'
246             else:
247                 chunk_dict['grade'] = 'wl'
248
249         elif graded.is_broken_wl():
250             chunk_dict['grade'] = 'wl-broken'
251         elif graded.is_xml():
252             chunk_dict['grade'] = 'xml'
253         else:
254             chunk_dict['grade'] = 'plain'
255             chunk_dict['fix'].append('wl')
256             choose_master = True
257
258         if chunk_dict['fix']:
259             need_fixing = True
260         chunks.append(chunk_dict)
261
262     if first_master or not need_fixing:
263         choose_master = False
264
265     if request.method == "POST":
266         form = forms.ChooseMasterForm(request.POST)
267         if not choose_master or form.is_valid():
268             if choose_master:
269                 first_master = form.cleaned_data['master']
270
271             # do the actual fixing
272             for c in chunks:
273                 if not c['fix']:
274                     continue
275
276                 text = c['chunk'].materialize()
277                 for fix in c['fix']:
278                     if fix == 'bad-master':
279                         text = xml_tools.change_master(text, first_master)
280                     elif fix == 'trim-begin':
281                         text = xml_tools.add_trim_begin(text)
282                     elif fix == 'trim-end':
283                         text = xml_tools.add_trim_end(text)
284                     elif fix == 'wl':
285                         text = xml_tools.basic_structure(text, first_master)
286                 author = request.user if request.user.is_authenticated() else None
287                 description = "auto-fix: " + ", ".join(c['fix'])
288                 c['chunk'].commit(text=text, author=author, 
289                     description=description)
290
291             return http.HttpResponseRedirect(book.get_absolute_url())
292     elif choose_master:
293         form = forms.ChooseMasterForm()
294     else:
295         form = None
296
297     return direct_to_template(request, "catalogue/book_detail.html", extra_context={
298         "book": book,
299         "chunks": chunks,
300         "need_fixing": need_fixing,
301         "choose_master": choose_master,
302         "first_master": first_master,
303         "form": form,
304     })
305
306
307 def chunk_add(request, slug, chunk):
308     try:
309         doc = Chunk.get(slug, chunk)
310     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
311         raise Http404
312
313     if request.method == "POST":
314         form = forms.ChunkAddForm(request.POST, instance=doc)
315         if form.is_valid():
316             if request.user.is_authenticated():
317                 creator = request.user
318             else:
319                 creator = None
320             doc.split(creator=creator,
321                 slug=form.cleaned_data['slug'],
322                 title=form.cleaned_data['title'],
323             )
324
325             return http.HttpResponseRedirect(doc.book.get_absolute_url())
326     else:
327         form = forms.ChunkAddForm(initial={
328                 "slug": str(doc.number + 1),
329                 "title": "cz. %d" % (doc.number + 1, ),
330         })
331
332     return direct_to_template(request, "catalogue/chunk_add.html", extra_context={
333         "chunk": doc,
334         "form": form,
335     })
336
337
338 def chunk_edit(request, slug, chunk):
339     try:
340         doc = Chunk.get(slug, chunk)
341     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
342         raise Http404
343     if request.method == "POST":
344         form = forms.ChunkForm(request.POST, instance=doc)
345         if form.is_valid():
346             form.save()
347             return http.HttpResponseRedirect(doc.book.get_absolute_url())
348     else:
349         form = forms.ChunkForm(instance=doc)
350     return direct_to_template(request, "catalogue/chunk_edit.html", extra_context={
351         "chunk": doc,
352         "form": form,
353     })
354
355
356 def book_append(request, slug):
357     book = get_object_or_404(Book, slug=slug)
358     if request.method == "POST":
359         form = forms.BookAppendForm(request.POST)
360         if form.is_valid():
361             append_to = form.cleaned_data['append_to']
362             append_to.append(book)
363             return http.HttpResponseRedirect(append_to.get_absolute_url())
364     else:
365         form = forms.BookAppendForm()
366     return direct_to_template(request, "catalogue/book_append_to.html", extra_context={
367         "book": book,
368         "form": form,
369     })
370
371
372 def book_edit(request, slug):
373     book = get_object_or_404(Book, slug=slug)
374     if request.method == "POST":
375         form = forms.BookForm(request.POST, instance=book)
376         if form.is_valid():
377             form.save()
378             return http.HttpResponseRedirect(book.get_absolute_url())
379     else:
380         form = forms.BookForm(instance=book)
381     return direct_to_template(request, "catalogue/book_edit.html", extra_context={
382         "book": book,
383         "form": form,
384     })
385
386
387 @require_POST
388 @login_required
389 def publish(request, slug):
390     book = get_object_or_404(Book, slug=slug)
391     try:
392         book.publish(request.user)
393     except BaseException, e:
394         return http.HttpResponse(e)
395     else:
396         return http.HttpResponseRedirect(book.get_absolute_url())