4 logger = logging.getLogger("fnp.wiki")
6 from django.conf import settings
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
15 from django.contrib.auth.decorators import login_required
17 from wiki.models import getstorage, DocumentNotFound, normalize_name, split_name, join_name
18 from wiki.forms import DocumentTextSaveForm, DocumentTagForm, DocumentCreateForm
19 from datetime import datetime
20 from django.utils.encoding import smart_unicode
21 from django.utils.translation import ugettext_lazy as _
25 # Quick hack around caching problems, TODO: use ETags
27 from django.views.decorators.cache import never_cache
36 def normalized_name(view):
38 @functools.wraps(view)
39 def decorated(request, name, *args):
40 normalized = normalize_name(name)
41 logger.debug('View check %r -> %r', name, normalized)
43 if normalized != name:
44 return http.HttpResponseRedirect(
45 reverse('wiki_' + view.__name__, kwargs={'name': normalized}))
47 return view(request, name, *args)
53 def document_list(request):
54 return direct_to_template(request, 'wiki/document_list.html', extra_context={
55 'docs': getstorage().all(),
56 'last_docs': sorted(request.session.get("wiki_last_docs", {}).items(),
57 key=operator.itemgetter(1), reverse=True),
63 def editor(request, name, template_name='wiki/document_details.html'):
64 storage = getstorage()
67 document = storage.get(name)
68 except DocumentNotFound:
69 return http.HttpResponseRedirect(reverse("wiki_create_missing", args=[name]))
71 access_time = datetime.now()
72 last_documents = request.session.get("wiki_last_docs", {})
73 last_documents[name] = access_time
75 if len(last_documents) > MAX_LAST_DOCS:
76 oldest_key = min(last_documents, key=last_documents.__getitem__)
77 del last_documents[oldest_key]
78 request.session['wiki_last_docs'] = last_documents
80 return direct_to_template(request, template_name, extra_context={
82 'document_name': document.name,
83 'document_info': document.info,
84 'document_meta': document.meta,
86 "text_save": DocumentTextSaveForm(prefix="textsave"),
87 "add_tag": DocumentTagForm(prefix="addtag"),
94 def editor_readonly(request, name, template_name='wiki/document_details_readonly.html'):
95 name = normalize_name(name)
96 storage = getstorage()
99 revision = request.GET['revision']
100 document = storage.get(name, revision)
101 except (KeyError, DocumentNotFound) as e:
104 access_time = datetime.now()
105 last_documents = request.session.get("wiki_last_docs", {})
106 last_documents[name] = access_time
108 if len(last_documents) > MAX_LAST_DOCS:
109 oldest_key = min(last_documents, key=last_documents.__getitem__)
110 del last_documents[oldest_key]
111 request.session['wiki_last_docs'] = last_documents
113 return direct_to_template(request, template_name, extra_context={
114 'document': document,
115 'document_name': document.name,
116 'document_info': dict(document.info(), readonly=True),
117 'document_meta': document.meta,
122 def create_missing(request, name):
123 storage = getstorage()
125 if request.method == "POST":
126 form = DocumentCreateForm(request.POST, request.FILES)
128 doc = storage.create_document(
129 name=form.cleaned_data['id'],
130 text=form.cleaned_data['text'],
133 return http.HttpResponseRedirect(reverse("wiki_editor", args=[doc.name]))
135 form = DocumentCreateForm(initial={
136 "id": name.replace(" ", "_"),
137 "title": name.title(),
140 return direct_to_template(request, "wiki/document_create_missing.html", extra_context={
141 "document_name": name,
148 def text(request, name):
149 storage = getstorage()
151 if request.method == 'POST':
152 form = DocumentTextSaveForm(request.POST, prefix="textsave")
155 revision = form.cleaned_data['parent_revision']
157 document = storage.get_or_404(name, revision)
158 document.text = form.cleaned_data['text']
160 comment = form.cleaned_data['comment']
162 if form.cleaned_data['stage_completed']:
163 comment += '\n#stage-finished: %s\n' % form.cleaned_data['stage_completed']
165 author = "%s <%s>" % (form.cleaned_data['author_name'], form.cleaned_data['author_email'])
167 storage.put(document, author=author, comment=comment, parent=revision)
168 document = storage.get(name)
170 return JSONResponse({
171 'text': document.plain_text if revision != document.revision else None,
172 'meta': document.meta(),
173 'revision': document.revision,
176 return JSONFormInvalid(form)
178 revision = request.GET.get("revision", None)
182 revision = revision and int(revision)
183 logger.info("Fetching %s", revision)
184 document = storage.get(name, revision)
187 logger.info("Fetching tag %s", revision)
188 document = storage.get_by_tag(name, revision)
189 except DocumentNotFound:
192 return JSONResponse({
193 'text': document.plain_text,
194 'meta': document.meta(),
195 'revision': document.revision,
202 def revert(request, name):
203 storage = getstorage()
204 revision = request.POST['target_revision']
207 document = storage.revert(name, revision)
209 return JSONResponse({
210 'text': document.plain_text if revision != document.revision else None,
211 'meta': document.meta(),
212 'revision': document.revision,
214 except DocumentNotFound:
218 def gallery(request, directory):
221 smart_unicode(settings.MEDIA_URL),
222 smart_unicode(settings.FILEBROWSER_DIRECTORY),
223 smart_unicode(directory)))
225 base_dir = os.path.join(
226 smart_unicode(settings.MEDIA_ROOT),
227 smart_unicode(settings.FILEBROWSER_DIRECTORY),
228 smart_unicode(directory))
230 def map_to_url(filename):
231 return "%s/%s" % (base_url, smart_unicode(filename))
233 def is_image(filename):
234 return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
236 images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
238 return JSONResponse(images)
239 except (IndexError, OSError) as e:
240 logger.exception("Unable to fetch gallery")
246 def diff(request, name):
247 storage = getstorage()
249 revA = int(request.GET.get('from', 0))
250 revB = int(request.GET.get('to', 0))
253 revA, revB = revB, revA
258 docA = storage.get_or_404(name, int(revA))
259 docB = storage.get_or_404(name, int(revB))
261 return http.HttpResponse(nice_diff.html_diff_table(docA.plain_text.splitlines(),
262 docB.plain_text.splitlines(), context=3))
267 def history(request, name):
268 storage = getstorage()
271 changesets = list(storage.history(name))
273 return JSONResponse(changesets)
277 @ajax_require_permission('wiki.can_change_tags')
278 def add_tag(request, name):
279 name = normalize_name(name)
280 storage = getstorage()
282 form = DocumentTagForm(request.POST, prefix="addtag")
284 doc = storage.get_or_404(form.cleaned_data['id'])
285 doc.add_tag(tag=form.cleaned_data['tag'],
286 revision=form.cleaned_data['revision'],
287 author=request.user.username)
288 return JSONResponse({"message": _("Tag added")})
290 return JSONFormInvalid(form)
294 @ajax_require_permission('wiki.can_publish')
295 def publish(request, name):
296 name = normalize_name(name)
298 storage = getstorage()
299 document = storage.get_by_tag(name, "ready_to_publish")
301 api = wlapi.WLAPI(**settings.WL_API_CONFIG)
304 return JSONResponse({"result": api.publish_book(document)})
305 except wlapi.APICallException, e:
306 return JSONServerError({"message": str(e)})
309 def status_report(request):