1 from datetime import datetime
7 from django.conf import settings
8 from django.core.urlresolvers import reverse
9 from django import http
10 from django.http import Http404, HttpResponseForbidden
11 from django.middleware.gzip import GZipMiddleware
12 from django.utils.decorators import decorator_from_middleware
13 from django.utils.encoding import smart_unicode
14 from django.utils.formats import localize
15 from django.utils.translation import ugettext as _
16 from django.views.decorators.http import require_POST, require_GET
17 from django.shortcuts import get_object_or_404, render
18 from django.contrib.auth.decorators import login_required
20 from catalogue.models import Document, Template
21 from dvcs.models import Revision
23 from wiki import forms
24 from wiki.helpers import (JSONResponse, JSONFormInvalid, JSONServerError,
25 ajax_require_permission)
28 # Quick hack around caching problems, TODO: use ETags
30 from django.views.decorators.cache import never_cache
32 logger = logging.getLogger("fnp.wiki")
37 def get_history(document):
39 for i, revision in enumerate(document.history()):
42 "description": revision.description,
43 "author": revision.author_str(),
44 "date": localize(revision.created_at),
46 "revision": revision.pk,
47 "published": _("Published") + ": " + \
48 localize(revision.publish_log.order_by('-timestamp')[0].timestamp) \
49 if revision.publish_log.exists() else "",
56 def editor(request, pk, chunk=None, template_name='wiki/bootstrap.html'):
57 doc = get_object_or_404(Document, pk=pk, deleted=False)
58 #~ if not doc.accessible(request):
59 #~ return HttpResponseForbidden("Not authorized.")
61 access_time = datetime.now()
63 save_form = forms.DocumentTextSaveForm(user=request.user, prefix="textsave")
65 version = int(request.GET.get('version', None))
69 text = doc.at_revision(version).materialize()
71 text = doc.materialize()
72 revision = doc.revision
73 history = get_history(doc)
74 return render(request, template_name, {
75 'serialized_document_data': json.dumps({
77 'document_id': doc.pk,
78 'title': doc.meta().get('title', ''),
80 'version': len(history), #version or chunk.revision(),
81 'revision': revision.pk,
83 'assignment': str(doc.assigned_to),
85 'serialized_templates': json.dumps([
86 {'id': t.id, 'name': t.name, 'content': t.content} for t in Template.objects.filter(is_partial=True)
89 "text_save": save_form,
90 "text_revert": forms.DocumentTextRevertForm(prefix="textrevert"),
91 "text_publish": forms.DocumentTextPublishForm(prefix="textpublish"),
98 def editor_readonly(request, slug, chunk=None, template_name='wiki/document_details_readonly.html'):
100 chunk = Chunk.get(slug, chunk)
101 revision = request.GET['revision']
102 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist, KeyError):
104 if not chunk.book.accessible(request):
105 return HttpResponseForbidden("Not authorized.")
107 access_time = datetime.now()
108 last_books = request.session.get("wiki_last_books", {})
109 last_books[slug, chunk.slug] = {
111 'title': chunk.book.title,
114 if len(last_books) > MAX_LAST_DOCS:
115 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
116 del last_books[oldest_key]
117 request.session['wiki_last_books'] = last_books
119 return render(request, template_name, {
121 'revision': revision,
123 'REDMINE_URL': settings.REDMINE_URL,
128 @decorator_from_middleware(GZipMiddleware)
129 def text(request, doc_id):
130 doc = get_object_or_404(Document, pk=doc_id, deleted=False)
131 #~ if not doc.book.accessible(request):
132 #~ return HttpResponseForbidden("Not authorized.")
134 if request.method == 'POST':
135 form = forms.DocumentTextSaveForm(request.POST, user=request.user, prefix="textsave")
137 if request.user.is_authenticated():
138 author = request.user
141 text = form.cleaned_data['text']
142 #~ parent_revision = form.cleaned_data['parent_revision']
143 #~ if parent_revision is not None:
144 #~ parent = doc.at_revision(parent_revision)
147 stage = form.cleaned_data['stage']
148 #~ tags = [stage] if stage else []
149 #~ publishable = (form.cleaned_data['publishable'] and
150 #~ request.user.has_perm('catalogue.can_pubmark'))
152 doc.commit(author=author,
155 description=form.cleaned_data['comment'],
156 author_name=form.cleaned_data['author_name'],
157 author_email=form.cleaned_data['author_email'],
161 from traceback import print_exc
164 #revision = doc.revision()
165 return JSONResponse({
166 'text': None, #doc.materialize() if parent_revision != revision else None,
167 #'version': revision,
168 #'stage': doc.stage.name if doc.stage else None,
169 'assignment': doc.assigned_to.username if doc.assigned_to else None
172 return JSONFormInvalid(form)
174 revision = request.GET.get("revision", None)
177 revision = int(revision)
178 except (ValueError, TypeError):
179 revision = doc.revision()
181 if revision is not None:
182 text = doc.at_revision(revision).materialize()
186 return JSONResponse({
189 'revision': revision,
195 def revert(request, doc_id):
196 form = forms.DocumentTextRevertForm(request.POST, prefix="textrevert")
198 doc = get_object_or_404(Document, pk=doc_id, deleted=False)
199 rev = get_object_or_404(Revision, pk=form.cleaned_data['revision'])
201 comment = form.cleaned_data['comment']
202 comment += "\n#revert to %s" % rev.pk
204 if request.user.is_authenticated():
205 author = request.user
209 #before = doc.revision
210 logger.info("Reverting %s to %s", doc_id, rev.pk)
212 doc.commit(author=author,
213 text=rev.materialize(),
216 #author_name=form.cleaned_data['author_name'], #?
217 #author_email=form.cleaned_data['author_email'], #?
220 return JSONResponse({
221 #'document': None, #doc.materialize() if before != doc.revision else None,
222 #'version': doc.revision(),
225 return JSONFormInvalid(form)
229 def gallery(request, directory):
230 if not request.user.is_authenticated():
231 return HttpResponseForbidden("Not authorized.")
235 smart_unicode(settings.MEDIA_URL),
236 smart_unicode(settings.IMAGE_DIR),
237 smart_unicode(directory)))
239 base_dir = os.path.join(
240 smart_unicode(settings.MEDIA_ROOT),
241 smart_unicode(settings.IMAGE_DIR),
242 smart_unicode(directory))
244 def map_to_url(filename):
245 return urllib.quote("%s/%s" % (base_url, smart_unicode(filename)))
247 def is_image(filename):
248 return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
250 images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
253 return JSONResponse(images)
254 except (IndexError, OSError):
255 logger.exception("Unable to fetch gallery")
260 def diff(request, doc_id):
261 revA = int(request.GET.get('from', 0))
262 revB = int(request.GET.get('to', 0))
265 revA, revB = revB, revA
270 # TODO: check if revisions in line.
272 doc = get_object_or_404(Document, pk=doc_id, deleted=False)
274 # allow diff from the beginning
276 docA = Revision.objects.get(pk=revA).materialize()
279 docB = Revision.objects.get(pk=revB).materialize()
281 return http.HttpResponse(nice_diff.html_diff_table(docA.splitlines(),
282 docB.splitlines(), context=3))
286 def revision(request, chunk_id):
287 doc = get_object_or_404(Chunk, pk=chunk_id)
288 if not doc.book.accessible(request):
289 return HttpResponseForbidden("Not authorized.")
290 return http.HttpResponse(str(doc.revision()))
294 def history(request, doc_id):
296 doc = get_object_or_404(Document, pk=doc_id, deleted=False)
298 return JSONResponse(get_history(doc))