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