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