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.db.models import Count
13 from django.views.generic.simple import direct_to_template
14 from django.views.decorators.http import require_POST, require_GET
15 from django.core.urlresolvers import reverse
16 from wiki.helpers import (JSONResponse, JSONFormInvalid, JSONServerError,
17 ajax_require_permission, recursive_groupby, active_tab)
18 from wiki import helpers
19 from django import http
20 from django.shortcuts import get_object_or_404, redirect
21 from django.http import Http404
23 from wiki.models import Book, Chunk, Theme
24 from wiki import forms
25 from datetime import datetime
26 from django.utils.encoding import smart_unicode
27 from django.utils.translation import ugettext_lazy as _
28 from django.utils.decorators import decorator_from_middleware
29 from django.middleware.gzip import GZipMiddleware
33 from wiki import xml_tools
34 from apiclient import api_call
37 # Quick hack around caching problems, TODO: use ETags
39 from django.views.decorators.cache import never_cache
49 def document_list(request):
50 chunks_list = helpers.ChunksList(Chunk.objects.order_by(
51 'book__title', 'book', 'number'))
53 return direct_to_template(request, 'wiki/document_list.html', extra_context={
55 #'books': [helpers.BookChunks(b) for b in Book.objects.all().select_related()],
56 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
57 key=lambda x: x[1]['time'], reverse=True),
61 @active_tab('unassigned')
63 def unassigned(request):
64 chunks_list = helpers.ChunksList(Chunk.objects.filter(
65 user=None).order_by('book__title', 'book__id', 'number'))
67 return direct_to_template(request, 'wiki/document_list.html', extra_context={
69 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
70 key=lambda x: x[1]['time'], reverse=True),
75 def user(request, username=None):
77 if request.user.is_authenticated():
82 user = get_object_or_404(User, username=username)
84 chunks_list = helpers.ChunksList(Chunk.objects.filter(
85 user=user).order_by('book__title', 'book', 'number'))
87 return direct_to_template(request, 'wiki/document_list.html', extra_context={
89 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
90 key=lambda x: x[1]['time'], reverse=True),
92 my = login_required(active_tab('my')(user))
97 return direct_to_template(request, 'wiki/user_list.html', extra_context={
98 'users': User.objects.all().annotate(count=Count('chunk')).order_by(
99 '-count', 'last_name', 'first_name'),
104 def editor(request, slug, chunk=None, template_name='wiki/document_details.html'):
106 chunk = Chunk.get(slug, chunk)
107 except Chunk.MultipleObjectsReturned:
110 except Chunk.DoesNotExist:
113 book = Book.objects.get(slug=slug)
114 except Book.DoesNotExist:
115 return http.HttpResponseRedirect(reverse("wiki_create_missing", args=[slug]))
119 access_time = datetime.now()
120 last_books = request.session.get("wiki_last_books", {})
121 last_books[slug, chunk.slug] = {
123 'title': chunk.pretty_name(),
126 if len(last_books) > MAX_LAST_DOCS:
127 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
128 del last_books[oldest_key]
129 request.session['wiki_last_books'] = last_books
131 return direct_to_template(request, template_name, extra_context={
134 "text_save": forms.DocumentTextSaveForm(prefix="textsave"),
135 "text_revert": forms.DocumentTextRevertForm(prefix="textrevert"),
136 "add_tag": forms.DocumentTagForm(prefix="addtag"),
137 "pubmark": forms.DocumentPubmarkForm(prefix="pubmark"),
139 'REDMINE_URL': settings.REDMINE_URL,
144 def editor_readonly(request, slug, chunk=None, template_name='wiki/document_details_readonly.html'):
146 chunk = Chunk.get(slug, chunk)
147 revision = request.GET['revision']
148 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist, KeyError):
151 access_time = datetime.now()
152 last_books = request.session.get("wiki_last_books", {})
153 last_books[slug, chunk.slug] = {
155 'title': chunk.book.title,
158 if len(last_books) > MAX_LAST_DOCS:
159 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
160 del last_books[oldest_key]
161 request.session['wiki_last_books'] = last_books
163 return direct_to_template(request, template_name, extra_context={
165 'revision': revision,
167 'REDMINE_URL': settings.REDMINE_URL,
171 @active_tab('create')
172 def create_missing(request, slug=None):
175 slug = slug.replace(' ', '-')
177 if request.method == "POST":
178 form = forms.DocumentCreateForm(request.POST, request.FILES)
181 if request.user.is_authenticated():
182 creator = request.user
185 book = Book.create(creator=creator,
186 slug=form.cleaned_data['slug'],
187 title=form.cleaned_data['title'],
188 text=form.cleaned_data['text'],
191 return http.HttpResponseRedirect(reverse("wiki_editor", args=[book.slug]))
193 form = forms.DocumentCreateForm(initial={
195 "title": slug.replace('-', ' ').title(),
198 return direct_to_template(request, "wiki/document_create_missing.html", extra_context={
204 @active_tab('upload')
206 if request.method == "POST":
207 form = forms.DocumentsUploadForm(request.POST, request.FILES)
211 if request.user.is_authenticated():
212 creator = request.user
216 zip = form.cleaned_data['zip']
221 existing = [book.slug for book in Book.objects.all()]
222 for filename in zip.namelist():
223 if filename[-1] == '/':
225 title = os.path.basename(filename)[:-4]
226 slug = slughifi(title)
227 if not (slug and filename.endswith('.xml')):
228 skipped_list.append(filename)
230 error_list.append((filename, slug, _('Slug already used for %s' % slugs[slug])))
231 elif slug in existing:
232 error_list.append((filename, slug, _('Slug already used in repository.')))
235 zip.read(filename).decode('utf-8') # test read
236 ok_list.append((filename, slug, title))
237 except UnicodeDecodeError:
238 error_list.append((filename, title, _('File should be UTF-8 encoded.')))
239 slugs[slug] = filename
242 for filename, slug, title in ok_list:
243 Book.create(creator=creator,
246 text=zip.read(filename).decode('utf-8'),
249 return direct_to_template(request, "wiki/document_upload.html", extra_context={
252 "skipped_list": skipped_list,
253 "error_list": error_list,
256 form = forms.DocumentsUploadForm()
258 return direct_to_template(request, "wiki/document_upload.html", extra_context={
264 @decorator_from_middleware(GZipMiddleware)
265 def text(request, slug, chunk=None):
267 doc = Chunk.get(slug, chunk)
268 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
271 if request.method == 'POST':
272 form = forms.DocumentTextSaveForm(request.POST, prefix="textsave")
274 if request.user.is_authenticated():
275 author = request.user
278 text = form.cleaned_data['text']
279 parent_revision = form.cleaned_data['parent_revision']
280 parent = doc.at_revision(parent_revision)
281 stage = form.cleaned_data['stage_completed']
282 tags = [stage] if stage else []
283 doc.commit(author=author,
286 description=form.cleaned_data['comment'],
289 revision = doc.revision()
290 return JSONResponse({
291 'text': doc.materialize() if parent_revision != revision else None,
293 'revision': revision,
296 return JSONFormInvalid(form)
298 revision = request.GET.get("revision", None)
301 revision = int(revision)
302 except (ValueError, TypeError):
305 return JSONResponse({
306 'text': doc.at_revision(revision).materialize(),
308 'revision': revision if revision else doc.revision(),
313 def book_xml(request, slug):
314 xml = get_object_or_404(Book, slug=slug).materialize()
316 response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
317 response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
322 def book_txt(request, slug):
323 xml = get_object_or_404(Book, slug=slug).materialize()
326 librarian.text.transform(StringIO(xml), output)
327 text = output.getvalue()
328 response = http.HttpResponse(text, content_type='text/plain', mimetype='text/plain')
329 response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
334 def book_html(request, slug):
335 xml = get_object_or_404(Book, slug=slug).materialize()
338 librarian.html.transform(StringIO(xml), output, parse_dublincore=False,
340 html = output.getvalue()
341 response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
347 def revert(request, slug, chunk=None):
348 form = forms.DocumentTextRevertForm(request.POST, prefix="textrevert")
351 doc = Chunk.get(slug, chunk)
352 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
355 revision = form.cleaned_data['revision']
357 comment = form.cleaned_data['comment']
358 comment += "\n#revert to %s" % revision
360 if request.user.is_authenticated():
361 author = request.user
365 before = doc.revision()
366 logger.info("Reverting %s to %s", slug, revision)
367 doc.at_revision(revision).revert(author=author, description=comment)
369 return JSONResponse({
370 'text': doc.materialize() if before != doc.revision() else None,
372 'revision': doc.revision(),
375 return JSONFormInvalid(form)
379 def gallery(request, directory):
382 smart_unicode(settings.MEDIA_URL),
383 smart_unicode(settings.FILEBROWSER_DIRECTORY),
384 smart_unicode(directory)))
386 base_dir = os.path.join(
387 smart_unicode(settings.MEDIA_ROOT),
388 smart_unicode(settings.FILEBROWSER_DIRECTORY),
389 smart_unicode(directory))
391 def map_to_url(filename):
392 return "%s/%s" % (base_url, smart_unicode(filename))
394 def is_image(filename):
395 return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
397 images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
399 return JSONResponse(images)
400 except (IndexError, OSError):
401 logger.exception("Unable to fetch gallery")
406 def diff(request, slug, chunk=None):
407 revA = int(request.GET.get('from', 0))
408 revB = int(request.GET.get('to', 0))
411 revA, revB = revB, revA
417 doc = Chunk.get(slug, chunk)
418 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
420 docA = doc.at_revision(revA).materialize()
421 docB = doc.at_revision(revB).materialize()
423 return http.HttpResponse(nice_diff.html_diff_table(docA.splitlines(),
424 docB.splitlines(), context=3))
428 def revision(request, slug, chunk=None):
430 doc = Chunk.get(slug, chunk)
431 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
433 return http.HttpResponse(str(doc.revision()))
437 def history(request, slug, chunk=None):
440 doc = Chunk.get(slug, chunk)
441 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
445 for change in doc.history().order_by('-created_at'):
447 "version": change.revision,
448 "description": change.description,
449 "author": change.author_str(),
450 "date": change.created_at,
451 "publishable": "Publishable\n" if change.publishable else "",
452 "tag": ',\n'.join(unicode(tag) for tag in change.tags.all()),
454 return JSONResponse(changes)
457 def book(request, slug):
458 book = get_object_or_404(Book, slug=slug)
460 # TODO: most of this should go somewhere else
462 # do we need some automation?
466 choose_master = False
469 for i, chunk in enumerate(book):
475 graded = xml_tools.GradedText(chunk.materialize())
477 master = graded.master()
478 if first_master is None:
479 first_master = master
480 elif master != first_master:
481 chunk_dict['fix'].append('bad-master')
483 if i > 0 and not graded.has_trim_begin():
484 chunk_dict['fix'].append('trim-begin')
485 if i < length - 1 and not graded.has_trim_end():
486 chunk_dict['fix'].append('trim-end')
488 if chunk_dict['fix']:
489 chunk_dict['grade'] = 'wl-fix'
491 chunk_dict['grade'] = 'wl'
493 elif graded.is_broken_wl():
494 chunk_dict['grade'] = 'wl-broken'
495 elif graded.is_xml():
496 chunk_dict['grade'] = 'xml'
498 chunk_dict['grade'] = 'plain'
499 chunk_dict['fix'].append('wl')
502 if chunk_dict['fix']:
504 chunks.append(chunk_dict)
506 if first_master or not need_fixing:
507 choose_master = False
509 if request.method == "POST":
510 form = forms.ChooseMasterForm(request.POST)
511 if not choose_master or form.is_valid():
513 first_master = form.cleaned_data['master']
515 # do the actual fixing
520 text = c['chunk'].materialize()
522 if fix == 'bad-master':
523 text = xml_tools.change_master(text, first_master)
524 elif fix == 'trim-begin':
525 text = xml_tools.add_trim_begin(text)
526 elif fix == 'trim-end':
527 text = xml_tools.add_trim_end(text)
529 text = xml_tools.basic_structure(text, first_master)
530 author = request.user if request.user.is_authenticated() else None
531 description = "auto-fix: " + ", ".join(c['fix'])
532 c['chunk'].commit(text=text, author=author,
533 description=description)
535 return http.HttpResponseRedirect(book.get_absolute_url())
537 form = forms.ChooseMasterForm()
541 return direct_to_template(request, "wiki/book_detail.html", extra_context={
544 "need_fixing": need_fixing,
545 "choose_master": choose_master,
546 "first_master": first_master,
551 def chunk_add(request, slug, chunk):
553 doc = Chunk.get(slug, chunk)
554 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
557 if request.method == "POST":
558 form = forms.ChunkAddForm(request.POST, instance=doc)
560 if request.user.is_authenticated():
561 creator = request.user
564 doc.split(creator=creator,
565 slug=form.cleaned_data['slug'],
566 comment=form.cleaned_data['comment'],
569 return http.HttpResponseRedirect(doc.book.get_absolute_url())
571 form = forms.ChunkAddForm(initial={
572 "slug": str(doc.number + 1),
573 "comment": "cz. %d" % (doc.number + 1, ),
576 return direct_to_template(request, "wiki/chunk_add.html", extra_context={
582 def chunk_edit(request, slug, chunk):
584 doc = Chunk.get(slug, chunk)
585 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
587 if request.method == "POST":
588 form = forms.ChunkForm(request.POST, instance=doc)
591 return http.HttpResponseRedirect(doc.book.get_absolute_url())
593 form = forms.ChunkForm(instance=doc)
594 return direct_to_template(request, "wiki/chunk_edit.html", extra_context={
600 def book_append(request, slug):
601 book = get_object_or_404(Book, slug=slug)
602 if request.method == "POST":
603 form = forms.BookAppendForm(request.POST)
605 append_to = form.cleaned_data['append_to']
606 append_to.append(book)
607 return http.HttpResponseRedirect(append_to.get_absolute_url())
609 form = forms.BookAppendForm()
610 return direct_to_template(request, "wiki/book_append_to.html", extra_context={
616 def book_edit(request, slug):
617 book = get_object_or_404(Book, slug=slug)
618 if request.method == "POST":
619 form = forms.BookForm(request.POST, instance=book)
622 return http.HttpResponseRedirect(book.get_absolute_url())
624 form = forms.BookForm(instance=book)
625 return direct_to_template(request, "wiki/book_edit.html", extra_context={
632 @ajax_require_permission('wiki.can_change_tags')
633 def add_tag(request, slug, chunk=None):
634 form = forms.DocumentTagForm(request.POST, prefix="addtag")
637 doc = Chunk.get(slug, chunk)
638 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
641 tag = form.cleaned_data['tag']
642 revision = form.cleaned_data['revision']
643 doc.at_revision(revision).tags.add(tag)
644 return JSONResponse({"message": _("Tag added")})
646 return JSONFormInvalid(form)
650 @ajax_require_permission('wiki.can_pubmark')
651 def pubmark(request, slug, chunk=None):
652 form = forms.DocumentPubmarkForm(request.POST, prefix="pubmark")
655 doc = Chunk.get(slug, chunk)
656 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
659 revision = form.cleaned_data['revision']
660 publishable = form.cleaned_data['publishable']
661 change = doc.at_revision(revision)
662 print publishable, change.publishable
663 if publishable != change.publishable:
664 change.publishable = publishable
666 return JSONResponse({"message": _("Revision marked")})
668 return JSONResponse({"message": _("Nothing changed")})
670 return JSONFormInvalid(form)
675 def publish(request, slug):
676 book = get_object_or_404(Book, slug=slug)
678 ret = api_call(request.user, "books", {"book_xml": book.materialize()})
679 except BaseException, e:
680 return http.HttpResponse(e)
682 book.last_published = datetime.now()
684 return http.HttpResponseRedirect(book.get_absolute_url())
688 prefix = request.GET.get('q', '')
689 return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))