2 from StringIO import StringIO
4 logger = logging.getLogger("fnp.wiki")
8 from django.conf import settings
10 from django.contrib.auth.decorators import login_required
11 from django.views.generic.simple import direct_to_template
12 from django.views.decorators.http import require_POST, require_GET
13 from django.core.urlresolvers import reverse
14 from wiki.helpers import (JSONResponse, JSONFormInvalid, JSONServerError,
15 ajax_require_permission, recursive_groupby)
16 from django import http
17 from django.shortcuts import get_object_or_404, redirect
18 from django.http import Http404
20 from wiki.models import Book, Chunk, Theme
21 from wiki import forms
22 from datetime import datetime
23 from django.utils.encoding import smart_unicode
24 from django.utils.translation import ugettext_lazy as _
25 from django.utils.decorators import decorator_from_middleware
26 from django.middleware.gzip import GZipMiddleware
30 from wiki import xml_tools
31 from apiclient import api_call
34 # Quick hack around caching problems, TODO: use ETags
36 from django.views.decorators.cache import never_cache
45 def document_list(request):
46 return direct_to_template(request, 'wiki/document_list.html', extra_context={
47 'books': Book.objects.all(),
48 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
49 key=lambda x: x[1]['time'], reverse=True),
54 def editor(request, slug, chunk=None, template_name='wiki/document_details.html'):
56 chunk = Chunk.get(slug, chunk)
57 except Chunk.MultipleObjectsReturned:
60 except Chunk.DoesNotExist:
63 book = Book.objects.get(slug=slug)
64 except Book.DoesNotExist:
65 return http.HttpResponseRedirect(reverse("wiki_create_missing", args=[slug]))
69 access_time = datetime.now()
70 last_books = request.session.get("wiki_last_books", {})
71 last_books[slug, chunk.slug] = {
73 'title': chunk.pretty_name(),
76 if len(last_books) > MAX_LAST_DOCS:
77 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
78 del last_books[oldest_key]
79 request.session['wiki_last_books'] = last_books
81 return direct_to_template(request, template_name, extra_context={
84 "text_save": forms.DocumentTextSaveForm(prefix="textsave"),
85 "text_revert": forms.DocumentTextRevertForm(prefix="textrevert"),
86 "add_tag": forms.DocumentTagForm(prefix="addtag"),
87 "pubmark": forms.DocumentPubmarkForm(prefix="pubmark"),
89 'REDMINE_URL': settings.REDMINE_URL,
94 def editor_readonly(request, slug, chunk=None, template_name='wiki/document_details_readonly.html'):
96 chunk = Chunk.get(slug, chunk)
97 revision = request.GET['revision']
98 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist, KeyError):
101 access_time = datetime.now()
102 last_books = request.session.get("wiki_last_books", {})
103 last_books[slug, chunk.slug] = {
105 'title': chunk.book.title,
108 if len(last_books) > MAX_LAST_DOCS:
109 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
110 del last_books[oldest_key]
111 request.session['wiki_last_books'] = last_books
113 return direct_to_template(request, template_name, extra_context={
115 'revision': revision,
117 'REDMINE_URL': settings.REDMINE_URL,
121 def create_missing(request, slug):
122 slug = slug.replace(' ', '-')
124 if request.method == "POST":
125 form = forms.DocumentCreateForm(request.POST, request.FILES)
128 if request.user.is_authenticated():
129 creator = request.user
132 book = Book.create(creator=creator,
133 slug=form.cleaned_data['slug'],
134 title=form.cleaned_data['title'],
135 text=form.cleaned_data['text'],
138 return http.HttpResponseRedirect(reverse("wiki_editor", args=[book.slug]))
140 form = forms.DocumentCreateForm(initial={
142 "title": slug.replace('-', ' ').title(),
145 return direct_to_template(request, "wiki/document_create_missing.html", extra_context={
152 if request.method == "POST":
153 form = forms.DocumentsUploadForm(request.POST, request.FILES)
157 if request.user.is_authenticated():
158 creator = request.user
162 zip = form.cleaned_data['zip']
167 existing = [book.slug for book in Book.objects.all()]
168 for filename in zip.namelist():
169 if filename[-1] == '/':
171 title = os.path.basename(filename)[:-4]
172 slug = slughifi(title)
173 if not (slug and filename.endswith('.xml')):
174 skipped_list.append(filename)
176 error_list.append((filename, slug, _('Slug already used for %s' % slugs[slug])))
177 elif slug in existing:
178 error_list.append((filename, slug, _('Slug already used in repository.')))
181 zip.read(filename).decode('utf-8') # test read
182 ok_list.append((filename, slug, title))
183 except UnicodeDecodeError:
184 error_list.append((filename, title, _('File should be UTF-8 encoded.')))
185 slugs[slug] = filename
188 for filename, slug, title in ok_list:
189 Book.create(creator=creator,
192 text=zip.read(filename).decode('utf-8'),
195 return direct_to_template(request, "wiki/document_upload.html", extra_context={
198 "skipped_list": skipped_list,
199 "error_list": error_list,
202 form = forms.DocumentsUploadForm()
204 return direct_to_template(request, "wiki/document_upload.html", extra_context={
210 @decorator_from_middleware(GZipMiddleware)
211 def text(request, slug, chunk=None):
213 doc = Chunk.get(slug, chunk)
214 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
217 if request.method == 'POST':
218 form = forms.DocumentTextSaveForm(request.POST, prefix="textsave")
220 if request.user.is_authenticated():
221 author = request.user
224 text = form.cleaned_data['text']
225 parent_revision = form.cleaned_data['parent_revision']
226 parent = doc.at_revision(parent_revision)
227 stage = form.cleaned_data['stage_completed']
228 tags = [stage] if stage else []
229 doc.commit(author=author,
232 description=form.cleaned_data['comment'],
235 revision = doc.revision()
236 return JSONResponse({
237 'text': doc.materialize() if parent_revision != revision else None,
239 'revision': revision,
242 return JSONFormInvalid(form)
244 revision = request.GET.get("revision", None)
247 revision = int(revision)
248 except (ValueError, TypeError):
251 return JSONResponse({
252 'text': doc.at_revision(revision).materialize(),
254 'revision': revision if revision else doc.revision(),
259 def book_xml(request, slug):
260 xml = get_object_or_404(Book, slug=slug).materialize()
262 response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
263 response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
268 def book_txt(request, slug):
269 xml = get_object_or_404(Book, slug=slug).materialize()
272 librarian.text.transform(StringIO(xml), output)
273 text = output.getvalue()
274 response = http.HttpResponse(text, content_type='text/plain', mimetype='text/plain')
275 response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
280 def book_html(request, slug):
281 xml = get_object_or_404(Book, slug=slug).materialize()
284 librarian.html.transform(StringIO(xml), output, parse_dublincore=False,
286 html = output.getvalue()
287 response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
293 def revert(request, slug, chunk=None):
294 form = forms.DocumentTextRevertForm(request.POST, prefix="textrevert")
297 doc = Chunk.get(slug, chunk)
298 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
301 revision = form.cleaned_data['revision']
303 comment = form.cleaned_data['comment']
304 comment += "\n#revert to %s" % revision
306 if request.user.is_authenticated():
307 author = request.user
311 before = doc.revision()
312 logger.info("Reverting %s to %s", slug, revision)
313 doc.at_revision(revision).revert(author=author, description=comment)
315 return JSONResponse({
316 'text': doc.materialize() if before != doc.revision() else None,
318 'revision': doc.revision(),
321 return JSONFormInvalid(form)
325 def gallery(request, directory):
328 smart_unicode(settings.MEDIA_URL),
329 smart_unicode(settings.FILEBROWSER_DIRECTORY),
330 smart_unicode(directory)))
332 base_dir = os.path.join(
333 smart_unicode(settings.MEDIA_ROOT),
334 smart_unicode(settings.FILEBROWSER_DIRECTORY),
335 smart_unicode(directory))
337 def map_to_url(filename):
338 return "%s/%s" % (base_url, smart_unicode(filename))
340 def is_image(filename):
341 return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
343 images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
345 return JSONResponse(images)
346 except (IndexError, OSError):
347 logger.exception("Unable to fetch gallery")
352 def diff(request, slug, chunk=None):
353 revA = int(request.GET.get('from', 0))
354 revB = int(request.GET.get('to', 0))
357 revA, revB = revB, revA
363 doc = Chunk.get(slug, chunk)
364 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
366 docA = doc.at_revision(revA).materialize()
367 docB = doc.at_revision(revB).materialize()
369 return http.HttpResponse(nice_diff.html_diff_table(docA.splitlines(),
370 docB.splitlines(), context=3))
374 def revision(request, slug, chunk=None):
376 doc = Chunk.get(slug, chunk)
377 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
379 return http.HttpResponse(str(doc.revision()))
383 def history(request, slug, chunk=None):
386 doc = Chunk.get(slug, chunk)
387 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
391 for change in doc.history().order_by('-created_at'):
393 "version": change.revision,
394 "description": change.description,
395 "author": change.author_str(),
396 "date": change.created_at,
397 "publishable": "Publishable\n" if change.publishable else "",
398 "tag": ',\n'.join(unicode(tag) for tag in change.tags.all()),
400 return JSONResponse(changes)
403 def book(request, slug):
404 book = get_object_or_404(Book, slug=slug)
406 # TODO: most of this should go somewhere else
408 # do we need some automation?
412 choose_master = False
415 for i, chunk in enumerate(book):
421 graded = xml_tools.GradedText(chunk.materialize())
423 master = graded.master()
424 if first_master is None:
425 first_master = master
426 elif master != first_master:
427 chunk_dict['fix'].append('bad-master')
429 if i > 0 and not graded.has_trim_begin():
430 chunk_dict['fix'].append('trim-begin')
431 if i < length - 1 and not graded.has_trim_end():
432 chunk_dict['fix'].append('trim-end')
434 if chunk_dict['fix']:
435 chunk_dict['grade'] = 'wl-fix'
437 chunk_dict['grade'] = 'wl'
439 elif graded.is_broken_wl():
440 chunk_dict['grade'] = 'wl-broken'
441 elif graded.is_xml():
442 chunk_dict['grade'] = 'xml'
444 chunk_dict['grade'] = 'plain'
445 chunk_dict['fix'].append('wl')
448 if chunk_dict['fix']:
450 chunks.append(chunk_dict)
452 if first_master or not need_fixing:
453 choose_master = False
455 if request.method == "POST":
456 form = forms.ChooseMasterForm(request.POST)
457 if not choose_master or form.is_valid():
459 first_master = form.cleaned_data['master']
461 # do the actual fixing
466 text = c['chunk'].materialize()
468 if fix == 'bad-master':
469 text = xml_tools.change_master(text, first_master)
470 elif fix == 'trim-begin':
471 text = xml_tools.add_trim_begin(text)
472 elif fix == 'trim-end':
473 text = xml_tools.add_trim_end(text)
475 text = xml_tools.basic_structure(text, first_master)
476 author = request.user if request.user.is_authenticated() else None
477 description = "auto-fix: " + ", ".join(c['fix'])
478 c['chunk'].commit(text=text, author=author,
479 description=description)
481 return http.HttpResponseRedirect(book.get_absolute_url())
483 form = forms.ChooseMasterForm()
487 return direct_to_template(request, "wiki/book_detail.html", extra_context={
490 "need_fixing": need_fixing,
491 "choose_master": choose_master,
492 "first_master": first_master,
497 def chunk_add(request, slug, chunk):
499 doc = Chunk.get(slug, chunk)
500 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
503 if request.method == "POST":
504 form = forms.ChunkAddForm(request.POST, instance=doc)
506 if request.user.is_authenticated():
507 creator = request.user
510 doc.split(creator=creator,
511 slug=form.cleaned_data['slug'],
512 comment=form.cleaned_data['comment'],
515 return http.HttpResponseRedirect(doc.book.get_absolute_url())
517 form = forms.ChunkAddForm(initial={
518 "slug": str(doc.number + 1),
519 "comment": "cz. %d" % (doc.number + 1, ),
522 return direct_to_template(request, "wiki/chunk_add.html", extra_context={
528 def chunk_edit(request, slug, chunk):
530 doc = Chunk.get(slug, chunk)
531 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
533 if request.method == "POST":
534 form = forms.ChunkForm(request.POST, instance=doc)
537 return http.HttpResponseRedirect(doc.book.get_absolute_url())
539 form = forms.ChunkForm(instance=doc)
540 return direct_to_template(request, "wiki/chunk_edit.html", extra_context={
546 def book_append(request, slug):
547 book = get_object_or_404(Book, slug=slug)
548 if request.method == "POST":
549 form = forms.BookAppendForm(request.POST)
551 append_to = form.cleaned_data['append_to']
552 append_to.append(book)
553 return http.HttpResponseRedirect(append_to.get_absolute_url())
555 form = forms.BookAppendForm()
556 return direct_to_template(request, "wiki/book_append_to.html", extra_context={
562 def book_edit(request, slug):
563 book = get_object_or_404(Book, slug=slug)
564 if request.method == "POST":
565 form = forms.BookForm(request.POST, instance=book)
568 return http.HttpResponseRedirect(book.get_absolute_url())
570 form = forms.BookForm(instance=book)
571 return direct_to_template(request, "wiki/book_edit.html", extra_context={
578 @ajax_require_permission('wiki.can_change_tags')
579 def add_tag(request, slug, chunk=None):
580 form = forms.DocumentTagForm(request.POST, prefix="addtag")
583 doc = Chunk.get(slug, chunk)
584 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
587 tag = form.cleaned_data['tag']
588 revision = form.cleaned_data['revision']
589 doc.at_revision(revision).tags.add(tag)
590 return JSONResponse({"message": _("Tag added")})
592 return JSONFormInvalid(form)
596 @ajax_require_permission('wiki.can_pubmark')
597 def pubmark(request, slug, chunk=None):
598 form = forms.DocumentPubmarkForm(request.POST, prefix="pubmark")
601 doc = Chunk.get(slug, chunk)
602 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
605 revision = form.cleaned_data['revision']
606 publishable = form.cleaned_data['publishable']
607 change = doc.at_revision(revision)
608 print publishable, change.publishable
609 if publishable != change.publishable:
610 change.publishable = publishable
612 return JSONResponse({"message": _("Revision marked")})
614 return JSONResponse({"message": _("Nothing changed")})
616 return JSONFormInvalid(form)
621 def publish(request, slug):
622 book = get_object_or_404(Book, slug=slug)
624 ret = api_call(request.user, "books", {"book_xml": book.materialize()})
625 except BaseException, e:
626 return http.HttpResponse(e)
628 book.last_published = datetime.now()
630 return http.HttpResponseRedirect(book.get_absolute_url())
634 prefix = request.GET.get('q', '')
635 return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))