Fix.
[redakcja.git] / src / isbn / views.py
1 from django.contrib.auth.decorators import permission_required
2 from django.shortcuts import render, get_object_or_404, redirect
3 from librarian import DCNS, RDFNS
4 from lxml import etree
5 from documents.models import Book
6 from .models import Isbn, IsbnPool
7
8
9 def isbn_list(request):
10     return render(request, 'isbn/list.html', {
11         'pools': IsbnPool.objects.all(),
12         'list': Isbn.objects.all(),
13     })
14
15
16 MIME = {
17     'html': 'text/html',
18     'pdf': 'application/pdf',
19     'txt': 'text/plain',
20     'epub': 'application/epub+zip',
21     'mobi': 'application/x-mobipocket-ebook',
22 }
23
24
25 @permission_required('isbn.add_isbn')
26 def generate(request, document_id):
27     document = get_object_or_404(Book, id=document_id)
28     book = document.catalogue_book
29     chunk = document[0]
30     head = chunk.head
31     orig_xml = head.materialize()
32     tree = etree.fromstring(orig_xml)
33     rdfdesc = tree.find('.//' + RDFNS('Description'))
34
35     for form, value in Isbn.formats_from_document(document):
36         if value: continue
37         isbn = Isbn.get_for_book(book, form)
38
39         etree.SubElement(rdfdesc, DCNS('relation.hasFormat'), id="mobi").text = f"https://wolnelektury.pl/media/book/{form}mobi/{book.slug}.{form}"
40         etree.SubElement(
41             rdfdesc, 'meta', refines=f'#{form}', id=f'{form}-id', property='dcterms:identifier'
42         ).text = 'ISBN-' + isbn.get_code(True)
43         etree.SubElement(rdfdesc, 'meta', refines=f'#{form}-id', property='identifier-type').text = 'ISBN'
44         etree.SubElement(rdfdesc, 'meta', refines=f'#{form}', property='dcterms:format').text = MIME[form]
45
46     xml = etree.tostring(tree, encoding='unicode')
47     chunk.commit(
48         text=xml,
49         author=request.user,
50         parent=head,
51         description='Auto ISBN',
52         publishable=head.publishable
53     )
54
55     return redirect(document.get_absolute_url())