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