import json
import os
+from urllib.parse import urljoin
import tempfile
import traceback
import zipfile
from datetime import datetime
+from django.apps import apps
from django.conf import settings
from django.db import models
from django.utils.timezone import now
from librarian.cover import make_cover
-from librarian.builders import EpubBuilder, MobiBuilder
from .publishers.legimi import Legimi
from .publishers.woblink import Woblink
os.unlink(f.name)
def build_for(self, book, z):
- wldoc2 = book.wldocument(librarian2=True)
- slug = wldoc2.meta.url.slug
+ Site = apps.get_model('sites', 'Site')
+ slug = book.dc_slug
for item in self.get_definition():
- wldoc = book.wldocument()
- wldoc2 = book.wldocument(librarian2=True)
- base_url = 'file://' + book.gallery_path() + '/'
-
ext = item['type']
if item['type'] == 'cover':
+ wldoc = book.wldocument()
kwargs = {}
if self.logo:
kwargs['cover_logo'] = self.logo.path
if k in item:
kwargs[k] = item[k]
cover = make_cover(wldoc.book_info, **kwargs)
- output = cover.output_file()
+ output = cover.output_file().get_bytes()
ext = cover.ext()
- elif item['type'] == 'pdf':
- cover_kwargs = {}
+ elif item['type'] in ('pdf', 'epub', 'mobi'):
+ options = {}
if 'cover_class' in item:
- cover_kwargs['cover_class'] = item['cover_class']
+ options['cover_class'] = item['cover_class']
if self.logo:
- cover_kwargs['cover_logo'] = self.logo.path
- cover = lambda *args, **kwargs: make_cover(*args, **kwargs, **cover_kwargs)
- output = wldoc.as_pdf(cover=cover, base_url=base_url)
-
- elif item['type'] == 'epub':
- cover_kwargs = {}
- if 'cover_class' in item:
- cover_kwargs['cover_class'] = item['cover_class']
- if self.logo:
- cover_kwargs['cover_logo'] = self.logo.path
- cover = lambda *args, **kwargs: make_cover(*args, **kwargs, **cover_kwargs)
-
- output = EpubBuilder(
- cover=cover,
- base_url=base_url,
- fundraising=item.get('fundraising', []),
- ).build(wldoc2)
-
- elif item['type'] == 'mobi':
- output = MobiBuilder(
- cover=cover,
- base_url=base_url,
- fundraising=item.get('fundraising', []),
- ).build(wldoc2)
+ logo_url = urljoin(
+ 'https://' + Site.objects.get_current().domain,
+ self.logo.url
+ )
+ options['cover_logo'] = logo_url
+ if 'fundraising' in item:
+ options['fundraising'] = item['fundraising']
+ output = remote_build(book, item['type'], options=options)
fname = f'{slug}/{slug}.'
if 'slug' in item:
fname += item['slug'] + '.'
fname += ext
-
- z.writestr(
- fname,
- output.get_bytes()
- )
+ z.writestr(fname, output)
class SiteBook(models.Model):
if wlbook.meta.audience in ('L', 'SP1', 'SP2', 'SP3', 'SP4'):
description += '<p><em>{}</em> to lektura szkolna.'.format(wlbook.meta.title)
- if wlbook.tree.find('//pe') is not None:
+ if wlbook.tree.find('.//pe') is not None:
description += '<br>Ebook <em>{title}</em> zawiera przypisy opracowane specjalnie dla uczennic i uczniów {school}.'.format(
title=wlbook.meta.title,
school='szkoły podstawowej' if wlbook.meta.audience.startswith('SP') else 'liceum i technikum'
from django.utils.html import escape
from django.utils.safestring import mark_safe
from librarian.functions import lang_code_3to2
-from librarian.builders import EpubBuilder, MobiBuilder
-from librarian.covers.marquise import MarquiseCover, LabelMarquiseCover
+from librarian.covers.marquise import LabelMarquiseCover
from lxml import html
from catalogue.models import Audience, Thema
+from documents.remote_build import remote_build
from .base import BasePublisher
cover = LabelMarquiseCover(meta, width=1200).output_file()
texts = site.get_texts()
- epub_file = EpubBuilder(
- cover=MarquiseCover,
- fundraising=texts,
- base_url='file://' + book.gallery_path() + '/'
- ).build(wlbook).get_file()
- mobi_file = MobiBuilder(
- cover=MarquiseCover,
- fundraising=texts,
- base_url='file://' + book.gallery_path() + '/'
- ).build(wlbook).get_file()
+ epub_file = remote_build(book, 'epub', options={
+ 'fundraising': texts,
+ })
+ mobi_file = remote_build(book, 'mobi', options={
+ 'fundraising': texts,
+ })
book_data = {
"Title": meta.title,
from librarian.builders.html import SnippetHtmlBuilder
from librarian.functions import lang_code_3to2
from catalogue.models import Audience, Author, Thema
+from documents.remote_build import remote_build
from .. import models
from .base import BasePublisher
from .woblink_constants import WOBLINK_CATEGORIES
texts = site.get_texts()
epub_id, epub_demo = self.send_epub(
- woblink_id, wldoc, book.gallery_path(),
+ woblink_id, book,
fundraising=texts
)
mobi_id, mobi_demo = self.send_mobi(
- woblink_id, wldoc, book.gallery_path(),
+ woblink_id, book,
fundraising=texts
)
self.edit_step4(
return file_id
- def send_epub(self, woblink_id, doc, gallery_path, fundraising=None):
- from librarian.builders import EpubBuilder
- content = EpubBuilder(
- base_url='file://' + gallery_path + '/',
- fundraising=fundraising or [],
- ).build(doc).get_file()
+ def send_epub(self, woblink_id, book, fundraising=None):
+ content = remote_build(book, 'epub', options={
+ "fundraising": fundraising or [],
+ })
file_id = self.upload_file(
woblink_id,
- doc.meta.url.slug + '.epub',
+ book.dc_slug + '.epub',
content,
'Epub',
'application/epub+zip'
demo_id = self.generate_demo(woblink_id, 'epub')
return file_id, demo_id
- def send_mobi(self, woblink_id, doc, gallery_path, fundraising=None):
- from librarian.builders import MobiBuilder
- content = MobiBuilder(
- base_url='file://' + gallery_path + '/',
- fundraising=fundraising or [],
- ).build(doc).get_file()
+ def send_mobi(self, woblink_id, book, fundraising=None):
+ content = remote_build(book, 'mobi', options={
+ "fundraising": fundraising or [],
+ })
file_id = self.upload_file(
woblink_id,
- doc.meta.url.slug + '.mobi',
+ book.dc_slug + '.mobi',
content,
'Mobi',
'application/x-mobipocket-ebook'
self.publishable = publishable
def by_slug(self, slug):
- print(slug)
return BytesIO(Book.objects.get(dc_slug=slug
).materialize(publishable=self.publishable
).encode('utf-8'))
self.public = False
self.save()
post_publish.send(sender=br)
-
- def latex_dir(self):
- doc = self.wldocument()
- return doc.latex_dir(cover=True, ilustr_path=self.gallery_path())
# This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
+from urllib.parse import urljoin
+from django.apps import apps
from django.db import models
from django.utils.translation import gettext_lazy as _
def __str__(self):
return self.name
+
+ def logo_for_cover(self):
+ Site = apps.get_model('sites', 'Site')
+ domain = Site.objects.get_current().domain
+ logo = self.logo_mono or self.logo
+ if logo:
+ url = logo.url
+ return urljoin(
+ 'https://' + domain,
+ url
+ )
--- /dev/null
+# This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
+# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
+#
+import json
+import requests
+from django.conf import settings
+from documents.models import Book
+
+
+def gather_files(book, publishable=True):
+ files = []
+ todo = [book]
+ while todo:
+ b = todo.pop()
+ xml = book.materialize(publishable=publishable)
+ files.append((
+ 'doc' if b == book else 'part',
+ (b.dc_slug + '.xml', xml, 'application/xml')
+ ))
+ for part in b.wldocument(publishable=publishable).book_info.parts:
+ todo.push(Book.objects.get(dc_slug=part.slug))
+ return files
+
+
+def remote_build(book, fmt, publishable=True, options=None, content=None):
+ if not settings.REMOTE_BUILD_URL or not settings.REMOTE_BUILD_TOKEN:
+ raise RuntimeError('Remote build not configured')
+
+ if book is None:
+ assert content
+ files = [('doc', ('doc.xml', content, 'application/xml'))]
+ else:
+ files = gather_files(book, publishable=publishable)
+
+ if options:
+ options = json.dumps(options)
+ response = requests.post(
+ settings.REMOTE_BUILD_URL + '/build/pdf',
+ headers={'Authorization': 'Bearer ' + settings.REMOTE_BUILD_TOKEN},
+ files=files,
+ data={'options': options}
+ )
+ if response.status_code != 200:
+ try:
+ error = response.json()
+ except ValueError:
+ error = {'error': response.text}
+ message = '%d: %s' % (response.status_code, error.get('error'))
+ if error.get('log'):
+ message += '\n' + error['log']
+ raise RuntimeError(message)
+ return response.content
<a href="{% url 'documents_book_txt' book.slug %}" rel="nofollow">{% trans "TXT version" %}</a><br/>
<a href="{% url 'documents_book_pdf' book.slug %}" rel="nofollow">{% trans "PDF version" %}</a><br/>
<a href="{% url 'documents_book_pdf_mobile' book.slug %}" rel="nofollow">{% trans "PDF version for mobiles" %}</a><br/>
- <a href="{% url 'documents_book_epub' book.slug %}" rel="nofollow">{% trans "EPUB version" %}</a>
- <a href="{% url 'documents_book_epubcheck' book.slug %}" rel="nofollow">sprawdź</a><br/>
+ <a href="{% url 'documents_book_epub' book.slug %}" rel="nofollow">{% trans "EPUB version" %}</a><br/>
<a href="{% url 'documents_book_mobi' book.slug %}" rel="nofollow">{% trans "MOBI version" %}</a><br/>
</p>
path('book/<slug:slug>/txt', views.book_txt, name="documents_book_txt"),
path('book/<slug:slug>/html', views.book_html, name="documents_book_html"),
path('book/<slug:slug>/epub', views.book_epub, name="documents_book_epub"),
- path('book/<slug:slug>/epubcheck', views.book_epubcheck, name="documents_book_epubcheck"),
path('book/<slug:slug>/mobi', views.book_mobi, name="documents_book_mobi"),
path('book/<slug:slug>/pdf', views.book_pdf, name="documents_book_pdf"),
path('book/<slug:slug>/pdf-mobile', views.book_pdf, kwargs={'mobile': True}, name="documents_book_pdf_mobile"),
from .helpers import active_tab
from .models import (Book, Chunk, Image, BookPublishRecord,
ChunkPublishRecord, ImagePublishRecord, Project)
+from .remote_build import remote_build
import catalogue.models
from fileupload.views import UploadView
html = doc.as_html(
gallery_url='%stmp/html/' % settings.MEDIA_URL,
gallery_path='%s/tmp/html/' % settings.MEDIA_ROOT,
- base_url=request.build_absolute_uri(book.gallery_url()),
- options={'gallery': "'%s'" % book.gallery_url()})
+ )
html = html.get_bytes().decode('utf-8') if html is not None else ''
# response = http.HttpResponse(html, content_type='text/html')
if not book.accessible(request):
return HttpResponseForbidden("Not authorized.")
- # TODO: move to celery
- doc = book.wldocument()
- # TODO: error handling
- customizations = ['26pt', 'nothemes', 'nomargins', 'notoc'] if mobile else None
- pdf_file = doc.as_pdf(cover=True, base_url=request.build_absolute_uri(book.gallery_url()), customizations=customizations)
- from .ebook_utils import serve_file
- return serve_file(pdf_file.get_filename(),
- book.slug + '.pdf', 'application/pdf')
+ customizations = ['notoc']
+ if mobile:
+ customizations += ['26pt', 'nothemes', 'nomargins']
+ options = {
+ 'customizations': customizations
+ }
+ if book.project is not None and (logo := book.project.logo_for_cover()):
+ options['cover_logo'] = logo
+ try:
+ content = remote_build(book, 'pdf', options=options)
+ except RuntimeError as e:
+ return HttpResponse(str(e))
+
+ response = HttpResponse(content_type='application/pdf')
+ response['Content-Disposition'] = f'attachment; filename={book.dc_slug}.pdf'
+ response.write(content)
+ return response
+
@login_required
book = get_object_or_404(Book, slug=slug)
if not book.accessible(request):
return HttpResponseForbidden("Not authorized.")
+ options = {
+ #'debug': True
+ }
+ if book.project is not None and (logo := book.project.logo_for_cover()):
+ options['cover_logo'] = logo
+ try:
+ content = remote_build(book, 'epub', options=options)
+ except RuntimeError as e:
+ return HttpResponse(str(e))
- # TODO: move to celery
- doc = book.wldocument(librarian2=True)
- # TODO: error handling
-
- from librarian.builders import EpubBuilder
- epub = EpubBuilder(
- base_url='file://' + book.gallery_path() + '/',
- debug=True
- ).build(doc).get_bytes()
response = HttpResponse(content_type='application/epub+zip')
response['Content-Disposition'] = 'attachment; filename=%s' % book.slug + '.epub'
- response.write(epub)
+ response.write(content)
return response
-@login_required
-@never_cache
-def book_epubcheck(request, slug):
- book = get_object_or_404(Book, slug=slug)
- if not book.accessible(request):
- return HttpResponseForbidden("Not authorized.")
-
- # TODO: move to celery
- doc = book.wldocument(librarian2=True)
- # TODO: error handling
-
- from librarian.builders import EpubBuilder
- epub = EpubBuilder(
- base_url='file://' + book.gallery_path() + '/',
- debug=True
- ).build(doc)
- fname = epub.get_filename()
-
- messages = epubcheck.epubcheck(fname)
- for message in messages:
- for location in message.get('locations', []):
- if 'wl_chunk' in location:
- location['wl_chunk'] = book[location['wl_chunk']]
- return render(request, 'documents/book_epubcheck.html', {
- 'messages': messages,
- 'book': book,
- })
-
-
@login_required
@never_cache
def book_mobi(request, slug):
if not book.accessible(request):
return HttpResponseForbidden("Not authorized.")
- # TODO: move to celery
- doc = book.wldocument(librarian2=True)
- # TODO: error handling
- from librarian.builders import MobiBuilder
- mobi = MobiBuilder(
- base_url='file://' + book.gallery_path() + '/'
- ).build(doc).get_bytes()
+ options = {}
+ if book.project is not None and (logo := book.project.logo_for_cover()):
+ options['cover_logo'] = logo
+ try:
+ content = remote_build(book, 'mobi', options=options)
+ except RuntimeError as e:
+ return HttpResponse(str(e))
response = HttpResponse(content_type='application/x-mobipocket-ebook')
- response['Content-Disposition'] = 'attachment; filename=%s' % book.slug + '.mobi'
- response.write(mobi)
+ response['Content-Disposition'] = f'attachment; filename={book.dc_slug}.mobi'
+ response.write(content)
return response
# This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
-import os.path
+import os
PROJECT_ROOT = os.path.realpath(os.path.dirname(os.path.dirname(__file__)))
LEGIMI_PUBLISHER_ID = None
MIN_COVER_SIZE = (800, 800)
+
+REMOTE_BUILD_URL = os.environ.get('REMOTE_BUILD_URL')
+REMOTE_BUILD_TOKEN = os.environ.get('REMOTE_BUILD_TOKEN')