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