#1230: german quotes in special chas
[redakcja.git] / apps / wiki / views.py
1 import os
2 import functools
3 import logging
4 logger = logging.getLogger("fnp.wiki")
5
6 from django.conf import settings
7
8 from django.views.generic.simple import direct_to_template
9 from django.views.decorators.http import require_POST, require_GET
10 from django.core.urlresolvers import reverse
11 from wiki.helpers import (JSONResponse, JSONFormInvalid, JSONServerError,
12                 ajax_require_permission, recursive_groupby)
13 from django import http
14
15 from wiki.models import getstorage, DocumentNotFound, normalize_name, split_name, join_name, Theme
16 from wiki.forms import DocumentTextSaveForm, DocumentTextRevertForm, DocumentTagForm, DocumentCreateForm, DocumentsUploadForm
17 from datetime import datetime
18 from django.utils.encoding import smart_unicode
19 from django.utils.translation import ugettext_lazy as _
20 from django.utils.decorators import decorator_from_middleware
21 from django.middleware.gzip import GZipMiddleware
22
23
24 #
25 # Quick hack around caching problems, TODO: use ETags
26 #
27 from django.views.decorators.cache import never_cache
28
29 import wlapi
30 import nice_diff
31 import operator
32
33 MAX_LAST_DOCS = 10
34
35
36 def normalized_name(view):
37
38     @functools.wraps(view)
39     def decorated(request, name, *args):
40         normalized = normalize_name(name)
41         logger.debug('View check %r -> %r', name, normalized)
42
43         if normalized != name:
44             return http.HttpResponseRedirect(
45                         reverse('wiki_' + view.__name__, kwargs={'name': normalized}))
46
47         return view(request, name, *args)
48
49     return decorated
50
51
52 @never_cache
53 def document_list(request):
54     return direct_to_template(request, 'wiki/document_list.html', extra_context={
55         'docs': getstorage().all(),
56         'last_docs': sorted(request.session.get("wiki_last_docs", {}).items(),
57                         key=operator.itemgetter(1), reverse=True),
58     })
59
60
61 @never_cache
62 @normalized_name
63 def editor(request, name, template_name='wiki/document_details.html'):
64     storage = getstorage()
65
66     try:
67         document = storage.get(name)
68     except DocumentNotFound:
69         return http.HttpResponseRedirect(reverse("wiki_create_missing", args=[name]))
70
71     access_time = datetime.now()
72     last_documents = request.session.get("wiki_last_docs", {})
73     last_documents[name] = access_time
74
75     if len(last_documents) > MAX_LAST_DOCS:
76         oldest_key = min(last_documents, key=last_documents.__getitem__)
77         del last_documents[oldest_key]
78     request.session['wiki_last_docs'] = last_documents
79
80     return direct_to_template(request, template_name, extra_context={
81         'document': document,
82         'document_name': document.name,
83         'document_info': document.info,
84         'document_meta': document.meta,
85         'forms': {
86             "text_save": DocumentTextSaveForm(prefix="textsave"),
87             "text_revert": DocumentTextRevertForm(prefix="textrevert"),
88             "add_tag": DocumentTagForm(prefix="addtag"),
89         },
90         'REDMINE_URL': settings.REDMINE_URL,
91     })
92
93
94 @require_GET
95 @normalized_name
96 def editor_readonly(request, name, template_name='wiki/document_details_readonly.html'):
97     name = normalize_name(name)
98     storage = getstorage()
99
100     try:
101         revision = request.GET['revision']
102         document = storage.get(name, revision)
103     except (KeyError, DocumentNotFound):
104         raise http.Http404
105
106     access_time = datetime.now()
107     last_documents = request.session.get("wiki_last_docs", {})
108     last_documents[name] = access_time
109
110     if len(last_documents) > MAX_LAST_DOCS:
111         oldest_key = min(last_documents, key=last_documents.__getitem__)
112         del last_documents[oldest_key]
113     request.session['wiki_last_docs'] = last_documents
114
115     return direct_to_template(request, template_name, extra_context={
116         'document': document,
117         'document_name': document.name,
118         'document_info': dict(document.info(), readonly=True),
119         'document_meta': document.meta,
120         'REDMINE_URL': settings.REDMINE_URL,
121     })
122
123
124 @normalized_name
125 def create_missing(request, name):
126     storage = getstorage()
127
128     if request.method == "POST":
129         form = DocumentCreateForm(request.POST, request.FILES)
130         if form.is_valid():
131             doc = storage.create_document(
132                 name=form.cleaned_data['id'],
133                 text=form.cleaned_data['text'],
134             )
135
136             return http.HttpResponseRedirect(reverse("wiki_editor", args=[doc.name]))
137     else:
138         form = DocumentCreateForm(initial={
139                 "id": name.replace(" ", "_"),
140                 "title": name.title(),
141         })
142
143     return direct_to_template(request, "wiki/document_create_missing.html", extra_context={
144         "document_name": name,
145         "form": form,
146     })
147
148
149 def upload(request):
150     storage = getstorage()
151
152     if request.method == "POST":
153         form = DocumentsUploadForm(request.POST, request.FILES)
154         if form.is_valid():
155             zip = form.cleaned_data['zip']
156             skipped_list = []
157             ok_list = []
158             error_list = []
159             titles = {}
160             existing = storage.all()
161             for filename in zip.namelist():
162                 if filename[-1] == '/':
163                     continue
164                 title = normalize_name(os.path.basename(filename)[:-4])
165                 if not (title and filename.endswith('.xml')):
166                     skipped_list.append(filename)
167                 elif title in titles:
168                     error_list.append((filename, title, _('Title already used for %s' % titles[title])))
169                 elif title in existing:
170                     error_list.append((filename, title, _('Title already used in repository.')))
171                 else:
172                     try:
173                         zip.read(filename).decode('utf-8') # test read
174                         ok_list.append((filename, title))
175                     except UnicodeDecodeError:
176                         error_list.append((filename, title, _('File should be UTF-8 encoded.')))
177                     titles[title] = filename
178
179             if not error_list:
180                 for filename, title in ok_list:
181                     storage.create_document(
182                         name=title,
183                         text=zip.read(filename).decode('utf-8')
184                     )
185
186             return direct_to_template(request, "wiki/document_upload.html", extra_context={
187                 "form": form,
188                 "ok_list": ok_list,
189                 "skipped_list": skipped_list,
190                 "error_list": error_list,
191             })
192                 #doc = storage.create_document(
193                 #    name=base,
194                 #    text=form.cleaned_data['text'],
195
196             
197             return http.HttpResponse('\n'.join(yeslist) + '\n\n' + '\n'.join(nolist))
198     else:
199         form = DocumentsUploadForm()
200
201     return direct_to_template(request, "wiki/document_upload.html", extra_context={
202         "form": form,
203     })
204
205
206 @never_cache
207 @normalized_name
208 @decorator_from_middleware(GZipMiddleware)
209 def text(request, name):
210     storage = getstorage()
211
212     if request.method == 'POST':
213         form = DocumentTextSaveForm(request.POST, prefix="textsave")
214         if form.is_valid():
215             revision = form.cleaned_data['parent_revision']
216             document = storage.get_or_404(name, revision)          
217             document.text = form.cleaned_data['text']
218             comment = form.cleaned_data['comment']
219             if form.cleaned_data['stage_completed']:        
220                 comment += '\n#stage-finished: %s\n' % form.cleaned_data['stage_completed']         
221             if request.user.is_authenticated():
222                 author_name = request.user
223                 author_email = request.user.email
224             else:
225                 author_name = form.cleaned_data['author_name']
226                 author_email = form.cleaned_data['author_email']
227             author = "%s <%s>" % (author_name, author_email)
228             storage.put(document, author=author, comment=comment, parent=revision)           
229             document = storage.get(name)          
230             return JSONResponse({
231                 'text': document.plain_text if revision != document.revision else None,
232                 'meta': document.meta(),
233                 'revision': document.revision,
234             })
235         else:
236             return JSONFormInvalid(form)
237     else:
238         revision = request.GET.get("revision", None)
239
240         try:
241             try:
242                 revision = revision and int(revision)
243                 logger.info("Fetching %s", revision)
244                 document = storage.get(name, revision)
245             except ValueError:
246                 # treat as a tag
247                 logger.info("Fetching tag %s", revision)
248                 document = storage.get_by_tag(name, revision)
249         except DocumentNotFound:
250             raise http.Http404
251
252         return JSONResponse({
253             'text': document.plain_text,
254             'meta': document.meta(),
255             'revision': document.revision,
256         })
257
258
259 @never_cache
260 @normalized_name
261 @require_POST
262 def revert(request, name):
263     storage = getstorage()
264     form = DocumentTextRevertForm(request.POST, prefix="textrevert")
265     if form.is_valid():
266         print 'valid'
267         revision = form.cleaned_data['revision']
268
269         comment = form.cleaned_data['comment']
270         comment += "\n#revert to %s" % revision
271
272         if request.user.is_authenticated():
273             author_name = request.user
274             author_email = request.user.email
275         else:
276             author_name = form.cleaned_data['author_name']
277             author_email = form.cleaned_data['author_email']
278         author = "%s <%s>" % (author_name, author_email)
279
280         before = storage.get(name).revision
281         logger.info("Reverting %s to %s", name, revision)
282         storage.revert(name, revision, comment=comment, author=author)
283         logger.info("Fetching %s", name)
284         document = storage.get(name)
285
286
287         return JSONResponse({
288             'text': document.plain_text if before != document.revision else None,
289             'meta': document.meta(),
290             'revision': document.revision,
291         })
292     else:
293         print 'invalid'
294         return JSONFormInvalid(form)
295
296
297 @never_cache
298 def gallery(request, directory):
299     try:
300         base_url = ''.join((
301                         smart_unicode(settings.MEDIA_URL),
302                         smart_unicode(settings.FILEBROWSER_DIRECTORY),
303                         smart_unicode(directory)))
304
305         base_dir = os.path.join(
306                     smart_unicode(settings.MEDIA_ROOT),
307                     smart_unicode(settings.FILEBROWSER_DIRECTORY),
308                     smart_unicode(directory))
309
310         def map_to_url(filename):
311             return "%s/%s" % (base_url, smart_unicode(filename))
312
313         def is_image(filename):
314             return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
315
316         images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
317         images.sort()
318         return JSONResponse(images)
319     except (IndexError, OSError):
320         logger.exception("Unable to fetch gallery")
321         raise http.Http404
322
323
324 @never_cache
325 @normalized_name
326 def diff(request, name):
327     storage = getstorage()
328
329     revA = int(request.GET.get('from', 0))
330     revB = int(request.GET.get('to', 0))
331
332     if revA > revB:
333         revA, revB = revB, revA
334
335     if revB == 0:
336         revB = None
337
338     docA = storage.get_or_404(name, int(revA))
339     docB = storage.get_or_404(name, int(revB))
340
341     return http.HttpResponse(nice_diff.html_diff_table(docA.plain_text.splitlines(),
342                                          docB.plain_text.splitlines(), context=3))
343
344
345 @never_cache
346 @normalized_name
347 def revision(request, name):
348     storage = getstorage()
349
350     try:
351         return http.HttpResponse(str(storage.doc_meta(name)['revision']))
352     except DocumentNotFound:
353         raise http.Http404
354
355
356 @never_cache
357 @normalized_name
358 def history(request, name):
359     storage = getstorage()
360
361     # TODO: pagination
362     changesets = list(storage.history(name))
363
364     return JSONResponse(changesets)
365
366
367 @require_POST
368 @ajax_require_permission('wiki.can_change_tags')
369 def add_tag(request, name):
370     name = normalize_name(name)
371     storage = getstorage()
372
373     form = DocumentTagForm(request.POST, prefix="addtag")
374     if form.is_valid():
375         doc = storage.get_or_404(form.cleaned_data['id'])
376         doc.add_tag(tag=form.cleaned_data['tag'],
377                     revision=form.cleaned_data['revision'],
378                     author=request.user.username)
379         return JSONResponse({"message": _("Tag added")})
380     else:
381         return JSONFormInvalid(form)
382
383
384 @require_POST
385 @ajax_require_permission('wiki.can_publish')
386 def publish(request, name):
387     name = normalize_name(name)
388
389     storage = getstorage()
390     document = storage.get_by_tag(name, "ready_to_publish")
391
392     api = wlapi.WLAPI(**settings.WL_API_CONFIG)
393
394     try:
395         return JSONResponse({"result": api.publish_book(document)})
396     except wlapi.APICallException, e:
397         return JSONServerError({"message": str(e)})
398
399
400 def themes(request):
401     prefix = request.GET.get('q', '')
402     return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))