new error pages
[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
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
50     access_time = datetime.now()
51     last_books = request.session.get("wiki_last_books", {})
52     last_books[slug, chunk.slug] = {
53         'time': access_time,
54         'title': chunk.pretty_name(),
55         }
56
57     if len(last_books) > MAX_LAST_DOCS:
58         oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
59         del last_books[oldest_key]
60     request.session['wiki_last_books'] = last_books
61
62     return direct_to_template(request, template_name, extra_context={
63         'chunk': chunk,
64         'forms': {
65             "text_save": forms.DocumentTextSaveForm(user=request.user, prefix="textsave"),
66             "text_revert": forms.DocumentTextRevertForm(prefix="textrevert"),
67             "pubmark": forms.DocumentPubmarkForm(prefix="pubmark"),
68         },
69         'REDMINE_URL': settings.REDMINE_URL,
70     })
71
72
73 @require_GET
74 def editor_readonly(request, slug, chunk=None, template_name='wiki/document_details_readonly.html'):
75     try:
76         chunk = Chunk.get(slug, chunk)
77         revision = request.GET['revision']
78     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist, KeyError):
79         raise Http404
80
81     access_time = datetime.now()
82     last_books = request.session.get("wiki_last_books", {})
83     last_books[slug, chunk.slug] = {
84         'time': access_time,
85         'title': chunk.book.title,
86         }
87
88     if len(last_books) > MAX_LAST_DOCS:
89         oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
90         del last_books[oldest_key]
91     request.session['wiki_last_books'] = last_books
92
93     return direct_to_template(request, template_name, extra_context={
94         'chunk': chunk,
95         'revision': revision,
96         'readonly': True,
97         'REDMINE_URL': settings.REDMINE_URL,
98     })
99
100
101 @never_cache
102 @decorator_from_middleware(GZipMiddleware)
103 def text(request, chunk_id):
104     doc = get_object_or_404(Chunk, pk=chunk_id)
105
106     if request.method == 'POST':
107         form = forms.DocumentTextSaveForm(request.POST, user=request.user, prefix="textsave")
108         if form.is_valid():
109             if request.user.is_authenticated():
110                 author = request.user
111             else:
112                 author = None
113             text = form.cleaned_data['text']
114             parent_revision = form.cleaned_data['parent_revision']
115             if parent_revision is not None:
116                 parent = doc.at_revision(parent_revision)
117             else:
118                 parent = None
119             stage = form.cleaned_data['stage_completed']
120             tags = [stage] if stage else []
121             doc.commit(author=author,
122                        text=text,
123                        parent=parent,
124                        description=form.cleaned_data['comment'],
125                        tags=tags,
126                        author_name=form.cleaned_data['author_name'],
127                        author_email=form.cleaned_data['author_email'],
128                        )
129             revision = doc.revision()
130             return JSONResponse({
131                 'text': doc.materialize() if parent_revision != revision else None,
132                 'meta': {},
133                 'revision': revision,
134             })
135         else:
136             return JSONFormInvalid(form)
137     else:
138         revision = request.GET.get("revision", None)
139         
140         try:
141             revision = int(revision)
142         except (ValueError, TypeError):
143             revision = doc.revision()
144
145         if revision is not None:
146             text = doc.at_revision(revision).materialize()
147         else:
148             text = ''
149
150         return JSONResponse({
151             'text': text,
152             'meta': {},
153             'revision': revision,
154         })
155
156
157 @never_cache
158 @require_POST
159 def revert(request, chunk_id):
160     form = forms.DocumentTextRevertForm(request.POST, prefix="textrevert")
161     if form.is_valid():
162         doc = get_object_or_404(Chunk, pk=chunk_id)
163
164         revision = form.cleaned_data['revision']
165
166         comment = form.cleaned_data['comment']
167         comment += "\n#revert to %s" % revision
168
169         if request.user.is_authenticated():
170             author = request.user
171         else:
172             author = None
173
174         before = doc.revision()
175         logger.info("Reverting %s to %s", chunk_id, revision)
176         doc.at_revision(revision).revert(author=author, description=comment)
177
178         return JSONResponse({
179             'text': doc.materialize() if before != doc.revision() else None,
180             'meta': {},
181             'revision': doc.revision(),
182         })
183     else:
184         return JSONFormInvalid(form)
185
186
187 @never_cache
188 def gallery(request, directory):
189     try:
190         base_url = ''.join((
191                         smart_unicode(settings.MEDIA_URL),
192                         smart_unicode(settings.FILEBROWSER_DIRECTORY),
193                         smart_unicode(directory)))
194
195         base_dir = os.path.join(
196                     smart_unicode(settings.MEDIA_ROOT),
197                     smart_unicode(settings.FILEBROWSER_DIRECTORY),
198                     smart_unicode(directory))
199
200         def map_to_url(filename):
201             return "%s/%s" % (base_url, smart_unicode(filename))
202
203         def is_image(filename):
204             return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
205
206         images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
207         images.sort()
208         return JSONResponse(images)
209     except (IndexError, OSError):
210         logger.exception("Unable to fetch gallery")
211         raise http.Http404
212
213
214 @never_cache
215 def diff(request, chunk_id):
216     revA = int(request.GET.get('from', 0))
217     revB = int(request.GET.get('to', 0))
218
219     if revA > revB:
220         revA, revB = revB, revA
221
222     if revB == 0:
223         revB = None
224
225     doc = get_object_or_404(Chunk, pk=chunk_id)
226     # allow diff from the beginning
227     if revA:
228         docA = doc.at_revision(revA).materialize()
229     else:
230         docA = ""
231     docB = doc.at_revision(revB).materialize()
232
233     return http.HttpResponse(nice_diff.html_diff_table(docA.splitlines(),
234                                          docB.splitlines(), context=3))
235
236
237 @never_cache
238 def revision(request, chunk_id):
239     doc = get_object_or_404(Chunk, pk=chunk_id)
240     return http.HttpResponse(str(doc.revision()))
241
242
243 @never_cache
244 def history(request, chunk_id):
245     # TODO: pagination
246     doc = get_object_or_404(Chunk, pk=chunk_id)
247
248     changes = []
249     for change in doc.history().order_by('-created_at'):
250         changes.append({
251                 "version": change.revision,
252                 "description": change.description,
253                 "author": change.author_str(),
254                 "date": change.created_at,
255                 "publishable": _("Publishable") + "\n" if change.publishable else "",
256                 "tag": ',\n'.join(unicode(tag) for tag in change.tags.all()),
257             })
258     return JSONResponse(changes)
259
260
261 @require_POST
262 @ajax_require_permission('catalogue.can_pubmark')
263 def pubmark(request, chunk_id):
264     form = forms.DocumentPubmarkForm(request.POST, prefix="pubmark")
265     if form.is_valid():
266         doc = get_object_or_404(Chunk, pk=chunk_id)
267
268         revision = form.cleaned_data['revision']
269         publishable = form.cleaned_data['publishable']
270         change = doc.at_revision(revision)
271         if publishable != change.publishable:
272             change.set_publishable(publishable)
273             return JSONResponse({"message": _("Revision marked")})
274         else:
275             return JSONResponse({"message": _("Nothing changed")})
276     else:
277         return JSONFormInvalid(form)
278
279
280 def themes(request):
281     prefix = request.GET.get('q', '')
282     return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))