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