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_lazy as _
13 from django.views.decorators.http import require_POST, require_GET
14 from django.views.generic.simple import direct_to_template
16 from catalogue.models import Book, Chunk
18 from wiki import forms
19 from wiki.helpers import (JSONResponse, JSONFormInvalid, JSONServerError,
20 ajax_require_permission)
21 from wiki.models import Theme
24 # Quick hack around caching problems, TODO: use ETags
26 from django.views.decorators.cache import never_cache
28 logger = logging.getLogger("fnp.wiki")
34 def editor(request, slug, chunk=None, template_name='wiki/document_details.html'):
36 chunk = Chunk.get(slug, chunk)
37 except Chunk.MultipleObjectsReturned:
40 except Chunk.DoesNotExist:
43 book = Book.objects.get(slug=slug)
44 except Book.DoesNotExist:
45 return http.HttpResponseRedirect(reverse("catalogue_create_missing", args=[slug]))
49 access_time = datetime.now()
50 last_books = request.session.get("wiki_last_books", {})
51 last_books[slug, chunk.slug] = {
53 'title': chunk.pretty_name(),
56 if len(last_books) > MAX_LAST_DOCS:
57 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
58 del last_books[oldest_key]
59 request.session['wiki_last_books'] = last_books
61 return direct_to_template(request, template_name, extra_context={
64 "text_save": forms.DocumentTextSaveForm(prefix="textsave"),
65 "text_revert": forms.DocumentTextRevertForm(prefix="textrevert"),
66 "pubmark": forms.DocumentPubmarkForm(prefix="pubmark"),
68 'REDMINE_URL': settings.REDMINE_URL,
73 def editor_readonly(request, slug, chunk=None, template_name='wiki/document_details_readonly.html'):
75 chunk = Chunk.get(slug, chunk)
76 revision = request.GET['revision']
77 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist, KeyError):
80 access_time = datetime.now()
81 last_books = request.session.get("wiki_last_books", {})
82 last_books[slug, chunk.slug] = {
84 'title': chunk.book.title,
87 if len(last_books) > MAX_LAST_DOCS:
88 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
89 del last_books[oldest_key]
90 request.session['wiki_last_books'] = last_books
92 return direct_to_template(request, template_name, extra_context={
96 'REDMINE_URL': settings.REDMINE_URL,
101 @decorator_from_middleware(GZipMiddleware)
102 def text(request, slug, chunk=None):
104 doc = Chunk.get(slug, chunk)
105 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
108 if request.method == 'POST':
109 form = forms.DocumentTextSaveForm(request.POST, prefix="textsave")
111 if request.user.is_authenticated():
112 author = request.user
115 text = form.cleaned_data['text']
116 parent_revision = form.cleaned_data['parent_revision']
117 if parent_revision is not None:
118 parent = doc.at_revision(parent_revision)
121 stage = form.cleaned_data['stage_completed']
122 tags = [stage] if stage else []
123 doc.commit(author=author,
126 description=form.cleaned_data['comment'],
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, slug, chunk=None):
160 form = forms.DocumentTextRevertForm(request.POST, prefix="textrevert")
163 doc = Chunk.get(slug, chunk)
164 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
167 revision = form.cleaned_data['revision']
169 comment = form.cleaned_data['comment']
170 comment += "\n#revert to %s" % revision
172 if request.user.is_authenticated():
173 author = request.user
177 before = doc.revision()
178 logger.info("Reverting %s to %s", slug, revision)
179 doc.at_revision(revision).revert(author=author, description=comment)
181 return JSONResponse({
182 'text': doc.materialize() if before != doc.revision() else None,
184 'revision': doc.revision(),
187 return JSONFormInvalid(form)
191 def gallery(request, directory):
194 smart_unicode(settings.MEDIA_URL),
195 smart_unicode(settings.FILEBROWSER_DIRECTORY),
196 smart_unicode(directory)))
198 base_dir = os.path.join(
199 smart_unicode(settings.MEDIA_ROOT),
200 smart_unicode(settings.FILEBROWSER_DIRECTORY),
201 smart_unicode(directory))
203 def map_to_url(filename):
204 return "%s/%s" % (base_url, smart_unicode(filename))
206 def is_image(filename):
207 return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
209 images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
211 return JSONResponse(images)
212 except (IndexError, OSError):
213 logger.exception("Unable to fetch gallery")
218 def diff(request, slug, chunk=None):
219 revA = int(request.GET.get('from', 0))
220 revB = int(request.GET.get('to', 0))
223 revA, revB = revB, revA
229 doc = Chunk.get(slug, chunk)
230 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
232 docA = doc.at_revision(revA).materialize()
233 docB = doc.at_revision(revB).materialize()
235 return http.HttpResponse(nice_diff.html_diff_table(docA.splitlines(),
236 docB.splitlines(), context=3))
240 def revision(request, slug, chunk=None):
242 doc = Chunk.get(slug, chunk)
243 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
245 return http.HttpResponse(str(doc.revision()))
249 def history(request, slug, chunk=None):
252 doc = Chunk.get(slug, chunk)
253 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
257 for change in doc.history().order_by('-created_at'):
259 "version": change.revision,
260 "description": change.description,
261 "author": change.author_str(),
262 "date": change.created_at,
263 "publishable": "Publishable\n" if change.publishable else "",
264 "tag": ',\n'.join(unicode(tag) for tag in change.tags.all()),
266 return JSONResponse(changes)
270 @ajax_require_permission('wiki.can_pubmark')
271 def pubmark(request, slug, chunk=None):
272 form = forms.DocumentPubmarkForm(request.POST, prefix="pubmark")
275 doc = Chunk.get(slug, chunk)
276 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
279 revision = form.cleaned_data['revision']
280 publishable = form.cleaned_data['publishable']
281 change = doc.at_revision(revision)
282 if publishable != change.publishable:
283 change.set_publishable(publishable)
284 return JSONResponse({"message": _("Revision marked")})
286 return JSONResponse({"message": _("Nothing changed")})
288 return JSONFormInvalid(form)
292 prefix = request.GET.get('q', '')
293 return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))