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 parent = doc.at_revision(parent_revision)
118 stage = form.cleaned_data['stage_completed']
119 tags = [stage] if stage else []
120 doc.commit(author=author,
123 description=form.cleaned_data['comment'],
126 revision = doc.revision()
127 return JSONResponse({
128 'text': doc.materialize() if parent_revision != revision else None,
130 'revision': revision,
133 return JSONFormInvalid(form)
135 revision = request.GET.get("revision", None)
138 revision = int(revision)
139 except (ValueError, TypeError):
142 return JSONResponse({
143 'text': doc.at_revision(revision).materialize(),
145 'revision': revision if revision else doc.revision(),
151 def revert(request, slug, chunk=None):
152 form = forms.DocumentTextRevertForm(request.POST, prefix="textrevert")
155 doc = Chunk.get(slug, chunk)
156 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
159 revision = form.cleaned_data['revision']
161 comment = form.cleaned_data['comment']
162 comment += "\n#revert to %s" % revision
164 if request.user.is_authenticated():
165 author = request.user
169 before = doc.revision()
170 logger.info("Reverting %s to %s", slug, revision)
171 doc.at_revision(revision).revert(author=author, description=comment)
173 return JSONResponse({
174 'text': doc.materialize() if before != doc.revision() else None,
176 'revision': doc.revision(),
179 return JSONFormInvalid(form)
183 def gallery(request, directory):
186 smart_unicode(settings.MEDIA_URL),
187 smart_unicode(settings.FILEBROWSER_DIRECTORY),
188 smart_unicode(directory)))
190 base_dir = os.path.join(
191 smart_unicode(settings.MEDIA_ROOT),
192 smart_unicode(settings.FILEBROWSER_DIRECTORY),
193 smart_unicode(directory))
195 def map_to_url(filename):
196 return "%s/%s" % (base_url, smart_unicode(filename))
198 def is_image(filename):
199 return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
201 images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
203 return JSONResponse(images)
204 except (IndexError, OSError):
205 logger.exception("Unable to fetch gallery")
210 def diff(request, slug, chunk=None):
211 revA = int(request.GET.get('from', 0))
212 revB = int(request.GET.get('to', 0))
215 revA, revB = revB, revA
221 doc = Chunk.get(slug, chunk)
222 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
224 docA = doc.at_revision(revA).materialize()
225 docB = doc.at_revision(revB).materialize()
227 return http.HttpResponse(nice_diff.html_diff_table(docA.splitlines(),
228 docB.splitlines(), context=3))
232 def revision(request, slug, chunk=None):
234 doc = Chunk.get(slug, chunk)
235 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
237 return http.HttpResponse(str(doc.revision()))
241 def history(request, slug, chunk=None):
244 doc = Chunk.get(slug, chunk)
245 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
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('wiki.can_pubmark')
263 def pubmark(request, slug, chunk=None):
264 form = forms.DocumentPubmarkForm(request.POST, prefix="pubmark")
267 doc = Chunk.get(slug, chunk)
268 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
271 revision = form.cleaned_data['revision']
272 publishable = form.cleaned_data['publishable']
273 change = doc.at_revision(revision)
274 if publishable != change.publishable:
275 change.publishable = publishable
277 return JSONResponse({"message": _("Revision marked")})
279 return JSONResponse({"message": _("Nothing changed")})
281 return JSONFormInvalid(form)
285 prefix = request.GET.get('q', '')
286 return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))