a68fa35d708ec1229290adb59aa6c08cfbeed12b
[redakcja.git] / apps / wiki / views.py
1 import os
2 from StringIO import StringIO
3 import logging
4 logger = logging.getLogger("fnp.wiki")
5
6 from lxml import etree
7
8 from django.conf import settings
9
10 from django.contrib.auth.decorators import login_required
11 from django.views.generic.simple import direct_to_template
12 from django.views.decorators.http import require_POST, require_GET
13 from django.core.urlresolvers import reverse
14 from wiki.helpers import (JSONResponse, JSONFormInvalid, JSONServerError,
15                 ajax_require_permission, recursive_groupby)
16 from django import http
17 from django.shortcuts import get_object_or_404, redirect
18 from django.http import Http404
19
20 from wiki.models import Book, Chunk, Theme
21 from wiki import forms
22 from datetime import datetime
23 from django.utils.encoding import smart_unicode
24 from django.utils.translation import ugettext_lazy as _
25 from django.utils.decorators import decorator_from_middleware
26 from django.middleware.gzip import GZipMiddleware
27
28 import librarian.html
29 import librarian.text
30 from wiki import xml_tools
31 from apiclient import api_call
32
33 #
34 # Quick hack around caching problems, TODO: use ETags
35 #
36 from django.views.decorators.cache import never_cache
37
38 import nice_diff
39 import operator
40
41 MAX_LAST_DOCS = 10
42
43
44 @never_cache
45 def document_list(request):
46     return direct_to_template(request, 'wiki/document_list.html', extra_context={
47         'books': Book.objects.all(),
48         'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
49                         key=lambda x: x[1]['time'], reverse=True),
50     })
51
52
53 @never_cache
54 def editor(request, slug, chunk=None, template_name='wiki/document_details.html'):
55     try:
56         chunk = Chunk.get(slug, chunk)
57     except Chunk.MultipleObjectsReturned:
58         # TODO: choice page
59         raise Http404
60     except Chunk.DoesNotExist:
61         if chunk is None:
62             try:
63                 book = Book.objects.get(slug=slug)
64             except Book.DoesNotExist:
65                 return http.HttpResponseRedirect(reverse("wiki_create_missing", args=[slug]))
66         else:
67             raise Http404
68
69     access_time = datetime.now()
70     last_books = request.session.get("wiki_last_books", {})
71     last_books[slug, chunk.slug] = {
72         'time': access_time,
73         'title': chunk.pretty_name(),
74         }
75
76     if len(last_books) > MAX_LAST_DOCS:
77         oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
78         del last_books[oldest_key]
79     request.session['wiki_last_books'] = last_books
80
81     return direct_to_template(request, template_name, extra_context={
82         'chunk': chunk,
83         'forms': {
84             "text_save": forms.DocumentTextSaveForm(prefix="textsave"),
85             "text_revert": forms.DocumentTextRevertForm(prefix="textrevert"),
86             "add_tag": forms.DocumentTagForm(prefix="addtag"),
87             "pubmark": forms.DocumentPubmarkForm(prefix="pubmark"),
88         },
89         'REDMINE_URL': settings.REDMINE_URL,
90     })
91
92
93 @require_GET
94 def editor_readonly(request, slug, chunk=None, template_name='wiki/document_details_readonly.html'):
95     try:
96         chunk = Chunk.get(slug, chunk)
97         revision = request.GET['revision']
98     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist, KeyError):
99         raise Http404
100
101     access_time = datetime.now()
102     last_books = request.session.get("wiki_last_books", {})
103     last_books[slug, chunk.slug] = {
104         'time': access_time,
105         'title': chunk.book.title,
106         }
107
108     if len(last_books) > MAX_LAST_DOCS:
109         oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
110         del last_books[oldest_key]
111     request.session['wiki_last_books'] = last_books
112
113     return direct_to_template(request, template_name, extra_context={
114         'chunk': chunk,
115         'revision': revision,
116         'readonly': True,
117         'REDMINE_URL': settings.REDMINE_URL,
118     })
119
120
121 def create_missing(request, slug):
122     slug = slug.replace(' ', '-')
123
124     if request.method == "POST":
125         form = forms.DocumentCreateForm(request.POST, request.FILES)
126         if form.is_valid():
127             
128             if request.user.is_authenticated():
129                 creator = request.user
130             else:
131                 creator = None
132             book = Book.create(creator=creator,
133                 slug=form.cleaned_data['slug'],
134                 title=form.cleaned_data['title'],
135                 text=form.cleaned_data['text'],
136             )
137
138             return http.HttpResponseRedirect(reverse("wiki_editor", args=[book.slug]))
139     else:
140         form = forms.DocumentCreateForm(initial={
141                 "slug": slug,
142                 "title": slug.replace('-', ' ').title(),
143         })
144
145     return direct_to_template(request, "wiki/document_create_missing.html", extra_context={
146         "slug": slug,
147         "form": form,
148     })
149
150
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, "wiki/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, "wiki/document_upload.html", extra_context={
205         "form": form,
206     })
207
208
209 @never_cache
210 @decorator_from_middleware(GZipMiddleware)
211 def text(request, slug, chunk=None):
212     try:
213         doc = Chunk.get(slug, chunk)
214     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
215         raise Http404
216
217     if request.method == 'POST':
218         form = forms.DocumentTextSaveForm(request.POST, prefix="textsave")
219         if form.is_valid():
220             if request.user.is_authenticated():
221                 author = request.user
222             else:
223                 author = None
224             text = form.cleaned_data['text']
225             parent_revision = form.cleaned_data['parent_revision']
226             parent = doc.at_revision(parent_revision)
227             stage = form.cleaned_data['stage_completed']
228             tags = [stage] if stage else []
229             doc.commit(author=author,
230                        text=text,
231                        parent=parent,
232                        description=form.cleaned_data['comment'],
233                        tags=tags,
234                        )
235             revision = doc.revision()
236             return JSONResponse({
237                 'text': doc.materialize() if parent_revision != revision else None,
238                 'meta': {},
239                 'revision': revision,
240             })
241         else:
242             return JSONFormInvalid(form)
243     else:
244         revision = request.GET.get("revision", None)
245         
246         try:
247             revision = int(revision)
248         except (ValueError, TypeError):
249             revision = None
250
251         return JSONResponse({
252             'text': doc.at_revision(revision).materialize(),
253             'meta': {},
254             'revision': revision if revision else doc.revision(),
255         })
256
257
258 @never_cache
259 def book_xml(request, slug):
260     xml = get_object_or_404(Book, slug=slug).materialize()
261
262     response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
263     response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
264     return response
265
266
267 @never_cache
268 def book_txt(request, slug):
269     xml = get_object_or_404(Book, slug=slug).materialize()
270     output = StringIO()
271     # errors?
272     librarian.text.transform(StringIO(xml), output)
273     text = output.getvalue()
274     response = http.HttpResponse(text, content_type='text/plain', mimetype='text/plain')
275     response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
276     return response
277
278
279 @never_cache
280 def book_html(request, slug):
281     xml = get_object_or_404(Book, slug=slug).materialize()
282     output = StringIO()
283     # errors?
284     librarian.html.transform(StringIO(xml), output, parse_dublincore=False,
285                              flags=['full-page'])
286     html = output.getvalue()
287     response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
288     return response
289
290
291 @never_cache
292 @require_POST
293 def revert(request, slug, chunk=None):
294     form = forms.DocumentTextRevertForm(request.POST, prefix="textrevert")
295     if form.is_valid():
296         try:
297             doc = Chunk.get(slug, chunk)
298         except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
299             raise Http404
300
301         revision = form.cleaned_data['revision']
302
303         comment = form.cleaned_data['comment']
304         comment += "\n#revert to %s" % revision
305
306         if request.user.is_authenticated():
307             author = request.user
308         else:
309             author = None
310
311         before = doc.revision()
312         logger.info("Reverting %s to %s", slug, revision)
313         doc.at_revision(revision).revert(author=author, description=comment)
314
315         return JSONResponse({
316             'text': doc.materialize() if before != doc.revision() else None,
317             'meta': {},
318             'revision': doc.revision(),
319         })
320     else:
321         return JSONFormInvalid(form)
322
323
324 @never_cache
325 def gallery(request, directory):
326     try:
327         base_url = ''.join((
328                         smart_unicode(settings.MEDIA_URL),
329                         smart_unicode(settings.FILEBROWSER_DIRECTORY),
330                         smart_unicode(directory)))
331
332         base_dir = os.path.join(
333                     smart_unicode(settings.MEDIA_ROOT),
334                     smart_unicode(settings.FILEBROWSER_DIRECTORY),
335                     smart_unicode(directory))
336
337         def map_to_url(filename):
338             return "%s/%s" % (base_url, smart_unicode(filename))
339
340         def is_image(filename):
341             return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
342
343         images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
344         images.sort()
345         return JSONResponse(images)
346     except (IndexError, OSError):
347         logger.exception("Unable to fetch gallery")
348         raise http.Http404
349
350
351 @never_cache
352 def diff(request, slug, chunk=None):
353     revA = int(request.GET.get('from', 0))
354     revB = int(request.GET.get('to', 0))
355
356     if revA > revB:
357         revA, revB = revB, revA
358
359     if revB == 0:
360         revB = None
361
362     try:
363         doc = Chunk.get(slug, chunk)
364     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
365         raise Http404
366     docA = doc.at_revision(revA).materialize()
367     docB = doc.at_revision(revB).materialize()
368
369     return http.HttpResponse(nice_diff.html_diff_table(docA.splitlines(),
370                                          docB.splitlines(), context=3))
371
372
373 @never_cache
374 def revision(request, slug, chunk=None):
375     try:
376         doc = Chunk.get(slug, chunk)
377     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
378         raise Http404
379     return http.HttpResponse(str(doc.revision()))
380
381
382 @never_cache
383 def history(request, slug, chunk=None):
384     # TODO: pagination
385     try:
386         doc = Chunk.get(slug, chunk)
387     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
388         raise Http404
389
390     changes = []
391     for change in doc.history().order_by('-created_at'):
392         changes.append({
393                 "version": change.revision,
394                 "description": change.description,
395                 "author": change.author_str(),
396                 "date": change.created_at,
397                 "publishable": "Publishable\n" if change.publishable else "",
398                 "tag": ',\n'.join(unicode(tag) for tag in change.tags.all()),
399             })
400     return JSONResponse(changes)
401
402
403 def book(request, slug):
404     book = get_object_or_404(Book, slug=slug)
405
406     # TODO: most of this should go somewhere else
407
408     # do we need some automation?
409     first_master = None
410     chunks = []
411     need_fixing = False
412     choose_master = False
413
414     length = len(book)
415     for i, chunk in enumerate(book):
416         chunk_dict = {
417             "chunk": chunk,
418             "fix": [],
419             "grade": ""
420             }
421         graded = xml_tools.GradedText(chunk.materialize())
422         if graded.is_wl():
423             master = graded.master()
424             if first_master is None:
425                 first_master = master
426             elif master != first_master:
427                 chunk_dict['fix'].append('bad-master')
428
429             if i > 0 and not graded.has_trim_begin():
430                 chunk_dict['fix'].append('trim-begin')
431             if i < length - 1 and not graded.has_trim_end():
432                 chunk_dict['fix'].append('trim-end')
433
434             if chunk_dict['fix']:
435                 chunk_dict['grade'] = 'wl-fix'
436             else:
437                 chunk_dict['grade'] = 'wl'
438
439         elif graded.is_broken_wl():
440             chunk_dict['grade'] = 'wl-broken'
441         elif graded.is_xml():
442             chunk_dict['grade'] = 'xml'
443         else:
444             chunk_dict['grade'] = 'plain'
445             chunk_dict['fix'].append('wl')
446             choose_master = True
447
448         if chunk_dict['fix']:
449             need_fixing = True
450         chunks.append(chunk_dict)
451
452     if first_master or not need_fixing:
453         choose_master = False
454
455     if request.method == "POST":
456         form = forms.ChooseMasterForm(request.POST)
457         if not choose_master or form.is_valid():
458             if choose_master:
459                 first_master = form.cleaned_data['master']
460
461             # do the actual fixing
462             for c in chunks:
463                 if not c['fix']:
464                     continue
465
466                 text = c['chunk'].materialize()
467                 for fix in c['fix']:
468                     if fix == 'bad-master':
469                         text = xml_tools.change_master(text, first_master)
470                     elif fix == 'trim-begin':
471                         text = xml_tools.add_trim_begin(text)
472                     elif fix == 'trim-end':
473                         text = xml_tools.add_trim_end(text)
474                     elif fix == 'wl':
475                         text = xml_tools.basic_structure(text, first_master)
476                 author = request.user if request.user.is_authenticated() else None
477                 description = "auto-fix: " + ", ".join(c['fix'])
478                 c['chunk'].commit(text=text, author=author, 
479                     description=description)
480
481             return http.HttpResponseRedirect(book.get_absolute_url())
482     elif choose_master:
483         form = forms.ChooseMasterForm()
484     else:
485         form = None
486
487     return direct_to_template(request, "wiki/book_detail.html", extra_context={
488         "book": book,
489         "chunks": chunks,
490         "need_fixing": need_fixing,
491         "choose_master": choose_master,
492         "first_master": first_master,
493         "form": form,
494     })
495
496
497 def chunk_add(request, slug, chunk):
498     try:
499         doc = Chunk.get(slug, chunk)
500     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
501         raise Http404
502
503     if request.method == "POST":
504         form = forms.ChunkAddForm(request.POST, instance=doc)
505         if form.is_valid():
506             if request.user.is_authenticated():
507                 creator = request.user
508             else:
509                 creator = None
510             doc.split(creator=creator,
511                 slug=form.cleaned_data['slug'],
512                 comment=form.cleaned_data['comment'],
513             )
514
515             return http.HttpResponseRedirect(doc.book.get_absolute_url())
516     else:
517         form = forms.ChunkAddForm(initial={
518                 "slug": str(doc.number + 1),
519                 "comment": "cz. %d" % (doc.number + 1, ),
520         })
521
522     return direct_to_template(request, "wiki/chunk_add.html", extra_context={
523         "chunk": doc,
524         "form": form,
525     })
526
527
528 def chunk_edit(request, slug, chunk):
529     try:
530         doc = Chunk.get(slug, chunk)
531     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
532         raise Http404
533     if request.method == "POST":
534         form = forms.ChunkForm(request.POST, instance=doc)
535         if form.is_valid():
536             form.save()
537             return http.HttpResponseRedirect(doc.book.get_absolute_url())
538     else:
539         form = forms.ChunkForm(instance=doc)
540     return direct_to_template(request, "wiki/chunk_edit.html", extra_context={
541         "chunk": doc,
542         "form": form,
543     })
544
545
546 def book_append(request, slug):
547     book = get_object_or_404(Book, slug=slug)
548     if request.method == "POST":
549         form = forms.BookAppendForm(request.POST)
550         if form.is_valid():
551             append_to = form.cleaned_data['append_to']
552             append_to.append(book)
553             return http.HttpResponseRedirect(append_to.get_absolute_url())
554     else:
555         form = forms.BookAppendForm()
556     return direct_to_template(request, "wiki/book_append_to.html", extra_context={
557         "book": book,
558         "form": form,
559     })
560
561
562 def book_edit(request, slug):
563     book = get_object_or_404(Book, slug=slug)
564     if request.method == "POST":
565         form = forms.BookForm(request.POST, instance=book)
566         if form.is_valid():
567             form.save()
568             return http.HttpResponseRedirect(book.get_absolute_url())
569     else:
570         form = forms.BookForm(instance=book)
571     return direct_to_template(request, "wiki/book_edit.html", extra_context={
572         "book": book,
573         "form": form,
574     })
575
576
577 @require_POST
578 @ajax_require_permission('wiki.can_change_tags')
579 def add_tag(request, slug, chunk=None):
580     form = forms.DocumentTagForm(request.POST, prefix="addtag")
581     if form.is_valid():
582         try:
583             doc = Chunk.get(slug, chunk)
584         except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
585             raise Http404
586
587         tag = form.cleaned_data['tag']
588         revision = form.cleaned_data['revision']
589         doc.at_revision(revision).tags.add(tag)
590         return JSONResponse({"message": _("Tag added")})
591     else:
592         return JSONFormInvalid(form)
593
594
595 @require_POST
596 @ajax_require_permission('wiki.can_pubmark')
597 def pubmark(request, slug, chunk=None):
598     form = forms.DocumentPubmarkForm(request.POST, prefix="pubmark")
599     if form.is_valid():
600         try:
601             doc = Chunk.get(slug, chunk)
602         except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
603             raise Http404
604
605         revision = form.cleaned_data['revision']
606         publishable = form.cleaned_data['publishable']
607         change = doc.at_revision(revision)
608         print publishable, change.publishable
609         if publishable != change.publishable:
610             change.publishable = publishable
611             change.save()
612             return JSONResponse({"message": _("Revision marked")})
613         else:
614             return JSONResponse({"message": _("Nothing changed")})
615     else:
616         return JSONFormInvalid(form)
617
618
619 @require_POST
620 @login_required
621 def publish(request, slug):
622     book = get_object_or_404(Book, slug=slug)
623     try:
624         ret = api_call(request.user, "books", {"book_xml": book.materialize()})
625     except BaseException, e:
626         return http.HttpResponse(e)
627     else:
628         book.last_published = datetime.now()
629         book.save()
630         return http.HttpResponseRedirect(book.get_absolute_url())
631
632
633 def themes(request):
634     prefix = request.GET.get('q', '')
635     return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))