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.
4 from hashlib import sha1
5 from os import makedirs
8 from django.conf import settings
9 from django.contrib.auth.decorators import permission_required
10 from django.http import HttpResponse, HttpResponseRedirect, Http404, JsonResponse
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
25 PREVIEW_SIZE = (212, 300)
28 def preview(request, book, chunk=None, rev=None):
29 """Creates a cover image.
31 If chunk and rev number are given, use version from given revision.
32 If rev is not given, use publishable version.
35 chunk = Chunk.get(book, chunk)
36 except Chunk.DoesNotExist:
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)
44 revision = chunk.at_revision(rev)
45 except Chunk.change_model.DoesNotExist:
48 revision = chunk.publishable()
51 xml = revision.materialize().encode('utf-8')
54 info = BookInfo.from_bytes(xml)
55 except Exception as 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
63 if not (height or width):
64 width, height = PREVIEW_SIZE
66 cover_class = request.GET.get('cover_class', 'default')
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)
73 if 'download' in request.GET:
74 response['Content-Disposition'] = 'attachment; filename=%s.jpg' % chunk.book.slug
81 def preview_from_xml(request):
82 xml = request.POST['xml']
84 info = BookInfo.from_bytes(xml.encode('utf-8'))
85 except Exception as 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)
91 cover_dir = 'cover/preview'
93 makedirs(os.path.join(settings.MEDIA_ROOT, cover_dir))
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))
103 def image(request, pk):
104 img = get_object_or_404(Image, pk=pk)
106 if not request.accepts('text/html') and request.accepts('application/json') or request.GET.get('format') == 'json':
107 return JsonResponse({
109 'author': img.author,
110 'license_name': img.license_name,
111 'license_url': img.license_url,
112 'source_url': img.source_url,
113 'attribution': img.attribution,
114 'cut_left': img.cut_left,
115 'cut_right': img.cut_right,
116 'cut_top': img.cut_top,
117 'cut_bottom': img.cut_bottom,
118 'file': img.file.url,
119 'use_file': img.use_file.url,
122 if request.user.has_perm('cover.change_image'):
123 if request.method == "POST":
124 form = forms.ImageEditForm(request.POST, request.FILES, instance=img)
127 return HttpResponseRedirect(img.get_absolute_url())
129 form = forms.ImageEditForm(instance=img)
132 form = forms.ReadonlyImageEditForm(instance=img)
135 return render(request, "cover/image_detail.html", {
136 "object": Image.objects.get(id=img.id),
138 "editable": editable,
142 def image_file(request, pk):
143 img = get_object_or_404(Image, pk=pk)
144 return HttpResponseRedirect(img.file.url)
148 def image_list(request):
149 return render(request, "cover/image_list.html", {
150 'object_list': Image.objects.all().order_by('-id'),
151 'can_add': request.user.has_perm('cover.add_image'),
155 @permission_required('cover.add_image')
157 def add_image(request):
159 if request.method == 'POST':
160 if request.POST.get('form_id') == 'import':
161 ff = forms.ImportForm(request.POST)
163 form = forms.ImageAddForm(ff.cleaned_data)
165 form = forms.ImageAddForm(request.POST, request.FILES)
168 return HttpResponseRedirect(obj.get_absolute_url())
170 form = forms.ImageAddForm()
172 ff = forms.ImportForm()
173 return render(request, 'cover/add_image.html', {
178 @permission_required('cover.add_image')
179 def quick_import(request, pk):
180 url = request.POST.get('url')
181 if url.startswith('%s://%s/' % (
183 request.get_host())):
184 cover_id = url.rstrip('/').rsplit('/', 1)[-1]
185 cover = Image.objects.get(pk=cover_id)
187 data = get_import_data(url)
188 same = Image.objects.filter(source_url=data['source_url'])
189 if not same.exists():
190 same = Image.objects.filter(download_url=data['download_url'])
194 form = forms.ImageAddForm(data)
198 # We have a cover. Now let's commit.
199 book = Book.objects.get(pk=pk)
201 text = chunk.head.materialize()
203 root = etree.fromstring(text)
204 rdf = root.find('.//' + RDFNS('Description'))
205 for tag in 'url', 'attribution', 'source':
206 for elem in rdf.findall('.//' + DCNS('relation.coverImage.%s' % tag)):
208 e = etree.Element(DCNS('relation.coverImage.url'))
209 e.text = request.build_absolute_uri(cover.use_file.url)
212 e = etree.Element(DCNS('relation.coverImage.attribution'))
215 e.text += cover.title + ', '
217 e.text += cover.author + ', '
218 e.text += cover.license_name
221 e = etree.Element(DCNS('relation.coverImage.source'))
222 e.text = cover.get_full_url()
226 xml = etree.tostring(root, encoding='unicode')
231 publishable=chunk.head.publishable,
233 return HttpResponseRedirect(book.get_absolute_url())