book sorting fix
[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(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, 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                        )
127             revision = doc.revision()
128             return JSONResponse({
129                 'text': doc.materialize() if parent_revision != revision else None,
130                 'meta': {},
131                 'revision': revision,
132             })
133         else:
134             return JSONFormInvalid(form)
135     else:
136         revision = request.GET.get("revision", None)
137         
138         try:
139             revision = int(revision)
140         except (ValueError, TypeError):
141             revision = doc.revision()
142
143         if revision is not None:
144             text = doc.at_revision(revision).materialize()
145         else:
146             text = ''
147
148         return JSONResponse({
149             'text': text,
150             'meta': {},
151             'revision': revision,
152         })
153
154
155 @never_cache
156 @require_POST
157 def revert(request, chunk_id):
158     form = forms.DocumentTextRevertForm(request.POST, prefix="textrevert")
159     if form.is_valid():
160         doc = get_object_or_404(Chunk, pk=chunk_id)
161
162         revision = form.cleaned_data['revision']
163
164         comment = form.cleaned_data['comment']
165         comment += "\n#revert to %s" % revision
166
167         if request.user.is_authenticated():
168             author = request.user
169         else:
170             author = None
171
172         before = doc.revision()
173         logger.info("Reverting %s to %s", chunk_id, revision)
174         doc.at_revision(revision).revert(author=author, description=comment)
175
176         return JSONResponse({
177             'text': doc.materialize() if before != doc.revision() else None,
178             'meta': {},
179             'revision': doc.revision(),
180         })
181     else:
182         return JSONFormInvalid(form)
183
184
185 @never_cache
186 def gallery(request, directory):
187     try:
188         base_url = ''.join((
189                         smart_unicode(settings.MEDIA_URL),
190                         smart_unicode(settings.FILEBROWSER_DIRECTORY),
191                         smart_unicode(directory)))
192
193         base_dir = os.path.join(
194                     smart_unicode(settings.MEDIA_ROOT),
195                     smart_unicode(settings.FILEBROWSER_DIRECTORY),
196                     smart_unicode(directory))
197
198         def map_to_url(filename):
199             return "%s/%s" % (base_url, smart_unicode(filename))
200
201         def is_image(filename):
202             return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
203
204         images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
205         images.sort()
206         return JSONResponse(images)
207     except (IndexError, OSError):
208         logger.exception("Unable to fetch gallery")
209         raise http.Http404
210
211
212 @never_cache
213 def diff(request, chunk_id):
214     revA = int(request.GET.get('from', 0))
215     revB = int(request.GET.get('to', 0))
216
217     if revA > revB:
218         revA, revB = revB, revA
219
220     if revB == 0:
221         revB = None
222
223     doc = get_object_or_404(Chunk, pk=chunk_id)
224     # allow diff from the beginning
225     if revA:
226         docA = doc.at_revision(revA).materialize()
227     else:
228         docA = ""
229     docB = doc.at_revision(revB).materialize()
230
231     return http.HttpResponse(nice_diff.html_diff_table(docA.splitlines(),
232                                          docB.splitlines(), context=3))
233
234
235 @never_cache
236 def revision(request, chunk_id):
237     doc = get_object_or_404(Chunk, pk=chunk_id)
238     return http.HttpResponse(str(doc.revision()))
239
240
241 @never_cache
242 def history(request, chunk_id):
243     # TODO: pagination
244     doc = get_object_or_404(Chunk, pk=chunk_id)
245
246     changes = []
247     for change in doc.history().order_by('-created_at'):
248         changes.append({
249                 "version": change.revision,
250                 "description": change.description,
251                 "author": change.author_str(),
252                 "date": change.created_at,
253                 "publishable": _("Publishable") + "\n" if change.publishable else "",
254                 "tag": ',\n'.join(unicode(tag) for tag in change.tags.all()),
255             })
256     return JSONResponse(changes)
257
258
259 @require_POST
260 @ajax_require_permission('catalogue.can_pubmark')
261 def pubmark(request, chunk_id):
262     form = forms.DocumentPubmarkForm(request.POST, prefix="pubmark")
263     if form.is_valid():
264         doc = get_object_or_404(Chunk, pk=chunk_id)
265
266         revision = form.cleaned_data['revision']
267         publishable = form.cleaned_data['publishable']
268         change = doc.at_revision(revision)
269         if publishable != change.publishable:
270             change.set_publishable(publishable)
271             return JSONResponse({"message": _("Revision marked")})
272         else:
273             return JSONResponse({"message": _("Nothing changed")})
274     else:
275         return JSONFormInvalid(form)
276
277
278 def themes(request):
279     prefix = request.GET.get('q', '')
280     return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))