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