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