Fix unicode error on gallery view.
[redakcja.git] / apps / wiki / views.py
1 from datetime import datetime
2 import os
3 import logging
4 import urllib
5
6 from django.conf import settings
7 from django.core.urlresolvers import reverse
8 from django import http
9 from django.http import Http404, HttpResponseForbidden
10 from django.middleware.gzip import GZipMiddleware
11 from django.utils.decorators import decorator_from_middleware
12 from django.utils.encoding import smart_unicode
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 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[slug, chunk.slug] = {
56         'time': access_time,
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': access_time,
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                         smart_unicode(settings.MEDIA_URL),
205                         smart_unicode(settings.IMAGE_DIR),
206                         smart_unicode(directory)))
207
208         base_dir = os.path.join(
209                     smart_unicode(settings.MEDIA_ROOT),
210                     smart_unicode(settings.IMAGE_DIR),
211                     smart_unicode(directory))
212
213         def map_to_url(filename):
214             return urllib.quote("%s/%s" % (base_url, smart_unicode(filename)))
215
216         def is_image(filename):
217             return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
218
219         images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
220         images.sort()
221
222         if not request.user.is_authenticated():
223             return HttpResponseForbidden("Not authorized.")
224
225         return JSONResponse(images)
226     except (IndexError, OSError):
227         logger.exception("Unable to fetch gallery")
228         raise http.Http404
229
230
231 @never_cache
232 def diff(request, chunk_id):
233     revA = int(request.GET.get('from', 0))
234     revB = int(request.GET.get('to', 0))
235
236     if revA > revB:
237         revA, revB = revB, revA
238
239     if revB == 0:
240         revB = None
241
242     doc = get_object_or_404(Chunk, pk=chunk_id)
243     if not doc.book.accessible(request):
244         return HttpResponseForbidden("Not authorized.")
245
246     # allow diff from the beginning
247     if revA:
248         docA = doc.at_revision(revA).materialize()
249     else:
250         docA = ""
251     docB = doc.at_revision(revB).materialize()
252
253     return http.HttpResponse(nice_diff.html_diff_table(docA.splitlines(),
254                                          docB.splitlines(), context=3))
255
256
257 @never_cache
258 def revision(request, chunk_id):
259     doc = get_object_or_404(Chunk, pk=chunk_id)
260     if not doc.book.accessible(request):
261         return HttpResponseForbidden("Not authorized.")
262     return http.HttpResponse(str(doc.revision()))
263
264
265 @never_cache
266 def history(request, chunk_id):
267     # TODO: pagination
268     doc = get_object_or_404(Chunk, pk=chunk_id)
269     if not doc.book.accessible(request):
270         return HttpResponseForbidden("Not authorized.")
271
272     changes = []
273     for change in doc.history().reverse():
274         changes.append({
275                 "version": change.revision,
276                 "description": change.description,
277                 "author": change.author_str(),
278                 "date": localize(change.created_at),
279                 "publishable": _("Publishable") + "\n" if change.publishable else "",
280                 "tag": ',\n'.join(unicode(tag) for tag in change.tags.all()),
281                 "published": _("Published") + ": " + \
282                     localize(change.publish_log.order_by('-book_record__timestamp')[0].book_record.timestamp) \
283                     if change.publish_log.exists() else "",
284             })
285     return JSONResponse(changes)
286
287
288 @require_POST
289 @ajax_require_permission('catalogue.can_pubmark')
290 def pubmark(request, chunk_id):
291     form = forms.DocumentPubmarkForm(request.POST, prefix="pubmark")
292     if form.is_valid():
293         doc = get_object_or_404(Chunk, pk=chunk_id)
294         if not doc.book.accessible(request):
295             return HttpResponseForbidden("Not authorized.")
296
297         revision = form.cleaned_data['revision']
298         publishable = form.cleaned_data['publishable']
299         change = doc.at_revision(revision)
300         if publishable != change.publishable:
301             change.set_publishable(publishable)
302             return JSONResponse({"message": _("Revision marked")})
303         else:
304             return JSONResponse({"message": _("Nothing changed")})
305     else:
306         return JSONFormInvalid(form)
307
308
309 def themes(request):
310     prefix = request.GET.get('q', '')
311     return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))