Added DVCS application - mercurial on database.
[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 django.contrib.auth.decorators import login_required
16
17 from wiki.models import getstorage, DocumentNotFound, normalize_name, split_name, join_name
18 from wiki.forms import DocumentTextSaveForm, DocumentTagForm, DocumentCreateForm
19 from datetime import datetime
20 from django.utils.encoding import smart_unicode
21 from django.utils.translation import ugettext_lazy as _
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     })
90
91
92 @require_GET
93 @normalized_name
94 def editor_readonly(request, name, template_name='wiki/document_details_readonly.html'):
95     name = normalize_name(name)
96     storage = getstorage()
97
98     try:
99         revision = request.GET['revision']
100         document = storage.get(name, revision)
101     except (KeyError, DocumentNotFound) as e:
102         raise http.Http404
103
104     access_time = datetime.now()
105     last_documents = request.session.get("wiki_last_docs", {})
106     last_documents[name] = access_time
107
108     if len(last_documents) > MAX_LAST_DOCS:
109         oldest_key = min(last_documents, key=last_documents.__getitem__)
110         del last_documents[oldest_key]
111     request.session['wiki_last_docs'] = last_documents
112
113     return direct_to_template(request, template_name, extra_context={
114         'document': document,
115         'document_name': document.name,
116         'document_info': dict(document.info(), readonly=True),
117         'document_meta': document.meta,
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                 name=form.cleaned_data['id'],
130                 text=form.cleaned_data['text'],
131             )
132
133             return http.HttpResponseRedirect(reverse("wiki_editor", 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
154         if form.is_valid():
155             revision = form.cleaned_data['parent_revision']
156
157             document = storage.get_or_404(name, revision)
158             document.text = form.cleaned_data['text']
159
160             comment = form.cleaned_data['comment']
161
162             if form.cleaned_data['stage_completed']:
163                 comment += '\n#stage-finished: %s\n' % form.cleaned_data['stage_completed']
164
165             author = "%s <%s>" % (form.cleaned_data['author_name'], form.cleaned_data['author_email'])
166
167             storage.put(document, author=author, comment=comment, parent=revision)
168             document = storage.get(name)
169
170             return JSONResponse({
171                 'text': document.plain_text if revision != document.revision else None,
172                 'meta': document.meta(),
173                 'revision': document.revision,
174             })
175         else:
176             return JSONFormInvalid(form)
177     else:
178         revision = request.GET.get("revision", None)
179
180         try:
181             try:
182                 revision = revision and int(revision)
183                 logger.info("Fetching %s", revision)
184                 document = storage.get(name, revision)
185             except ValueError:
186                 # treat as a tag
187                 logger.info("Fetching tag %s", revision)
188                 document = storage.get_by_tag(name, revision)
189         except DocumentNotFound:
190             raise http.Http404
191
192         return JSONResponse({
193             'text': document.plain_text,
194             'meta': document.meta(),
195             'revision': document.revision,
196         })
197
198
199 @never_cache
200 @normalized_name
201 @require_POST
202 def revert(request, name):
203     storage = getstorage()
204     revision = request.POST['target_revision']
205
206     try:
207         document = storage.revert(name, revision)
208
209         return JSONResponse({
210             'text': document.plain_text if revision != document.revision else None,
211             'meta': document.meta(),
212             'revision': document.revision,
213         })
214     except DocumentNotFound:
215         raise http.Http404
216
217 @never_cache
218 def gallery(request, directory):
219     try:
220         base_url = ''.join((
221                         smart_unicode(settings.MEDIA_URL),
222                         smart_unicode(settings.FILEBROWSER_DIRECTORY),
223                         smart_unicode(directory)))
224
225         base_dir = os.path.join(
226                     smart_unicode(settings.MEDIA_ROOT),
227                     smart_unicode(settings.FILEBROWSER_DIRECTORY),
228                     smart_unicode(directory))
229
230         def map_to_url(filename):
231             return "%s/%s" % (base_url, smart_unicode(filename))
232
233         def is_image(filename):
234             return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
235
236         images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
237         images.sort()
238         return JSONResponse(images)
239     except (IndexError, OSError) as e:
240         logger.exception("Unable to fetch gallery")
241         raise http.Http404
242
243
244 @never_cache
245 @normalized_name
246 def diff(request, name):
247     storage = getstorage()
248
249     revA = int(request.GET.get('from', 0))
250     revB = int(request.GET.get('to', 0))
251
252     if revA > revB:
253         revA, revB = revB, revA
254
255     if revB == 0:
256         revB = None
257
258     docA = storage.get_or_404(name, int(revA))
259     docB = storage.get_or_404(name, int(revB))
260
261     return http.HttpResponse(nice_diff.html_diff_table(docA.plain_text.splitlines(),
262                                          docB.plain_text.splitlines(), context=3))
263
264
265 @never_cache
266 @normalized_name
267 def history(request, name):
268     storage = getstorage()
269
270     # TODO: pagination
271     changesets = list(storage.history(name))
272
273     return JSONResponse(changesets)
274
275
276 @require_POST
277 @ajax_require_permission('wiki.can_change_tags')
278 def add_tag(request, name):
279     name = normalize_name(name)
280     storage = getstorage()
281
282     form = DocumentTagForm(request.POST, prefix="addtag")
283     if form.is_valid():
284         doc = storage.get_or_404(form.cleaned_data['id'])
285         doc.add_tag(tag=form.cleaned_data['tag'],
286                     revision=form.cleaned_data['revision'],
287                     author=request.user.username)
288         return JSONResponse({"message": _("Tag added")})
289     else:
290         return JSONFormInvalid(form)
291
292
293 @require_POST
294 @ajax_require_permission('wiki.can_publish')
295 def publish(request, name):
296     name = normalize_name(name)
297
298     storage = getstorage()
299     document = storage.get_by_tag(name, "ready_to_publish")
300
301     api = wlapi.WLAPI(**settings.WL_API_CONFIG)
302
303     try:
304         return JSONResponse({"result": api.publish_book(document)})
305     except wlapi.APICallException, e:
306         return JSONServerError({"message": str(e)})
307
308 @login_required
309 def status_report(request):
310     pass
311