3 from django.conf import settings
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
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 _
20 # Quick hack around caching problems, TODO: use ETags
22 from django.views.decorators.cache import never_cache
25 logger = logging.getLogger("fnp.peanut.api")
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),
44 def document_detail(request, name, template_name='wiki/document_details.html'):
45 storage = getstorage()
48 document = storage.get(name)
49 except DocumentNotFound:
50 return http.HttpResponseRedirect(reverse("wiki_create_missing", args=[name]))
52 access_time = datetime.now()
53 last_documents = request.session.get("wiki_last_docs", {})
54 last_documents[name] = access_time
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
61 return direct_to_template(request, template_name, extra_context={
63 'document_name': document.name,
64 'document_info': document.info,
65 'document_meta': document.meta,
67 "text_save": DocumentTextSaveForm(prefix="textsave"),
68 "add_tag": DocumentTagForm(prefix="addtag"),
74 def document_detail_readonly(request, name, template_name='wiki/document_details_readonly.html'):
75 storage = getstorage()
78 revision = request.GET['revision']
79 document = storage.get(name, revision)
80 except (KeyError, DocumentNotFound) as e:
83 access_time = datetime.now()
84 last_documents = request.session.get("wiki_last_docs", {})
85 last_documents[name] = access_time
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
92 return direct_to_template(request, template_name, extra_context={
94 'document_name': document.name,
95 'document_info': dict(document.info(), readonly=True),
96 'document_meta': document.meta,
100 def document_create_missing(request, name):
101 storage = getstorage()
103 if request.method == "POST":
104 form = DocumentCreateForm(request.POST, request.FILES)
106 doc = storage.create_document(
107 id=form.cleaned_data['id'],
108 text=form.cleaned_data['text'],
111 return http.HttpResponseRedirect(reverse("wiki_details", args=[doc.name]))
113 form = DocumentCreateForm(initial={
114 "id": name.replace(" ", "_"),
115 "title": name.title(),
118 return direct_to_template(request, "wiki/document_create_missing.html", extra_context={
119 "document_name": name,
125 def document_text(request, name):
126 storage = getstorage()
128 if request.method == 'POST':
129 form = DocumentTextSaveForm(request.POST, prefix="textsave")
132 revision = form.cleaned_data['parent_revision']
134 document = storage.get_or_404(name, revision)
135 document.text = form.cleaned_data['text']
137 storage.put(document,
138 author=form.cleaned_data['author'] or request.user.username,
139 comment=form.cleaned_data['comment'],
143 document = storage.get(name)
145 return JSONResponse({
146 'text': document.plain_text if revision != document.revision else None,
147 'meta': document.meta(),
148 'revision': document.revision,
151 return JSONFormInvalid(form)
153 revision = request.GET.get("revision", None)
157 revision = revision and int(revision)
158 logger.info("Fetching %s", revision)
159 document = storage.get(name, revision)
162 logger.info("Fetching tag %s", revision)
163 document = storage.get_by_tag(name, revision)
164 except DocumentNotFound:
167 return JSONResponse({
168 'text': document.plain_text,
169 'meta': document.meta(),
170 'revision': document.revision,
175 def document_gallery(request, directory):
178 smart_unicode(settings.MEDIA_URL),
179 smart_unicode(settings.FILEBROWSER_DIRECTORY),
180 smart_unicode(directory)))
182 base_dir = os.path.join(
183 smart_unicode(settings.MEDIA_ROOT),
184 smart_unicode(settings.FILEBROWSER_DIRECTORY),
185 smart_unicode(directory))
187 def map_to_url(filename):
188 return "%s/%s" % (base_url, smart_unicode(filename))
190 def is_image(filename):
191 return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
193 images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
195 return JSONResponse(images)
196 except (IndexError, OSError) as e:
197 logger.exception("Unable to fetch gallery")
202 def document_diff(request, name):
203 storage = getstorage()
205 revA = int(request.GET.get('from', 0))
206 revB = int(request.GET.get('to', 0))
209 revA, revB = revB, revA
214 docA = storage.get_or_404(name, int(revA))
215 docB = storage.get_or_404(name, int(revB))
217 return http.HttpResponse(nice_diff.html_diff_table(docA.plain_text.splitlines(),
218 docB.plain_text.splitlines(), context=3))
222 def document_history(request, name):
223 storage = getstorage()
226 changesets = list(storage.history(name))
228 return JSONResponse(changesets)
232 @ajax_require_permission('wiki.can_change_tags')
233 def document_add_tag(request, name):
234 storage = getstorage()
236 form = DocumentTagForm(request.POST, prefix="addtag")
238 doc = storage.get_or_404(form.cleaned_data['id'])
239 doc.add_tag(tag=form.cleaned_data['tag'],
240 revision=form.cleaned_data['revision'],
241 author=request.user.username)
242 return JSONResponse({"message": _("Tag added")})
244 return JSONFormInvalid(form)
248 @ajax_require_permission('wiki.can_publish')
249 def document_publish(request, name):
250 storage = getstorage()
251 document = storage.get_by_tag(name, "ready_to_publish")
253 api = wlapi.WLAPI(**settings.WL_API_CONFIG)
256 return JSONResponse({"result": api.publish_book(document)})
257 except wlapi.APICallException, e:
258 return JSONServerError({"message": str(e)})
262 return http.HttpResponse('pong')