Fixes for inserting footnotes, references.
[redakcja.git] / src / cover / views.py
1 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 from hashlib import sha1
5 from os import makedirs
6 import os.path
7 import PIL.Image
8 from django.conf import settings
9 from django.contrib.auth.decorators import permission_required
10 from django.http import HttpResponse, HttpResponseRedirect, Http404
11 from django.shortcuts import get_object_or_404, render
12 from django.views.decorators.csrf import csrf_exempt
13 from django.views.decorators.http import require_POST
14 from lxml import etree
15 from librarian import RDFNS, DCNS
16 from librarian.cover import make_cover
17 from librarian.dcparser import BookInfo
18 from documents.helpers import active_tab
19 from documents.models import Book, Chunk
20 from cover.models import Image
21 from cover import forms
22 from cover.utils import get_import_data
23
24
25 PREVIEW_SIZE = (212, 300)
26
27
28 def preview(request, book, chunk=None, rev=None):
29     """Creates a cover image.
30
31     If chunk and rev number are given, use version from given revision.
32     If rev is not given, use publishable version.
33     """
34     try:
35         chunk = Chunk.get(book, chunk)
36     except Chunk.DoesNotExist:
37         raise Http404
38
39     if chunk.book.cover and rev is None and not request.GET.get('width') and not request.GET.get('height'):
40         return HttpResponseRedirect(chunk.book.cover.url)
41
42     if rev is not None:
43         try:
44             revision = chunk.at_revision(rev)
45         except Chunk.change_model.DoesNotExist:
46             raise Http404
47     else:
48         revision = chunk.publishable()
49         if revision is None:
50             revision = chunk.head
51     xml = revision.materialize().encode('utf-8')
52
53     try:
54         info = BookInfo.from_bytes(xml)
55     except Exception as e:
56         print(e)
57         return HttpResponseRedirect(os.path.join(settings.STATIC_URL, "img/sample_cover.png"))
58     width = request.GET.get('width')
59     width = int(width) if width else None
60     height=request.GET.get('height')
61     height = int(height) if height else None
62
63     if not (height or width):
64         width, height = PREVIEW_SIZE
65
66     cover_class = request.GET.get('cover_class', 'default')
67
68     cover = make_cover(info, cover_class=cover_class, width=width, height=height)
69     response = HttpResponse(content_type=cover.mime_type())
70     img = cover.final_image()
71     img.save(response, cover.format)
72
73     if 'download' in request.GET:
74         response['Content-Disposition'] = 'attachment; filename=%s.jpg' % chunk.book.slug
75
76     return response
77
78
79 @csrf_exempt
80 @require_POST
81 def preview_from_xml(request):
82     xml = request.POST['xml']
83     try:
84         info = BookInfo.from_bytes(xml.encode('utf-8'))
85     except Exception as e:
86         print(e)
87         return HttpResponse(os.path.join(settings.STATIC_URL, "img/sample_cover.png"))
88     coverid = sha1(etree.tostring(info.to_etree())).hexdigest()
89     cover = make_cover(info)
90
91     cover_dir = 'cover/preview'
92     try:
93         makedirs(os.path.join(settings.MEDIA_ROOT, cover_dir))
94     except OSError:
95         pass
96     fname = os.path.join(cover_dir, "%s.%s" % (coverid, cover.ext()))
97     img = cover.image().resize(PREVIEW_SIZE, PIL.Image.ANTIALIAS)
98     img.save(os.path.join(settings.MEDIA_ROOT, fname))
99     return HttpResponse(os.path.join(settings.MEDIA_URL, fname))
100
101
102 @active_tab('cover')
103 def image(request, pk):
104     img = get_object_or_404(Image, pk=pk)
105
106     if request.user.has_perm('cover.change_image'):
107         if request.method == "POST":
108             form = forms.ImageEditForm(request.POST, request.FILES, instance=img)
109             if form.is_valid():
110                 form.save()
111                 return HttpResponseRedirect(img.get_absolute_url())
112         else:
113             form = forms.ImageEditForm(instance=img)
114         editable = True
115     else:
116         form = forms.ReadonlyImageEditForm(instance=img)
117         editable = False
118
119     return render(request, "cover/image_detail.html", {
120         "object": Image.objects.get(id=img.id),
121         "form": form,
122         "editable": editable,
123     })
124
125
126 def image_file(request, pk):
127     img = get_object_or_404(Image, pk=pk)
128     return HttpResponseRedirect(img.file.url)
129
130
131 @active_tab('cover')
132 def image_list(request):
133     return render(request, "cover/image_list.html", {
134         'object_list': Image.objects.all().order_by('-id'),
135         'can_add': request.user.has_perm('cover.add_image'),
136     })
137
138
139 @permission_required('cover.add_image')
140 @active_tab('cover')
141 def add_image(request):
142     form = ff = None
143     if request.method == 'POST':
144         if request.POST.get('form_id') == 'import':
145             ff = forms.ImportForm(request.POST)
146             if ff.is_valid():
147                 form = forms.ImageAddForm(ff.cleaned_data)
148         else:
149             form = forms.ImageAddForm(request.POST, request.FILES)
150             if form.is_valid():
151                 obj = form.save()
152                 return HttpResponseRedirect(obj.get_absolute_url())
153     if form is None:
154         form = forms.ImageAddForm()
155     if ff is None:
156         ff = forms.ImportForm()
157     return render(request, 'cover/add_image.html', {
158             'form': form,
159             'ff': ff,
160         })
161
162 @permission_required('cover.add_image')
163 def quick_import(request, pk):
164     url = request.POST.get('url')
165     if url.startswith('%s://%s/' % (
166             request.scheme,
167             request.get_host())):
168         cover_id = url.rstrip('/').rsplit('/', 1)[-1]
169         cover = Image.objects.get(pk=cover_id)
170     else:
171         data = get_import_data(url)
172         same = Image.objects.filter(source_url=data['source_url'])
173         if not same.exists():
174             same = Image.objects.filter(download_url=data['download_url'])
175         if same.exists():
176             cover = same.first()
177         else:
178             form = forms.ImageAddForm(data)
179             if form.is_valid():
180                 cover = form.save()
181
182     # We have a cover. Now let's commit.
183     book = Book.objects.get(pk=pk)
184     chunk = book[0]
185     text = chunk.head.materialize()
186
187     root = etree.fromstring(text)
188     rdf = root.find('.//' + RDFNS('Description'))
189     for tag in 'url', 'attribution', 'source':
190         for elem in rdf.findall('.//' + DCNS('relation.coverImage.%s' % tag)):
191             rdf.remove(elem)
192     e = etree.Element(DCNS('relation.coverImage.url'))
193     e.text = request.build_absolute_uri(cover.use_file.url)
194     rdf.append(e)
195     e.tail = '\n    '
196     e = etree.Element(DCNS('relation.coverImage.attribution'))
197     e.text = ''
198     if cover.title:
199         e.text += cover.title + ', '
200     if cover.author:
201         e.text += cover.author + ', '
202     e.text += cover.license_name
203     e.tail = '\n    '
204     rdf.append(e)
205     e = etree.Element(DCNS('relation.coverImage.source'))
206     e.text = cover.get_full_url()
207     e.tail = '\n    '
208     rdf.append(e)
209
210     xml = etree.tostring(root, encoding='unicode')
211     chunk.commit(
212         xml,
213         author=request.user,
214         comment='Cover',
215         publishable=chunk.head.publishable,
216     )
217     return HttpResponseRedirect(book.get_absolute_url())
218