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, 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 "add_tag": DocumentTagForm(prefix="addtag"),
89 'REDMINE_URL': settings.REDMINE_URL,
95 def editor_readonly(request, name, template_name='wiki/document_details_readonly.html'):
96 name = normalize_name(name)
97 storage = getstorage()
100 revision = request.GET['revision']
101 document = storage.get(name, revision)
102 except (KeyError, DocumentNotFound):
105 access_time = datetime.now()
106 last_documents = request.session.get("wiki_last_docs", {})
107 last_documents[name] = access_time
109 if len(last_documents) > MAX_LAST_DOCS:
110 oldest_key = min(last_documents, key=last_documents.__getitem__)
111 del last_documents[oldest_key]
112 request.session['wiki_last_docs'] = last_documents
114 return direct_to_template(request, template_name, extra_context={
115 'document': document,
116 'document_name': document.name,
117 'document_info': dict(document.info(), readonly=True),
118 'document_meta': document.meta,
119 'REDMINE_URL': settings.REDMINE_URL,
124 def create_missing(request, name):
125 storage = getstorage()
127 if request.method == "POST":
128 form = DocumentCreateForm(request.POST, request.FILES)
130 doc = storage.create_document(
131 name=form.cleaned_data['id'],
132 text=form.cleaned_data['text'],
135 return http.HttpResponseRedirect(reverse("wiki_editor", args=[doc.name]))
137 form = DocumentCreateForm(initial={
138 "id": name.replace(" ", "_"),
139 "title": name.title(),
142 return direct_to_template(request, "wiki/document_create_missing.html", extra_context={
143 "document_name": name,
149 storage = getstorage()
151 if request.method == "POST":
152 form = DocumentsUploadForm(request.POST, request.FILES)
154 zip = form.cleaned_data['zip']
159 existing = storage.all()
160 for filename in zip.namelist():
161 if filename[-1] == '/':
163 title = normalize_name(os.path.basename(filename)[:-4])
164 if not (title and filename.endswith('.xml')):
165 skipped_list.append(filename)
166 elif title in titles:
167 error_list.append((filename, title, _('Title already used for %s' % titles[title])))
168 elif title in existing:
169 error_list.append((filename, title, _('Title already used in repository.')))
172 zip.read(filename).decode('utf-8') # test read
173 ok_list.append((filename, title))
174 except UnicodeDecodeError:
175 error_list.append((filename, title, _('File should be UTF-8 encoded.')))
176 titles[title] = filename
179 for filename, title in ok_list:
180 storage.create_document(
182 text=zip.read(filename).decode('utf-8')
185 return direct_to_template(request, "wiki/document_upload.html", extra_context={
188 "skipped_list": skipped_list,
189 "error_list": error_list,
191 #doc = storage.create_document(
193 # text=form.cleaned_data['text'],
196 return http.HttpResponse('\n'.join(yeslist) + '\n\n' + '\n'.join(nolist))
198 form = DocumentsUploadForm()
200 return direct_to_template(request, "wiki/document_upload.html", extra_context={
207 @decorator_from_middleware(GZipMiddleware)
208 def text(request, name):
209 storage = getstorage()
211 if request.method == 'POST':
212 form = DocumentTextSaveForm(request.POST, prefix="textsave")
214 revision = form.cleaned_data['parent_revision']
215 document = storage.get_or_404(name, revision)
216 document.text = form.cleaned_data['text']
217 comment = form.cleaned_data['comment']
218 if form.cleaned_data['stage_completed']:
219 comment += '\n#stage-finished: %s\n' % form.cleaned_data['stage_completed']
220 if request.user.is_authenticated():
221 author_name = request.user
222 author_email = request.user.email
224 author_name = form.cleaned_data['author_name']
225 author_email = form.cleaned_data['author_email']
226 author = "%s <%s>" % (author_name, author_email)
227 storage.put(document, author=author, comment=comment, parent=revision)
228 document = storage.get(name)
229 return JSONResponse({
230 'text': document.plain_text if revision != document.revision else None,
231 'meta': document.meta(),
232 'revision': document.revision,
235 return JSONFormInvalid(form)
237 revision = request.GET.get("revision", None)
241 revision = revision and int(revision)
242 logger.info("Fetching %s", revision)
243 document = storage.get(name, revision)
246 logger.info("Fetching tag %s", revision)
247 document = storage.get_by_tag(name, revision)
248 except DocumentNotFound:
251 return JSONResponse({
252 'text': document.plain_text,
253 'meta': document.meta(),
254 'revision': document.revision,
261 def revert(request, name):
262 storage = getstorage()
263 revision = request.POST['target_revision']
266 document = storage.revert(name, revision)
268 return JSONResponse({
269 'text': document.plain_text if revision != document.revision else None,
270 'meta': document.meta(),
271 'revision': document.revision,
273 except DocumentNotFound:
277 def gallery(request, directory):
280 smart_unicode(settings.MEDIA_URL),
281 smart_unicode(settings.FILEBROWSER_DIRECTORY),
282 smart_unicode(directory)))
284 base_dir = os.path.join(
285 smart_unicode(settings.MEDIA_ROOT),
286 smart_unicode(settings.FILEBROWSER_DIRECTORY),
287 smart_unicode(directory))
289 def map_to_url(filename):
290 return "%s/%s" % (base_url, smart_unicode(filename))
292 def is_image(filename):
293 return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
295 images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
297 return JSONResponse(images)
298 except (IndexError, OSError):
299 logger.exception("Unable to fetch gallery")
305 def diff(request, name):
306 storage = getstorage()
308 revA = int(request.GET.get('from', 0))
309 revB = int(request.GET.get('to', 0))
312 revA, revB = revB, revA
317 docA = storage.get_or_404(name, int(revA))
318 docB = storage.get_or_404(name, int(revB))
320 return http.HttpResponse(nice_diff.html_diff_table(docA.plain_text.splitlines(),
321 docB.plain_text.splitlines(), context=3))
326 def revision(request, name):
327 storage = getstorage()
330 return http.HttpResponse(str(storage.doc_meta(name)['revision']))
331 except DocumentNotFound:
337 def history(request, name):
338 storage = getstorage()
341 changesets = list(storage.history(name))
343 return JSONResponse(changesets)
347 @ajax_require_permission('wiki.can_change_tags')
348 def add_tag(request, name):
349 name = normalize_name(name)
350 storage = getstorage()
352 form = DocumentTagForm(request.POST, prefix="addtag")
354 doc = storage.get_or_404(form.cleaned_data['id'])
355 doc.add_tag(tag=form.cleaned_data['tag'],
356 revision=form.cleaned_data['revision'],
357 author=request.user.username)
358 return JSONResponse({"message": _("Tag added")})
360 return JSONFormInvalid(form)
364 @ajax_require_permission('wiki.can_publish')
365 def publish(request, name):
366 name = normalize_name(name)
368 storage = getstorage()
369 document = storage.get_by_tag(name, "ready_to_publish")
371 api = wlapi.WLAPI(**settings.WL_API_CONFIG)
374 return JSONResponse({"result": api.publish_book(document)})
375 except wlapi.APICallException, e:
376 return JSONServerError({"message": str(e)})
380 prefix = request.GET.get('q', '')
381 return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))