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