From c34afb18f77c163ee18ab181061f66f28a90ea22 Mon Sep 17 00:00:00 2001 From: Radek Czajka Date: Tue, 24 Nov 2026 18:17:45 +0100 Subject: [PATCH] Use remote builder --- src/depot/models.py | 58 ++++------- src/depot/publishers/base.py | 2 +- src/depot/publishers/legimi.py | 20 ++-- src/depot/publishers/woblink.py | 29 +++--- src/documents/ebook_utils.py | 1 - src/documents/models/book.py | 4 - src/documents/models/project.py | 13 +++ src/documents/remote_build.py | 52 ++++++++++ .../templates/documents/book_detail.html | 3 +- src/documents/urls.py | 1 - src/documents/views.py | 97 ++++++++----------- src/redakcja/settings/defaults.py | 5 +- 12 files changed, 149 insertions(+), 136 deletions(-) create mode 100644 src/documents/remote_build.py diff --git a/src/depot/models.py b/src/depot/models.py index 62a360aa..244a135b 100644 --- a/src/depot/models.py +++ b/src/depot/models.py @@ -1,14 +1,15 @@ 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 @@ -61,16 +62,13 @@ class Package(models.Model): 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 @@ -78,48 +76,28 @@ class Package(models.Model): 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): diff --git a/src/depot/publishers/base.py b/src/depot/publishers/base.py index 8fff399c..cdc1ff31 100644 --- a/src/depot/publishers/base.py +++ b/src/depot/publishers/base.py @@ -25,7 +25,7 @@ class BasePublisher: if wlbook.meta.audience in ('L', 'SP1', 'SP2', 'SP3', 'SP4'): description += '

{} to lektura szkolna.'.format(wlbook.meta.title) - if wlbook.tree.find('//pe') is not None: + if wlbook.tree.find('.//pe') is not None: description += '
Ebook {title} 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' diff --git a/src/depot/publishers/legimi.py b/src/depot/publishers/legimi.py index 11a1c038..ab7e0e14 100644 --- a/src/depot/publishers/legimi.py +++ b/src/depot/publishers/legimi.py @@ -5,10 +5,10 @@ from django.conf import settings 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 @@ -194,16 +194,12 @@ class Legimi(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, diff --git a/src/depot/publishers/woblink.py b/src/depot/publishers/woblink.py index 4d147413..72b99c5e 100644 --- a/src/depot/publishers/woblink.py +++ b/src/depot/publishers/woblink.py @@ -9,6 +9,7 @@ from django.utils.safestring import mark_safe 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 @@ -399,11 +400,11 @@ class Woblink(BasePublisher): 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( @@ -592,15 +593,13 @@ class Woblink(BasePublisher): 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' @@ -608,15 +607,13 @@ class Woblink(BasePublisher): 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' diff --git a/src/documents/ebook_utils.py b/src/documents/ebook_utils.py index 5c36cbee..e75ed777 100644 --- a/src/documents/ebook_utils.py +++ b/src/documents/ebook_utils.py @@ -14,7 +14,6 @@ class RedakcjaDocProvider(DocProvider): 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')) diff --git a/src/documents/models/book.py b/src/documents/models/book.py index 1245ceab..2a4dea46 100644 --- a/src/documents/models/book.py +++ b/src/documents/models/book.py @@ -528,7 +528,3 @@ class Book(models.Model): 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()) diff --git a/src/documents/models/project.py b/src/documents/models/project.py index 9efee5a6..9d3aa363 100644 --- a/src/documents/models/project.py +++ b/src/documents/models/project.py @@ -1,6 +1,8 @@ # 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 _ @@ -24,3 +26,14 @@ class Project(models.Model): 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 + ) diff --git a/src/documents/remote_build.py b/src/documents/remote_build.py new file mode 100644 index 00000000..78abe0a9 --- /dev/null +++ b/src/documents/remote_build.py @@ -0,0 +1,52 @@ +# 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 diff --git a/src/documents/templates/documents/book_detail.html b/src/documents/templates/documents/book_detail.html index 8bf4329a..eafd9ee8 100644 --- a/src/documents/templates/documents/book_detail.html +++ b/src/documents/templates/documents/book_detail.html @@ -193,8 +193,7 @@ {% trans "TXT version" %}
{% trans "PDF version" %}
{% trans "PDF version for mobiles" %}
- {% trans "EPUB version" %} - sprawdź
+ {% trans "EPUB version" %}
{% trans "MOBI version" %}

diff --git a/src/documents/urls.py b/src/documents/urls.py index f23aad88..e847509b 100644 --- a/src/documents/urls.py +++ b/src/documents/urls.py @@ -42,7 +42,6 @@ urlpatterns = [ path('book//txt', views.book_txt, name="documents_book_txt"), path('book//html', views.book_html, name="documents_book_html"), path('book//epub', views.book_epub, name="documents_book_epub"), - path('book//epubcheck', views.book_epubcheck, name="documents_book_epubcheck"), path('book//mobi', views.book_mobi, name="documents_book_mobi"), path('book//pdf', views.book_pdf, name="documents_book_pdf"), path('book//pdf-mobile', views.book_pdf, kwargs={'mobile': True}, name="documents_book_pdf_mobile"), diff --git a/src/documents/views.py b/src/documents/views.py index 1fe7b054..fd1eef66 100644 --- a/src/documents/views.py +++ b/src/documents/views.py @@ -37,6 +37,7 @@ from . import helpers 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 @@ -267,8 +268,7 @@ def book_html(request, slug): 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') @@ -290,14 +290,24 @@ def book_pdf(request, slug, mobile=False): 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 @@ -306,51 +316,22 @@ def book_epub(request, slug): 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): @@ -358,16 +339,16 @@ 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 diff --git a/src/redakcja/settings/defaults.py b/src/redakcja/settings/defaults.py index 6e880841..11edc514 100644 --- a/src/redakcja/settings/defaults.py +++ b/src/redakcja/settings/defaults.py @@ -1,7 +1,7 @@ # 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__))) @@ -78,3 +78,6 @@ LEGIMI_PASSWORD = None 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') -- 2.20.1