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