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