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