import { execFile } from 'node:child_process' import { randomUUID } from 'node:crypto' import { access, copyFile, mkdir, open, rename, rm, stat } from 'node:fs/promises' import { basename, join } from 'node:path' import { fileURLToPath } from 'node:url' import { promisify } from 'node:util' import sharp from 'sharp' import { storage } from './config.js' const run = promisify(execFile) export const files = join(storage, 'media') export const staging = join(storage, 'incoming') export const mediaDir = id => join(files, id) const original = id => join(mediaDir(id), 'original') const commands = { timeout: 30_000, maxBuffer: 512 * 1024, env: { PATH: process.env.PATH, HOME: process.env.HOME, XDG_CACHE_HOME: process.env.XDG_CACHE_HOME, LC_ALL: 'C', } } const imageOptions = { limitInputPixels: 40_000_000, failOn: 'error' } const pdfLimit = 500 export async function prepareStorage() { await mkdir(files, { recursive: true, mode: 0o750 }) await mkdir(staging, { recursive: true, mode: 0o750 }) } async function pdfMetadata(path) { const { stdout } = await run('pdfinfo', [path], commands) const count = Number(stdout.match(/^Pages:\s+(\d+)$/m)?.[1]) if (!count || count > pdfLimit || /^Encrypted:\s+yes/m.test(stdout)) { throw new Error(`PDFs müssen unverschlüsselt sein und dürfen höchstens ${pdfLimit} Seiten haben.`) } const { stdout: details } = await run('pdfinfo', ['-f', '1', '-l', String(count), path], commands) const sizes = [...details.matchAll(/^Page\s+(?:(\d+)\s+)?size:\s*([\d.]+)\s+x\s+([\d.]+)/gm)] const rotations = [...details.matchAll(/^Page\s+(?:(\d+)\s+)?rot:\s*(-?\d+)/gm)] const turns = new Map(rotations.map((match, index) => [Number(match[1] || index + 1), Math.abs(Number(match[2])) % 180 === 90])) if (sizes.length !== count) throw new Error('Die Seitengrößen konnten nicht gelesen werden.') return { pages: sizes.map(([ , page, width, height], index) => { const ratio = turns.get(Number(page || index + 1)) ? Number(height) / Number(width) : Number(width) / Number(height) return Math.max(0.01, Math.min(100, ratio)) }) } } async function imageMetadata(path, target) { const image = sharp(path, imageOptions) const { format } = await image.metadata() if (!['jpeg', 'png', 'webp', 'gif', 'avif', 'heif'].includes(format)) { throw new Error('Unterstützte Bildformate sind JPEG, PNG, WebP, GIF und AVIF.') } const { width, height } = await image.autoOrient() .resize(1920, 1920, { fit: 'inside', withoutEnlargement: true }).webp({ quality: 82 }).toFile(target) return { width, height } } export async function saveUpload(file, id) { const input = await open(file.path) const buffer = Buffer.alloc(1024) try { await input.read(buffer, 0, buffer.length, 0) } finally { await input.close() } const isPdf = buffer.includes('%PDF-') await mkdir(mediaDir(id)) const metadata = isPdf ? await pdfMetadata(file.path) : await imageMetadata(file.path, join(mediaDir(id), 'display.webp')) await rename(file.path, original(id)) const name = basename(file.originalname).replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 240) || 'Datei' return { id, name, kind: isPdf ? 'pdf' : 'image', bytes: file.size, metadata } } export async function importDemoImage(id) { const path = fileURLToPath(new URL('./demo/campus.webp', import.meta.url)) const file = await stat(path).catch(error => { if (error.code !== 'ENOENT') throw error return null }) if (!file) return null await mkdir(mediaDir(id)) await copyFile(path, original(id)) await copyFile(path, join(mediaDir(id), 'display.webp')) const { width, height } = await sharp(path).metadata() return { bytes: file.size, metadata: { width, height } } } const rendering = new Map() const queue = [] let running = 0 const renderConcurrency = 2 function dispatch() { while (running < renderConcurrency && queue.length) { const { action, resolve, reject } = queue.shift() running++ action().then(resolve, reject).finally(() => { running--; dispatch() }) } } export async function renderPage(id, page, size) { const target = join(mediaDir(id), `page-${page}-${size}.jpg`) try { await access(target); return target } catch (error) { if (error.code !== 'ENOENT') throw error } if (rendering.has(target)) return rendering.get(target) if (queue.length >= 40) throw Object.assign(new Error('PDF-Renderer ausgelastet.'), { status: 503 }) const pending = new Promise((resolve, reject) => { queue.push({ resolve, reject, action: async () => { const temp = join(mediaDir(id), `render-${randomUUID()}`) try { await run('pdftoppm', ['-f', String(page), '-l', String(page), '-scale-to', String(size), '-jpeg', '-jpegopt', 'quality=83,optimize=y', '-singlefile', original(id), temp], commands) await rename(temp + '.jpg', target) return target } finally { await rm(temp + '.jpg', { force: true }) } } }) dispatch() }).finally(() => rendering.delete(target)) rendering.set(target, pending) return pending }