827a483885a35013883d1e7f173db3d94c7eb7a8
[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, Template
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             'stage': chunk.stage.name if chunk.stage else None,
92             'assignment': chunk.user.username if chunk.user else None
93         }),
94         'serialized_templates': simplejson.dumps([
95             {'id': t.id, 'name': t.name, 'content': t.content} for t in Template.objects.filter(is_partial=True)
96         ]),
97         'forms': {
98             "text_save": save_form,
99             "text_revert": forms.DocumentTextRevertForm(prefix="textrevert")
100         },
101         'tags': list(save_form.fields['stage_completed'].choices),
102         'can_pubmark': request.user.has_perm('catalogue.can_pubmark'),
103         'slug': chunk.book.slug
104     })
105
106
107 @require_GET
108 def editor_readonly(request, slug, chunk=None, template_name='wiki/document_details_readonly.html'):
109     try:
110         chunk = Chunk.get(slug, chunk)
111         revision = request.GET['revision']
112     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist, KeyError):
113         raise Http404
114     if not chunk.book.accessible(request):
115         return HttpResponseForbidden("Not authorized.")
116
117     access_time = datetime.now()
118     last_books = request.session.get("wiki_last_books", {})
119     last_books[slug, chunk.slug] = {
120         'time': access_time,
121         'title': chunk.book.title,
122         }
123
124     if len(last_books) > MAX_LAST_DOCS:
125         oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
126         del last_books[oldest_key]
127     request.session['wiki_last_books'] = last_books
128
129     return render(request, template_name, {
130         'chunk': chunk,
131         'revision': revision,
132         'readonly': True,
133         'REDMINE_URL': settings.REDMINE_URL,
134     })
135
136
137 @never_cache
138 @decorator_from_middleware(GZipMiddleware)
139 def text(request, chunk_id):
140     doc = get_object_or_404(Chunk, pk=chunk_id)
141     if not doc.book.accessible(request):
142         return HttpResponseForbidden("Not authorized.")
143
144     if request.method == 'POST':
145         form = forms.DocumentTextSaveForm(request.POST, user=request.user, prefix="textsave")
146         if form.is_valid():
147             if request.user.is_authenticated():
148                 author = request.user
149             else:
150                 author = None
151             text = form.cleaned_data['text']
152             parent_revision = form.cleaned_data['parent_revision']
153             if parent_revision is not None:
154                 parent = doc.at_revision(parent_revision)
155             else:
156                 parent = None
157             stage = form.cleaned_data['stage_completed']
158             tags = [stage] if stage else []
159             publishable = (form.cleaned_data['publishable'] and
160                     request.user.has_perm('catalogue.can_pubmark'))
161             doc.commit(author=author,
162                        text=text,
163                        parent=parent,
164                        description=form.cleaned_data['comment'],
165                        tags=tags,
166                        author_name=form.cleaned_data['author_name'],
167                        author_email=form.cleaned_data['author_email'],
168                        publishable=publishable,
169                        )
170             revision = doc.revision()
171             return JSONResponse({
172                 'text': doc.materialize() if parent_revision != revision else None,
173                 'version': revision,
174                 'stage': doc.stage.name if doc.stage else None,
175                 'assignment': doc.user.username if doc.user else None
176             })
177         else:
178             return JSONFormInvalid(form)
179     else:
180         revision = request.GET.get("revision", None)
181         
182         try:
183             revision = int(revision)
184         except (ValueError, TypeError):
185             revision = doc.revision()
186
187         if revision is not None:
188             text = doc.at_revision(revision).materialize()
189         else:
190             text = ''
191
192         return JSONResponse({
193             'text': text,
194             'meta': {},
195             'revision': revision,
196         })
197
198
199 @never_cache
200 @require_POST
201 def revert(request, chunk_id):
202     form = forms.DocumentTextRevertForm(request.POST, prefix="textrevert")
203     if form.is_valid():
204         doc = get_object_or_404(Chunk, pk=chunk_id)
205         if not doc.book.accessible(request):
206             return HttpResponseForbidden("Not authorized.")
207
208         revision = form.cleaned_data['revision']
209
210         comment = form.cleaned_data['comment']
211         comment += "\n#revert to %s" % revision
212
213         if request.user.is_authenticated():
214             author = request.user
215         else:
216             author = None
217
218         before = doc.revision()
219         logger.info("Reverting %s to %s", chunk_id, revision)
220         doc.at_revision(revision).revert(author=author, description=comment)
221
222         return JSONResponse({
223             'document': doc.materialize() if before != doc.revision() else None,
224             'version': doc.revision(),
225         })
226     else:
227         return JSONFormInvalid(form)
228
229
230 @never_cache
231 def gallery(request, directory):
232     try:
233         base_url = ''.join((
234                         smart_unicode(settings.MEDIA_URL),
235                         smart_unicode(settings.IMAGE_DIR),
236                         smart_unicode(directory)))
237
238         base_dir = os.path.join(
239                     smart_unicode(settings.MEDIA_ROOT),
240                     smart_unicode(settings.IMAGE_DIR),
241                     smart_unicode(directory))
242
243         def map_to_url(filename):
244             return urllib.quote("%s/%s" % (base_url, smart_unicode(filename)))
245
246         def is_image(filename):
247             return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
248
249         images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
250         images.sort()
251
252         if not request.user.is_authenticated():
253             return HttpResponseForbidden("Not authorized.")
254
255         return JSONResponse(images)
256     except (IndexError, OSError):
257         logger.exception("Unable to fetch gallery")
258         raise http.Http404
259
260
261 @never_cache
262 def diff(request, chunk_id):
263     revA = int(request.GET.get('from', 0))
264     revB = int(request.GET.get('to', 0))
265
266     if revA > revB:
267         revA, revB = revB, revA
268
269     if revB == 0:
270         revB = None
271
272     doc = get_object_or_404(Chunk, pk=chunk_id)
273     if not doc.book.accessible(request):
274         return HttpResponseForbidden("Not authorized.")
275
276     # allow diff from the beginning
277     if revA:
278         docA = doc.at_revision(revA).materialize()
279     else:
280         docA = ""
281     docB = doc.at_revision(revB).materialize()
282
283     return http.HttpResponse(nice_diff.html_diff_table(docA.splitlines(),
284                                          docB.splitlines(), context=3))
285
286
287 @never_cache
288 def revision(request, chunk_id):
289     doc = get_object_or_404(Chunk, pk=chunk_id)
290     if not doc.book.accessible(request):
291         return HttpResponseForbidden("Not authorized.")
292     return http.HttpResponse(str(doc.revision()))
293
294
295 @never_cache
296 def history(request, chunk_id):
297     # TODO: pagination
298     doc = get_object_or_404(Chunk, pk=chunk_id)
299     if not doc.book.accessible(request):
300         return HttpResponseForbidden("Not authorized.")
301
302     return JSONResponse(get_history(doc))
303
304
305 @require_POST
306 @ajax_require_permission('catalogue.can_pubmark')
307 def pubmark(request, chunk_id):
308     form = forms.DocumentPubmarkForm(request.POST, prefix="pubmark")
309     if form.is_valid():
310         doc = get_object_or_404(Chunk, pk=chunk_id)
311         if not doc.book.accessible(request):
312             return HttpResponseForbidden("Not authorized.")
313
314         revision = form.cleaned_data['revision']
315         publishable = form.cleaned_data['publishable']
316         change = doc.at_revision(revision)
317         if publishable != change.publishable:
318             change.set_publishable(publishable)
319             return JSONResponse({"message": _("Revision marked")})
320         else:
321             return JSONResponse({"message": _("Nothing changed")})
322     else:
323         return JSONFormInvalid(form)
324
325
326 def themes(request):
327     prefix = request.GET.get('q', '')
328     return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))