b6e4c400aa2b90a1f6d8abb95ae358c954c4a414
[redakcja.git] / apps / catalogue / views.py
1 from datetime import datetime
2 import logging
3 import os
4 from StringIO import StringIO
5 from urllib import unquote
6 from urlparse import urlsplit, urlunsplit
7
8 from django.contrib import auth
9 from django.contrib.auth.models import User
10 from django.contrib.auth.decorators import login_required, permission_required
11 from django.core.urlresolvers import reverse
12 from django.db.models import Count, Q
13 from django import http
14 from django.http import Http404
15 from django.shortcuts import get_object_or_404, render
16 from django.utils.encoding import iri_to_uri
17 from django.utils.http import urlquote_plus
18 from django.utils.translation import ugettext_lazy as _
19 from django.views.decorators.http import require_POST
20 from django.views.generic.simple import direct_to_template
21
22 import librarian.html
23 import librarian.text
24
25 from apiclient import NotAuthorizedError
26 from catalogue import forms
27 from catalogue import helpers
28 from catalogue.helpers import active_tab
29 from catalogue.models import Book, Chunk, BookPublishRecord, ChunkPublishRecord
30 from catalogue.tasks import publishable_error
31 from catalogue import xml_tools
32
33 #
34 # Quick hack around caching problems, TODO: use ETags
35 #
36 from django.views.decorators.cache import never_cache
37
38 logger = logging.getLogger("fnp.catalogue")
39
40
41 @active_tab('all')
42 @never_cache
43 def document_list(request):
44     return render(request, 'catalogue/document_list.html')
45
46
47 @never_cache
48 def user(request, username):
49     user = get_object_or_404(User, username=username)
50     return render(request, 'catalogue/user_page.html', {"viewed_user": user})
51
52
53 @login_required
54 @active_tab('my')
55 @never_cache
56 def my(request):
57     return render(request, 'catalogue/my_page.html', {
58         'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
59                         key=lambda x: x[1]['time'], reverse=True),
60
61         "logout_to": '/',
62         })
63
64
65 @active_tab('users')
66 def users(request):
67     return direct_to_template(request, 'catalogue/user_list.html', extra_context={
68         'users': User.objects.all().annotate(count=Count('chunk')).order_by(
69             '-count', 'last_name', 'first_name'),
70     })
71
72
73 @active_tab('activity')
74 def activity(request):
75     return render(request, 'catalogue/activity.html')
76
77
78 @never_cache
79 def logout_then_redirect(request):
80     auth.logout(request)
81     return http.HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
82
83
84 @permission_required('catalogue.add_book')
85 @active_tab('create')
86 def create_missing(request, slug=None):
87     if slug is None:
88         slug = ''
89     slug = slug.replace(' ', '-')
90
91     if request.method == "POST":
92         form = forms.DocumentCreateForm(request.POST, request.FILES)
93         if form.is_valid():
94             
95             if request.user.is_authenticated():
96                 creator = request.user
97             else:
98                 creator = None
99             book = Book.create(
100                 text=form.cleaned_data['text'],
101                 creator=creator,
102                 slug=form.cleaned_data['slug'],
103                 title=form.cleaned_data['title'],
104             )
105
106             return http.HttpResponseRedirect(reverse("wiki_editor", args=[book.slug]))
107     else:
108         form = forms.DocumentCreateForm(initial={
109                 "slug": slug,
110                 "title": slug.replace('-', ' ').title(),
111         })
112
113     return direct_to_template(request, "catalogue/document_create_missing.html", extra_context={
114         "slug": slug,
115         "form": form,
116
117         "logout_to": '/',
118     })
119
120
121 @permission_required('catalogue.add_book')
122 @active_tab('upload')
123 def upload(request):
124     if request.method == "POST":
125         form = forms.DocumentsUploadForm(request.POST, request.FILES)
126         if form.is_valid():
127             import slughifi
128
129             if request.user.is_authenticated():
130                 creator = request.user
131             else:
132                 creator = None
133
134             zip = form.cleaned_data['zip']
135             skipped_list = []
136             ok_list = []
137             error_list = []
138             slugs = {}
139             existing = [book.slug for book in Book.objects.all()]
140             for filename in zip.namelist():
141                 if filename[-1] == '/':
142                     continue
143                 title = os.path.basename(filename)[:-4]
144                 slug = slughifi(title)
145                 if not (slug and filename.endswith('.xml')):
146                     skipped_list.append(filename)
147                 elif slug in slugs:
148                     error_list.append((filename, slug, _('Slug already used for %s' % slugs[slug])))
149                 elif slug in existing:
150                     error_list.append((filename, slug, _('Slug already used in repository.')))
151                 else:
152                     try:
153                         zip.read(filename).decode('utf-8') # test read
154                         ok_list.append((filename, slug, title))
155                     except UnicodeDecodeError:
156                         error_list.append((filename, title, _('File should be UTF-8 encoded.')))
157                     slugs[slug] = filename
158
159             if not error_list:
160                 for filename, slug, title in ok_list:
161                     book = Book.create(
162                         text=zip.read(filename).decode('utf-8'),
163                         creator=creator,
164                         slug=slug,
165                         title=title,
166                     )
167
168             return direct_to_template(request, "catalogue/document_upload.html", extra_context={
169                 "form": form,
170                 "ok_list": ok_list,
171                 "skipped_list": skipped_list,
172                 "error_list": error_list,
173
174                 "logout_to": '/',
175             })
176     else:
177         form = forms.DocumentsUploadForm()
178
179     return direct_to_template(request, "catalogue/document_upload.html", extra_context={
180         "form": form,
181
182         "logout_to": '/',
183     })
184
185
186 @never_cache
187 def book_xml(request, slug):
188     xml = get_object_or_404(Book, slug=slug).materialize()
189
190     response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
191     response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
192     return response
193
194
195 @never_cache
196 def book_txt(request, slug):
197     xml = get_object_or_404(Book, slug=slug).materialize()
198     output = StringIO()
199     # errors?
200     librarian.text.transform(StringIO(xml), output)
201     text = output.getvalue()
202     response = http.HttpResponse(text, content_type='text/plain', mimetype='text/plain')
203     response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
204     return response
205
206
207 @never_cache
208 def book_html(request, slug):
209     xml = get_object_or_404(Book, slug=slug).materialize()
210     output = StringIO()
211     # errors?
212     librarian.html.transform(StringIO(xml), output, parse_dublincore=False,
213                              flags=['full-page'])
214     html = output.getvalue()
215     response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
216     return response
217
218
219 @never_cache
220 def revision(request, slug, chunk=None):
221     try:
222         doc = Chunk.get(slug, chunk)
223     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
224         raise Http404
225     return http.HttpResponse(str(doc.revision()))
226
227
228 def book(request, slug):
229     book = get_object_or_404(Book, slug=slug)
230
231     if request.user.has_perm('catalogue.change_book'):
232         if request.method == "POST":
233             form = forms.BookForm(request.POST, instance=book)
234             if form.is_valid():
235                 form.save()
236                 return http.HttpResponseRedirect(book.get_absolute_url())
237         else:
238             form = forms.BookForm(instance=book)
239             editable = True
240     else:
241         form = forms.ReadonlyBookForm(instance=book)
242         editable = False
243
244     task = publishable_error.delay(book)
245     publish_error = t.wait()
246     publishable = publish_error is None
247
248     try:
249         book.assert_publishable()
250     except AssertionError, e:
251         publishable = False
252         publishable_error = e
253     else:
254         publishable = True
255         publishable_error = None
256
257     return direct_to_template(request, "catalogue/book_detail.html", extra_context={
258         "book": book,
259         "publishable": publishable,
260         "publishable_error": publish_error,
261         "form": form,
262         "editable": editable,
263     })
264
265
266 @permission_required('catalogue.add_chunk')
267 def chunk_add(request, slug, chunk):
268     try:
269         doc = Chunk.get(slug, chunk)
270     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
271         raise Http404
272
273     if request.method == "POST":
274         form = forms.ChunkAddForm(request.POST, instance=doc)
275         if form.is_valid():
276             if request.user.is_authenticated():
277                 creator = request.user
278             else:
279                 creator = None
280             doc.split(creator=creator,
281                 slug=form.cleaned_data['slug'],
282                 title=form.cleaned_data['title'],
283             )
284
285             return http.HttpResponseRedirect(doc.book.get_absolute_url())
286     else:
287         form = forms.ChunkAddForm(initial={
288                 "slug": str(doc.number + 1),
289                 "title": "cz. %d" % (doc.number + 1, ),
290         })
291
292     return direct_to_template(request, "catalogue/chunk_add.html", extra_context={
293         "chunk": doc,
294         "form": form,
295     })
296
297
298 def chunk_edit(request, slug, chunk):
299     try:
300         doc = Chunk.get(slug, chunk)
301     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
302         raise Http404
303     if request.method == "POST":
304         form = forms.ChunkForm(request.POST, instance=doc)
305         if form.is_valid():
306             form.save()
307             go_next = request.GET.get('next', None)
308             if go_next:
309                 go_next = urlquote_plus(unquote(iri_to_uri(go_next)), safe='/?=&')
310             else:
311                 go_next = doc.book.get_absolute_url()
312             return http.HttpResponseRedirect(go_next)
313     else:
314         form = forms.ChunkForm(instance=doc)
315
316     parts = urlsplit(request.META['HTTP_REFERER'])
317     parts = ['', ''] + list(parts[2:])
318     go_next = urlquote_plus(urlunsplit(parts))
319
320     return direct_to_template(request, "catalogue/chunk_edit.html", extra_context={
321         "chunk": doc,
322         "form": form,
323         "go_next": go_next,
324     })
325
326
327 @permission_required('catalogue.change_book')
328 def book_append(request, slug):
329     book = get_object_or_404(Book, slug=slug)
330     if request.method == "POST":
331         form = forms.BookAppendForm(book, request.POST)
332         if form.is_valid():
333             append_to = form.cleaned_data['append_to']
334             append_to.append(book)
335             return http.HttpResponseRedirect(append_to.get_absolute_url())
336     else:
337         form = forms.BookAppendForm(book)
338     return direct_to_template(request, "catalogue/book_append_to.html", extra_context={
339         "book": book,
340         "form": form,
341
342         "logout_to": '/',
343     })
344
345
346 @require_POST
347 @login_required
348 def publish(request, slug):
349     book = get_object_or_404(Book, slug=slug)
350     try:
351         book.publish(request.user)
352     except NotAuthorizedError:
353         return http.HttpResponseRedirect(reverse('apiclient_oauth'))
354     except BaseException, e:
355         return http.HttpResponse(e)
356     else:
357         return http.HttpResponseRedirect(book.get_absolute_url())