4348cb85ce344aa3115151e07db2e7efb3ccf9b9
[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, 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             "add_tag": DocumentTagForm(prefix="addtag"),
88         },
89         'REDMINE_URL': settings.REDMINE_URL,
90     })
91
92
93 @require_GET
94 @normalized_name
95 def editor_readonly(request, name, template_name='wiki/document_details_readonly.html'):
96     name = normalize_name(name)
97     storage = getstorage()
98
99     try:
100         revision = request.GET['revision']
101         document = storage.get(name, revision)
102     except (KeyError, DocumentNotFound):
103         raise http.Http404
104
105     access_time = datetime.now()
106     last_documents = request.session.get("wiki_last_docs", {})
107     last_documents[name] = access_time
108
109     if len(last_documents) > MAX_LAST_DOCS:
110         oldest_key = min(last_documents, key=last_documents.__getitem__)
111         del last_documents[oldest_key]
112     request.session['wiki_last_docs'] = last_documents
113
114     return direct_to_template(request, template_name, extra_context={
115         'document': document,
116         'document_name': document.name,
117         'document_info': dict(document.info(), readonly=True),
118         'document_meta': document.meta,
119         'REDMINE_URL': settings.REDMINE_URL,
120     })
121
122
123 @normalized_name
124 def create_missing(request, name):
125     storage = getstorage()
126
127     if request.method == "POST":
128         form = DocumentCreateForm(request.POST, request.FILES)
129         if form.is_valid():
130             doc = storage.create_document(
131                 name=form.cleaned_data['id'],
132                 text=form.cleaned_data['text'],
133             )
134
135             return http.HttpResponseRedirect(reverse("wiki_editor", args=[doc.name]))
136     else:
137         form = DocumentCreateForm(initial={
138                 "id": name.replace(" ", "_"),
139                 "title": name.title(),
140         })
141
142     return direct_to_template(request, "wiki/document_create_missing.html", extra_context={
143         "document_name": name,
144         "form": form,
145     })
146
147
148 def upload(request):
149     storage = getstorage()
150
151     if request.method == "POST":
152         form = DocumentsUploadForm(request.POST, request.FILES)
153         if form.is_valid():
154             zip = form.cleaned_data['zip']
155             skipped_list = []
156             ok_list = []
157             error_list = []
158             titles = {}
159             existing = storage.all()
160             for filename in zip.namelist():
161                 if filename[-1] == '/':
162                     continue
163                 title = normalize_name(os.path.basename(filename)[:-4])
164                 if not (title and filename.endswith('.xml')):
165                     skipped_list.append(filename)
166                 elif title in titles:
167                     error_list.append((filename, title, _('Title already used for %s' % titles[title])))
168                 elif title in existing:
169                     error_list.append((filename, title, _('Title already used in repository.')))
170                 else:
171                     try:
172                         zip.read(filename).decode('utf-8') # test read
173                         ok_list.append((filename, title))
174                     except UnicodeDecodeError:
175                         error_list.append((filename, title, _('File should be UTF-8 encoded.')))
176                     titles[title] = filename
177
178             if not error_list:
179                 for filename, title in ok_list:
180                     storage.create_document(
181                         name=title,
182                         text=zip.read(filename).decode('utf-8')
183                     )
184
185             return direct_to_template(request, "wiki/document_upload.html", extra_context={
186                 "form": form,
187                 "ok_list": ok_list,
188                 "skipped_list": skipped_list,
189                 "error_list": error_list,
190             })
191                 #doc = storage.create_document(
192                 #    name=base,
193                 #    text=form.cleaned_data['text'],
194
195             
196             return http.HttpResponse('\n'.join(yeslist) + '\n\n' + '\n'.join(nolist))
197     else:
198         form = DocumentsUploadForm()
199
200     return direct_to_template(request, "wiki/document_upload.html", extra_context={
201         "form": form,
202     })
203
204
205 @never_cache
206 @normalized_name
207 @decorator_from_middleware(GZipMiddleware)
208 def text(request, name):
209     storage = getstorage()
210
211     if request.method == 'POST':
212         form = DocumentTextSaveForm(request.POST, prefix="textsave")
213         if form.is_valid():
214             revision = form.cleaned_data['parent_revision']
215             document = storage.get_or_404(name, revision)          
216             document.text = form.cleaned_data['text']
217             comment = form.cleaned_data['comment']
218             if form.cleaned_data['stage_completed']:        
219                 comment += '\n#stage-finished: %s\n' % form.cleaned_data['stage_completed']         
220             if request.user.is_authenticated():
221                 author_name = request.user
222                 author_email = request.user.email
223             else:
224                 author_name = form.cleaned_data['author_name']
225                 author_email = form.cleaned_data['author_email']
226             author = "%s <%s>" % (author_name, author_email)
227             storage.put(document, author=author, comment=comment, parent=revision)           
228             document = storage.get(name)          
229             return JSONResponse({
230                 'text': document.plain_text if revision != document.revision else None,
231                 'meta': document.meta(),
232                 'revision': document.revision,
233             })
234         else:
235             return JSONFormInvalid(form)
236     else:
237         revision = request.GET.get("revision", None)
238
239         try:
240             try:
241                 revision = revision and int(revision)
242                 logger.info("Fetching %s", revision)
243                 document = storage.get(name, revision)
244             except ValueError:
245                 # treat as a tag
246                 logger.info("Fetching tag %s", revision)
247                 document = storage.get_by_tag(name, revision)
248         except DocumentNotFound:
249             raise http.Http404
250
251         return JSONResponse({
252             'text': document.plain_text,
253             'meta': document.meta(),
254             'revision': document.revision,
255         })
256
257
258 @never_cache
259 @normalized_name
260 @require_POST
261 def revert(request, name):
262     storage = getstorage()
263     revision = request.POST['target_revision']
264
265     try:
266         document = storage.revert(name, revision)
267
268         return JSONResponse({
269             'text': document.plain_text if revision != document.revision else None,
270             'meta': document.meta(),
271             'revision': document.revision,
272         })
273     except DocumentNotFound:
274         raise http.Http404
275
276 @never_cache
277 def gallery(request, directory):
278     try:
279         base_url = ''.join((
280                         smart_unicode(settings.MEDIA_URL),
281                         smart_unicode(settings.FILEBROWSER_DIRECTORY),
282                         smart_unicode(directory)))
283
284         base_dir = os.path.join(
285                     smart_unicode(settings.MEDIA_ROOT),
286                     smart_unicode(settings.FILEBROWSER_DIRECTORY),
287                     smart_unicode(directory))
288
289         def map_to_url(filename):
290             return "%s/%s" % (base_url, smart_unicode(filename))
291
292         def is_image(filename):
293             return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
294
295         images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
296         images.sort()
297         return JSONResponse(images)
298     except (IndexError, OSError):
299         logger.exception("Unable to fetch gallery")
300         raise http.Http404
301
302
303 @never_cache
304 @normalized_name
305 def diff(request, name):
306     storage = getstorage()
307
308     revA = int(request.GET.get('from', 0))
309     revB = int(request.GET.get('to', 0))
310
311     if revA > revB:
312         revA, revB = revB, revA
313
314     if revB == 0:
315         revB = None
316
317     docA = storage.get_or_404(name, int(revA))
318     docB = storage.get_or_404(name, int(revB))
319
320     return http.HttpResponse(nice_diff.html_diff_table(docA.plain_text.splitlines(),
321                                          docB.plain_text.splitlines(), context=3))
322
323
324 @never_cache
325 @normalized_name
326 def history(request, name):
327     storage = getstorage()
328
329     # TODO: pagination
330     changesets = list(storage.history(name))
331
332     return JSONResponse(changesets)
333
334
335 @require_POST
336 @ajax_require_permission('wiki.can_change_tags')
337 def add_tag(request, name):
338     name = normalize_name(name)
339     storage = getstorage()
340
341     form = DocumentTagForm(request.POST, prefix="addtag")
342     if form.is_valid():
343         doc = storage.get_or_404(form.cleaned_data['id'])
344         doc.add_tag(tag=form.cleaned_data['tag'],
345                     revision=form.cleaned_data['revision'],
346                     author=request.user.username)
347         return JSONResponse({"message": _("Tag added")})
348     else:
349         return JSONFormInvalid(form)
350
351
352 @require_POST
353 @ajax_require_permission('wiki.can_publish')
354 def publish(request, name):
355     name = normalize_name(name)
356
357     storage = getstorage()
358     document = storage.get_by_tag(name, "ready_to_publish")
359
360     api = wlapi.WLAPI(**settings.WL_API_CONFIG)
361
362     try:
363         return JSONResponse({"result": api.publish_book(document)})
364     except wlapi.APICallException, e:
365         return JSONServerError({"message": str(e)})
366
367
368 def themes(request):
369     prefix = request.GET.get('q', '')
370     return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))