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, Q
11 from django import http
12 from django.http import Http404
13 from django.shortcuts import get_object_or_404, render
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 NotAuthorizedError
23 from catalogue import forms
24 from catalogue import helpers
25 from catalogue.helpers import active_tab
26 from catalogue.models import Book, Chunk, BookPublishRecord, ChunkPublishRecord
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 return render(request, 'catalogue/document_list.html')
44 def user(request, username):
45 user = get_object_or_404(User, username=username)
46 return render(request, 'catalogue/user_page.html', {"viewed_user": user})
53 return render(request, 'catalogue/my_page.html', {
54 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
55 key=lambda x: x[1]['time'], reverse=True),
61 return direct_to_template(request, 'catalogue/user_list.html', extra_context={
62 'users': User.objects.all().annotate(count=Count('chunk')).order_by(
63 '-count', 'last_name', 'first_name'),
67 @active_tab('activity')
68 def activity(request):
69 return render(request, 'catalogue/activity.html')
73 def logout_then_redirect(request):
75 return http.HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
79 def create_missing(request, slug=None):
82 slug = slug.replace(' ', '-')
84 if request.method == "POST":
85 form = forms.DocumentCreateForm(request.POST, request.FILES)
88 if request.user.is_authenticated():
89 creator = request.user
93 text=form.cleaned_data['text'],
95 slug=form.cleaned_data['slug'],
96 title=form.cleaned_data['title'],
99 return http.HttpResponseRedirect(reverse("wiki_editor", args=[book.slug]))
101 form = forms.DocumentCreateForm(initial={
103 "title": slug.replace('-', ' ').title(),
106 return direct_to_template(request, "catalogue/document_create_missing.html", extra_context={
112 @active_tab('upload')
114 if request.method == "POST":
115 form = forms.DocumentsUploadForm(request.POST, request.FILES)
119 if request.user.is_authenticated():
120 creator = request.user
124 zip = form.cleaned_data['zip']
129 existing = [book.slug for book in Book.objects.all()]
130 for filename in zip.namelist():
131 if filename[-1] == '/':
133 title = os.path.basename(filename)[:-4]
134 slug = slughifi(title)
135 if not (slug and filename.endswith('.xml')):
136 skipped_list.append(filename)
138 error_list.append((filename, slug, _('Slug already used for %s' % slugs[slug])))
139 elif slug in existing:
140 error_list.append((filename, slug, _('Slug already used in repository.')))
143 zip.read(filename).decode('utf-8') # test read
144 ok_list.append((filename, slug, title))
145 except UnicodeDecodeError:
146 error_list.append((filename, title, _('File should be UTF-8 encoded.')))
147 slugs[slug] = filename
150 for filename, slug, title in ok_list:
152 text=zip.read(filename).decode('utf-8'),
158 return direct_to_template(request, "catalogue/document_upload.html", extra_context={
161 "skipped_list": skipped_list,
162 "error_list": error_list,
165 form = forms.DocumentsUploadForm()
167 return direct_to_template(request, "catalogue/document_upload.html", extra_context={
173 def book_xml(request, slug):
174 xml = get_object_or_404(Book, slug=slug).materialize()
176 response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
177 response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
182 def book_txt(request, slug):
183 xml = get_object_or_404(Book, slug=slug).materialize()
186 librarian.text.transform(StringIO(xml), output)
187 text = output.getvalue()
188 response = http.HttpResponse(text, content_type='text/plain', mimetype='text/plain')
189 response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
194 def book_html(request, slug):
195 xml = get_object_or_404(Book, slug=slug).materialize()
198 librarian.html.transform(StringIO(xml), output, parse_dublincore=False,
200 html = output.getvalue()
201 response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
206 def revision(request, slug, chunk=None):
208 doc = Chunk.get(slug, chunk)
209 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
211 return http.HttpResponse(str(doc.revision()))
214 def book(request, slug):
215 book = get_object_or_404(Book, slug=slug)
217 # TODO: most of this should go somewhere else
219 # do we need some automation?
223 choose_master = False
225 length = book.chunk_set.count()
226 for i, chunk in enumerate(book):
232 graded = xml_tools.GradedText(chunk.materialize())
234 master = graded.master()
235 if first_master is None:
236 first_master = master
237 elif master != first_master:
238 chunk_dict['fix'].append('bad-master')
240 if i > 0 and not graded.has_trim_begin():
241 chunk_dict['fix'].append('trim-begin')
242 if i < length - 1 and not graded.has_trim_end():
243 chunk_dict['fix'].append('trim-end')
245 if chunk_dict['fix']:
246 chunk_dict['grade'] = 'wl-fix'
248 chunk_dict['grade'] = 'wl'
250 elif graded.is_broken_wl():
251 chunk_dict['grade'] = 'wl-broken'
252 elif graded.is_xml():
253 chunk_dict['grade'] = 'xml'
255 chunk_dict['grade'] = 'plain'
256 chunk_dict['fix'].append('wl')
259 if chunk_dict['fix']:
261 chunks.append(chunk_dict)
263 if first_master or not need_fixing:
264 choose_master = False
266 if request.method == "POST":
267 form = forms.ChooseMasterForm(request.POST)
268 if not choose_master or form.is_valid():
270 first_master = form.cleaned_data['master']
272 # do the actual fixing
277 text = c['chunk'].materialize()
279 if fix == 'bad-master':
280 text = xml_tools.change_master(text, first_master)
281 elif fix == 'trim-begin':
282 text = xml_tools.add_trim_begin(text)
283 elif fix == 'trim-end':
284 text = xml_tools.add_trim_end(text)
286 text = xml_tools.basic_structure(text, first_master)
287 author = request.user if request.user.is_authenticated() else None
288 description = "auto-fix: " + ", ".join(c['fix'])
289 c['chunk'].commit(text=text, author=author,
290 description=description)
292 return http.HttpResponseRedirect(book.get_absolute_url())
294 form = forms.ChooseMasterForm()
299 book.assert_publishable()
300 except AssertionError, e:
302 publishable_error = e
305 publishable_error = None
307 return direct_to_template(request, "catalogue/book_detail.html", extra_context={
309 "publishable": publishable,
310 "publishable_error": publishable_error,
312 "need_fixing": need_fixing,
313 "choose_master": choose_master,
314 "first_master": first_master,
319 def chunk_add(request, slug, chunk):
321 doc = Chunk.get(slug, chunk)
322 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
325 if request.method == "POST":
326 form = forms.ChunkAddForm(request.POST, instance=doc)
328 if request.user.is_authenticated():
329 creator = request.user
332 doc.split(creator=creator,
333 slug=form.cleaned_data['slug'],
334 title=form.cleaned_data['title'],
337 return http.HttpResponseRedirect(doc.book.get_absolute_url())
339 form = forms.ChunkAddForm(initial={
340 "slug": str(doc.number + 1),
341 "title": "cz. %d" % (doc.number + 1, ),
344 return direct_to_template(request, "catalogue/chunk_add.html", extra_context={
350 def chunk_edit(request, slug, chunk):
352 doc = Chunk.get(slug, chunk)
353 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
355 if request.method == "POST":
356 form = forms.ChunkForm(request.POST, instance=doc)
359 return http.HttpResponseRedirect(doc.book.get_absolute_url())
361 form = forms.ChunkForm(instance=doc)
362 return direct_to_template(request, "catalogue/chunk_edit.html", extra_context={
368 def book_append(request, slug):
369 book = get_object_or_404(Book, slug=slug)
370 if request.method == "POST":
371 form = forms.BookAppendForm(request.POST)
373 append_to = form.cleaned_data['append_to']
374 append_to.append(book)
375 return http.HttpResponseRedirect(append_to.get_absolute_url())
377 form = forms.BookAppendForm()
378 return direct_to_template(request, "catalogue/book_append_to.html", extra_context={
384 def book_edit(request, slug):
385 book = get_object_or_404(Book, slug=slug)
386 if request.method == "POST":
387 form = forms.BookForm(request.POST, instance=book)
390 return http.HttpResponseRedirect(book.get_absolute_url())
392 form = forms.BookForm(instance=book)
393 return direct_to_template(request, "catalogue/book_edit.html", extra_context={
401 def publish(request, slug):
402 book = get_object_or_404(Book, slug=slug)
404 book.publish(request.user)
405 except NotAuthorizedError:
406 return http.HttpResponseRedirect(reverse('apiclient_oauth'))
407 except BaseException, e:
408 return http.HttpResponse(e)
410 return http.HttpResponseRedirect(book.get_absolute_url())