loading overlay fix
[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
17 from datetime import datetime
18 from django.utils.encoding import smart_unicode
19 from django.utils.translation import ugettext_lazy as _
20
21
22 #
23 # Quick hack around caching problems, TODO: use ETags
24 #
25 from django.views.decorators.cache import never_cache
26
27 import wlapi
28 import nice_diff
29 import operator
30
31 MAX_LAST_DOCS = 10
32
33
34 def normalized_name(view):
35
36     @functools.wraps(view)
37     def decorated(request, name, *args):
38         normalized = normalize_name(name)
39         logger.debug('View check %r -> %r', name, normalized)
40
41         if normalized != name:
42             return http.HttpResponseRedirect(
43                         reverse('wiki_' + view.__name__, kwargs={'name': normalized}))
44
45         return view(request, name, *args)
46
47     return decorated
48
49
50 @never_cache
51 def document_list(request):
52     return direct_to_template(request, 'wiki/document_list.html', extra_context={
53         'docs': getstorage().all(),
54         'last_docs': sorted(request.session.get("wiki_last_docs", {}).items(),
55                         key=operator.itemgetter(1), reverse=True),
56     })
57
58
59 @never_cache
60 @normalized_name
61 def editor(request, name, template_name='wiki/document_details.html'):
62     storage = getstorage()
63
64     try:
65         document = storage.get(name)
66     except DocumentNotFound:
67         return http.HttpResponseRedirect(reverse("wiki_create_missing", args=[name]))
68
69     access_time = datetime.now()
70     last_documents = request.session.get("wiki_last_docs", {})
71     last_documents[name] = access_time
72
73     if len(last_documents) > MAX_LAST_DOCS:
74         oldest_key = min(last_documents, key=last_documents.__getitem__)
75         del last_documents[oldest_key]
76     request.session['wiki_last_docs'] = last_documents
77
78     return direct_to_template(request, template_name, extra_context={
79         'document': document,
80         'document_name': document.name,
81         'document_info': document.info,
82         'document_meta': document.meta,
83         'forms': {
84             "text_save": DocumentTextSaveForm(prefix="textsave"),
85             "add_tag": DocumentTagForm(prefix="addtag"),
86         },
87         'REDMINE_URL': settings.REDMINE_URL,
88     })
89
90
91 @require_GET
92 @normalized_name
93 def editor_readonly(request, name, template_name='wiki/document_details_readonly.html'):
94     name = normalize_name(name)
95     storage = getstorage()
96
97     try:
98         revision = request.GET['revision']
99         document = storage.get(name, revision)
100     except (KeyError, DocumentNotFound):
101         raise http.Http404
102
103     access_time = datetime.now()
104     last_documents = request.session.get("wiki_last_docs", {})
105     last_documents[name] = access_time
106
107     if len(last_documents) > MAX_LAST_DOCS:
108         oldest_key = min(last_documents, key=last_documents.__getitem__)
109         del last_documents[oldest_key]
110     request.session['wiki_last_docs'] = last_documents
111
112     return direct_to_template(request, template_name, extra_context={
113         'document': document,
114         'document_name': document.name,
115         'document_info': dict(document.info(), readonly=True),
116         'document_meta': document.meta,
117         'REDMINE_URL': settings.REDMINE_URL,
118     })
119
120
121 @normalized_name
122 def create_missing(request, name):
123     storage = getstorage()
124
125     if request.method == "POST":
126         form = DocumentCreateForm(request.POST, request.FILES)
127         if form.is_valid():
128             doc = storage.create_document(
129                 id=form.cleaned_data['id'],
130                 text=form.cleaned_data['text'],
131             )
132
133             return http.HttpResponseRedirect(reverse("wiki_details", args=[doc.name]))
134     else:
135         form = DocumentCreateForm(initial={
136                 "id": name.replace(" ", "_"),
137                 "title": name.title(),
138         })
139
140     return direct_to_template(request, "wiki/document_create_missing.html", extra_context={
141         "document_name": name,
142         "form": form,
143     })
144
145
146 @never_cache
147 @normalized_name
148 def text(request, name):
149     storage = getstorage()
150
151     if request.method == 'POST':
152         form = DocumentTextSaveForm(request.POST, prefix="textsave")
153         if form.is_valid():
154             revision = form.cleaned_data['parent_revision']
155             document = storage.get_or_404(name, revision)          
156             document.text = form.cleaned_data['text']
157             comment = form.cleaned_data['comment']
158             if form.cleaned_data['stage_completed']:        
159                 comment += '\n#stage-finished: %s\n' % form.cleaned_data['stage_completed']         
160             author = "%s <%s>" % (form.cleaned_data['author_name'], form.cleaned_data['author_email'])           
161             storage.put(document, author=author, comment=comment, parent=revision)           
162             document = storage.get(name)          
163             return JSONResponse({
164                 'text': document.plain_text if revision != document.revision else None,
165                 'meta': document.meta(),
166                 'revision': document.revision,
167             })
168         else:
169             return JSONFormInvalid(form)
170     else:
171         revision = request.GET.get("revision", None)
172
173         try:
174             try:
175                 revision = revision and int(revision)
176                 logger.info("Fetching %s", revision)
177                 document = storage.get(name, revision)
178             except ValueError:
179                 # treat as a tag
180                 logger.info("Fetching tag %s", revision)
181                 document = storage.get_by_tag(name, revision)
182         except DocumentNotFound:
183             raise http.Http404
184
185         return JSONResponse({
186             'text': document.plain_text,
187             'meta': document.meta(),
188             'revision': document.revision,
189         })
190
191
192 @never_cache
193 @normalized_name
194 @require_POST
195 def revert(request, name):
196     storage = getstorage()
197     revision = request.POST['target_revision']
198
199     try:
200         document = storage.revert(name, revision)
201
202         return JSONResponse({
203             'text': document.plain_text if revision != document.revision else None,
204             'meta': document.meta(),
205             'revision': document.revision,
206         })
207     except DocumentNotFound:
208         raise http.Http404
209
210 @never_cache
211 def gallery(request, directory):
212     try:
213         base_url = ''.join((
214                         smart_unicode(settings.MEDIA_URL),
215                         smart_unicode(settings.FILEBROWSER_DIRECTORY),
216                         smart_unicode(directory)))
217
218         base_dir = os.path.join(
219                     smart_unicode(settings.MEDIA_ROOT),
220                     smart_unicode(settings.FILEBROWSER_DIRECTORY),
221                     smart_unicode(directory))
222
223         def map_to_url(filename):
224             return "%s/%s" % (base_url, smart_unicode(filename))
225
226         def is_image(filename):
227             return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
228
229         images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
230         images.sort()
231         return JSONResponse(images)
232     except (IndexError, OSError):
233         logger.exception("Unable to fetch gallery")
234         raise http.Http404
235
236
237 @never_cache
238 @normalized_name
239 def diff(request, name):
240     storage = getstorage()
241
242     revA = int(request.GET.get('from', 0))
243     revB = int(request.GET.get('to', 0))
244
245     if revA > revB:
246         revA, revB = revB, revA
247
248     if revB == 0:
249         revB = None
250
251     docA = storage.get_or_404(name, int(revA))
252     docB = storage.get_or_404(name, int(revB))
253
254     return http.HttpResponse(nice_diff.html_diff_table(docA.plain_text.splitlines(),
255                                          docB.plain_text.splitlines(), context=3))
256
257
258 @never_cache
259 @normalized_name
260 def history(request, name):
261     storage = getstorage()
262
263     # TODO: pagination
264     changesets = list(storage.history(name))
265
266     return JSONResponse(changesets)
267
268
269 @require_POST
270 @ajax_require_permission('wiki.can_change_tags')
271 def add_tag(request, name):
272     name = normalize_name(name)
273     storage = getstorage()
274
275     form = DocumentTagForm(request.POST, prefix="addtag")
276     if form.is_valid():
277         doc = storage.get_or_404(form.cleaned_data['id'])
278         doc.add_tag(tag=form.cleaned_data['tag'],
279                     revision=form.cleaned_data['revision'],
280                     author=request.user.username)
281         return JSONResponse({"message": _("Tag added")})
282     else:
283         return JSONFormInvalid(form)
284
285
286 @require_POST
287 @ajax_require_permission('wiki.can_publish')
288 def publish(request, name):
289     name = normalize_name(name)
290
291     storage = getstorage()
292     document = storage.get_by_tag(name, "ready_to_publish")
293
294     api = wlapi.WLAPI(**settings.WL_API_CONFIG)
295
296     try:
297         return JSONResponse({"result": api.publish_book(document)})
298     except wlapi.APICallException, e:
299         return JSONServerError({"message": str(e)})
300
301
302 def themes(request):
303     prefix = request.GET.get('q', '')
304     return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))