9b7d8076114c887428ef015376f829985d4201f3
[redakcja.git] / apps / wiki / views.py
1 import os
2
3 from django.conf import settings
4
5 from django.views.generic.simple import direct_to_template
6 from django.views.decorators.http import require_POST
7 from django.core.urlresolvers import reverse
8 from wiki.helpers import JSONResponse, JSONFormInvalid, JSONServerError, ajax_require_permission
9 from django import http
10
11 from wiki.models import getstorage, DocumentNotFound
12 from wiki.forms import DocumentTextSaveForm, DocumentTagForm, DocumentCreateForm
13 from datetime import datetime
14 from django.utils.encoding import smart_unicode
15 from django.utils.translation import ugettext_lazy as _
16
17 import wlapi
18
19 #
20 # Quick hack around caching problems, TODO: use ETags
21 #
22 from django.views.decorators.cache import never_cache
23
24 import logging
25 logger = logging.getLogger("fnp.peanut.api")
26
27 import nice_diff
28 import operator
29
30 MAX_LAST_DOCS = 10
31
32
33 @never_cache
34 def document_list(request, template_name='wiki/document_list.html'):
35     # TODO: find a way to cache "Storage All"
36     return direct_to_template(request, template_name, extra_context={
37         'document_list': getstorage().all(),
38         'last_docs': sorted(request.session.get("wiki_last_docs", {}).items(),
39                         key=operator.itemgetter(1), reverse=True),
40     })
41
42
43 @never_cache
44 def document_detail(request, name, template_name='wiki/document_details.html'):
45     storage = getstorage()
46
47     try:
48         document = storage.get(name)
49     except DocumentNotFound:
50         return http.HttpResponseRedirect(reverse("wiki_create_missing", args=[name]))
51
52     access_time = datetime.now()
53     last_documents = request.session.get("wiki_last_docs", {})
54     last_documents[name] = access_time
55
56     if len(last_documents) > MAX_LAST_DOCS:
57         oldest_key = min(last_documents, key=last_documents.__getitem__)
58         del last_documents[oldest_key]
59     request.session['wiki_last_docs'] = last_documents
60
61     return direct_to_template(request, template_name, extra_context={
62         'document': document,
63         'document_name': document.name,
64         'document_info': document.info,
65         'document_meta': document.meta,
66         'forms': {
67             "text_save": DocumentTextSaveForm(prefix="textsave"),
68             "add_tag": DocumentTagForm(prefix="addtag"),
69         },
70     })
71
72
73 def document_create_missing(request, name):
74     storage = getstorage()
75
76     if request.method == "POST":
77         form = DocumentCreateForm(request.POST, request.FILES)
78         if form.is_valid():
79             doc = storage.create_document(
80                 id=form.cleaned_data['id'],
81                 text=form.cleaned_data['text'],
82             )
83
84             return http.HttpResponseRedirect(reverse("wiki_details", args=[doc.name]))
85     else:
86         form = DocumentCreateForm(initial={
87                 "id": name.replace(" ", "_"),
88                 "title": name.title(),
89         })
90
91     return direct_to_template(request, "wiki/document_create_missing.html", extra_context={
92         "document_name": name,
93         "form": form,
94     })
95
96
97 @never_cache
98 def document_text(request, name):
99     storage = getstorage()
100
101     if request.method == 'POST':
102         form = DocumentTextSaveForm(request.POST, prefix="textsave")
103
104         if form.is_valid():
105             revision = form.cleaned_data['parent_revision']
106
107             document = storage.get_or_404(name, revision)
108             document.text = form.cleaned_data['text']
109
110             storage.put(document,
111                 author=form.cleaned_data['author'] or request.user.username,
112                 comment=form.cleaned_data['comment'],
113                 parent=revision,
114             )
115
116             document = storage.get(name)
117
118             return JSONResponse({
119                 'text': document.plain_text if revision != document.revision else None,
120                 'meta': document.meta(),
121                 'revision': document.revision,
122             })
123         else:
124             return JSONFormInvalid(form)
125     else:
126         revision = request.GET.get("revision", None)
127
128         try:
129             try:
130                 revision = revision and int(revision)
131                 logger.info("Fetching %s", revision)
132                 document = storage.get(name, revision)
133             except ValueError:
134                 # treat as a tag
135                 logger.info("Fetching tag %s", revision)
136                 document = storage.get_by_tag(name, revision)
137         except DocumentNotFound:
138             raise http.Http404
139
140         return JSONResponse({
141             'text': document.plain_text,
142             'meta': document.meta(),
143             'revision': document.revision,
144         })
145
146
147 @never_cache
148 def document_gallery(request, directory):
149     try:
150         base_url = ''.join((
151                         smart_unicode(settings.MEDIA_URL),
152                         smart_unicode(settings.FILEBROWSER_DIRECTORY),
153                         smart_unicode(directory)))
154
155         base_dir = os.path.join(
156                     smart_unicode(settings.MEDIA_ROOT),
157                     smart_unicode(settings.FILEBROWSER_DIRECTORY),
158                     smart_unicode(directory))
159
160         def map_to_url(filename):
161             return "%s/%s" % (base_url, smart_unicode(filename))
162
163         def is_image(filename):
164             return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
165
166         images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
167         images.sort()
168         return JSONResponse(images)
169     except (IndexError, OSError) as e:
170         logger.exception("Unable to fetch gallery")
171         raise http.Http404
172
173
174 @never_cache
175 def document_diff(request, name):
176     storage = getstorage()
177
178     revA = int(request.GET.get('from', 0))
179     revB = int(request.GET.get('to', 0))
180
181     if revA > revB:
182         revA, revB = revB, revA
183
184     if revB == 0:
185         revB = None
186
187     docA = storage.get_or_404(name, int(revA))
188     docB = storage.get_or_404(name, int(revB))
189
190     return http.HttpResponse(nice_diff.html_diff_table(docA.plain_text.splitlines(),
191                                          docB.plain_text.splitlines(), context=3))
192
193
194 @never_cache
195 def document_history(request, name):
196     storage = getstorage()
197
198     # TODO: pagination
199     changesets = list(storage.history(name))
200
201     return JSONResponse(changesets)
202
203
204 @require_POST
205 @ajax_require_permission('wiki.can_change_tags')
206 def document_add_tag(request, name):
207     storage = getstorage()
208
209     form = DocumentTagForm(request.POST, prefix="addtag")
210     if form.is_valid():
211         doc = storage.get_or_404(form.cleaned_data['id'])
212         doc.add_tag(tag=form.cleaned_data['tag'],
213                     revision=form.cleaned_data['revision'],
214                     author=request.user.username)
215         return JSONResponse({"message": _("Tag added")})
216     else:
217         return JSONFormInvalid(form)
218
219
220 @require_POST
221 @ajax_require_permission('wiki.can_publish')
222 def document_publish(request, name):
223     storage = getstorage()
224     document = storage.get_by_tag(name, "ready_to_publish")
225
226     api = wlapi.WLAPI(**settings.WL_API_CONFIG)
227
228     try:
229         return JSONResponse({"result": api.publish_book(document)})
230     except wlapi.APICallException, e:
231         return JSONServerError({"message": str(e)})