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 catalogue import forms
23 from catalogue import helpers
24 from catalogue.helpers import active_tab
25 from catalogue.models import Book, Chunk, BookPublishRecord, ChunkPublishRecord
26 from catalogue import xml_tools
29 # Quick hack around caching problems, TODO: use ETags
31 from django.views.decorators.cache import never_cache
33 logger = logging.getLogger("fnp.catalogue")
36 def slug_filter(qs, value, filter_field, model, model_field='slug', unset=''):
38 return qs.filter(**{filter_field: None})
42 obj = model._default_manager.get(**{model_field: value})
43 except model.DoesNotExist:
46 return qs.filter(**{filter_field: obj})
51 def document_list(request, filters=None):
52 chunks = Chunk.objects.order_by('book__title', 'book', 'number')
54 chunks = slug_filter(chunks, request.GET.get('user', None), 'user', User, 'username')
55 chunks = slug_filter(chunks, request.GET.get('stage', None), 'stage', Chunk.tag_model, 'slug')
57 chunks_list = helpers.ChunksList(chunks)
59 return direct_to_template(request, 'catalogue/document_list.html', extra_context={
61 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
62 key=lambda x: x[1]['time'], reverse=True),
63 'stages': Chunk.tag_model.objects.all(),
64 'users': User.objects.annotate(count=Count('chunk')).order_by('-count', 'last_name', 'first_name'),
69 def user(request, username=None):
71 if request.user.is_authenticated():
76 user = get_object_or_404(User, username=username)
78 chunks_list = helpers.ChunksList(Chunk.objects.filter(
79 user=user).order_by('book__title', 'book', 'number'))
81 return direct_to_template(request, 'catalogue/document_list.html', extra_context={
83 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
84 key=lambda x: x[1]['time'], reverse=True),
86 'stages': Chunk.tag_model.objects.all(),
88 my = login_required(active_tab('my')(user))
93 return direct_to_template(request, 'catalogue/user_list.html', extra_context={
94 'users': User.objects.all().annotate(count=Count('chunk')).order_by(
95 '-count', 'last_name', 'first_name'),
100 def logout_then_redirect(request):
102 return http.HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
105 @active_tab('create')
106 def create_missing(request, slug=None):
109 slug = slug.replace(' ', '-')
111 if request.method == "POST":
112 form = forms.DocumentCreateForm(request.POST, request.FILES)
115 if request.user.is_authenticated():
116 creator = request.user
119 book = Book.create(creator=creator,
120 slug=form.cleaned_data['slug'],
121 title=form.cleaned_data['title'],
122 text=form.cleaned_data['text'],
125 return http.HttpResponseRedirect(reverse("wiki_editor", args=[book.slug]))
127 form = forms.DocumentCreateForm(initial={
129 "title": slug.replace('-', ' ').title(),
132 return direct_to_template(request, "catalogue/document_create_missing.html", extra_context={
138 @active_tab('upload')
140 if request.method == "POST":
141 form = forms.DocumentsUploadForm(request.POST, request.FILES)
145 if request.user.is_authenticated():
146 creator = request.user
150 zip = form.cleaned_data['zip']
155 existing = [book.slug for book in Book.objects.all()]
156 for filename in zip.namelist():
157 if filename[-1] == '/':
159 title = os.path.basename(filename)[:-4]
160 slug = slughifi(title)
161 if not (slug and filename.endswith('.xml')):
162 skipped_list.append(filename)
164 error_list.append((filename, slug, _('Slug already used for %s' % slugs[slug])))
165 elif slug in existing:
166 error_list.append((filename, slug, _('Slug already used in repository.')))
169 zip.read(filename).decode('utf-8') # test read
170 ok_list.append((filename, slug, title))
171 except UnicodeDecodeError:
172 error_list.append((filename, title, _('File should be UTF-8 encoded.')))
173 slugs[slug] = filename
176 for filename, slug, title in ok_list:
177 Book.create(creator=creator,
180 text=zip.read(filename).decode('utf-8'),
183 return direct_to_template(request, "catalogue/document_upload.html", extra_context={
186 "skipped_list": skipped_list,
187 "error_list": error_list,
190 form = forms.DocumentsUploadForm()
192 return direct_to_template(request, "catalogue/document_upload.html", extra_context={
198 def book_xml(request, slug):
199 xml = get_object_or_404(Book, slug=slug).materialize()
201 response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
202 response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
207 def book_txt(request, slug):
208 xml = get_object_or_404(Book, slug=slug).materialize()
211 librarian.text.transform(StringIO(xml), output)
212 text = output.getvalue()
213 response = http.HttpResponse(text, content_type='text/plain', mimetype='text/plain')
214 response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
219 def book_html(request, slug):
220 xml = get_object_or_404(Book, slug=slug).materialize()
223 librarian.html.transform(StringIO(xml), output, parse_dublincore=False,
225 html = output.getvalue()
226 response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
231 def revision(request, slug, chunk=None):
233 doc = Chunk.get(slug, chunk)
234 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
236 return http.HttpResponse(str(doc.revision()))
239 def book(request, slug):
240 book = get_object_or_404(Book, slug=slug)
242 # TODO: most of this should go somewhere else
244 # do we need some automation?
248 choose_master = False
250 length = book.chunk_set.count()
251 for i, chunk in enumerate(book):
257 graded = xml_tools.GradedText(chunk.materialize())
259 master = graded.master()
260 if first_master is None:
261 first_master = master
262 elif master != first_master:
263 chunk_dict['fix'].append('bad-master')
265 if i > 0 and not graded.has_trim_begin():
266 chunk_dict['fix'].append('trim-begin')
267 if i < length - 1 and not graded.has_trim_end():
268 chunk_dict['fix'].append('trim-end')
270 if chunk_dict['fix']:
271 chunk_dict['grade'] = 'wl-fix'
273 chunk_dict['grade'] = 'wl'
275 elif graded.is_broken_wl():
276 chunk_dict['grade'] = 'wl-broken'
277 elif graded.is_xml():
278 chunk_dict['grade'] = 'xml'
280 chunk_dict['grade'] = 'plain'
281 chunk_dict['fix'].append('wl')
284 if chunk_dict['fix']:
286 chunks.append(chunk_dict)
288 if first_master or not need_fixing:
289 choose_master = False
291 if request.method == "POST":
292 form = forms.ChooseMasterForm(request.POST)
293 if not choose_master or form.is_valid():
295 first_master = form.cleaned_data['master']
297 # do the actual fixing
302 text = c['chunk'].materialize()
304 if fix == 'bad-master':
305 text = xml_tools.change_master(text, first_master)
306 elif fix == 'trim-begin':
307 text = xml_tools.add_trim_begin(text)
308 elif fix == 'trim-end':
309 text = xml_tools.add_trim_end(text)
311 text = xml_tools.basic_structure(text, first_master)
312 author = request.user if request.user.is_authenticated() else None
313 description = "auto-fix: " + ", ".join(c['fix'])
314 c['chunk'].commit(text=text, author=author,
315 description=description)
317 return http.HttpResponseRedirect(book.get_absolute_url())
319 form = forms.ChooseMasterForm()
323 return direct_to_template(request, "catalogue/book_detail.html", extra_context={
326 "need_fixing": need_fixing,
327 "choose_master": choose_master,
328 "first_master": first_master,
333 def chunk_add(request, slug, chunk):
335 doc = Chunk.get(slug, chunk)
336 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
339 if request.method == "POST":
340 form = forms.ChunkAddForm(request.POST, instance=doc)
342 if request.user.is_authenticated():
343 creator = request.user
346 doc.split(creator=creator,
347 slug=form.cleaned_data['slug'],
348 comment=form.cleaned_data['comment'],
351 return http.HttpResponseRedirect(doc.book.get_absolute_url())
353 form = forms.ChunkAddForm(initial={
354 "slug": str(doc.number + 1),
355 "comment": "cz. %d" % (doc.number + 1, ),
358 return direct_to_template(request, "catalogue/chunk_add.html", extra_context={
364 def chunk_edit(request, slug, chunk):
366 doc = Chunk.get(slug, chunk)
367 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
369 if request.method == "POST":
370 form = forms.ChunkForm(request.POST, instance=doc)
373 return http.HttpResponseRedirect(doc.book.get_absolute_url())
375 form = forms.ChunkForm(instance=doc)
376 return direct_to_template(request, "catalogue/chunk_edit.html", extra_context={
382 def book_append(request, slug):
383 book = get_object_or_404(Book, slug=slug)
384 if request.method == "POST":
385 form = forms.BookAppendForm(request.POST)
387 append_to = form.cleaned_data['append_to']
388 append_to.append(book)
389 return http.HttpResponseRedirect(append_to.get_absolute_url())
391 form = forms.BookAppendForm()
392 return direct_to_template(request, "catalogue/book_append_to.html", extra_context={
398 def book_edit(request, slug):
399 book = get_object_or_404(Book, slug=slug)
400 if request.method == "POST":
401 form = forms.BookForm(request.POST, instance=book)
404 return http.HttpResponseRedirect(book.get_absolute_url())
406 form = forms.BookForm(instance=book)
407 return direct_to_template(request, "catalogue/book_edit.html", extra_context={
415 def publish(request, slug):
416 book = get_object_or_404(Book, slug=slug)
418 book.publish(request.user)
419 except BaseException, e:
420 return http.HttpResponse(e)
422 return http.HttpResponseRedirect(book.get_absolute_url())