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 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")
38 def document_list(request):
39 return render(request, 'catalogue/document_list.html')
43 def user(request, username):
44 user = get_object_or_404(User, username=username)
45 return render(request, 'catalogue/user_page.html', {"viewed_user": user})
52 return render(request, 'catalogue/my_page.html', {
53 'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
54 key=lambda x: x[1]['time'], reverse=True),
60 return direct_to_template(request, 'catalogue/user_list.html', extra_context={
61 'users': User.objects.all().annotate(count=Count('chunk')).order_by(
62 '-count', 'last_name', 'first_name'),
66 @active_tab('activity')
67 def activity(request):
68 return render(request, 'catalogue/activity.html')
72 def logout_then_redirect(request):
74 return http.HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
78 def create_missing(request, slug=None):
81 slug = slug.replace(' ', '-')
83 if request.method == "POST":
84 form = forms.DocumentCreateForm(request.POST, request.FILES)
87 if request.user.is_authenticated():
88 creator = request.user
92 text=form.cleaned_data['text'],
94 slug=form.cleaned_data['slug'],
95 title=form.cleaned_data['title'],
98 return http.HttpResponseRedirect(reverse("wiki_editor", args=[book.slug]))
100 form = forms.DocumentCreateForm(initial={
102 "title": slug.replace('-', ' ').title(),
105 return direct_to_template(request, "catalogue/document_create_missing.html", extra_context={
111 @active_tab('upload')
113 if request.method == "POST":
114 form = forms.DocumentsUploadForm(request.POST, request.FILES)
118 if request.user.is_authenticated():
119 creator = request.user
123 zip = form.cleaned_data['zip']
128 existing = [book.slug for book in Book.objects.all()]
129 for filename in zip.namelist():
130 if filename[-1] == '/':
132 title = os.path.basename(filename)[:-4]
133 slug = slughifi(title)
134 if not (slug and filename.endswith('.xml')):
135 skipped_list.append(filename)
137 error_list.append((filename, slug, _('Slug already used for %s' % slugs[slug])))
138 elif slug in existing:
139 error_list.append((filename, slug, _('Slug already used in repository.')))
142 zip.read(filename).decode('utf-8') # test read
143 ok_list.append((filename, slug, title))
144 except UnicodeDecodeError:
145 error_list.append((filename, title, _('File should be UTF-8 encoded.')))
146 slugs[slug] = filename
149 for filename, slug, title in ok_list:
151 text=zip.read(filename).decode('utf-8'),
157 return direct_to_template(request, "catalogue/document_upload.html", extra_context={
160 "skipped_list": skipped_list,
161 "error_list": error_list,
164 form = forms.DocumentsUploadForm()
166 return direct_to_template(request, "catalogue/document_upload.html", extra_context={
172 def book_xml(request, slug):
173 xml = get_object_or_404(Book, slug=slug).materialize()
175 response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
176 response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
181 def book_txt(request, slug):
182 xml = get_object_or_404(Book, slug=slug).materialize()
185 librarian.text.transform(StringIO(xml), output)
186 text = output.getvalue()
187 response = http.HttpResponse(text, content_type='text/plain', mimetype='text/plain')
188 response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
193 def book_html(request, slug):
194 xml = get_object_or_404(Book, slug=slug).materialize()
197 librarian.html.transform(StringIO(xml), output, parse_dublincore=False,
199 html = output.getvalue()
200 response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
205 def revision(request, slug, chunk=None):
207 doc = Chunk.get(slug, chunk)
208 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
210 return http.HttpResponse(str(doc.revision()))
213 def book(request, slug):
214 book = get_object_or_404(Book, slug=slug)
216 # TODO: most of this should go somewhere else
218 # do we need some automation?
222 choose_master = False
224 length = book.chunk_set.count()
225 for i, chunk in enumerate(book):
231 graded = xml_tools.GradedText(chunk.materialize())
233 master = graded.master()
234 if first_master is None:
235 first_master = master
236 elif master != first_master:
237 chunk_dict['fix'].append('bad-master')
239 if i > 0 and not graded.has_trim_begin():
240 chunk_dict['fix'].append('trim-begin')
241 if i < length - 1 and not graded.has_trim_end():
242 chunk_dict['fix'].append('trim-end')
244 if chunk_dict['fix']:
245 chunk_dict['grade'] = 'wl-fix'
247 chunk_dict['grade'] = 'wl'
249 elif graded.is_broken_wl():
250 chunk_dict['grade'] = 'wl-broken'
251 elif graded.is_xml():
252 chunk_dict['grade'] = 'xml'
254 chunk_dict['grade'] = 'plain'
255 chunk_dict['fix'].append('wl')
258 if chunk_dict['fix']:
260 chunks.append(chunk_dict)
262 if first_master or not need_fixing:
263 choose_master = False
265 if request.method == "POST":
266 form = forms.ChooseMasterForm(request.POST)
267 if not choose_master or form.is_valid():
269 first_master = form.cleaned_data['master']
271 # do the actual fixing
276 text = c['chunk'].materialize()
278 if fix == 'bad-master':
279 text = xml_tools.change_master(text, first_master)
280 elif fix == 'trim-begin':
281 text = xml_tools.add_trim_begin(text)
282 elif fix == 'trim-end':
283 text = xml_tools.add_trim_end(text)
285 text = xml_tools.basic_structure(text, first_master)
286 author = request.user if request.user.is_authenticated() else None
287 description = "auto-fix: " + ", ".join(c['fix'])
288 c['chunk'].commit(text=text, author=author,
289 description=description)
291 return http.HttpResponseRedirect(book.get_absolute_url())
293 form = forms.ChooseMasterForm()
297 return direct_to_template(request, "catalogue/book_detail.html", extra_context={
300 "need_fixing": need_fixing,
301 "choose_master": choose_master,
302 "first_master": first_master,
307 def chunk_add(request, slug, chunk):
309 doc = Chunk.get(slug, chunk)
310 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
313 if request.method == "POST":
314 form = forms.ChunkAddForm(request.POST, instance=doc)
316 if request.user.is_authenticated():
317 creator = request.user
320 doc.split(creator=creator,
321 slug=form.cleaned_data['slug'],
322 title=form.cleaned_data['title'],
325 return http.HttpResponseRedirect(doc.book.get_absolute_url())
327 form = forms.ChunkAddForm(initial={
328 "slug": str(doc.number + 1),
329 "title": "cz. %d" % (doc.number + 1, ),
332 return direct_to_template(request, "catalogue/chunk_add.html", extra_context={
338 def chunk_edit(request, slug, chunk):
340 doc = Chunk.get(slug, chunk)
341 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
343 if request.method == "POST":
344 form = forms.ChunkForm(request.POST, instance=doc)
347 return http.HttpResponseRedirect(doc.book.get_absolute_url())
349 form = forms.ChunkForm(instance=doc)
350 return direct_to_template(request, "catalogue/chunk_edit.html", extra_context={
356 def book_append(request, slug):
357 book = get_object_or_404(Book, slug=slug)
358 if request.method == "POST":
359 form = forms.BookAppendForm(request.POST)
361 append_to = form.cleaned_data['append_to']
362 append_to.append(book)
363 return http.HttpResponseRedirect(append_to.get_absolute_url())
365 form = forms.BookAppendForm()
366 return direct_to_template(request, "catalogue/book_append_to.html", extra_context={
372 def book_edit(request, slug):
373 book = get_object_or_404(Book, slug=slug)
374 if request.method == "POST":
375 form = forms.BookForm(request.POST, instance=book)
378 return http.HttpResponseRedirect(book.get_absolute_url())
380 form = forms.BookForm(instance=book)
381 return direct_to_template(request, "catalogue/book_edit.html", extra_context={
389 def publish(request, slug):
390 book = get_object_or_404(Book, slug=slug)
392 book.publish(request.user)
393 except BaseException, e:
394 return http.HttpResponse(e)
396 return http.HttpResponseRedirect(book.get_absolute_url())