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