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
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 = (216, 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.
34 chunk = Chunk.get(book, chunk)
37 revision = chunk.at_revision(rev)
38 except Chunk.change_model.DoesNotExist:
41 revision = chunk.publishable()
44 xml = revision.materialize().encode('utf-8')
47 info = BookInfo.from_bytes(xml)
48 except Exception as e:
50 return HttpResponseRedirect(os.path.join(settings.STATIC_URL, "img/sample_cover.png"))
51 width = request.GET.get('width')
52 width = int(width) if width else None
53 height=request.GET.get('height')
54 height = int(height) if height else None
56 if not (height or width):
57 width, height = PREVIEW_SIZE
59 cover_class = request.GET.get('cover_class', 'default')
61 cover = make_cover(info, cover_class=cover_class, width=width, height=height)
62 response = HttpResponse(content_type=cover.mime_type())
63 img = cover.final_image()
64 img.save(response, cover.format)
66 if 'download' in request.GET:
67 response['Content-Disposition'] = 'attachment; filename=%s.jpg' % chunk.book.slug
74 def preview_from_xml(request):
75 xml = request.POST['xml']
77 info = BookInfo.from_bytes(xml.encode('utf-8'))
78 except Exception as e:
80 return HttpResponse(os.path.join(settings.STATIC_URL, "img/sample_cover.png"))
81 coverid = sha1(etree.tostring(info.to_etree())).hexdigest()
82 cover = make_cover(info)
84 cover_dir = 'cover/preview'
86 makedirs(os.path.join(settings.MEDIA_ROOT, cover_dir))
89 fname = os.path.join(cover_dir, "%s.%s" % (coverid, cover.ext()))
90 img = cover.image().resize(PREVIEW_SIZE, PIL.Image.ANTIALIAS)
91 img.save(os.path.join(settings.MEDIA_ROOT, fname))
92 return HttpResponse(os.path.join(settings.MEDIA_URL, fname))
96 def image(request, pk):
97 img = get_object_or_404(Image, pk=pk)
99 if request.user.has_perm('cover.change_image'):
100 if request.method == "POST":
101 form = forms.ImageEditForm(request.POST, request.FILES, instance=img)
104 return HttpResponseRedirect(img.get_absolute_url())
106 form = forms.ImageEditForm(instance=img)
109 form = forms.ReadonlyImageEditForm(instance=img)
112 return render(request, "cover/image_detail.html", {
113 "object": Image.objects.get(id=img.id),
115 "editable": editable,
119 def image_file(request, pk):
120 img = get_object_or_404(Image, pk=pk)
121 return HttpResponseRedirect(img.file.url)
125 def image_list(request):
126 return render(request, "cover/image_list.html", {
127 'object_list': Image.objects.all().order_by('-id'),
128 'can_add': request.user.has_perm('cover.add_image'),
132 @permission_required('cover.add_image')
134 def add_image(request):
136 if request.method == 'POST':
137 if request.POST.get('form_id') == 'import':
138 ff = forms.ImportForm(request.POST)
140 form = forms.ImageAddForm(ff.cleaned_data)
142 form = forms.ImageAddForm(request.POST, request.FILES)
145 return HttpResponseRedirect(obj.get_absolute_url())
147 form = forms.ImageAddForm()
149 ff = forms.ImportForm()
150 return render(request, 'cover/add_image.html', {
155 @permission_required('cover.add_image')
156 def quick_import(request, pk):
157 url = request.POST.get('url')
158 if url.startswith('%s://%s/' % (
160 request.get_host())):
161 cover_id = url.rstrip('/').rsplit('/', 1)[-1]
162 cover = Image.objects.get(pk=cover_id)
164 data = get_import_data(url)
165 same = Image.objects.filter(source_url=data['source_url'])
166 if not same.exists():
167 same = Image.objects.filter(download_url=data['download_url'])
171 form = forms.ImageAddForm(data)
175 # We have a cover. Now let's commit.
176 book = Book.objects.get(pk=pk)
178 text = chunk.head.materialize()
180 root = etree.fromstring(text)
181 rdf = root.find('.//' + RDFNS('Description'))
182 for tag in 'url', 'attribution', 'source':
183 for elem in rdf.findall('.//' + DCNS('relation.coverImage.%s' % tag)):
185 e = etree.Element(DCNS('relation.coverImage.url'))
186 e.text = request.build_absolute_uri(cover.use_file.url)
189 e = etree.Element(DCNS('relation.coverImage.attribution'))
192 e.text += cover.title + ', '
194 e.text += cover.author + ', '
195 e.text += cover.license_name
198 e = etree.Element(DCNS('relation.coverImage.source'))
199 e.text = cover.get_full_url()
203 xml = etree.tostring(root, encoding='unicode')
208 publishable=chunk.head.publishable,
210 return HttpResponseRedirect(book.get_absolute_url())