2 from StringIO import StringIO
4 logger = logging.getLogger("fnp.wiki")
8 from django.conf import settings
10 from django.contrib import auth
11 from django.contrib.auth.models import User
12 from django.contrib.auth.decorators import login_required
13 from django.db.models import Count
14 from django.utils.http import urlquote_plus
15 from django.views.generic.simple import direct_to_template
16 from django.views.decorators.http import require_POST, require_GET
17 from django.core.urlresolvers import reverse
18 from wiki.helpers import (JSONResponse, JSONFormInvalid, JSONServerError,
19 ajax_require_permission, recursive_groupby, active_tab)
20 from wiki import helpers
21 from django import http
22 from django.shortcuts import get_object_or_404, redirect
23 from django.http import Http404
25 from wiki.models import Book, Chunk, Theme
26 from wiki import forms
27 from datetime import datetime
28 from django.utils.encoding import smart_unicode
29 from django.utils.translation import ugettext_lazy as _
30 from django.utils.decorators import decorator_from_middleware
31 from django.middleware.gzip import GZipMiddleware
35 from wiki import xml_tools
36 from apiclient import api_call
39 # Quick hack around caching problems, TODO: use ETags
41 from django.views.decorators.cache import never_cache
51 def document_list(request):
52 chunks_list = helpers.ChunksList(Chunk.objects.order_by(
53 'book__title', 'book', 'number'))
55 return direct_to_template(request, 'wiki/document_list.html', extra_context={
57 #'books': [helpers.BookChunks(b) for b in Book.objects.all().select_related()],
58 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
59 key=lambda x: x[1]['time'], reverse=True),
63 @active_tab('unassigned')
65 def unassigned(request):
66 chunks_list = helpers.ChunksList(Chunk.objects.filter(
67 user=None).order_by('book__title', 'book__id', 'number'))
69 return direct_to_template(request, 'wiki/document_list.html', extra_context={
71 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
72 key=lambda x: x[1]['time'], reverse=True),
77 def user(request, username=None):
79 if request.user.is_authenticated():
84 user = get_object_or_404(User, username=username)
86 chunks_list = helpers.ChunksList(Chunk.objects.filter(
87 user=user).order_by('book__title', 'book', 'number'))
89 return direct_to_template(request, 'wiki/document_list.html', extra_context={
91 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
92 key=lambda x: x[1]['time'], reverse=True),
94 my = login_required(active_tab('my')(user))
99 return direct_to_template(request, 'wiki/user_list.html', extra_context={
100 'users': User.objects.all().annotate(count=Count('chunk')).order_by(
101 '-count', 'last_name', 'first_name'),
106 def logout_then_redirect(request):
108 return http.HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
112 def editor(request, slug, chunk=None, template_name='wiki/document_details.html'):
114 chunk = Chunk.get(slug, chunk)
115 except Chunk.MultipleObjectsReturned:
118 except Chunk.DoesNotExist:
121 book = Book.objects.get(slug=slug)
122 except Book.DoesNotExist:
123 return http.HttpResponseRedirect(reverse("wiki_create_missing", args=[slug]))
127 access_time = datetime.now()
128 last_books = request.session.get("wiki_last_books", {})
129 last_books[slug, chunk.slug] = {
131 'title': chunk.pretty_name(),
134 if len(last_books) > MAX_LAST_DOCS:
135 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
136 del last_books[oldest_key]
137 request.session['wiki_last_books'] = last_books
139 return direct_to_template(request, template_name, extra_context={
142 "text_save": forms.DocumentTextSaveForm(prefix="textsave"),
143 "text_revert": forms.DocumentTextRevertForm(prefix="textrevert"),
144 "add_tag": forms.DocumentTagForm(prefix="addtag"),
145 "pubmark": forms.DocumentPubmarkForm(prefix="pubmark"),
147 'REDMINE_URL': settings.REDMINE_URL,
152 def editor_readonly(request, slug, chunk=None, template_name='wiki/document_details_readonly.html'):
154 chunk = Chunk.get(slug, chunk)
155 revision = request.GET['revision']
156 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist, KeyError):
159 access_time = datetime.now()
160 last_books = request.session.get("wiki_last_books", {})
161 last_books[slug, chunk.slug] = {
163 'title': chunk.book.title,
166 if len(last_books) > MAX_LAST_DOCS:
167 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
168 del last_books[oldest_key]
169 request.session['wiki_last_books'] = last_books
171 return direct_to_template(request, template_name, extra_context={
173 'revision': revision,
175 'REDMINE_URL': settings.REDMINE_URL,
179 @active_tab('create')
180 def create_missing(request, slug=None):
183 slug = slug.replace(' ', '-')
185 if request.method == "POST":
186 form = forms.DocumentCreateForm(request.POST, request.FILES)
189 if request.user.is_authenticated():
190 creator = request.user
193 book = Book.create(creator=creator,
194 slug=form.cleaned_data['slug'],
195 title=form.cleaned_data['title'],
196 text=form.cleaned_data['text'],
199 return http.HttpResponseRedirect(reverse("wiki_editor", args=[book.slug]))
201 form = forms.DocumentCreateForm(initial={
203 "title": slug.replace('-', ' ').title(),
206 return direct_to_template(request, "wiki/document_create_missing.html", extra_context={
212 @active_tab('upload')
214 if request.method == "POST":
215 form = forms.DocumentsUploadForm(request.POST, request.FILES)
219 if request.user.is_authenticated():
220 creator = request.user
224 zip = form.cleaned_data['zip']
229 existing = [book.slug for book in Book.objects.all()]
230 for filename in zip.namelist():
231 if filename[-1] == '/':
233 title = os.path.basename(filename)[:-4]
234 slug = slughifi(title)
235 if not (slug and filename.endswith('.xml')):
236 skipped_list.append(filename)
238 error_list.append((filename, slug, _('Slug already used for %s' % slugs[slug])))
239 elif slug in existing:
240 error_list.append((filename, slug, _('Slug already used in repository.')))
243 zip.read(filename).decode('utf-8') # test read
244 ok_list.append((filename, slug, title))
245 except UnicodeDecodeError:
246 error_list.append((filename, title, _('File should be UTF-8 encoded.')))
247 slugs[slug] = filename
250 for filename, slug, title in ok_list:
251 Book.create(creator=creator,
254 text=zip.read(filename).decode('utf-8'),
257 return direct_to_template(request, "wiki/document_upload.html", extra_context={
260 "skipped_list": skipped_list,
261 "error_list": error_list,
264 form = forms.DocumentsUploadForm()
266 return direct_to_template(request, "wiki/document_upload.html", extra_context={
272 @decorator_from_middleware(GZipMiddleware)
273 def text(request, slug, chunk=None):
275 doc = Chunk.get(slug, chunk)
276 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
279 if request.method == 'POST':
280 form = forms.DocumentTextSaveForm(request.POST, prefix="textsave")
282 if request.user.is_authenticated():
283 author = request.user
286 text = form.cleaned_data['text']
287 parent_revision = form.cleaned_data['parent_revision']
288 parent = doc.at_revision(parent_revision)
289 stage = form.cleaned_data['stage_completed']
290 tags = [stage] if stage else []
291 doc.commit(author=author,
294 description=form.cleaned_data['comment'],
297 revision = doc.revision()
298 return JSONResponse({
299 'text': doc.materialize() if parent_revision != revision else None,
301 'revision': revision,
304 return JSONFormInvalid(form)
306 revision = request.GET.get("revision", None)
309 revision = int(revision)
310 except (ValueError, TypeError):
313 return JSONResponse({
314 'text': doc.at_revision(revision).materialize(),
316 'revision': revision if revision else doc.revision(),
321 def book_xml(request, slug):
322 xml = get_object_or_404(Book, slug=slug).materialize()
324 response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
325 response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
330 def book_txt(request, slug):
331 xml = get_object_or_404(Book, slug=slug).materialize()
334 librarian.text.transform(StringIO(xml), output)
335 text = output.getvalue()
336 response = http.HttpResponse(text, content_type='text/plain', mimetype='text/plain')
337 response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
342 def book_html(request, slug):
343 xml = get_object_or_404(Book, slug=slug).materialize()
346 librarian.html.transform(StringIO(xml), output, parse_dublincore=False,
348 html = output.getvalue()
349 response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
355 def revert(request, slug, chunk=None):
356 form = forms.DocumentTextRevertForm(request.POST, prefix="textrevert")
359 doc = Chunk.get(slug, chunk)
360 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
363 revision = form.cleaned_data['revision']
365 comment = form.cleaned_data['comment']
366 comment += "\n#revert to %s" % revision
368 if request.user.is_authenticated():
369 author = request.user
373 before = doc.revision()
374 logger.info("Reverting %s to %s", slug, revision)
375 doc.at_revision(revision).revert(author=author, description=comment)
377 return JSONResponse({
378 'text': doc.materialize() if before != doc.revision() else None,
380 'revision': doc.revision(),
383 return JSONFormInvalid(form)
387 def gallery(request, directory):
390 smart_unicode(settings.MEDIA_URL),
391 smart_unicode(settings.FILEBROWSER_DIRECTORY),
392 smart_unicode(directory)))
394 base_dir = os.path.join(
395 smart_unicode(settings.MEDIA_ROOT),
396 smart_unicode(settings.FILEBROWSER_DIRECTORY),
397 smart_unicode(directory))
399 def map_to_url(filename):
400 return "%s/%s" % (base_url, smart_unicode(filename))
402 def is_image(filename):
403 return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
405 images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
407 return JSONResponse(images)
408 except (IndexError, OSError):
409 logger.exception("Unable to fetch gallery")
414 def diff(request, slug, chunk=None):
415 revA = int(request.GET.get('from', 0))
416 revB = int(request.GET.get('to', 0))
419 revA, revB = revB, revA
425 doc = Chunk.get(slug, chunk)
426 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
428 docA = doc.at_revision(revA).materialize()
429 docB = doc.at_revision(revB).materialize()
431 return http.HttpResponse(nice_diff.html_diff_table(docA.splitlines(),
432 docB.splitlines(), context=3))
436 def revision(request, slug, chunk=None):
438 doc = Chunk.get(slug, chunk)
439 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
441 return http.HttpResponse(str(doc.revision()))
445 def history(request, slug, chunk=None):
448 doc = Chunk.get(slug, chunk)
449 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
453 for change in doc.history().order_by('-created_at'):
455 "version": change.revision,
456 "description": change.description,
457 "author": change.author_str(),
458 "date": change.created_at,
459 "publishable": "Publishable\n" if change.publishable else "",
460 "tag": ',\n'.join(unicode(tag) for tag in change.tags.all()),
462 return JSONResponse(changes)
465 def book(request, slug):
466 book = get_object_or_404(Book, slug=slug)
468 # TODO: most of this should go somewhere else
470 # do we need some automation?
474 choose_master = False
477 for i, chunk in enumerate(book):
483 graded = xml_tools.GradedText(chunk.materialize())
485 master = graded.master()
486 if first_master is None:
487 first_master = master
488 elif master != first_master:
489 chunk_dict['fix'].append('bad-master')
491 if i > 0 and not graded.has_trim_begin():
492 chunk_dict['fix'].append('trim-begin')
493 if i < length - 1 and not graded.has_trim_end():
494 chunk_dict['fix'].append('trim-end')
496 if chunk_dict['fix']:
497 chunk_dict['grade'] = 'wl-fix'
499 chunk_dict['grade'] = 'wl'
501 elif graded.is_broken_wl():
502 chunk_dict['grade'] = 'wl-broken'
503 elif graded.is_xml():
504 chunk_dict['grade'] = 'xml'
506 chunk_dict['grade'] = 'plain'
507 chunk_dict['fix'].append('wl')
510 if chunk_dict['fix']:
512 chunks.append(chunk_dict)
514 if first_master or not need_fixing:
515 choose_master = False
517 if request.method == "POST":
518 form = forms.ChooseMasterForm(request.POST)
519 if not choose_master or form.is_valid():
521 first_master = form.cleaned_data['master']
523 # do the actual fixing
528 text = c['chunk'].materialize()
530 if fix == 'bad-master':
531 text = xml_tools.change_master(text, first_master)
532 elif fix == 'trim-begin':
533 text = xml_tools.add_trim_begin(text)
534 elif fix == 'trim-end':
535 text = xml_tools.add_trim_end(text)
537 text = xml_tools.basic_structure(text, first_master)
538 author = request.user if request.user.is_authenticated() else None
539 description = "auto-fix: " + ", ".join(c['fix'])
540 c['chunk'].commit(text=text, author=author,
541 description=description)
543 return http.HttpResponseRedirect(book.get_absolute_url())
545 form = forms.ChooseMasterForm()
549 return direct_to_template(request, "wiki/book_detail.html", extra_context={
552 "need_fixing": need_fixing,
553 "choose_master": choose_master,
554 "first_master": first_master,
559 def chunk_add(request, slug, chunk):
561 doc = Chunk.get(slug, chunk)
562 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
565 if request.method == "POST":
566 form = forms.ChunkAddForm(request.POST, instance=doc)
568 if request.user.is_authenticated():
569 creator = request.user
572 doc.split(creator=creator,
573 slug=form.cleaned_data['slug'],
574 comment=form.cleaned_data['comment'],
577 return http.HttpResponseRedirect(doc.book.get_absolute_url())
579 form = forms.ChunkAddForm(initial={
580 "slug": str(doc.number + 1),
581 "comment": "cz. %d" % (doc.number + 1, ),
584 return direct_to_template(request, "wiki/chunk_add.html", extra_context={
590 def chunk_edit(request, slug, chunk):
592 doc = Chunk.get(slug, chunk)
593 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
595 if request.method == "POST":
596 form = forms.ChunkForm(request.POST, instance=doc)
599 return http.HttpResponseRedirect(doc.book.get_absolute_url())
601 form = forms.ChunkForm(instance=doc)
602 return direct_to_template(request, "wiki/chunk_edit.html", extra_context={
608 def book_append(request, slug):
609 book = get_object_or_404(Book, slug=slug)
610 if request.method == "POST":
611 form = forms.BookAppendForm(request.POST)
613 append_to = form.cleaned_data['append_to']
614 append_to.append(book)
615 return http.HttpResponseRedirect(append_to.get_absolute_url())
617 form = forms.BookAppendForm()
618 return direct_to_template(request, "wiki/book_append_to.html", extra_context={
624 def book_edit(request, slug):
625 book = get_object_or_404(Book, slug=slug)
626 if request.method == "POST":
627 form = forms.BookForm(request.POST, instance=book)
630 return http.HttpResponseRedirect(book.get_absolute_url())
632 form = forms.BookForm(instance=book)
633 return direct_to_template(request, "wiki/book_edit.html", extra_context={
640 @ajax_require_permission('wiki.can_change_tags')
641 def add_tag(request, slug, chunk=None):
642 form = forms.DocumentTagForm(request.POST, prefix="addtag")
645 doc = Chunk.get(slug, chunk)
646 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
649 tag = form.cleaned_data['tag']
650 revision = form.cleaned_data['revision']
651 doc.at_revision(revision).tags.add(tag)
652 return JSONResponse({"message": _("Tag added")})
654 return JSONFormInvalid(form)
658 @ajax_require_permission('wiki.can_pubmark')
659 def pubmark(request, slug, chunk=None):
660 form = forms.DocumentPubmarkForm(request.POST, prefix="pubmark")
663 doc = Chunk.get(slug, chunk)
664 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
667 revision = form.cleaned_data['revision']
668 publishable = form.cleaned_data['publishable']
669 change = doc.at_revision(revision)
670 print publishable, change.publishable
671 if publishable != change.publishable:
672 change.publishable = publishable
674 return JSONResponse({"message": _("Revision marked")})
676 return JSONResponse({"message": _("Nothing changed")})
678 return JSONFormInvalid(form)
683 def publish(request, slug):
684 book = get_object_or_404(Book, slug=slug)
686 ret = api_call(request.user, "books", {"book_xml": book.materialize()})
687 except BaseException, e:
688 return http.HttpResponse(e)
690 book.last_published = datetime.now()
692 return http.HttpResponseRedirect(book.get_absolute_url())
696 prefix = request.GET.get('q', '')
697 return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))