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(user=request.user, 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, user=request.user, 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'],
126 author_name=form.cleaned_data['author_name'],
127 author_email=form.cleaned_data['author_email'],
129 revision = doc.revision()
130 return JSONResponse({
131 'text': doc.materialize() if parent_revision != revision else None,
133 'revision': revision,
136 return JSONFormInvalid(form)
138 revision = request.GET.get("revision", None)
141 revision = int(revision)
142 except (ValueError, TypeError):
143 revision = doc.revision()
145 if revision is not None:
146 text = doc.at_revision(revision).materialize()
150 return JSONResponse({
153 'revision': revision,
159 def revert(request, chunk_id):
160 form = forms.DocumentTextRevertForm(request.POST, prefix="textrevert")
162 doc = get_object_or_404(Chunk, pk=chunk_id)
164 revision = form.cleaned_data['revision']
166 comment = form.cleaned_data['comment']
167 comment += "\n#revert to %s" % revision
169 if request.user.is_authenticated():
170 author = request.user
174 before = doc.revision()
175 logger.info("Reverting %s to %s", chunk_id, revision)
176 doc.at_revision(revision).revert(author=author, description=comment)
178 return JSONResponse({
179 'text': doc.materialize() if before != doc.revision() else None,
181 'revision': doc.revision(),
184 return JSONFormInvalid(form)
188 def gallery(request, directory):
191 smart_unicode(settings.MEDIA_URL),
192 smart_unicode(settings.FILEBROWSER_DIRECTORY),
193 smart_unicode(directory)))
195 base_dir = os.path.join(
196 smart_unicode(settings.MEDIA_ROOT),
197 smart_unicode(settings.FILEBROWSER_DIRECTORY),
198 smart_unicode(directory))
200 def map_to_url(filename):
201 return "%s/%s" % (base_url, smart_unicode(filename))
203 def is_image(filename):
204 return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
206 images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
208 return JSONResponse(images)
209 except (IndexError, OSError):
210 logger.exception("Unable to fetch gallery")
215 def diff(request, chunk_id):
216 revA = int(request.GET.get('from', 0))
217 revB = int(request.GET.get('to', 0))
220 revA, revB = revB, revA
225 doc = get_object_or_404(Chunk, pk=chunk_id)
226 # allow diff from the beginning
228 docA = doc.at_revision(revA).materialize()
231 docB = doc.at_revision(revB).materialize()
233 return http.HttpResponse(nice_diff.html_diff_table(docA.splitlines(),
234 docB.splitlines(), context=3))
238 def revision(request, chunk_id):
239 doc = get_object_or_404(Chunk, pk=chunk_id)
240 return http.HttpResponse(str(doc.revision()))
244 def history(request, chunk_id):
246 doc = get_object_or_404(Chunk, pk=chunk_id)
249 for change in doc.history().order_by('-created_at'):
251 "version": change.revision,
252 "description": change.description,
253 "author": change.author_str(),
254 "date": change.created_at,
255 "publishable": _("Publishable") + "\n" if change.publishable else "",
256 "tag": ',\n'.join(unicode(tag) for tag in change.tags.all()),
258 return JSONResponse(changes)
262 @ajax_require_permission('catalogue.can_pubmark')
263 def pubmark(request, chunk_id):
264 form = forms.DocumentPubmarkForm(request.POST, prefix="pubmark")
266 doc = get_object_or_404(Chunk, pk=chunk_id)
268 revision = form.cleaned_data['revision']
269 publishable = form.cleaned_data['publishable']
270 change = doc.at_revision(revision)
271 if publishable != change.publishable:
272 change.set_publishable(publishable)
273 return JSONResponse({"message": _("Revision marked")})
275 return JSONResponse({"message": _("Nothing changed")})
277 return JSONFormInvalid(form)
281 prefix = request.GET.get('q', '')
282 return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))