Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

5.7 KB
Raw Blame
/**
 * Assemble a print-ready PDF from a comic issue's rendered cover + pages.
 * Filenames come from each record's proof/final slot (or legacy `filename`
 * for records that predate the split): finalImage > proofImage > legacy
 * filename. The comic-pages filename hook stamps each slot's filename at
 * media-job completion. Pages without any rendered slot are skipped — the
 * route surfaces "X of Y rendered" to the user before download.
 */

import { PDFDocument, rgb, StandardFonts } from '@cantoo/pdf-lib';
import { slugifyForFilename } from '../../lib/civitai.js';
import { getIssue } from './issues.js';
import { getSeries } from './series.js';
import { pickRenderedFilename } from '../../lib/renderSlot.js';
import { readImageFromMedia, embedImageBytes, fitImage } from '../../lib/pdfImageEmbed.js';
import { codedError } from '../../lib/codedError.js';

export const PAGE_SIZES = Object.freeze({
  'us-letter': { width: 612, height: 792 },
  'a4':        { width: 595.28, height: 841.89 },
  'tabloid':   { width: 792, height: 1224 },
});
export const DEFAULT_PAGE_SIZE = 'us-letter';

export const ERR_NO_RENDERED_PAGES = 'PIPELINE_COMIC_PDF_NO_PAGES';

const READ_OPTS = { subject: 'comic page image' };
const EMBED_OPTS = { unsupportedCode: 'PIPELINE_COMIC_PDF_UNSUPPORTED_IMAGE' };

/**
 * @returns {{ bytes: Uint8Array, pageCount: number, filename: string }}
 */
export async function buildComicPdf(issueId, opts = {}) {
  const issue = await getIssue(issueId);
  const series = await getSeries(issue.seriesId);

  const sizeKey = PAGE_SIZES[opts.size] ? opts.size : DEFAULT_PAGE_SIZE;
  const { width: pageW, height: pageH } = PAGE_SIZES[sizeKey];
  const includeCover = opts.includeCover !== false;
  const includeBackCover = opts.includeBackCover !== false;
  const includeColophon = opts.includeColophon !== false;

  // Read-fallback chain (finalImage → proofImage → legacy filename) lives
  // in server/lib/renderSlot.js so volume PDFs share it. See pickRenderedFilename
  // import + re-export at the top of this file.

  const comicPages = issue.stages?.comicPages || {};
  const cover = includeCover ? comicPages.cover : null;
  const backCover = includeBackCover ? comicPages.backCover : null;
  const pages = Array.isArray(comicPages.pages) ? comicPages.pages : [];

  const targets = [];
  const coverFilename = pickRenderedFilename(cover);
  if (coverFilename) targets.push(coverFilename);
  for (const p of pages) {
    const name = pickRenderedFilename(p);
    if (name) targets.push(name);
  }
  const backCoverFilename = pickRenderedFilename(backCover);
  if (backCoverFilename) targets.push(backCoverFilename);
  if (targets.length === 0) {
    throw codedError('Issue has no rendered pages or cover yet', ERR_NO_RENDERED_PAGES);
  }

  // Read all files concurrently — disk I/O parallelizes cleanly; @cantoo/pdf-lib's
  // embed is CPU-bound on the event loop so embedding stays sequential below.
  // One bad page must not fail the whole download, so errors are captured
  // alongside the bytes and logged when the loop reaches them.
  const loaded = await Promise.all(targets.map((filename) =>
    readImageFromMedia(filename, READ_OPTS)
      .then((bytes) => ({ filename, bytes }))
      .catch((err) => ({ filename, err })),
  ));

  const pdf = await PDFDocument.create();
  if (series.name || issue.title) {
    pdf.setTitle(`${series.name || 'Untitled'} #${issue.number || 1} — ${issue.title || ''}`.trim());
  }
  if (series.logline) pdf.setSubject(series.logline);
  pdf.setProducer('PortOS');
  pdf.setCreator('PortOS pipeline');

  let pageCount = 0;
  for (const entry of loaded) {
    if (entry.err) {
      console.error(`❌ comicPdf — skipped "${entry.filename}": ${entry.err.message || entry.err}`);
      continue;
    }
    const img = await embedImageBytes(pdf, entry.bytes, entry.filename, EMBED_OPTS).catch((err) => {
      console.error(`❌ comicPdf — embed failed "${entry.filename}": ${err.message || err}`);
      return null;
    });
    if (!img) continue;
    const page = pdf.addPage([pageW, pageH]);
    page.drawImage(img, fitImage(img.width, img.height, pageW, pageH));
    pageCount += 1;
  }

  if (pageCount === 0) {
    throw codedError('No usable pages — all embeds failed', ERR_NO_RENDERED_PAGES);
  }

  if (includeColophon) {
    const colophon = pdf.addPage([pageW, pageH]);
    const font = await pdf.embedFont(StandardFonts.Helvetica);
    const fontBold = await pdf.embedFont(StandardFonts.HelveticaBold);
    const left = 72;
    let cursor = pageH - 144;
    const drawLine = (text, { size = 11, bold = false, color = rgb(0.2, 0.2, 0.2) } = {}) => {
      colophon.drawText(text, { x: left, y: cursor, size, font: bold ? fontBold : font, color });
      cursor -= size + 8;
    };
    drawLine(series.name || 'Untitled Series', { size: 22, bold: true, color: rgb(0, 0, 0) });
    drawLine(`Issue #${issue.number || 1} — ${issue.title || ''}`.trim(), { size: 14, bold: true });
    cursor -= 12;
    if (series.logline) drawLine(`Logline: ${series.logline}`, { size: 10 });
    drawLine(`Generated: ${new Date().toISOString().slice(0, 19).replace('T', ' ')} UTC`, { size: 10 });
    drawLine(`Page count (rendered art): ${pageCount}`, { size: 10 });
    cursor -= 16;
    drawLine('Generated by PortOS pipeline.', { size: 9, color: rgb(0.45, 0.45, 0.45) });
    pageCount += 1;
  }

  const bytes = await pdf.save();
  return { bytes, pageCount, filename: buildPdfFilename(series, issue) };
}

function buildPdfFilename(series, issue) {
  const seriesSlug = slugifyForFilename(series.name || 'series');
  const num = String(issue.number || 1).padStart(2, '0');
  const titleSlug = issue.title ? slugifyForFilename(issue.title) : '';
  return titleSlug ? `${seriesSlug}-${num}-${titleSlug}.pdf` : `${seriesSlug}-${num}.pdf`;
}