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")
37 def slug_filter(qs, value, filter_field, model, model_field='slug', unset=''):
39 return qs.filter(**{filter_field: None})
43 obj = model._default_manager.get(**{model_field: value})
44 except model.DoesNotExist:
47 return qs.filter(**{filter_field: obj})
52 def document_list(request, filters=None):
53 chunks = Chunk.objects.order_by('book__title', 'book', 'number')
55 chunks = slug_filter(chunks, request.GET.get('user', None), 'user', User, 'username')
56 chunks = slug_filter(chunks, request.GET.get('stage', None), 'stage', Chunk.tag_model, 'slug')
58 chunks_list = helpers.ChunksList(chunks)
60 return direct_to_template(request, 'catalogue/document_list.html', extra_context={
62 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
63 key=lambda x: x[1]['time'], reverse=True),
64 'stages': Chunk.tag_model.objects.all(),
65 'users': User.objects.annotate(count=Count('chunk')).order_by('-count', 'last_name', 'first_name'),
69 @active_tab('unassigned')
71 def unassigned(request):
72 chunks_list = helpers.ChunksList(Chunk.objects.filter(
73 user=None).order_by('book__title', 'book__id', 'number'))
75 return direct_to_template(request, 'catalogue/document_list.html', extra_context={
77 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
78 key=lambda x: x[1]['time'], reverse=True),
83 def user(request, username=None):
85 if request.user.is_authenticated():
90 user = get_object_or_404(User, username=username)
92 chunks_list = helpers.ChunksList(Chunk.objects.filter(
93 user=user).order_by('book__title', 'book', 'number'))
95 return direct_to_template(request, 'catalogue/document_list.html', extra_context={
97 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
98 key=lambda x: x[1]['time'], reverse=True),
100 my = login_required(active_tab('my')(user))
105 return direct_to_template(request, 'catalogue/user_list.html', extra_context={
106 'users': User.objects.all().annotate(count=Count('chunk')).order_by(
107 '-count', 'last_name', 'first_name'),
112 def logout_then_redirect(request):
114 return http.HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
117 @active_tab('create')
118 def create_missing(request, slug=None):
121 slug = slug.replace(' ', '-')
123 if request.method == "POST":
124 form = forms.DocumentCreateForm(request.POST, request.FILES)
127 if request.user.is_authenticated():
128 creator = request.user
131 book = Book.create(creator=creator,
132 slug=form.cleaned_data['slug'],
133 title=form.cleaned_data['title'],
134 text=form.cleaned_data['text'],
137 return http.HttpResponseRedirect(reverse("wiki_editor", args=[book.slug]))
139 form = forms.DocumentCreateForm(initial={
141 "title": slug.replace('-', ' ').title(),
144 return direct_to_template(request, "catalogue/document_create_missing.html", extra_context={
150 @active_tab('upload')
152 if request.method == "POST":
153 form = forms.DocumentsUploadForm(request.POST, request.FILES)
157 if request.user.is_authenticated():
158 creator = request.user
162 zip = form.cleaned_data['zip']
167 existing = [book.slug for book in Book.objects.all()]
168 for filename in zip.namelist():
169 if filename[-1] == '/':
171 title = os.path.basename(filename)[:-4]
172 slug = slughifi(title)
173 if not (slug and filename.endswith('.xml')):
174 skipped_list.append(filename)
176 error_list.append((filename, slug, _('Slug already used for %s' % slugs[slug])))
177 elif slug in existing:
178 error_list.append((filename, slug, _('Slug already used in repository.')))
181 zip.read(filename).decode('utf-8') # test read
182 ok_list.append((filename, slug, title))
183 except UnicodeDecodeError:
184 error_list.append((filename, title, _('File should be UTF-8 encoded.')))
185 slugs[slug] = filename
188 for filename, slug, title in ok_list:
189 Book.create(creator=creator,
192 text=zip.read(filename).decode('utf-8'),
195 return direct_to_template(request, "catalogue/document_upload.html", extra_context={
198 "skipped_list": skipped_list,
199 "error_list": error_list,
202 form = forms.DocumentsUploadForm()
204 return direct_to_template(request, "catalogue/document_upload.html", extra_context={
210 def book_xml(request, slug):
211 xml = get_object_or_404(Book, slug=slug).materialize()
213 response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
214 response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
219 def book_txt(request, slug):
220 xml = get_object_or_404(Book, slug=slug).materialize()
223 librarian.text.transform(StringIO(xml), output)
224 text = output.getvalue()
225 response = http.HttpResponse(text, content_type='text/plain', mimetype='text/plain')
226 response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
231 def book_html(request, slug):
232 xml = get_object_or_404(Book, slug=slug).materialize()
235 librarian.html.transform(StringIO(xml), output, parse_dublincore=False,
237 html = output.getvalue()
238 response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
243 def revision(request, slug, chunk=None):
245 doc = Chunk.get(slug, chunk)
246 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
248 return http.HttpResponse(str(doc.revision()))
251 def book(request, slug):
252 book = get_object_or_404(Book, slug=slug)
254 # TODO: most of this should go somewhere else
256 # do we need some automation?
260 choose_master = False
262 length = book.chunk_set.count()
263 for i, chunk in enumerate(book):
269 graded = xml_tools.GradedText(chunk.materialize())
271 master = graded.master()
272 if first_master is None:
273 first_master = master
274 elif master != first_master:
275 chunk_dict['fix'].append('bad-master')
277 if i > 0 and not graded.has_trim_begin():
278 chunk_dict['fix'].append('trim-begin')
279 if i < length - 1 and not graded.has_trim_end():
280 chunk_dict['fix'].append('trim-end')
282 if chunk_dict['fix']:
283 chunk_dict['grade'] = 'wl-fix'
285 chunk_dict['grade'] = 'wl'
287 elif graded.is_broken_wl():
288 chunk_dict['grade'] = 'wl-broken'
289 elif graded.is_xml():
290 chunk_dict['grade'] = 'xml'
292 chunk_dict['grade'] = 'plain'
293 chunk_dict['fix'].append('wl')
296 if chunk_dict['fix']:
298 chunks.append(chunk_dict)
300 if first_master or not need_fixing:
301 choose_master = False
303 if request.method == "POST":
304 form = forms.ChooseMasterForm(request.POST)
305 if not choose_master or form.is_valid():
307 first_master = form.cleaned_data['master']
309 # do the actual fixing
314 text = c['chunk'].materialize()
316 if fix == 'bad-master':
317 text = xml_tools.change_master(text, first_master)
318 elif fix == 'trim-begin':
319 text = xml_tools.add_trim_begin(text)
320 elif fix == 'trim-end':
321 text = xml_tools.add_trim_end(text)
323 text = xml_tools.basic_structure(text, first_master)
324 author = request.user if request.user.is_authenticated() else None
325 description = "auto-fix: " + ", ".join(c['fix'])
326 c['chunk'].commit(text=text, author=author,
327 description=description)
329 return http.HttpResponseRedirect(book.get_absolute_url())
331 form = forms.ChooseMasterForm()
335 return direct_to_template(request, "catalogue/book_detail.html", extra_context={
338 "need_fixing": need_fixing,
339 "choose_master": choose_master,
340 "first_master": first_master,
345 def chunk_add(request, slug, chunk):
347 doc = Chunk.get(slug, chunk)
348 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
351 if request.method == "POST":
352 form = forms.ChunkAddForm(request.POST, instance=doc)
354 if request.user.is_authenticated():
355 creator = request.user
358 doc.split(creator=creator,
359 slug=form.cleaned_data['slug'],
360 comment=form.cleaned_data['comment'],
363 return http.HttpResponseRedirect(doc.book.get_absolute_url())
365 form = forms.ChunkAddForm(initial={
366 "slug": str(doc.number + 1),
367 "comment": "cz. %d" % (doc.number + 1, ),
370 return direct_to_template(request, "catalogue/chunk_add.html", extra_context={
376 def chunk_edit(request, slug, chunk):
378 doc = Chunk.get(slug, chunk)
379 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
381 if request.method == "POST":
382 form = forms.ChunkForm(request.POST, instance=doc)
385 return http.HttpResponseRedirect(doc.book.get_absolute_url())
387 form = forms.ChunkForm(instance=doc)
388 return direct_to_template(request, "catalogue/chunk_edit.html", extra_context={
394 def book_append(request, slug):
395 book = get_object_or_404(Book, slug=slug)
396 if request.method == "POST":
397 form = forms.BookAppendForm(request.POST)
399 append_to = form.cleaned_data['append_to']
400 append_to.append(book)
401 return http.HttpResponseRedirect(append_to.get_absolute_url())
403 form = forms.BookAppendForm()
404 return direct_to_template(request, "catalogue/book_append_to.html", extra_context={
410 def book_edit(request, slug):
411 book = get_object_or_404(Book, slug=slug)
412 if request.method == "POST":
413 form = forms.BookForm(request.POST, instance=book)
416 return http.HttpResponseRedirect(book.get_absolute_url())
418 form = forms.BookForm(instance=book)
419 return direct_to_template(request, "catalogue/book_edit.html", extra_context={
427 def publish(request, slug):
428 book = get_object_or_404(Book, slug=slug)
430 ret = api_call(request.user, "books", {"book_xml": book.materialize()})
431 except BaseException, e:
432 return http.HttpResponse(e)
434 book.last_published = datetime.now()
436 return http.HttpResponseRedirect(book.get_absolute_url())