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
91 book = Book.objects.create(
92 slug=form.cleaned_data['slug'],
93 title=form.cleaned_data['title'],
95 book.chunk_set.all().update(creator=creator)
96 book[0].commit(text=form.cleaned_data['text'], author=creator)
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:
150 Book.create(creator=creator,
153 text=zip.read(filename).decode('utf-8'),
156 return direct_to_template(request, "catalogue/document_upload.html", extra_context={
159 "skipped_list": skipped_list,
160 "error_list": error_list,
163 form = forms.DocumentsUploadForm()
165 return direct_to_template(request, "catalogue/document_upload.html", extra_context={
171 def book_xml(request, slug):
172 xml = get_object_or_404(Book, slug=slug).materialize()
174 response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
175 response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
180 def book_txt(request, slug):
181 xml = get_object_or_404(Book, slug=slug).materialize()
184 librarian.text.transform(StringIO(xml), output)
185 text = output.getvalue()
186 response = http.HttpResponse(text, content_type='text/plain', mimetype='text/plain')
187 response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
192 def book_html(request, slug):
193 xml = get_object_or_404(Book, slug=slug).materialize()
196 librarian.html.transform(StringIO(xml), output, parse_dublincore=False,
198 html = output.getvalue()
199 response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
204 def revision(request, slug, chunk=None):
206 doc = Chunk.get(slug, chunk)
207 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
209 return http.HttpResponse(str(doc.revision()))
212 def book(request, slug):
213 book = get_object_or_404(Book, slug=slug)
215 # TODO: most of this should go somewhere else
217 # do we need some automation?
221 choose_master = False
223 length = book.chunk_set.count()
224 for i, chunk in enumerate(book):
230 graded = xml_tools.GradedText(chunk.materialize())
232 master = graded.master()
233 if first_master is None:
234 first_master = master
235 elif master != first_master:
236 chunk_dict['fix'].append('bad-master')
238 if i > 0 and not graded.has_trim_begin():
239 chunk_dict['fix'].append('trim-begin')
240 if i < length - 1 and not graded.has_trim_end():
241 chunk_dict['fix'].append('trim-end')
243 if chunk_dict['fix']:
244 chunk_dict['grade'] = 'wl-fix'
246 chunk_dict['grade'] = 'wl'
248 elif graded.is_broken_wl():
249 chunk_dict['grade'] = 'wl-broken'
250 elif graded.is_xml():
251 chunk_dict['grade'] = 'xml'
253 chunk_dict['grade'] = 'plain'
254 chunk_dict['fix'].append('wl')
257 if chunk_dict['fix']:
259 chunks.append(chunk_dict)
261 if first_master or not need_fixing:
262 choose_master = False
264 if request.method == "POST":
265 form = forms.ChooseMasterForm(request.POST)
266 if not choose_master or form.is_valid():
268 first_master = form.cleaned_data['master']
270 # do the actual fixing
275 text = c['chunk'].materialize()
277 if fix == 'bad-master':
278 text = xml_tools.change_master(text, first_master)
279 elif fix == 'trim-begin':
280 text = xml_tools.add_trim_begin(text)
281 elif fix == 'trim-end':
282 text = xml_tools.add_trim_end(text)
284 text = xml_tools.basic_structure(text, first_master)
285 author = request.user if request.user.is_authenticated() else None
286 description = "auto-fix: " + ", ".join(c['fix'])
287 c['chunk'].commit(text=text, author=author,
288 description=description)
290 return http.HttpResponseRedirect(book.get_absolute_url())
292 form = forms.ChooseMasterForm()
296 return direct_to_template(request, "catalogue/book_detail.html", extra_context={
299 "need_fixing": need_fixing,
300 "choose_master": choose_master,
301 "first_master": first_master,
306 def chunk_add(request, slug, chunk):
308 doc = Chunk.get(slug, chunk)
309 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
312 if request.method == "POST":
313 form = forms.ChunkAddForm(request.POST, instance=doc)
315 if request.user.is_authenticated():
316 creator = request.user
319 doc.split(creator=creator,
320 slug=form.cleaned_data['slug'],
321 title=form.cleaned_data['title'],
324 return http.HttpResponseRedirect(doc.book.get_absolute_url())
326 form = forms.ChunkAddForm(initial={
327 "slug": str(doc.number + 1),
328 "title": "cz. %d" % (doc.number + 1, ),
331 return direct_to_template(request, "catalogue/chunk_add.html", extra_context={
337 def chunk_edit(request, slug, chunk):
339 doc = Chunk.get(slug, chunk)
340 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
342 if request.method == "POST":
343 form = forms.ChunkForm(request.POST, instance=doc)
346 return http.HttpResponseRedirect(doc.book.get_absolute_url())
348 form = forms.ChunkForm(instance=doc)
349 return direct_to_template(request, "catalogue/chunk_edit.html", extra_context={
355 def book_append(request, slug):
356 book = get_object_or_404(Book, slug=slug)
357 if request.method == "POST":
358 form = forms.BookAppendForm(request.POST)
360 append_to = form.cleaned_data['append_to']
361 append_to.append(book)
362 return http.HttpResponseRedirect(append_to.get_absolute_url())
364 form = forms.BookAppendForm()
365 return direct_to_template(request, "catalogue/book_append_to.html", extra_context={
371 def book_edit(request, slug):
372 book = get_object_or_404(Book, slug=slug)
373 if request.method == "POST":
374 form = forms.BookForm(request.POST, instance=book)
377 return http.HttpResponseRedirect(book.get_absolute_url())
379 form = forms.BookForm(instance=book)
380 return direct_to_template(request, "catalogue/book_edit.html", extra_context={
388 def publish(request, slug):
389 book = get_object_or_404(Book, slug=slug)
391 book.publish(request.user)
392 except BaseException, e:
393 return http.HttpResponse(e)
395 return http.HttpResponseRedirect(book.get_absolute_url())