Added buttons to scroll toolbar buttons. Fixes #606.
[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, require_GET
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 @require_GET
74 def document_detail_readonly(request, name, template_name='wiki/document_details_readonly.html'):
75     storage = getstorage()
76
77     try:
78         revision = request.GET['revision']
79         document = storage.get(name, revision)
80     except (KeyError, DocumentNotFound) as e:
81         raise http.Http404
82
83     access_time = datetime.now()
84     last_documents = request.session.get("wiki_last_docs", {})
85     last_documents[name] = access_time
86
87     if len(last_documents) > MAX_LAST_DOCS:
88         oldest_key = min(last_documents, key=last_documents.__getitem__)
89         del last_documents[oldest_key]
90     request.session['wiki_last_docs'] = last_documents
91
92     return direct_to_template(request, template_name, extra_context={
93         'document': document,
94         'document_name': document.name,
95         'document_info': dict(document.info(), readonly=True),
96         'document_meta': document.meta,
97     })
98
99
100 def document_create_missing(request, name):
101     storage = getstorage()
102
103     if request.method == "POST":
104         form = DocumentCreateForm(request.POST, request.FILES)
105         if form.is_valid():
106             doc = storage.create_document(
107                 id=form.cleaned_data['id'],
108                 text=form.cleaned_data['text'],
109             )
110
111             return http.HttpResponseRedirect(reverse("wiki_details", args=[doc.name]))
112     else:
113         form = DocumentCreateForm(initial={
114                 "id": name.replace(" ", "_"),
115                 "title": name.title(),
116         })
117
118     return direct_to_template(request, "wiki/document_create_missing.html", extra_context={
119         "document_name": name,
120         "form": form,
121     })
122
123
124 @never_cache
125 def document_text(request, name):
126     storage = getstorage()
127
128     if request.method == 'POST':
129         form = DocumentTextSaveForm(request.POST, prefix="textsave")
130
131         if form.is_valid():
132             revision = form.cleaned_data['parent_revision']
133
134             document = storage.get_or_404(name, revision)
135             document.text = form.cleaned_data['text']
136
137             comment = form.cleaned_data['comment']
138
139             if form.cleaned_data['stage_completed']:
140                 comment += '\n#stage-finished: %s\n' % form.cleaned_data['stage_completed']
141
142             author = "%s <%s>" % (form.cleaned_data['author_name'], form.cleaned_data['author_email'])
143
144             storage.put(document, author=author, comment=comment, parent=revision)
145             document = storage.get(name)
146
147             return JSONResponse({
148                 'text': document.plain_text if revision != document.revision else None,
149                 'meta': document.meta(),
150                 'revision': document.revision,
151             })
152         else:
153             return JSONFormInvalid(form)
154     else:
155         revision = request.GET.get("revision", None)
156
157         try:
158             try:
159                 revision = revision and int(revision)
160                 logger.info("Fetching %s", revision)
161                 document = storage.get(name, revision)
162             except ValueError:
163                 # treat as a tag
164                 logger.info("Fetching tag %s", revision)
165                 document = storage.get_by_tag(name, revision)
166         except DocumentNotFound:
167             raise http.Http404
168
169         return JSONResponse({
170             'text': document.plain_text,
171             'meta': document.meta(),
172             'revision': document.revision,
173         })
174
175
176 @never_cache
177 def document_gallery(request, directory):
178     try:
179         base_url = ''.join((
180                         smart_unicode(settings.MEDIA_URL),
181                         smart_unicode(settings.FILEBROWSER_DIRECTORY),
182                         smart_unicode(directory)))
183
184         base_dir = os.path.join(
185                     smart_unicode(settings.MEDIA_ROOT),
186                     smart_unicode(settings.FILEBROWSER_DIRECTORY),
187                     smart_unicode(directory))
188
189         def map_to_url(filename):
190             return "%s/%s" % (base_url, smart_unicode(filename))
191
192         def is_image(filename):
193             return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
194
195         images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
196         images.sort()
197         return JSONResponse(images)
198     except (IndexError, OSError) as e:
199         logger.exception("Unable to fetch gallery")
200         raise http.Http404
201
202
203 @never_cache
204 def document_diff(request, name):
205     storage = getstorage()
206
207     revA = int(request.GET.get('from', 0))
208     revB = int(request.GET.get('to', 0))
209
210     if revA > revB:
211         revA, revB = revB, revA
212
213     if revB == 0:
214         revB = None
215
216     docA = storage.get_or_404(name, int(revA))
217     docB = storage.get_or_404(name, int(revB))
218
219     return http.HttpResponse(nice_diff.html_diff_table(docA.plain_text.splitlines(),
220                                          docB.plain_text.splitlines(), context=3))
221
222
223 @never_cache
224 def document_history(request, name):
225     storage = getstorage()
226
227     # TODO: pagination
228     changesets = list(storage.history(name))
229
230     return JSONResponse(changesets)
231
232
233 @require_POST
234 @ajax_require_permission('wiki.can_change_tags')
235 def document_add_tag(request, name):
236     storage = getstorage()
237
238     form = DocumentTagForm(request.POST, prefix="addtag")
239     if form.is_valid():
240         doc = storage.get_or_404(form.cleaned_data['id'])
241         doc.add_tag(tag=form.cleaned_data['tag'],
242                     revision=form.cleaned_data['revision'],
243                     author=request.user.username)
244         return JSONResponse({"message": _("Tag added")})
245     else:
246         return JSONFormInvalid(form)
247
248
249 @require_POST
250 @ajax_require_permission('wiki.can_publish')
251 def document_publish(request, name):
252     storage = getstorage()
253     document = storage.get_by_tag(name, "ready_to_publish")
254
255     api = wlapi.WLAPI(**settings.WL_API_CONFIG)
256
257     try:
258         return JSONResponse({"result": api.publish_book(document)})
259     except wlapi.APICallException, e:
260         return JSONServerError({"message": str(e)})