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 wiki.models import getstorage, DocumentNotFound, normalize_name, split_name, join_name, Theme
16 from wiki.forms import DocumentTextSaveForm, DocumentTextRevertForm, DocumentTagForm, DocumentCreateForm, DocumentsUploadForm
17 from datetime import datetime
18 from django.utils.encoding import smart_unicode
19 from django.utils.translation import ugettext_lazy as _
20 from django.utils.decorators import decorator_from_middleware
21 from django.middleware.gzip import GZipMiddleware
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 "text_revert": DocumentTextRevertForm(prefix="textrevert"),
88 "add_tag": DocumentTagForm(prefix="addtag"),
90 'REDMINE_URL': settings.REDMINE_URL,
96 def editor_readonly(request, name, template_name='wiki/document_details_readonly.html'):
97 name = normalize_name(name)
98 storage = getstorage()
101 revision = request.GET['revision']
102 document = storage.get(name, revision)
103 except (KeyError, DocumentNotFound):
106 access_time = datetime.now()
107 last_documents = request.session.get("wiki_last_docs", {})
108 last_documents[name] = access_time
110 if len(last_documents) > MAX_LAST_DOCS:
111 oldest_key = min(last_documents, key=last_documents.__getitem__)
112 del last_documents[oldest_key]
113 request.session['wiki_last_docs'] = last_documents
115 return direct_to_template(request, template_name, extra_context={
116 'document': document,
117 'document_name': document.name,
118 'document_info': dict(document.info(), readonly=True),
119 'document_meta': document.meta,
120 'REDMINE_URL': settings.REDMINE_URL,
125 def create_missing(request, name):
126 storage = getstorage()
128 if request.method == "POST":
129 form = DocumentCreateForm(request.POST, request.FILES)
131 doc = storage.create_document(
132 name=form.cleaned_data['id'],
133 text=form.cleaned_data['text'],
136 return http.HttpResponseRedirect(reverse("wiki_editor", args=[doc.name]))
138 form = DocumentCreateForm(initial={
139 "id": name.replace(" ", "_"),
140 "title": name.title(),
143 return direct_to_template(request, "wiki/document_create_missing.html", extra_context={
144 "document_name": name,
150 storage = getstorage()
152 if request.method == "POST":
153 form = DocumentsUploadForm(request.POST, request.FILES)
155 zip = form.cleaned_data['zip']
160 existing = storage.all()
161 for filename in zip.namelist():
162 if filename[-1] == '/':
164 title = normalize_name(os.path.basename(filename)[:-4])
165 if not (title and filename.endswith('.xml')):
166 skipped_list.append(filename)
167 elif title in titles:
168 error_list.append((filename, title, _('Title already used for %s' % titles[title])))
169 elif title in existing:
170 error_list.append((filename, title, _('Title already used in repository.')))
173 zip.read(filename).decode('utf-8') # test read
174 ok_list.append((filename, title))
175 except UnicodeDecodeError:
176 error_list.append((filename, title, _('File should be UTF-8 encoded.')))
177 titles[title] = filename
180 for filename, title in ok_list:
181 storage.create_document(
183 text=zip.read(filename).decode('utf-8')
186 return direct_to_template(request, "wiki/document_upload.html", extra_context={
189 "skipped_list": skipped_list,
190 "error_list": error_list,
192 #doc = storage.create_document(
194 # text=form.cleaned_data['text'],
197 return http.HttpResponse('\n'.join(yeslist) + '\n\n' + '\n'.join(nolist))
199 form = DocumentsUploadForm()
201 return direct_to_template(request, "wiki/document_upload.html", extra_context={
208 @decorator_from_middleware(GZipMiddleware)
209 def text(request, name):
210 storage = getstorage()
212 if request.method == 'POST':
213 form = DocumentTextSaveForm(request.POST, prefix="textsave")
215 revision = form.cleaned_data['parent_revision']
216 document = storage.get_or_404(name, revision)
217 document.text = form.cleaned_data['text']
218 comment = form.cleaned_data['comment']
219 if form.cleaned_data['stage_completed']:
220 comment += '\n#stage-finished: %s\n' % form.cleaned_data['stage_completed']
221 if request.user.is_authenticated():
222 author_name = request.user
223 author_email = request.user.email
225 author_name = form.cleaned_data['author_name']
226 author_email = form.cleaned_data['author_email']
227 author = "%s <%s>" % (author_name, author_email)
228 storage.put(document, author=author, comment=comment, parent=revision)
229 document = storage.get(name)
230 return JSONResponse({
231 'text': document.plain_text if revision != document.revision else None,
232 'meta': document.meta(),
233 'revision': document.revision,
236 return JSONFormInvalid(form)
238 revision = request.GET.get("revision", None)
242 revision = revision and int(revision)
243 logger.info("Fetching %s", revision)
244 document = storage.get(name, revision)
247 logger.info("Fetching tag %s", revision)
248 document = storage.get_by_tag(name, revision)
249 except DocumentNotFound:
252 return JSONResponse({
253 'text': document.plain_text,
254 'meta': document.meta(),
255 'revision': document.revision,
262 def revert(request, name):
263 storage = getstorage()
264 form = DocumentTextRevertForm(request.POST, prefix="textrevert")
267 revision = form.cleaned_data['revision']
269 comment = form.cleaned_data['comment']
270 comment += "\n#revert to %s" % revision
272 if request.user.is_authenticated():
273 author_name = request.user
274 author_email = request.user.email
276 author_name = form.cleaned_data['author_name']
277 author_email = form.cleaned_data['author_email']
278 author = "%s <%s>" % (author_name, author_email)
280 before = storage.get(name).revision
281 logger.info("Reverting %s to %s", name, revision)
282 storage.revert(name, revision, comment=comment, author=author)
283 logger.info("Fetching %s", name)
284 document = storage.get(name)
287 return JSONResponse({
288 'text': document.plain_text if before != document.revision else None,
289 'meta': document.meta(),
290 'revision': document.revision,
294 return JSONFormInvalid(form)
298 def gallery(request, directory):
301 smart_unicode(settings.MEDIA_URL),
302 smart_unicode(settings.FILEBROWSER_DIRECTORY),
303 smart_unicode(directory)))
305 base_dir = os.path.join(
306 smart_unicode(settings.MEDIA_ROOT),
307 smart_unicode(settings.FILEBROWSER_DIRECTORY),
308 smart_unicode(directory))
310 def map_to_url(filename):
311 return "%s/%s" % (base_url, smart_unicode(filename))
313 def is_image(filename):
314 return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
316 images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
318 return JSONResponse(images)
319 except (IndexError, OSError):
320 logger.exception("Unable to fetch gallery")
326 def diff(request, name):
327 storage = getstorage()
329 revA = int(request.GET.get('from', 0))
330 revB = int(request.GET.get('to', 0))
333 revA, revB = revB, revA
338 docA = storage.get_or_404(name, int(revA))
339 docB = storage.get_or_404(name, int(revB))
341 return http.HttpResponse(nice_diff.html_diff_table(docA.plain_text.splitlines(),
342 docB.plain_text.splitlines(), context=3))
347 def revision(request, name):
348 storage = getstorage()
351 return http.HttpResponse(str(storage.doc_meta(name)['revision']))
352 except DocumentNotFound:
358 def history(request, name):
359 storage = getstorage()
362 changesets = list(storage.history(name))
364 return JSONResponse(changesets)
368 @ajax_require_permission('wiki.can_change_tags')
369 def add_tag(request, name):
370 name = normalize_name(name)
371 storage = getstorage()
373 form = DocumentTagForm(request.POST, prefix="addtag")
375 doc = storage.get_or_404(form.cleaned_data['id'])
376 doc.add_tag(tag=form.cleaned_data['tag'],
377 revision=form.cleaned_data['revision'],
378 author=request.user.username)
379 return JSONResponse({"message": _("Tag added")})
381 return JSONFormInvalid(form)
385 @ajax_require_permission('wiki.can_publish')
386 def publish(request, name):
387 name = normalize_name(name)
389 storage = getstorage()
390 document = storage.get_by_tag(name, "ready_to_publish")
392 api = wlapi.WLAPI(**settings.WL_API_CONFIG)
395 return JSONResponse({"result": api.publish_book(document)})
396 except wlapi.APICallException, e:
397 return JSONServerError({"message": str(e)})
401 prefix = request.GET.get('q', '')
402 return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))