Sexy images in gallery count.
[redakcja.git] / apps / wiki / views.py
1 import os
2 import functools
3 import logging
4 logger = logging.getLogger("fnp.wiki")
5
6 from django.conf import settings
7
8 from django.views.generic.simple import direct_to_template
9 from django.views.decorators.http import require_POST, require_GET
10 from django.core.urlresolvers import reverse
11 from wiki.helpers import (JSONResponse, JSONFormInvalid, JSONServerError,
12                 ajax_require_permission, recursive_groupby)
13 from django import http
14
15 from wiki.models import getstorage, DocumentNotFound, normalize_name, split_name, join_name, Theme
16 from wiki.forms import DocumentTextSaveForm, DocumentTagForm, DocumentCreateForm
17 from datetime import datetime
18 from django.utils.encoding import smart_unicode
19 from django.utils.translation import ugettext_lazy as _
20
21
22 #
23 # Quick hack around caching problems, TODO: use ETags
24 #
25 from django.views.decorators.cache import never_cache
26
27 import wlapi
28 import nice_diff
29 import operator
30
31 MAX_LAST_DOCS = 10
32
33
34 def normalized_name(view):
35
36     @functools.wraps(view)
37     def decorated(request, name, *args):
38         normalized = normalize_name(name)
39         logger.debug('View check %r -> %r', name, normalized)
40
41         if normalized != name:
42             return http.HttpResponseRedirect(
43                         reverse('wiki_' + view.__name__, kwargs={'name': normalized}))
44
45         return view(request, name, *args)
46
47     return decorated
48
49
50 @never_cache
51 def document_list(request):
52     return direct_to_template(request, 'wiki/document_list.html', extra_context={
53         'docs': getstorage().all(),
54         'last_docs': sorted(request.session.get("wiki_last_docs", {}).items(),
55                         key=operator.itemgetter(1), reverse=True),
56     })
57
58
59 @never_cache
60 @normalized_name
61 def editor(request, name, template_name='wiki/document_details.html'):
62     storage = getstorage()
63
64     try:
65         document = storage.get(name)
66     except DocumentNotFound:
67         return http.HttpResponseRedirect(reverse("wiki_create_missing", args=[name]))
68
69     access_time = datetime.now()
70     last_documents = request.session.get("wiki_last_docs", {})
71     last_documents[name] = access_time
72
73     if len(last_documents) > MAX_LAST_DOCS:
74         oldest_key = min(last_documents, key=last_documents.__getitem__)
75         del last_documents[oldest_key]
76     request.session['wiki_last_docs'] = last_documents
77
78     return direct_to_template(request, template_name, extra_context={
79         'document': document,
80         'document_name': document.name,
81         'document_info': document.info,
82         'document_meta': document.meta,
83         'forms': {
84             "text_save": DocumentTextSaveForm(prefix="textsave"),
85             "add_tag": DocumentTagForm(prefix="addtag"),
86         },
87     })
88
89
90 @require_GET
91 @normalized_name
92 def editor_readonly(request, name, template_name='wiki/document_details_readonly.html'):
93     name = normalize_name(name)
94     storage = getstorage()
95
96     try:
97         revision = request.GET['revision']
98         document = storage.get(name, revision)
99     except (KeyError, DocumentNotFound):
100         raise http.Http404
101
102     access_time = datetime.now()
103     last_documents = request.session.get("wiki_last_docs", {})
104     last_documents[name] = access_time
105
106     if len(last_documents) > MAX_LAST_DOCS:
107         oldest_key = min(last_documents, key=last_documents.__getitem__)
108         del last_documents[oldest_key]
109     request.session['wiki_last_docs'] = last_documents
110
111     return direct_to_template(request, template_name, extra_context={
112         'document': document,
113         'document_name': document.name,
114         'document_info': dict(document.info(), readonly=True),
115         'document_meta': document.meta,
116     })
117
118
119 @normalized_name
120 def create_missing(request, name):
121     storage = getstorage()
122
123     if request.method == "POST":
124         form = DocumentCreateForm(request.POST, request.FILES)
125         if form.is_valid():
126             doc = storage.create_document(
127                 id=form.cleaned_data['id'],
128                 text=form.cleaned_data['text'],
129             )
130
131             return http.HttpResponseRedirect(reverse("wiki_details", args=[doc.name]))
132     else:
133         form = DocumentCreateForm(initial={
134                 "id": name.replace(" ", "_"),
135                 "title": name.title(),
136         })
137
138     return direct_to_template(request, "wiki/document_create_missing.html", extra_context={
139         "document_name": name,
140         "form": form,
141     })
142
143
144 @never_cache
145 @normalized_name
146 def text(request, name):
147     storage = getstorage()
148
149     if request.method == 'POST':
150         form = DocumentTextSaveForm(request.POST, prefix="textsave")
151         if form.is_valid():
152             revision = form.cleaned_data['parent_revision']
153             document = storage.get_or_404(name, revision)          
154             document.text = form.cleaned_data['text']
155             comment = form.cleaned_data['comment']
156             if form.cleaned_data['stage_completed']:        
157                 comment += '\n#stage-finished: %s\n' % form.cleaned_data['stage_completed']         
158             author = "%s <%s>" % (form.cleaned_data['author_name'], form.cleaned_data['author_email'])           
159             storage.put(document, author=author, comment=comment, parent=revision)           
160             document = storage.get(name)          
161             return JSONResponse({
162                 'text': document.plain_text if revision != document.revision else None,
163                 'meta': document.meta(),
164                 'revision': document.revision,
165             })
166         else:
167             return JSONFormInvalid(form)
168     else:
169         revision = request.GET.get("revision", None)
170
171         try:
172             try:
173                 revision = revision and int(revision)
174                 logger.info("Fetching %s", revision)
175                 document = storage.get(name, revision)
176             except ValueError:
177                 # treat as a tag
178                 logger.info("Fetching tag %s", revision)
179                 document = storage.get_by_tag(name, revision)
180         except DocumentNotFound:
181             raise http.Http404
182
183         return JSONResponse({
184             'text': document.plain_text,
185             'meta': document.meta(),
186             'revision': document.revision,
187         })
188
189
190 @never_cache
191 @normalized_name
192 @require_POST
193 def revert(request, name):
194     storage = getstorage()
195     revision = request.POST['target_revision']
196
197     try:
198         document = storage.revert(name, revision)
199
200         return JSONResponse({
201             'text': document.plain_text if revision != document.revision else None,
202             'meta': document.meta(),
203             'revision': document.revision,
204         })
205     except DocumentNotFound:
206         raise http.Http404
207
208 @never_cache
209 def gallery(request, directory):
210     try:
211         base_url = ''.join((
212                         smart_unicode(settings.MEDIA_URL),
213                         smart_unicode(settings.FILEBROWSER_DIRECTORY),
214                         smart_unicode(directory)))
215
216         base_dir = os.path.join(
217                     smart_unicode(settings.MEDIA_ROOT),
218                     smart_unicode(settings.FILEBROWSER_DIRECTORY),
219                     smart_unicode(directory))
220
221         def map_to_url(filename):
222             return "%s/%s" % (base_url, smart_unicode(filename))
223
224         def is_image(filename):
225             return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
226
227         images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
228         images.sort()
229         return JSONResponse(images)
230     except (IndexError, OSError):
231         logger.exception("Unable to fetch gallery")
232         raise http.Http404
233
234
235 @never_cache
236 @normalized_name
237 def diff(request, name):
238     storage = getstorage()
239
240     revA = int(request.GET.get('from', 0))
241     revB = int(request.GET.get('to', 0))
242
243     if revA > revB:
244         revA, revB = revB, revA
245
246     if revB == 0:
247         revB = None
248
249     docA = storage.get_or_404(name, int(revA))
250     docB = storage.get_or_404(name, int(revB))
251
252     return http.HttpResponse(nice_diff.html_diff_table(docA.plain_text.splitlines(),
253                                          docB.plain_text.splitlines(), context=3))
254
255
256 @never_cache
257 @normalized_name
258 def history(request, name):
259     storage = getstorage()
260
261     # TODO: pagination
262     changesets = list(storage.history(name))
263
264     return JSONResponse(changesets)
265
266
267 @require_POST
268 @ajax_require_permission('wiki.can_change_tags')
269 def add_tag(request, name):
270     name = normalize_name(name)
271     storage = getstorage()
272
273     form = DocumentTagForm(request.POST, prefix="addtag")
274     if form.is_valid():
275         doc = storage.get_or_404(form.cleaned_data['id'])
276         doc.add_tag(tag=form.cleaned_data['tag'],
277                     revision=form.cleaned_data['revision'],
278                     author=request.user.username)
279         return JSONResponse({"message": _("Tag added")})
280     else:
281         return JSONFormInvalid(form)
282
283
284 @require_POST
285 @ajax_require_permission('wiki.can_publish')
286 def publish(request, name):
287     name = normalize_name(name)
288
289     storage = getstorage()
290     document = storage.get_by_tag(name, "ready_to_publish")
291
292     api = wlapi.WLAPI(**settings.WL_API_CONFIG)
293
294     try:
295         return JSONResponse({"result": api.publish_book(document)})
296     except wlapi.APICallException, e:
297         return JSONServerError({"message": str(e)})
298
299
300 def themes(request):
301     prefix = request.GET.get('q', '')
302     return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))