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
16 from wiki.forms import DocumentTextSaveForm, DocumentTagForm, DocumentCreateForm
17 from datetime import datetime
18 from django.utils.encoding import smart_unicode
19 from django.utils.translation import ugettext_lazy as _
23 # Quick hack around caching problems, TODO: use ETags
25 from django.views.decorators.cache import never_cache
34 def normalized_name(view):
36 @functools.wraps(view)
37 def decorated(request, name, *args):
38 normalized = normalize_name(name)
39 logger.debug('View check %r -> %r', name, normalized)
41 if normalized != name:
42 return http.HttpResponseRedirect(
43 reverse('wiki_' + view.__name__, kwargs={'name': normalized}))
45 return view(request, name, *args)
51 def document_list(request):
52 return direct_to_template(request, 'wiki/document_list.html', extra_context={
53 'docs': getstorage().all(),
54 'last_docs': sorted(request.session.get("wiki_last_docs", {}).items(),
55 key=operator.itemgetter(1), reverse=True),
61 def editor(request, name, template_name='wiki/document_details.html'):
62 storage = getstorage()
65 document = storage.get(name)
66 except DocumentNotFound:
67 return http.HttpResponseRedirect(reverse("wiki_create_missing", args=[name]))
69 access_time = datetime.now()
70 last_documents = request.session.get("wiki_last_docs", {})
71 last_documents[name] = access_time
73 if len(last_documents) > MAX_LAST_DOCS:
74 oldest_key = min(last_documents, key=last_documents.__getitem__)
75 del last_documents[oldest_key]
76 request.session['wiki_last_docs'] = last_documents
78 return direct_to_template(request, template_name, extra_context={
80 'document_name': document.name,
81 'document_info': document.info,
82 'document_meta': document.meta,
84 "text_save": DocumentTextSaveForm(prefix="textsave"),
85 "add_tag": DocumentTagForm(prefix="addtag"),
92 def editor_readonly(request, name, template_name='wiki/document_details_readonly.html'):
93 name = normalize_name(name)
94 storage = getstorage()
97 revision = request.GET['revision']
98 document = storage.get(name, revision)
99 except (KeyError, DocumentNotFound) as e:
102 access_time = datetime.now()
103 last_documents = request.session.get("wiki_last_docs", {})
104 last_documents[name] = access_time
106 if len(last_documents) > MAX_LAST_DOCS:
107 oldest_key = min(last_documents, key=last_documents.__getitem__)
108 del last_documents[oldest_key]
109 request.session['wiki_last_docs'] = last_documents
111 return direct_to_template(request, template_name, extra_context={
112 'document': document,
113 'document_name': document.name,
114 'document_info': dict(document.info(), readonly=True),
115 'document_meta': document.meta,
120 def create_missing(request, name):
121 storage = getstorage()
123 if request.method == "POST":
124 form = DocumentCreateForm(request.POST, request.FILES)
126 doc = storage.create_document(
127 id=form.cleaned_data['id'],
128 text=form.cleaned_data['text'],
131 return http.HttpResponseRedirect(reverse("wiki_details", args=[doc.name]))
133 form = DocumentCreateForm(initial={
134 "id": name.replace(" ", "_"),
135 "title": name.title(),
138 return direct_to_template(request, "wiki/document_create_missing.html", extra_context={
139 "document_name": name,
146 def text(request, name):
147 storage = getstorage()
149 if request.method == 'POST':
150 form = DocumentTextSaveForm(request.POST, prefix="textsave")
153 revision = form.cleaned_data['parent_revision']
155 document = storage.get_or_404(name, revision)
156 document.text = form.cleaned_data['text']
158 comment = form.cleaned_data['comment']
160 if form.cleaned_data['stage_completed']:
161 comment += '\n#stage-finished: %s\n' % form.cleaned_data['stage_completed']
163 author = "%s <%s>" % (form.cleaned_data['author_name'], form.cleaned_data['author_email'])
165 storage.put(document, author=author, comment=comment, parent=revision)
166 document = storage.get(name)
168 return JSONResponse({
169 'text': document.plain_text if revision != document.revision else None,
170 'meta': document.meta(),
171 'revision': document.revision,
174 return JSONFormInvalid(form)
176 revision = request.GET.get("revision", None)
180 revision = revision and int(revision)
181 logger.info("Fetching %s", revision)
182 document = storage.get(name, revision)
185 logger.info("Fetching tag %s", revision)
186 document = storage.get_by_tag(name, revision)
187 except DocumentNotFound:
190 return JSONResponse({
191 'text': document.plain_text,
192 'meta': document.meta(),
193 'revision': document.revision,
200 def revert(request, name):
201 storage = getstorage()
202 revision = request.POST['target_revision']
205 document = storage.revert(name, revision)
207 return JSONResponse({
208 'text': document.plain_text if revision != document.revision else None,
209 'meta': document.meta(),
210 'revision': document.revision,
212 except DocumentNotFound:
216 def gallery(request, directory):
219 smart_unicode(settings.MEDIA_URL),
220 smart_unicode(settings.FILEBROWSER_DIRECTORY),
221 smart_unicode(directory)))
223 base_dir = os.path.join(
224 smart_unicode(settings.MEDIA_ROOT),
225 smart_unicode(settings.FILEBROWSER_DIRECTORY),
226 smart_unicode(directory))
228 def map_to_url(filename):
229 return "%s/%s" % (base_url, smart_unicode(filename))
231 def is_image(filename):
232 return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
234 images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
236 return JSONResponse(images)
237 except (IndexError, OSError) as e:
238 logger.exception("Unable to fetch gallery")
244 def diff(request, name):
245 storage = getstorage()
247 revA = int(request.GET.get('from', 0))
248 revB = int(request.GET.get('to', 0))
251 revA, revB = revB, revA
256 docA = storage.get_or_404(name, int(revA))
257 docB = storage.get_or_404(name, int(revB))
259 return http.HttpResponse(nice_diff.html_diff_table(docA.plain_text.splitlines(),
260 docB.plain_text.splitlines(), context=3))
265 def history(request, name):
266 storage = getstorage()
269 changesets = list(storage.history(name))
271 return JSONResponse(changesets)
275 @ajax_require_permission('wiki.can_change_tags')
276 def add_tag(request, name):
277 name = normalize_name(name)
278 storage = getstorage()
280 form = DocumentTagForm(request.POST, prefix="addtag")
282 doc = storage.get_or_404(form.cleaned_data['id'])
283 doc.add_tag(tag=form.cleaned_data['tag'],
284 revision=form.cleaned_data['revision'],
285 author=request.user.username)
286 return JSONResponse({"message": _("Tag added")})
288 return JSONFormInvalid(form)
292 @ajax_require_permission('wiki.can_publish')
293 def publish(request, name):
294 name = normalize_name(name)
296 storage = getstorage()
297 document = storage.get_by_tag(name, "ready_to_publish")
299 api = wlapi.WLAPI(**settings.WL_API_CONFIG)
302 return JSONResponse({"result": api.publish_book(document)})
303 except wlapi.APICallException, e:
304 return JSONServerError({"message": str(e)})