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