import { promisify } from 'node:util' import child_process from 'node:child_process' import { existsSync, mkdirSync } from 'node:fs' import { writeFile } from 'node:fs/promises' import { detectPdfPage, withMediaOption } from '../../utils/pdfPageMedia' // Server-side print for the A4 picklist PDF (dashboard "Picking" reprint). // // Mirrors the generic /api/print/ route (write base64 → CUPS `lp`), but lets the // caller pick the target CUPS queue (a paper/A4 printer from CUST_Printer) and the // CUPS options. Both are whitelisted before being interpolated into the shell // command so a crafted printer name / option string can't inject extra commands. // // Body: { pathName, fileName, fileContent (base64), printer?, printOptions? } // printer → CUPS queue name; defaults to 'default'. // printOptions → CUPS options; defaults to '-o sides=one-sided' (A4 simplex). // `-o media=A5|A4` is appended from the PDF page size when not given. const SAFE_PRINTER = /^[A-Za-z0-9_.-]+$/ const SAFE_OPTIONS = /^[A-Za-z0-9=_.\- ]*$/ export default defineEventHandler(async (event) => { let data: any = {} const body = await readBody(event) const exec = promisify(child_process.exec) const pathName = body.pathName const filePath = `/root/storage/${pathName}` const fileName = body.fileName const fileContent = Buffer.from(body.fileContent, 'base64') // Fall back to safe defaults if the value is missing or fails the whitelist. const printer = SAFE_PRINTER.test(body.printer || '') ? body.printer : 'default' const printOptions = SAFE_OPTIONS.test(body.printOptions ?? '') && body.printOptions ? body.printOptions : '-o sides=one-sided' try { if(!existsSync(filePath)) { mkdirSync(filePath, { recursive: true }) } await writeFile(`${filePath}/${fileName}`, fileContent) // A5 / A4 pages get an explicit `-o media=` unless the caller set one, so the // A5 Lieferschein pulls A5 paper instead of the queue default. const page = await detectPdfPage(`${filePath}/${fileName}`) const options = withMediaOption(printOptions, page) const { stdout, stderr } = await exec(`lp -d ${printer} ${options} ${filePath}/${fileName}`) data = body data['message'] = !stderr ? 'success' : 'failed' data['printer'] = printer data['printOptions'] = options data['pageKind'] = page.kind data['stdout'] = stdout data['stderr'] = stderr } catch(err: any) { data = err } return data })