2 from StringIO import StringIO
4 logger = logging.getLogger("fnp.wiki")
8 from django.conf import settings
10 from django.contrib.auth.models import User
11 from django.contrib.auth.decorators import login_required
12 from django.views.generic.simple import direct_to_template
13 from django.views.decorators.http import require_POST, require_GET
14 from django.core.urlresolvers import reverse
15 from wiki.helpers import (JSONResponse, JSONFormInvalid, JSONServerError,
16 ajax_require_permission, recursive_groupby, active_tab)
17 from django import http
18 from django.shortcuts import get_object_or_404, redirect
19 from django.http import Http404
21 from wiki.models import Book, Chunk, Theme
22 from wiki import forms
23 from datetime import datetime
24 from django.utils.encoding import smart_unicode
25 from django.utils.translation import ugettext_lazy as _
26 from django.utils.decorators import decorator_from_middleware
27 from django.middleware.gzip import GZipMiddleware
31 from wiki import xml_tools
32 from apiclient import api_call
35 # Quick hack around caching problems, TODO: use ETags
37 from django.views.decorators.cache import never_cache
47 def document_list(request):
48 return direct_to_template(request, 'wiki/document_list.html', extra_context={
49 'books': Book.objects.all(),
50 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
51 key=lambda x: x[1]['time'], reverse=True),
55 @active_tab('unassigned')
57 def unassigned(request):
58 return direct_to_template(request, 'wiki/document_list.html', extra_context={
59 'books': Chunk.objects.filter(user=None),
60 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
61 key=lambda x: x[1]['time'], reverse=True),
66 def user(request, username=None):
68 if request.user.is_authenticated():
73 user = get_object_or_404(User, username=username)
75 return direct_to_template(request, 'wiki/document_list.html', extra_context={
76 'books': Chunk.objects.filter(user=user),
77 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
78 key=lambda x: x[1]['time'], reverse=True),
80 my = login_required(active_tab('my')(user))
84 def editor(request, slug, chunk=None, template_name='wiki/document_details.html'):
86 chunk = Chunk.get(slug, chunk)
87 except Chunk.MultipleObjectsReturned:
90 except Chunk.DoesNotExist:
93 book = Book.objects.get(slug=slug)
94 except Book.DoesNotExist:
95 return http.HttpResponseRedirect(reverse("wiki_create_missing", args=[slug]))
99 access_time = datetime.now()
100 last_books = request.session.get("wiki_last_books", {})
101 last_books[slug, chunk.slug] = {
103 'title': chunk.pretty_name(),
106 if len(last_books) > MAX_LAST_DOCS:
107 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
108 del last_books[oldest_key]
109 request.session['wiki_last_books'] = last_books
111 return direct_to_template(request, template_name, extra_context={
114 "text_save": forms.DocumentTextSaveForm(prefix="textsave"),
115 "text_revert": forms.DocumentTextRevertForm(prefix="textrevert"),
116 "add_tag": forms.DocumentTagForm(prefix="addtag"),
117 "pubmark": forms.DocumentPubmarkForm(prefix="pubmark"),
119 'REDMINE_URL': settings.REDMINE_URL,
124 def editor_readonly(request, slug, chunk=None, template_name='wiki/document_details_readonly.html'):
126 chunk = Chunk.get(slug, chunk)
127 revision = request.GET['revision']
128 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist, KeyError):
131 access_time = datetime.now()
132 last_books = request.session.get("wiki_last_books", {})
133 last_books[slug, chunk.slug] = {
135 'title': chunk.book.title,
138 if len(last_books) > MAX_LAST_DOCS:
139 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
140 del last_books[oldest_key]
141 request.session['wiki_last_books'] = last_books
143 return direct_to_template(request, template_name, extra_context={
145 'revision': revision,
147 'REDMINE_URL': settings.REDMINE_URL,
151 @active_tab('create')
152 def create_missing(request, slug=None):
155 slug = slug.replace(' ', '-')
157 if request.method == "POST":
158 form = forms.DocumentCreateForm(request.POST, request.FILES)
161 if request.user.is_authenticated():
162 creator = request.user
165 book = Book.create(creator=creator,
166 slug=form.cleaned_data['slug'],
167 title=form.cleaned_data['title'],
168 text=form.cleaned_data['text'],
171 return http.HttpResponseRedirect(reverse("wiki_editor", args=[book.slug]))
173 form = forms.DocumentCreateForm(initial={
175 "title": slug.replace('-', ' ').title(),
178 return direct_to_template(request, "wiki/document_create_missing.html", extra_context={
184 @active_tab('upload')
186 if request.method == "POST":
187 form = forms.DocumentsUploadForm(request.POST, request.FILES)
191 if request.user.is_authenticated():
192 creator = request.user
196 zip = form.cleaned_data['zip']
201 existing = [book.slug for book in Book.objects.all()]
202 for filename in zip.namelist():
203 if filename[-1] == '/':
205 title = os.path.basename(filename)[:-4]
206 slug = slughifi(title)
207 if not (slug and filename.endswith('.xml')):
208 skipped_list.append(filename)
210 error_list.append((filename, slug, _('Slug already used for %s' % slugs[slug])))
211 elif slug in existing:
212 error_list.append((filename, slug, _('Slug already used in repository.')))
215 zip.read(filename).decode('utf-8') # test read
216 ok_list.append((filename, slug, title))
217 except UnicodeDecodeError:
218 error_list.append((filename, title, _('File should be UTF-8 encoded.')))
219 slugs[slug] = filename
222 for filename, slug, title in ok_list:
223 Book.create(creator=creator,
226 text=zip.read(filename).decode('utf-8'),
229 return direct_to_template(request, "wiki/document_upload.html", extra_context={
232 "skipped_list": skipped_list,
233 "error_list": error_list,
236 form = forms.DocumentsUploadForm()
238 return direct_to_template(request, "wiki/document_upload.html", extra_context={
244 @decorator_from_middleware(GZipMiddleware)
245 def text(request, slug, chunk=None):
247 doc = Chunk.get(slug, chunk)
248 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
251 if request.method == 'POST':
252 form = forms.DocumentTextSaveForm(request.POST, prefix="textsave")
254 if request.user.is_authenticated():
255 author = request.user
258 text = form.cleaned_data['text']
259 parent_revision = form.cleaned_data['parent_revision']
260 parent = doc.at_revision(parent_revision)
261 stage = form.cleaned_data['stage_completed']
262 tags = [stage] if stage else []
263 doc.commit(author=author,
266 description=form.cleaned_data['comment'],
269 revision = doc.revision()
270 return JSONResponse({
271 'text': doc.materialize() if parent_revision != revision else None,
273 'revision': revision,
276 return JSONFormInvalid(form)
278 revision = request.GET.get("revision", None)
281 revision = int(revision)
282 except (ValueError, TypeError):
285 return JSONResponse({
286 'text': doc.at_revision(revision).materialize(),
288 'revision': revision if revision else doc.revision(),
293 def book_xml(request, slug):
294 xml = get_object_or_404(Book, slug=slug).materialize()
296 response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
297 response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
302 def book_txt(request, slug):
303 xml = get_object_or_404(Book, slug=slug).materialize()
306 librarian.text.transform(StringIO(xml), output)
307 text = output.getvalue()
308 response = http.HttpResponse(text, content_type='text/plain', mimetype='text/plain')
309 response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
314 def book_html(request, slug):
315 xml = get_object_or_404(Book, slug=slug).materialize()
318 librarian.html.transform(StringIO(xml), output, parse_dublincore=False,
320 html = output.getvalue()
321 response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
327 def revert(request, slug, chunk=None):
328 form = forms.DocumentTextRevertForm(request.POST, prefix="textrevert")
331 doc = Chunk.get(slug, chunk)
332 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
335 revision = form.cleaned_data['revision']
337 comment = form.cleaned_data['comment']
338 comment += "\n#revert to %s" % revision
340 if request.user.is_authenticated():
341 author = request.user
345 before = doc.revision()
346 logger.info("Reverting %s to %s", slug, revision)
347 doc.at_revision(revision).revert(author=author, description=comment)
349 return JSONResponse({
350 'text': doc.materialize() if before != doc.revision() else None,
352 'revision': doc.revision(),
355 return JSONFormInvalid(form)
359 def gallery(request, directory):
362 smart_unicode(settings.MEDIA_URL),
363 smart_unicode(settings.FILEBROWSER_DIRECTORY),
364 smart_unicode(directory)))
366 base_dir = os.path.join(
367 smart_unicode(settings.MEDIA_ROOT),
368 smart_unicode(settings.FILEBROWSER_DIRECTORY),
369 smart_unicode(directory))
371 def map_to_url(filename):
372 return "%s/%s" % (base_url, smart_unicode(filename))
374 def is_image(filename):
375 return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
377 images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
379 return JSONResponse(images)
380 except (IndexError, OSError):
381 logger.exception("Unable to fetch gallery")
386 def diff(request, slug, chunk=None):
387 revA = int(request.GET.get('from', 0))
388 revB = int(request.GET.get('to', 0))
391 revA, revB = revB, revA
397 doc = Chunk.get(slug, chunk)
398 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
400 docA = doc.at_revision(revA).materialize()
401 docB = doc.at_revision(revB).materialize()
403 return http.HttpResponse(nice_diff.html_diff_table(docA.splitlines(),
404 docB.splitlines(), context=3))
408 def revision(request, slug, chunk=None):
410 doc = Chunk.get(slug, chunk)
411 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
413 return http.HttpResponse(str(doc.revision()))
417 def history(request, slug, chunk=None):
420 doc = Chunk.get(slug, chunk)
421 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
425 for change in doc.history().order_by('-created_at'):
427 "version": change.revision,
428 "description": change.description,
429 "author": change.author_str(),
430 "date": change.created_at,
431 "publishable": "Publishable\n" if change.publishable else "",
432 "tag": ',\n'.join(unicode(tag) for tag in change.tags.all()),
434 return JSONResponse(changes)
437 def book(request, slug):
438 book = get_object_or_404(Book, slug=slug)
440 # TODO: most of this should go somewhere else
442 # do we need some automation?
446 choose_master = False
449 for i, chunk in enumerate(book):
455 graded = xml_tools.GradedText(chunk.materialize())
457 master = graded.master()
458 if first_master is None:
459 first_master = master
460 elif master != first_master:
461 chunk_dict['fix'].append('bad-master')
463 if i > 0 and not graded.has_trim_begin():
464 chunk_dict['fix'].append('trim-begin')
465 if i < length - 1 and not graded.has_trim_end():
466 chunk_dict['fix'].append('trim-end')
468 if chunk_dict['fix']:
469 chunk_dict['grade'] = 'wl-fix'
471 chunk_dict['grade'] = 'wl'
473 elif graded.is_broken_wl():
474 chunk_dict['grade'] = 'wl-broken'
475 elif graded.is_xml():
476 chunk_dict['grade'] = 'xml'
478 chunk_dict['grade'] = 'plain'
479 chunk_dict['fix'].append('wl')
482 if chunk_dict['fix']:
484 chunks.append(chunk_dict)
486 if first_master or not need_fixing:
487 choose_master = False
489 if request.method == "POST":
490 form = forms.ChooseMasterForm(request.POST)
491 if not choose_master or form.is_valid():
493 first_master = form.cleaned_data['master']
495 # do the actual fixing
500 text = c['chunk'].materialize()
502 if fix == 'bad-master':
503 text = xml_tools.change_master(text, first_master)
504 elif fix == 'trim-begin':
505 text = xml_tools.add_trim_begin(text)
506 elif fix == 'trim-end':
507 text = xml_tools.add_trim_end(text)
509 text = xml_tools.basic_structure(text, first_master)
510 author = request.user if request.user.is_authenticated() else None
511 description = "auto-fix: " + ", ".join(c['fix'])
512 c['chunk'].commit(text=text, author=author,
513 description=description)
515 return http.HttpResponseRedirect(book.get_absolute_url())
517 form = forms.ChooseMasterForm()
521 return direct_to_template(request, "wiki/book_detail.html", extra_context={
524 "need_fixing": need_fixing,
525 "choose_master": choose_master,
526 "first_master": first_master,
531 def chunk_add(request, slug, chunk):
533 doc = Chunk.get(slug, chunk)
534 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
537 if request.method == "POST":
538 form = forms.ChunkAddForm(request.POST, instance=doc)
540 if request.user.is_authenticated():
541 creator = request.user
544 doc.split(creator=creator,
545 slug=form.cleaned_data['slug'],
546 comment=form.cleaned_data['comment'],
549 return http.HttpResponseRedirect(doc.book.get_absolute_url())
551 form = forms.ChunkAddForm(initial={
552 "slug": str(doc.number + 1),
553 "comment": "cz. %d" % (doc.number + 1, ),
556 return direct_to_template(request, "wiki/chunk_add.html", extra_context={
562 def chunk_edit(request, slug, chunk):
564 doc = Chunk.get(slug, chunk)
565 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
567 if request.method == "POST":
568 form = forms.ChunkForm(request.POST, instance=doc)
571 return http.HttpResponseRedirect(doc.book.get_absolute_url())
573 form = forms.ChunkForm(instance=doc)
574 return direct_to_template(request, "wiki/chunk_edit.html", extra_context={
580 def book_append(request, slug):
581 book = get_object_or_404(Book, slug=slug)
582 if request.method == "POST":
583 form = forms.BookAppendForm(request.POST)
585 append_to = form.cleaned_data['append_to']
586 append_to.append(book)
587 return http.HttpResponseRedirect(append_to.get_absolute_url())
589 form = forms.BookAppendForm()
590 return direct_to_template(request, "wiki/book_append_to.html", extra_context={
596 def book_edit(request, slug):
597 book = get_object_or_404(Book, slug=slug)
598 if request.method == "POST":
599 form = forms.BookForm(request.POST, instance=book)
602 return http.HttpResponseRedirect(book.get_absolute_url())
604 form = forms.BookForm(instance=book)
605 return direct_to_template(request, "wiki/book_edit.html", extra_context={
612 @ajax_require_permission('wiki.can_change_tags')
613 def add_tag(request, slug, chunk=None):
614 form = forms.DocumentTagForm(request.POST, prefix="addtag")
617 doc = Chunk.get(slug, chunk)
618 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
621 tag = form.cleaned_data['tag']
622 revision = form.cleaned_data['revision']
623 doc.at_revision(revision).tags.add(tag)
624 return JSONResponse({"message": _("Tag added")})
626 return JSONFormInvalid(form)
630 @ajax_require_permission('wiki.can_pubmark')
631 def pubmark(request, slug, chunk=None):
632 form = forms.DocumentPubmarkForm(request.POST, prefix="pubmark")
635 doc = Chunk.get(slug, chunk)
636 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
639 revision = form.cleaned_data['revision']
640 publishable = form.cleaned_data['publishable']
641 change = doc.at_revision(revision)
642 print publishable, change.publishable
643 if publishable != change.publishable:
644 change.publishable = publishable
646 return JSONResponse({"message": _("Revision marked")})
648 return JSONResponse({"message": _("Nothing changed")})
650 return JSONFormInvalid(form)
655 def publish(request, slug):
656 book = get_object_or_404(Book, slug=slug)
658 ret = api_call(request.user, "books", {"book_xml": book.materialize()})
659 except BaseException, e:
660 return http.HttpResponse(e)
662 book.last_published = datetime.now()
664 return http.HttpResponseRedirect(book.get_absolute_url())
668 prefix = request.GET.get('q', '')
669 return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))