e1ef6aedb35993eb2d63c772257b21155d9d6d15
[redakcja.git] / apps / wiki / views.py
1 # -*- coding: utf-8 -*-
2 from datetime import datetime
3 import os
4 import logging
5 from time import mktime
6 import urllib
7
8 from django.conf import settings
9 from django.core.urlresolvers import reverse
10 from django import http
11 from django.http import Http404, HttpResponseForbidden
12 from django.middleware.gzip import GZipMiddleware
13 from django.utils.decorators import decorator_from_middleware
14 from django.utils.encoding import smart_unicode
15 from django.utils.formats import localize
16 from django.utils.translation import ugettext as _
17 from django.views.decorators.http import require_POST, require_GET
18 from django.shortcuts import get_object_or_404, render
19
20 from catalogue.models import Book, Chunk
21 import nice_diff
22 from wiki import forms
23 from wiki.helpers import (JSONResponse, JSONFormInvalid, JSONServerError,
24                 ajax_require_permission)
25 from wiki.models import Theme
26
27 #
28 # Quick hack around caching problems, TODO: use ETags
29 #
30 from django.views.decorators.cache import never_cache
31
32 logger = logging.getLogger("fnp.wiki")
33
34 MAX_LAST_DOCS = 10
35
36
37 @never_cache
38 def editor(request, slug, chunk=None, template_name='wiki/document_details.html'):
39     try:
40         chunk = Chunk.get(slug, chunk)
41     except Chunk.MultipleObjectsReturned:
42         # TODO: choice page
43         raise Http404
44     except Chunk.DoesNotExist:
45         if chunk is None:
46             try:
47                 book = Book.objects.get(slug=slug)
48             except Book.DoesNotExist:
49                 return http.HttpResponseRedirect(reverse("catalogue_create_missing", args=[slug]))
50         else:
51             raise Http404
52     if not chunk.book.accessible(request):
53         return HttpResponseForbidden("Not authorized.")
54
55     access_time = datetime.now()
56     last_books = request.session.get("wiki_last_books", {})
57     last_books[reverse(editor, args=[chunk.book.slug, chunk.slug])] = {
58         'time': mktime(access_time.timetuple()),
59         'title': chunk.pretty_name(),
60         }
61
62     if len(last_books) > MAX_LAST_DOCS:
63         oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
64         del last_books[oldest_key]
65     request.session['wiki_last_books'] = last_books
66
67     return render(request, template_name, {
68         'chunk': chunk,
69         'forms': {
70             "text_save": forms.DocumentTextSaveForm(user=request.user, prefix="textsave"),
71             "text_revert": forms.DocumentTextRevertForm(prefix="textrevert"),
72             "pubmark": forms.DocumentPubmarkForm(prefix="pubmark"),
73         },
74         'can_pubmark': request.user.has_perm('catalogue.can_pubmark'),
75         'REDMINE_URL': settings.REDMINE_URL,
76     })
77
78
79 @require_GET
80 def editor_readonly(request, slug, chunk=None, template_name='wiki/document_details_readonly.html'):
81     try:
82         chunk = Chunk.get(slug, chunk)
83         revision = request.GET['revision']
84     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist, KeyError):
85         raise Http404
86     if not chunk.book.accessible(request):
87         return HttpResponseForbidden("Not authorized.")
88
89     access_time = datetime.now()
90     last_books = request.session.get("wiki_last_books", {})
91     last_books[slug, chunk.slug] = {
92         'time': mktime(access_time.timetuple()),
93         'title': chunk.book.title,
94         }
95
96     if len(last_books) > MAX_LAST_DOCS:
97         oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
98         del last_books[oldest_key]
99     request.session['wiki_last_books'] = last_books
100
101     return render(request, template_name, {
102         'chunk': chunk,
103         'revision': revision,
104         'readonly': True,
105         'REDMINE_URL': settings.REDMINE_URL,
106     })
107
108
109 @never_cache
110 @decorator_from_middleware(GZipMiddleware)
111 def text(request, chunk_id):
112     doc = get_object_or_404(Chunk, pk=chunk_id)
113     if not doc.book.accessible(request):
114         return HttpResponseForbidden("Not authorized.")
115
116     if request.method == 'POST':
117         form = forms.DocumentTextSaveForm(request.POST, user=request.user, prefix="textsave")
118         if form.is_valid():
119             if request.user.is_authenticated():
120                 author = request.user
121             else:
122                 author = None
123             text = form.cleaned_data['text']
124             parent_revision = form.cleaned_data['parent_revision']
125             if parent_revision is not None:
126                 parent = doc.at_revision(parent_revision)
127             else:
128                 parent = None
129             stage = form.cleaned_data['stage_completed']
130             tags = [stage] if stage else []
131             publishable = (form.cleaned_data['publishable'] and
132                     request.user.has_perm('catalogue.can_pubmark'))
133             doc.commit(author=author,
134                        text=text,
135                        parent=parent,
136                        description=form.cleaned_data['comment'],
137                        tags=tags,
138                        author_name=form.cleaned_data['author_name'],
139                        author_email=form.cleaned_data['author_email'],
140                        publishable=publishable,
141                        )
142             revision = doc.revision()
143             return JSONResponse({
144                 'text': doc.materialize() if parent_revision != revision else None,
145                 'meta': {},
146                 'revision': revision,
147             })
148         else:
149             return JSONFormInvalid(form)
150     else:
151         revision = request.GET.get("revision", None)
152         
153         try:
154             revision = int(revision)
155         except (ValueError, TypeError):
156             revision = doc.revision()
157
158         if revision is not None:
159             text = doc.at_revision(revision).materialize()
160         else:
161             text = ''
162
163         return JSONResponse({
164             'text': text,
165             'meta': {},
166             'revision': revision,
167         })
168
169
170 @never_cache
171 @require_POST
172 def revert(request, chunk_id):
173     form = forms.DocumentTextRevertForm(request.POST, prefix="textrevert")
174     if form.is_valid():
175         doc = get_object_or_404(Chunk, pk=chunk_id)
176         if not doc.book.accessible(request):
177             return HttpResponseForbidden("Not authorized.")
178
179         revision = form.cleaned_data['revision']
180
181         comment = form.cleaned_data['comment']
182         comment += "\n#revert to %s" % revision
183
184         if request.user.is_authenticated():
185             author = request.user
186         else:
187             author = None
188
189         before = doc.revision()
190         logger.info("Reverting %s to %s", chunk_id, revision)
191         doc.at_revision(revision).revert(author=author, description=comment)
192
193         return JSONResponse({
194             'text': doc.materialize() if before != doc.revision() else None,
195             'meta': {},
196             'revision': doc.revision(),
197         })
198     else:
199         return JSONFormInvalid(form)
200
201
202 @never_cache
203 def gallery(request, directory):
204     try:
205         base_url = ''.join((
206                         smart_unicode(settings.MEDIA_URL),
207                         smart_unicode(settings.IMAGE_DIR),
208                         smart_unicode(directory)))
209
210         base_dir = os.path.join(
211                     smart_unicode(settings.MEDIA_ROOT),
212                     smart_unicode(settings.IMAGE_DIR),
213                     smart_unicode(directory))
214
215         def map_to_url(filename):
216             return urllib.quote(("%s/%s" % (base_url, smart_unicode(filename))).encode('utf-8'))
217
218         def is_image(filename):
219             return os.path.splitext(filename)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
220
221         images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
222         images.sort()
223
224         books = Book.objects.filter(gallery=directory)
225
226         if not all(book.public for book in books) and not request.user.is_authenticated():
227             return HttpResponseForbidden("Not authorized.")
228
229         return JSONResponse(images)
230     except (IndexError, OSError):
231         logger.exception("Unable to fetch gallery")
232         raise http.Http404
233
234
235 @never_cache
236 def diff(request, chunk_id):
237     revA = int(request.GET.get('from', 0))
238     revB = int(request.GET.get('to', 0))
239
240     if revA > revB:
241         revA, revB = revB, revA
242
243     if revB == 0:
244         revB = None
245
246     doc = get_object_or_404(Chunk, pk=chunk_id)
247     if not doc.book.accessible(request):
248         return HttpResponseForbidden("Not authorized.")
249
250     # allow diff from the beginning
251     if revA:
252         docA = doc.at_revision(revA).materialize()
253     else:
254         docA = ""
255     docB = doc.at_revision(revB).materialize()
256
257     return http.HttpResponse(nice_diff.html_diff_table(docA.splitlines(),
258                                          docB.splitlines(), context=3))
259
260
261 @never_cache
262 def revision(request, chunk_id):
263     doc = get_object_or_404(Chunk, pk=chunk_id)
264     if not doc.book.accessible(request):
265         return HttpResponseForbidden("Not authorized.")
266     return http.HttpResponse(str(doc.revision()))
267
268
269 @never_cache
270 def history(request, chunk_id):
271     # TODO: pagination
272     doc = get_object_or_404(Chunk, pk=chunk_id)
273     if not doc.book.accessible(request):
274         return HttpResponseForbidden("Not authorized.")
275
276     changes = []
277     for change in doc.history().reverse():
278         changes.append({
279                 "version": change.revision,
280                 "description": change.description,
281                 "author": change.author_str(),
282                 "date": localize(change.created_at),
283                 "publishable": _("Publishable") + "\n" if change.publishable else "",
284                 "tag": ',\n'.join(unicode(tag) for tag in change.tags.all()),
285                 "published": _("Published") + ": " + \
286                     localize(change.publish_log.order_by('-book_record__timestamp')[0].book_record.timestamp) \
287                     if change.publish_log.exists() else "",
288             })
289     return JSONResponse(changes)
290
291
292 @require_POST
293 @ajax_require_permission('catalogue.can_pubmark')
294 def pubmark(request, chunk_id):
295     form = forms.DocumentPubmarkForm(request.POST, prefix="pubmark")
296     if form.is_valid():
297         doc = get_object_or_404(Chunk, pk=chunk_id)
298         if not doc.book.accessible(request):
299             return HttpResponseForbidden("Not authorized.")
300
301         revision = form.cleaned_data['revision']
302         publishable = form.cleaned_data['publishable']
303         change = doc.at_revision(revision)
304         if publishable != change.publishable:
305             change.set_publishable(publishable)
306             return JSONResponse({"message": _("Revision marked")})
307         else:
308             return JSONResponse({"message": _("Nothing changed")})
309     else:
310         return JSONFormInvalid(form)
311
312
313 def themes(request):
314     prefix = request.GET.get('q', '')
315     return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))