1 from datetime import datetime
5 from django.conf import settings
6 from django.core.urlresolvers import reverse
7 from django import http
8 from django.http import Http404
9 from django.middleware.gzip import GZipMiddleware
10 from django.utils.decorators import decorator_from_middleware
11 from django.utils.encoding import smart_unicode
12 from django.utils.translation import ugettext as _
13 from django.views.decorators.http import require_POST, require_GET
14 from django.views.generic.simple import direct_to_template
15 from django.shortcuts import get_object_or_404
17 from catalogue.models import Book, Chunk
19 from wiki import forms
20 from wiki.helpers import (JSONResponse, JSONFormInvalid, JSONServerError,
21 ajax_require_permission)
22 from wiki.models import Theme
25 # Quick hack around caching problems, TODO: use ETags
27 from django.views.decorators.cache import never_cache
29 logger = logging.getLogger("fnp.wiki")
35 def editor(request, slug, chunk=None, template_name='wiki/document_details.html'):
37 chunk = Chunk.get(slug, chunk)
38 except Chunk.MultipleObjectsReturned:
41 except Chunk.DoesNotExist:
44 book = Book.objects.get(slug=slug)
45 except Book.DoesNotExist:
46 return http.HttpResponseRedirect(reverse("catalogue_create_missing", args=[slug]))
50 access_time = datetime.now()
51 last_books = request.session.get("wiki_last_books", {})
52 last_books[slug, chunk.slug] = {
54 'title': chunk.pretty_name(),
57 if len(last_books) > MAX_LAST_DOCS:
58 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
59 del last_books[oldest_key]
60 request.session['wiki_last_books'] = last_books
62 return direct_to_template(request, template_name, extra_context={
65 "text_save": forms.DocumentTextSaveForm(prefix="textsave"),
66 "text_revert": forms.DocumentTextRevertForm(prefix="textrevert"),
67 "pubmark": forms.DocumentPubmarkForm(prefix="pubmark"),
69 'REDMINE_URL': settings.REDMINE_URL,
74 def editor_readonly(request, slug, chunk=None, template_name='wiki/document_details_readonly.html'):
76 chunk = Chunk.get(slug, chunk)
77 revision = request.GET['revision']
78 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist, KeyError):
81 access_time = datetime.now()
82 last_books = request.session.get("wiki_last_books", {})
83 last_books[slug, chunk.slug] = {
85 'title': chunk.book.title,
88 if len(last_books) > MAX_LAST_DOCS:
89 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
90 del last_books[oldest_key]
91 request.session['wiki_last_books'] = last_books
93 return direct_to_template(request, template_name, extra_context={
97 'REDMINE_URL': settings.REDMINE_URL,
102 @decorator_from_middleware(GZipMiddleware)
103 def text(request, chunk_id):
104 doc = get_object_or_404(Chunk, pk=chunk_id)
106 if request.method == 'POST':
107 form = forms.DocumentTextSaveForm(request.POST, prefix="textsave")
109 if request.user.is_authenticated():
110 author = request.user
113 text = form.cleaned_data['text']
114 parent_revision = form.cleaned_data['parent_revision']
115 if parent_revision is not None:
116 parent = doc.at_revision(parent_revision)
119 stage = form.cleaned_data['stage_completed']
120 tags = [stage] if stage else []
121 doc.commit(author=author,
124 description=form.cleaned_data['comment'],
127 revision = doc.revision()
128 return JSONResponse({
129 'text': doc.materialize() if parent_revision != revision else None,
131 'revision': revision,
134 return JSONFormInvalid(form)
136 revision = request.GET.get("revision", None)
139 revision = int(revision)
140 except (ValueError, TypeError):
141 revision = doc.revision()
143 if revision is not None:
144 text = doc.at_revision(revision).materialize()
148 return JSONResponse({
151 'revision': revision,
157 def revert(request, chunk_id):
158 form = forms.DocumentTextRevertForm(request.POST, prefix="textrevert")
160 doc = get_object_or_404(Chunk, pk=chunk_id)
162 revision = form.cleaned_data['revision']
164 comment = form.cleaned_data['comment']
165 comment += "\n#revert to %s" % revision
167 if request.user.is_authenticated():
168 author = request.user
172 before = doc.revision()
173 logger.info("Reverting %s to %s", chunk_id, revision)
174 doc.at_revision(revision).revert(author=author, description=comment)
176 return JSONResponse({
177 'text': doc.materialize() if before != doc.revision() else None,
179 'revision': doc.revision(),
182 return JSONFormInvalid(form)
186 def gallery(request, directory):
189 smart_unicode(settings.MEDIA_URL),
190 smart_unicode(settings.FILEBROWSER_DIRECTORY),
191 smart_unicode(directory)))
193 base_dir = os.path.join(
194 smart_unicode(settings.MEDIA_ROOT),
195 smart_unicode(settings.FILEBROWSER_DIRECTORY),
196 smart_unicode(directory))
198 def map_to_url(filename):
199 return "%s/%s" % (base_url, smart_unicode(filename))
201 def is_image(filename):
202 return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
204 images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
206 return JSONResponse(images)
207 except (IndexError, OSError):
208 logger.exception("Unable to fetch gallery")
213 def diff(request, chunk_id):
214 revA = int(request.GET.get('from', 0))
215 revB = int(request.GET.get('to', 0))
218 revA, revB = revB, revA
223 doc = get_object_or_404(Chunk, pk=chunk_id)
224 # allow diff from the beginning
226 docA = doc.at_revision(revA).materialize()
229 docB = doc.at_revision(revB).materialize()
231 return http.HttpResponse(nice_diff.html_diff_table(docA.splitlines(),
232 docB.splitlines(), context=3))
236 def revision(request, chunk_id):
237 doc = get_object_or_404(Chunk, pk=chunk_id)
238 return http.HttpResponse(str(doc.revision()))
242 def history(request, chunk_id):
244 doc = get_object_or_404(Chunk, pk=chunk_id)
247 for change in doc.history().order_by('-created_at'):
249 "version": change.revision,
250 "description": change.description,
251 "author": change.author_str(),
252 "date": change.created_at,
253 "publishable": _("Publishable") + "\n" if change.publishable else "",
254 "tag": ',\n'.join(unicode(tag) for tag in change.tags.all()),
256 return JSONResponse(changes)
260 @ajax_require_permission('catalogue.can_pubmark')
261 def pubmark(request, chunk_id):
262 form = forms.DocumentPubmarkForm(request.POST, prefix="pubmark")
264 doc = get_object_or_404(Chunk, pk=chunk_id)
266 revision = form.cleaned_data['revision']
267 publishable = form.cleaned_data['publishable']
268 change = doc.at_revision(revision)
269 if publishable != change.publishable:
270 change.set_publishable(publishable)
271 return JSONResponse({"message": _("Revision marked")})
273 return JSONResponse({"message": _("Nothing changed")})
275 return JSONFormInvalid(form)
279 prefix = request.GET.get('q', '')
280 return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))