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 foreign_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})
49 def search_filter(qs, value, filter_field):
52 return qs.filter(**{"%s__icontains" % filter_field: value})
57 def document_list(request, filters=None):
58 chunks = Chunk.objects.order_by('book__title', 'book', 'number')
60 chunks = foreign_filter(chunks, request.GET.get('user', None), 'user', User, 'username')
61 chunks = foreign_filter(chunks, request.GET.get('stage', None), 'stage', Chunk.tag_model, 'slug')
62 chunks = search_filter(chunks, request.GET.get('title', None), 'book__title')
64 chunks_list = helpers.ChunksList(chunks)
66 users = User.objects.annotate(count=Count('chunk')).filter(count__gt=0).order_by('-count', 'last_name', 'first_name')
67 #users = User.objects.annotate(count=Count('chunk')).order_by('-count', 'last_name', 'first_name')
70 return direct_to_template(request, 'catalogue/document_list.html', extra_context={
72 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
73 key=lambda x: x[1]['time'], reverse=True),
74 'stages': Chunk.tag_model.objects.all(),
80 def user(request, username=None):
82 if request.user.is_authenticated():
87 user = get_object_or_404(User, username=username)
89 chunks_list = helpers.ChunksList(Chunk.objects.filter(
90 user=user).order_by('book__title', 'book', 'number'))
92 return direct_to_template(request, 'catalogue/document_list.html', extra_context={
94 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
95 key=lambda x: x[1]['time'], reverse=True),
97 'stages': Chunk.tag_model.objects.all(),
99 my = login_required(active_tab('my')(user))
104 return direct_to_template(request, 'catalogue/user_list.html', extra_context={
105 'users': User.objects.all().annotate(count=Count('chunk')).order_by(
106 '-count', 'last_name', 'first_name'),
111 def logout_then_redirect(request):
113 return http.HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
116 @active_tab('create')
117 def create_missing(request, slug=None):
120 slug = slug.replace(' ', '-')
122 if request.method == "POST":
123 form = forms.DocumentCreateForm(request.POST, request.FILES)
126 if request.user.is_authenticated():
127 creator = request.user
130 book = Book.create(creator=creator,
131 slug=form.cleaned_data['slug'],
132 title=form.cleaned_data['title'],
133 text=form.cleaned_data['text'],
136 return http.HttpResponseRedirect(reverse("wiki_editor", args=[book.slug]))
138 form = forms.DocumentCreateForm(initial={
140 "title": slug.replace('-', ' ').title(),
143 return direct_to_template(request, "catalogue/document_create_missing.html", extra_context={
149 @active_tab('upload')
151 if request.method == "POST":
152 form = forms.DocumentsUploadForm(request.POST, request.FILES)
156 if request.user.is_authenticated():
157 creator = request.user
161 zip = form.cleaned_data['zip']
166 existing = [book.slug for book in Book.objects.all()]
167 for filename in zip.namelist():
168 if filename[-1] == '/':
170 title = os.path.basename(filename)[:-4]
171 slug = slughifi(title)
172 if not (slug and filename.endswith('.xml')):
173 skipped_list.append(filename)
175 error_list.append((filename, slug, _('Slug already used for %s' % slugs[slug])))
176 elif slug in existing:
177 error_list.append((filename, slug, _('Slug already used in repository.')))
180 zip.read(filename).decode('utf-8') # test read
181 ok_list.append((filename, slug, title))
182 except UnicodeDecodeError:
183 error_list.append((filename, title, _('File should be UTF-8 encoded.')))
184 slugs[slug] = filename
187 for filename, slug, title in ok_list:
188 Book.create(creator=creator,
191 text=zip.read(filename).decode('utf-8'),
194 return direct_to_template(request, "catalogue/document_upload.html", extra_context={
197 "skipped_list": skipped_list,
198 "error_list": error_list,
201 form = forms.DocumentsUploadForm()
203 return direct_to_template(request, "catalogue/document_upload.html", extra_context={
209 def book_xml(request, slug):
210 xml = get_object_or_404(Book, slug=slug).materialize()
212 response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
213 response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
218 def book_txt(request, slug):
219 xml = get_object_or_404(Book, slug=slug).materialize()
222 librarian.text.transform(StringIO(xml), output)
223 text = output.getvalue()
224 response = http.HttpResponse(text, content_type='text/plain', mimetype='text/plain')
225 response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
230 def book_html(request, slug):
231 xml = get_object_or_404(Book, slug=slug).materialize()
234 librarian.html.transform(StringIO(xml), output, parse_dublincore=False,
236 html = output.getvalue()
237 response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
242 def revision(request, slug, chunk=None):
244 doc = Chunk.get(slug, chunk)
245 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
247 return http.HttpResponse(str(doc.revision()))
250 def book(request, slug):
251 book = get_object_or_404(Book, slug=slug)
253 # TODO: most of this should go somewhere else
255 # do we need some automation?
259 choose_master = False
261 length = book.chunk_set.count()
262 for i, chunk in enumerate(book):
268 graded = xml_tools.GradedText(chunk.materialize())
270 master = graded.master()
271 if first_master is None:
272 first_master = master
273 elif master != first_master:
274 chunk_dict['fix'].append('bad-master')
276 if i > 0 and not graded.has_trim_begin():
277 chunk_dict['fix'].append('trim-begin')
278 if i < length - 1 and not graded.has_trim_end():
279 chunk_dict['fix'].append('trim-end')
281 if chunk_dict['fix']:
282 chunk_dict['grade'] = 'wl-fix'
284 chunk_dict['grade'] = 'wl'
286 elif graded.is_broken_wl():
287 chunk_dict['grade'] = 'wl-broken'
288 elif graded.is_xml():
289 chunk_dict['grade'] = 'xml'
291 chunk_dict['grade'] = 'plain'
292 chunk_dict['fix'].append('wl')
295 if chunk_dict['fix']:
297 chunks.append(chunk_dict)
299 if first_master or not need_fixing:
300 choose_master = False
302 if request.method == "POST":
303 form = forms.ChooseMasterForm(request.POST)
304 if not choose_master or form.is_valid():
306 first_master = form.cleaned_data['master']
308 # do the actual fixing
313 text = c['chunk'].materialize()
315 if fix == 'bad-master':
316 text = xml_tools.change_master(text, first_master)
317 elif fix == 'trim-begin':
318 text = xml_tools.add_trim_begin(text)
319 elif fix == 'trim-end':
320 text = xml_tools.add_trim_end(text)
322 text = xml_tools.basic_structure(text, first_master)
323 author = request.user if request.user.is_authenticated() else None
324 description = "auto-fix: " + ", ".join(c['fix'])
325 c['chunk'].commit(text=text, author=author,
326 description=description)
328 return http.HttpResponseRedirect(book.get_absolute_url())
330 form = forms.ChooseMasterForm()
334 return direct_to_template(request, "catalogue/book_detail.html", extra_context={
337 "need_fixing": need_fixing,
338 "choose_master": choose_master,
339 "first_master": first_master,
344 def chunk_add(request, slug, chunk):
346 doc = Chunk.get(slug, chunk)
347 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
350 if request.method == "POST":
351 form = forms.ChunkAddForm(request.POST, instance=doc)
353 if request.user.is_authenticated():
354 creator = request.user
357 doc.split(creator=creator,
358 slug=form.cleaned_data['slug'],
359 comment=form.cleaned_data['comment'],
362 return http.HttpResponseRedirect(doc.book.get_absolute_url())
364 form = forms.ChunkAddForm(initial={
365 "slug": str(doc.number + 1),
366 "comment": "cz. %d" % (doc.number + 1, ),
369 return direct_to_template(request, "catalogue/chunk_add.html", extra_context={
375 def chunk_edit(request, slug, chunk):
377 doc = Chunk.get(slug, chunk)
378 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
380 if request.method == "POST":
381 form = forms.ChunkForm(request.POST, instance=doc)
384 return http.HttpResponseRedirect(doc.book.get_absolute_url())
386 form = forms.ChunkForm(instance=doc)
387 return direct_to_template(request, "catalogue/chunk_edit.html", extra_context={
393 def book_append(request, slug):
394 book = get_object_or_404(Book, slug=slug)
395 if request.method == "POST":
396 form = forms.BookAppendForm(request.POST)
398 append_to = form.cleaned_data['append_to']
399 append_to.append(book)
400 return http.HttpResponseRedirect(append_to.get_absolute_url())
402 form = forms.BookAppendForm()
403 return direct_to_template(request, "catalogue/book_append_to.html", extra_context={
409 def book_edit(request, slug):
410 book = get_object_or_404(Book, slug=slug)
411 if request.method == "POST":
412 form = forms.BookForm(request.POST, instance=book)
415 return http.HttpResponseRedirect(book.get_absolute_url())
417 form = forms.BookForm(instance=book)
418 return direct_to_template(request, "catalogue/book_edit.html", extra_context={
426 def publish(request, slug):
427 book = get_object_or_404(Book, slug=slug)
429 book.publish(request.user)
430 except BaseException, e:
431 return http.HttpResponse(e)
433 return http.HttpResponseRedirect(book.get_absolute_url())