1 # -*- coding: utf-8 -*-
2 from datetime import datetime
8 from django.conf import settings
9 from django.core.urlresolvers import reverse
10 from django import http
11 from django.http import Http404, HttpResponseForbidden
12 from django.middleware.gzip import GZipMiddleware
13 from django.utils.decorators import decorator_from_middleware
14 from django.utils.encoding import smart_unicode
15 from django.utils.formats import localize
16 from django.utils.translation import ugettext as _
17 from django.views.decorators.http import require_POST, require_GET
18 from django.shortcuts import get_object_or_404, render
20 from catalogue.models import Book, Chunk, Template
22 from wiki import forms
23 from wiki.helpers import JSONResponse, JSONFormInvalid, ajax_require_permission
24 from wiki.models import Theme
27 # Quick hack around caching problems, TODO: use ETags
29 from django.views.decorators.cache import never_cache
31 logger = logging.getLogger("fnp.wiki")
36 def get_history(chunk):
38 for change in chunk.history():
40 "version": change.revision,
41 "description": change.description,
42 "author": change.author_str(),
43 "date": localize(change.created_at),
44 "publishable": _("Publishable") + "\n" if change.publishable else "",
45 "tag": ',\n'.join(unicode(tag) for tag in change.tags.all()),
47 _("Published") + ": " +
48 localize(change.publish_log.order_by('-book_record__timestamp')[0].book_record.timestamp)
49 if change.publish_log.exists() else ""),
56 def editor(request, slug, chunk=None, template_name='wiki/bootstrap.html'):
58 chunk = Chunk.get(slug, chunk)
59 except Chunk.MultipleObjectsReturned:
62 except Chunk.DoesNotExist:
65 book = Book.objects.get(slug=slug)
66 except Book.DoesNotExist:
67 return http.HttpResponseRedirect(reverse("catalogue_create_missing", args=[slug]))
70 if not chunk.book.accessible(request):
71 return HttpResponseForbidden("Not authorized.")
73 access_time = datetime.now()
74 last_books = request.session.get("wiki_last_books", {})
75 last_books[slug, chunk.slug] = {
77 'title': chunk.pretty_name(),
80 if len(last_books) > MAX_LAST_DOCS:
81 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
82 del last_books[oldest_key]
83 request.session['wiki_last_books'] = last_books
85 save_form = forms.DocumentTextSaveForm(user=request.user, chunk=chunk, prefix="textsave")
87 version = int(request.GET.get('version', None))
91 text = chunk.at_revision(version).materialize()
93 text = chunk.materialize()
94 return render(request, template_name, {
95 'serialized_document_data': json.dumps({
97 'document_id': chunk.id,
98 'title': chunk.book.title,
99 'history': get_history(chunk),
100 'version': version or chunk.revision(),
101 'stage': chunk.stage.name if chunk.stage else None,
102 'assignment': chunk.user.username if chunk.user else None
104 'serialized_templates': json.dumps([
105 {'id': t.id, 'name': t.name, 'content': t.content} for t in Template.objects.filter(is_partial=True)
108 "text_save": save_form,
109 "text_revert": forms.DocumentTextRevertForm(prefix="textrevert")
111 'tags': list(save_form.fields['stage_completed'].choices),
112 'can_pubmark': request.user.has_perm('catalogue.can_pubmark'),
113 'slug': chunk.book.slug
118 def editor_readonly(request, slug, chunk=None, template_name='wiki/document_details_readonly.html'):
120 chunk = Chunk.get(slug, chunk)
121 revision = request.GET['revision']
122 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist, KeyError):
124 if not chunk.book.accessible(request):
125 return HttpResponseForbidden("Not authorized.")
127 access_time = datetime.now()
128 last_books = request.session.get("wiki_last_books", {})
129 last_books[slug, chunk.slug] = {
131 'title': chunk.book.title,
134 if len(last_books) > MAX_LAST_DOCS:
135 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
136 del last_books[oldest_key]
137 request.session['wiki_last_books'] = last_books
139 return render(request, template_name, {
141 'revision': revision,
143 'REDMINE_URL': settings.REDMINE_URL,
148 @decorator_from_middleware(GZipMiddleware)
149 def text(request, chunk_id):
150 doc = get_object_or_404(Chunk, pk=chunk_id)
151 if not doc.book.accessible(request):
152 return HttpResponseForbidden("Not authorized.")
154 if request.method == 'POST':
155 form = forms.DocumentTextSaveForm(request.POST, user=request.user, chunk=doc, prefix="textsave")
158 parent_revision = form.cleaned_data['parent_revision']
159 revision = doc.revision()
160 return JSONResponse({
161 'text': doc.materialize() if parent_revision != revision else None,
163 'stage': doc.stage.name if doc.stage else None,
164 'assignment': doc.user.username if doc.user else None
167 return JSONFormInvalid(form)
169 revision = request.GET.get("revision", None)
172 revision = int(revision)
173 except (ValueError, TypeError):
174 revision = doc.revision()
176 if revision is not None:
177 text = doc.at_revision(revision).materialize()
181 return JSONResponse({
184 'revision': revision,
190 def revert(request, chunk_id):
191 form = forms.DocumentTextRevertForm(request.POST, prefix="textrevert")
193 doc = get_object_or_404(Chunk, pk=chunk_id)
194 if not doc.book.accessible(request):
195 return HttpResponseForbidden("Not authorized.")
197 revision = form.cleaned_data['revision']
199 comment = form.cleaned_data['comment']
200 comment += "\n#revert to %s" % revision
202 if request.user.is_authenticated():
203 author = request.user
207 before = doc.revision()
208 logger.info("Reverting %s to %s", chunk_id, revision)
209 doc.at_revision(revision).revert(author=author, description=comment)
211 return JSONResponse({
212 'document': doc.materialize() if before != doc.revision() else None,
213 'version': doc.revision(),
216 return JSONFormInvalid(form)
220 def gallery(request, directory):
223 smart_unicode(settings.MEDIA_URL),
224 smart_unicode(settings.IMAGE_DIR),
225 smart_unicode(directory)))
227 base_dir = os.path.join(
228 smart_unicode(settings.MEDIA_ROOT),
229 smart_unicode(settings.IMAGE_DIR),
230 smart_unicode(directory))
232 def map_to_url(filename):
233 return urllib.quote("%s/%s" % (base_url, smart_unicode(filename)))
235 def is_image(filename):
236 return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
238 images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
241 if not request.user.is_authenticated():
242 return HttpResponseForbidden("Not authorized.")
244 return JSONResponse(images)
245 except (IndexError, OSError):
246 logger.exception("Unable to fetch gallery")
251 def diff(request, chunk_id):
252 revA = int(request.GET.get('from', 0))
253 revB = int(request.GET.get('to', 0))
256 revA, revB = revB, revA
261 doc = get_object_or_404(Chunk, pk=chunk_id)
262 if not doc.book.accessible(request):
263 return HttpResponseForbidden("Not authorized.")
265 # allow diff from the beginning
267 docA = doc.at_revision(revA).materialize()
270 docB = doc.at_revision(revB).materialize()
272 return http.HttpResponse(nice_diff.html_diff_table(docA.splitlines(), docB.splitlines(), context=3))
276 def revision(request, chunk_id):
277 doc = get_object_or_404(Chunk, pk=chunk_id)
278 if not doc.book.accessible(request):
279 return HttpResponseForbidden("Not authorized.")
280 return http.HttpResponse(str(doc.revision()))
284 def history(request, chunk_id):
286 doc = get_object_or_404(Chunk, pk=chunk_id)
287 if not doc.book.accessible(request):
288 return HttpResponseForbidden("Not authorized.")
290 return JSONResponse(get_history(doc))
294 @ajax_require_permission('catalogue.can_pubmark')
295 def pubmark(request, chunk_id):
296 form = forms.DocumentPubmarkForm(request.POST, prefix="pubmark")
298 doc = get_object_or_404(Chunk, pk=chunk_id)
299 if not doc.book.accessible(request):
300 return HttpResponseForbidden("Not authorized.")
302 revision = form.cleaned_data['revision']
303 publishable = form.cleaned_data['publishable']
304 change = doc.at_revision(revision)
305 if publishable != change.publishable:
306 change.set_publishable(publishable)
307 return JSONResponse({"message": _("Revision marked")})
309 return JSONResponse({"message": _("Nothing changed")})
311 return JSONFormInvalid(form)
315 prefix = request.GET.get('q', '')
316 return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))