import fs from 'node:fs/promises'; import { join } from 'node:path'; import puppeteer from 'puppeteer-core'; import { escapeHtml, renderPages } from '../shared/magazine.js'; import { validatePublication } from './model.js'; import { audit, pool, releaseDir, transaction, uploadPath } from './storage.js'; const width = 794; const height = 1122; const styles = await fs.readFile(new URL('../shared/publication.css', import.meta.url), 'utf8'); const paper = `@page{size:${width}px ${height}px;margin:0}body{margin:0}.print-sheet{width:${width}px;height:${height}px;break-after:page}.print-sheet:last-child{break-after:auto}`; function documentHtml(title, pages) { return `${escapeHtml(title)}${pages.map(({ html }) => ``).join('')}`; } async function createPdf(draft, files) { const origin = 'http://folio-render.invalid'; const imageMap = new Map(files.filter((file) => file.mime.startsWith('image/')).map((file) => [file.id, file])); const pages = await renderPages(draft, (id) => `${origin}/image/${id}`, true); const browser = await puppeteer.launch({ executablePath: process.env.CHROMIUM_PATH || '/usr/bin/chromium', args: ['--no-sandbox', '--disable-dev-shm-usage', '--disable-background-networking'], headless: true, }); try { const page = await browser.newPage(); await page.setJavaScriptEnabled(false); await page.setRequestInterception(true); page.on('request', async (request) => { const url = new URL(request.url()); if (['data:', 'about:'].includes(url.protocol)) return request.continue(); const file = url.origin === origin && imageMap.get(url.pathname.slice('/image/'.length)); if (!file) return request.abort(); try { await request.respond({ status: 200, contentType: file.mime, body: await fs.readFile(uploadPath(file)) }); } catch { if (!request.isInterceptResolutionHandled()) await request.abort(); } }); await page.setViewport({ width, height }); await page.setContent(documentHtml(draft.title, pages), { waitUntil: 'load', timeout: 30000 }); const invalid = await page.evaluate(() => [...document.querySelectorAll('.folio-page')].findIndex((sheet) => (!sheet.querySelector('.folio-layout-free') && sheet.scrollHeight > sheet.clientHeight + 2) || [...sheet.querySelectorAll('img')].some((img) => !img.naturalWidth))); if (invalid !== -1) throw new Error(`„${pages[invalid].title}“ ist zu voll oder enthält ein Bild, das sich nicht laden lässt.`); return await page.pdf({ printBackground: true, preferCSSPageSize: true, timeout: 30000 }); } finally { await browser.close(); } } export const releasePath = (release, format) => join(releaseDir, `${release}.${format}`); export async function renderPublication(draft, slug, releaseId) { const pages = await renderPages(draft, (id) => `/api/public/${slug}/media/${releaseId}/${id}`); return { pages, html: documentHtml(draft.title, pages) }; } async function writeArtifact(path, contents) { const temp = `${path}.tmp`; await fs.writeFile(temp, contents); await fs.rename(temp, path); } async function publish(job) { const pdfPath = releasePath(job.id, 'pdf'); const htmlPath = releasePath(job.id, 'html'); let committed = false; try { const files = await validatePublication(pool, job.draft); const { pages, html } = await renderPublication(job.draft, job.slug, job.id); const pdf = await createPdf(job.draft, files); await writeArtifact(htmlPath, html); await writeArtifact(pdfPath, pdf); committed = await transaction(async (db) => { const magazine = await db.query('SELECT deleted_at FROM magazines WHERE id=$1 FOR UPDATE', [job.magazine_id]); if (magazine.rows[0]?.deleted_at) return false; const update = await db.query(`UPDATE releases SET state='ready',pages=$2,media_ids=$3,bytes=$4,published_at=now() WHERE id=$1 AND state='queued' RETURNING id`, [job.id, JSON.stringify(pages), files.map((file) => file.id), Buffer.byteLength(html) + pdf.length]); if (!update.rowCount) return false; await db.query('UPDATE magazines SET current_release=$2 WHERE id=$1', [job.magazine_id, job.id]); await audit(db, 'published', `„${job.draft.title}“ veröffentlicht`); return true; }); } catch (error) { console.error('Veröffentlichung:', error.message); await transaction(async (db) => { const updated = await db.query("UPDATE releases SET state='failed',error=$2 WHERE id=$1 AND state='queued'", [job.id, error.message.slice(0, 500)]); if (updated.rowCount) await audit(db, 'failed', `Veröffentlichung von „${job.draft.title}“ fehlgeschlagen`); }); } finally { if (!committed) await Promise.all([pdfPath, htmlPath, `${pdfPath}.tmp`, `${htmlPath}.tmp`].map((path) => fs.rm(path, { force: true }))); } } export function startPublishing() { let timer; let stopped = false; const run = async () => { let db; let locked = false; try { db = await pool.connect(); locked = (await db.query('SELECT pg_try_advisory_lock(918401) AS locked')).rows[0].locked; while (locked && !stopped) { const result = await db.query(`SELECT r.*,m.slug FROM releases r JOIN magazines m ON m.id=r.magazine_id WHERE r.state='queued' AND r.publish_at <= now() AND m.deleted_at IS NULL ORDER BY r.publish_at,r.created_at LIMIT 1`); if (!result.rowCount) break; await publish(result.rows[0]); } } catch (error) { console.error('Publishing-Worker:', error.message); } finally { if (db) { const unlockError = locked ? await db.query('SELECT pg_advisory_unlock(918401)').then(() => undefined).catch((error) => error) : undefined; db.release(unlockError); } if (!stopped) timer = setTimeout(run, 2500); } }; void run(); return () => { stopped = true; clearTimeout(timer); }; }