9a17faabf655d5141f1ce9d9fe52225ca99b37f1
[redakcja.git] / apps / wiki / views.py
1 from datetime import datetime
2 import json
3 import os
4 import logging
5 import urllib
6
7 from django.conf import settings
8 from django.core.urlresolvers import reverse
9 from django import http
10 from django.http import Http404, HttpResponseForbidden
11 from django.middleware.gzip import GZipMiddleware
12 from django.utils.decorators import decorator_from_middleware
13 from django.utils.encoding import smart_unicode
14 from django.utils.formats import localize
15 from django.utils.translation import ugettext as _
16 from django.views.decorators.http import require_POST, require_GET
17 from django.shortcuts import get_object_or_404, render
18 from django.contrib.auth.decorators import login_required
19
20 from catalogue.models import Document, Template
21 from dvcs.models import Revision
22 import nice_diff
23 from wiki import forms
24 from wiki.helpers import (JSONResponse, JSONFormInvalid, JSONServerError,
25                 ajax_require_permission)
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(document):
38     revisions = []
39     for i, revision in enumerate(document.history()):
40         revisions.append({
41                 "version": i + 1,
42                 "description": revision.description,
43                 "author": revision.author_str(),
44                 "date": localize(revision.created_at),
45                 "published": "",
46                 "revision": revision.pk,
47                 "published": _("Published") + ": " + \
48                     localize(revision.publish_log.order_by('-timestamp')[0].timestamp) \
49                     if revision.publish_log.exists() else "",
50             })
51     return revisions
52
53
54 @never_cache
55 #@login_required
56 def editor(request, pk, chunk=None, template_name='wiki/bootstrap.html'):
57     doc = get_object_or_404(Document, pk=pk, deleted=False)
58     #~ if not doc.accessible(request):
59         #~ return HttpResponseForbidden("Not authorized.")
60
61     access_time = datetime.now()
62
63     save_form = forms.DocumentTextSaveForm(user=request.user, prefix="textsave")
64     try:
65         version = int(request.GET.get('version', None))
66     except:
67         version = None
68     if version:
69         text = doc.at_revision(version).materialize()
70     else:
71         text = doc.materialize()
72         revision = doc.revision
73     history = get_history(doc)
74     return render(request, template_name, {
75         'serialized_document_data': json.dumps({
76             'document': text,
77             'document_id': doc.pk,
78             'title': doc.meta().get('title', ''),
79             'history': history,
80             'version': len(history), #version or chunk.revision(),
81             'revision': revision.pk,
82             'stage': doc.stage,
83             'assignment': str(doc.assigned_to),
84         }),
85         'serialized_templates': json.dumps([
86             {'id': t.id, 'name': t.name, 'content': t.content} for t in Template.objects.filter(is_partial=True)
87         ]),
88         'forms': {
89             "text_save": save_form,
90             "text_revert": forms.DocumentTextRevertForm(prefix="textrevert"),
91             "text_publish": forms.DocumentTextPublishForm(prefix="textpublish"),
92         },
93         'pk': doc.pk,
94     })
95
96
97 @require_GET
98 def editor_readonly(request, slug, chunk=None, template_name='wiki/document_details_readonly.html'):
99     try:
100         chunk = Chunk.get(slug, chunk)
101         revision = request.GET['revision']
102     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist, KeyError):
103         raise Http404
104     if not chunk.book.accessible(request):
105         return HttpResponseForbidden("Not authorized.")
106
107     access_time = datetime.now()
108     last_books = request.session.get("wiki_last_books", {})
109     last_books[slug, chunk.slug] = {
110         'time': access_time,
111         'title': chunk.book.title,
112         }
113
114     if len(last_books) > MAX_LAST_DOCS:
115         oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
116         del last_books[oldest_key]
117     request.session['wiki_last_books'] = last_books
118
119     return render(request, template_name, {
120         'chunk': chunk,
121         'revision': revision,
122         'readonly': True,
123         'REDMINE_URL': settings.REDMINE_URL,
124     })
125
126
127 @never_cache
128 @decorator_from_middleware(GZipMiddleware)
129 def text(request, doc_id):
130     doc = get_object_or_404(Document, pk=doc_id, deleted=False)
131     #~ if not doc.book.accessible(request):
132         #~ return HttpResponseForbidden("Not authorized.")
133
134     if request.method == 'POST':
135         form = forms.DocumentTextSaveForm(request.POST, user=request.user, prefix="textsave")
136         if form.is_valid():
137             if request.user.is_authenticated():
138                 author = request.user
139             else:
140                 author = None
141             text = form.cleaned_data['text']
142             #~ parent_revision = form.cleaned_data['parent_revision']
143             #~ if parent_revision is not None:
144                 #~ parent = doc.at_revision(parent_revision)
145             #~ else:
146                 #~ parent = None
147             stage = form.cleaned_data['stage']
148             #~ tags = [stage] if stage else []
149             #~ publishable = (form.cleaned_data['publishable'] and
150                     #~ request.user.has_perm('catalogue.can_pubmark'))
151             try:
152                 doc.commit(author=author,
153                        text=text,
154                        parent=False,
155                        description=form.cleaned_data['comment'],
156                        author_name=form.cleaned_data['author_name'],
157                        author_email=form.cleaned_data['author_email'],
158                        )
159                 doc.set_stage(stage)
160             except:
161                 from traceback import print_exc
162                 print_exc()
163                 raise
164             #revision = doc.revision()
165             return JSONResponse({
166                 'text': None, #doc.materialize() if parent_revision != revision else None,
167                 #'version': revision,
168                 #'stage': doc.stage.name if doc.stage else None,
169                 'assignment': doc.assigned_to.username if doc.assigned_to else None
170             })
171         else:
172             return JSONFormInvalid(form)
173     else:
174         revision = request.GET.get("revision", None)
175         
176         try:
177             revision = int(revision)
178         except (ValueError, TypeError):
179             revision = doc.revision()
180
181         if revision is not None:
182             text = doc.at_revision(revision).materialize()
183         else:
184             text = ''
185
186         return JSONResponse({
187             'text': text,
188             'meta': {},
189             'revision': revision,
190         })
191
192
193 @never_cache
194 @require_POST
195 def revert(request, doc_id):
196     form = forms.DocumentTextRevertForm(request.POST, prefix="textrevert")
197     if form.is_valid():
198         doc = get_object_or_404(Document, pk=doc_id, deleted=False)
199         rev = get_object_or_404(Revision, pk=form.cleaned_data['revision'])
200
201         comment = form.cleaned_data['comment']
202         comment += "\n#revert to %s" % rev.pk
203
204         if request.user.is_authenticated():
205             author = request.user
206         else:
207             author = None
208
209         #before = doc.revision
210         logger.info("Reverting %s to %s", doc_id, rev.pk)
211
212         doc.commit(author=author,
213                text=rev.materialize(),
214                parent=False, #?
215                description=comment,
216                #author_name=form.cleaned_data['author_name'], #?
217                #author_email=form.cleaned_data['author_email'], #?
218                )
219
220         return JSONResponse({
221             #'document': None, #doc.materialize() if before != doc.revision else None,
222             #'version': doc.revision(),
223         })
224     else:
225         return JSONFormInvalid(form)
226
227
228 @never_cache
229 def gallery(request, directory):
230     if not request.user.is_authenticated():
231         return HttpResponseForbidden("Not authorized.")
232
233     try:
234         base_url = ''.join((
235                         smart_unicode(settings.MEDIA_URL),
236                         smart_unicode(settings.IMAGE_DIR),
237                         smart_unicode(directory)))
238
239         base_dir = os.path.join(
240                     smart_unicode(settings.MEDIA_ROOT),
241                     smart_unicode(settings.IMAGE_DIR),
242                     smart_unicode(directory))
243
244         def map_to_url(filename):
245             return urllib.quote("%s/%s" % (base_url, smart_unicode(filename)))
246
247         def is_image(filename):
248             return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
249
250         images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
251         images.sort()
252
253         return JSONResponse(images)
254     except (IndexError, OSError):
255         logger.exception("Unable to fetch gallery")
256         raise http.Http404
257
258
259 @never_cache
260 def diff(request, doc_id):
261     revA = int(request.GET.get('from', 0))
262     revB = int(request.GET.get('to', 0))
263
264     if revA > revB:
265         revA, revB = revB, revA
266
267     if revB == 0:
268         revB = None
269
270     # TODO: check if revisions in line.
271
272     doc = get_object_or_404(Document, pk=doc_id, deleted=False)
273
274     # allow diff from the beginning
275     if revA:
276         docA = Revision.objects.get(pk=revA).materialize()
277     else:
278         docA = ""
279     docB = Revision.objects.get(pk=revB).materialize()
280
281     return http.HttpResponse(nice_diff.html_diff_table(docA.splitlines(),
282                                          docB.splitlines(), context=3))
283
284
285 @never_cache
286 def revision(request, chunk_id):
287     doc = get_object_or_404(Chunk, pk=chunk_id)
288     if not doc.book.accessible(request):
289         return HttpResponseForbidden("Not authorized.")
290     return http.HttpResponse(str(doc.revision()))
291
292
293 @never_cache
294 def history(request, doc_id):
295     # TODO: pagination
296     doc = get_object_or_404(Document, pk=doc_id, deleted=False)
297
298     return JSONResponse(get_history(doc))