1 from datetime import datetime
4 from StringIO import StringIO
6 from django.contrib import auth
7 from django.contrib.auth.models import User
8 from django.contrib.auth.decorators import login_required
9 from django.core.urlresolvers import reverse
10 from django.db.models import Count
11 from django import http
12 from django.http import Http404
13 from django.shortcuts import get_object_or_404
14 from django.utils.http import urlquote_plus
15 from django.utils.translation import ugettext_lazy as _
16 from django.views.decorators.http import require_POST
17 from django.views.generic.simple import direct_to_template
22 from apiclient import api_call
23 from catalogue import forms
24 from catalogue import helpers
25 from catalogue.helpers import active_tab
26 from catalogue.models import Book, Chunk
27 from catalogue import xml_tools
30 # Quick hack around caching problems, TODO: use ETags
32 from django.views.decorators.cache import never_cache
34 logger = logging.getLogger("fnp.catalogue")
39 def document_list(request):
40 chunks_list = helpers.ChunksList(Chunk.objects.order_by(
41 'book__title', 'book', 'number'))
43 return direct_to_template(request, 'catalogue/document_list.html', extra_context={
45 #'books': [helpers.BookChunks(b) for b in Book.objects.all().select_related()],
46 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
47 key=lambda x: x[1]['time'], reverse=True),
51 @active_tab('unassigned')
53 def unassigned(request):
54 chunks_list = helpers.ChunksList(Chunk.objects.filter(
55 user=None).order_by('book__title', 'book__id', 'number'))
57 return direct_to_template(request, 'catalogue/document_list.html', extra_context={
59 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
60 key=lambda x: x[1]['time'], reverse=True),
65 def user(request, username=None):
67 if request.user.is_authenticated():
72 user = get_object_or_404(User, username=username)
74 chunks_list = helpers.ChunksList(Chunk.objects.filter(
75 user=user).order_by('book__title', 'book', 'number'))
77 return direct_to_template(request, 'catalogue/document_list.html', extra_context={
79 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
80 key=lambda x: x[1]['time'], reverse=True),
82 my = login_required(active_tab('my')(user))
87 return direct_to_template(request, 'catalogue/user_list.html', extra_context={
88 'users': User.objects.all().annotate(count=Count('chunk')).order_by(
89 '-count', 'last_name', 'first_name'),
94 def logout_then_redirect(request):
96 return http.HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
100 def create_missing(request, slug=None):
103 slug = slug.replace(' ', '-')
105 if request.method == "POST":
106 form = forms.DocumentCreateForm(request.POST, request.FILES)
109 if request.user.is_authenticated():
110 creator = request.user
113 book = Book.create(creator=creator,
114 slug=form.cleaned_data['slug'],
115 title=form.cleaned_data['title'],
116 text=form.cleaned_data['text'],
119 return http.HttpResponseRedirect(reverse("wiki_editor", args=[book.slug]))
121 form = forms.DocumentCreateForm(initial={
123 "title": slug.replace('-', ' ').title(),
126 return direct_to_template(request, "catalogue/document_create_missing.html", extra_context={
132 @active_tab('upload')
134 if request.method == "POST":
135 form = forms.DocumentsUploadForm(request.POST, request.FILES)
139 if request.user.is_authenticated():
140 creator = request.user
144 zip = form.cleaned_data['zip']
149 existing = [book.slug for book in Book.objects.all()]
150 for filename in zip.namelist():
151 if filename[-1] == '/':
153 title = os.path.basename(filename)[:-4]
154 slug = slughifi(title)
155 if not (slug and filename.endswith('.xml')):
156 skipped_list.append(filename)
158 error_list.append((filename, slug, _('Slug already used for %s' % slugs[slug])))
159 elif slug in existing:
160 error_list.append((filename, slug, _('Slug already used in repository.')))
163 zip.read(filename).decode('utf-8') # test read
164 ok_list.append((filename, slug, title))
165 except UnicodeDecodeError:
166 error_list.append((filename, title, _('File should be UTF-8 encoded.')))
167 slugs[slug] = filename
170 for filename, slug, title in ok_list:
171 Book.create(creator=creator,
174 text=zip.read(filename).decode('utf-8'),
177 return direct_to_template(request, "catalogue/document_upload.html", extra_context={
180 "skipped_list": skipped_list,
181 "error_list": error_list,
184 form = forms.DocumentsUploadForm()
186 return direct_to_template(request, "catalogue/document_upload.html", extra_context={
192 def book_xml(request, slug):
193 xml = get_object_or_404(Book, slug=slug).materialize()
195 response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
196 response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
201 def book_txt(request, slug):
202 xml = get_object_or_404(Book, slug=slug).materialize()
205 librarian.text.transform(StringIO(xml), output)
206 text = output.getvalue()
207 response = http.HttpResponse(text, content_type='text/plain', mimetype='text/plain')
208 response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
213 def book_html(request, slug):
214 xml = get_object_or_404(Book, slug=slug).materialize()
217 librarian.html.transform(StringIO(xml), output, parse_dublincore=False,
219 html = output.getvalue()
220 response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
225 def revision(request, slug, chunk=None):
227 doc = Chunk.get(slug, chunk)
228 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
230 return http.HttpResponse(str(doc.revision()))
233 def book(request, slug):
234 book = get_object_or_404(Book, slug=slug)
236 # TODO: most of this should go somewhere else
238 # do we need some automation?
242 choose_master = False
244 length = book.chunk_set.count()
245 for i, chunk in enumerate(book):
251 graded = xml_tools.GradedText(chunk.materialize())
253 master = graded.master()
254 if first_master is None:
255 first_master = master
256 elif master != first_master:
257 chunk_dict['fix'].append('bad-master')
259 if i > 0 and not graded.has_trim_begin():
260 chunk_dict['fix'].append('trim-begin')
261 if i < length - 1 and not graded.has_trim_end():
262 chunk_dict['fix'].append('trim-end')
264 if chunk_dict['fix']:
265 chunk_dict['grade'] = 'wl-fix'
267 chunk_dict['grade'] = 'wl'
269 elif graded.is_broken_wl():
270 chunk_dict['grade'] = 'wl-broken'
271 elif graded.is_xml():
272 chunk_dict['grade'] = 'xml'
274 chunk_dict['grade'] = 'plain'
275 chunk_dict['fix'].append('wl')
278 if chunk_dict['fix']:
280 chunks.append(chunk_dict)
282 if first_master or not need_fixing:
283 choose_master = False
285 if request.method == "POST":
286 form = forms.ChooseMasterForm(request.POST)
287 if not choose_master or form.is_valid():
289 first_master = form.cleaned_data['master']
291 # do the actual fixing
296 text = c['chunk'].materialize()
298 if fix == 'bad-master':
299 text = xml_tools.change_master(text, first_master)
300 elif fix == 'trim-begin':
301 text = xml_tools.add_trim_begin(text)
302 elif fix == 'trim-end':
303 text = xml_tools.add_trim_end(text)
305 text = xml_tools.basic_structure(text, first_master)
306 author = request.user if request.user.is_authenticated() else None
307 description = "auto-fix: " + ", ".join(c['fix'])
308 c['chunk'].commit(text=text, author=author,
309 description=description)
311 return http.HttpResponseRedirect(book.get_absolute_url())
313 form = forms.ChooseMasterForm()
317 return direct_to_template(request, "catalogue/book_detail.html", extra_context={
320 "need_fixing": need_fixing,
321 "choose_master": choose_master,
322 "first_master": first_master,
327 def chunk_add(request, slug, chunk):
329 doc = Chunk.get(slug, chunk)
330 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
333 if request.method == "POST":
334 form = forms.ChunkAddForm(request.POST, instance=doc)
336 if request.user.is_authenticated():
337 creator = request.user
340 doc.split(creator=creator,
341 slug=form.cleaned_data['slug'],
342 comment=form.cleaned_data['comment'],
345 return http.HttpResponseRedirect(doc.book.get_absolute_url())
347 form = forms.ChunkAddForm(initial={
348 "slug": str(doc.number + 1),
349 "comment": "cz. %d" % (doc.number + 1, ),
352 return direct_to_template(request, "catalogue/chunk_add.html", extra_context={
358 def chunk_edit(request, slug, chunk):
360 doc = Chunk.get(slug, chunk)
361 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
363 if request.method == "POST":
364 form = forms.ChunkForm(request.POST, instance=doc)
367 return http.HttpResponseRedirect(doc.book.get_absolute_url())
369 form = forms.ChunkForm(instance=doc)
370 return direct_to_template(request, "catalogue/chunk_edit.html", extra_context={
376 def book_append(request, slug):
377 book = get_object_or_404(Book, slug=slug)
378 if request.method == "POST":
379 form = forms.BookAppendForm(request.POST)
381 append_to = form.cleaned_data['append_to']
382 append_to.append(book)
383 return http.HttpResponseRedirect(append_to.get_absolute_url())
385 form = forms.BookAppendForm()
386 return direct_to_template(request, "catalogue/book_append_to.html", extra_context={
392 def book_edit(request, slug):
393 book = get_object_or_404(Book, slug=slug)
394 if request.method == "POST":
395 form = forms.BookForm(request.POST, instance=book)
398 return http.HttpResponseRedirect(book.get_absolute_url())
400 form = forms.BookForm(instance=book)
401 return direct_to_template(request, "catalogue/book_edit.html", extra_context={
409 def publish(request, slug):
410 book = get_object_or_404(Book, slug=slug)
412 ret = api_call(request.user, "books", {"book_xml": book.materialize()})
413 except BaseException, e:
414 return http.HttpResponse(e)
416 book.last_published = datetime.now()
418 return http.HttpResponseRedirect(book.get_absolute_url())