#!/usr/bin/env node // noinspection XmlDeprecatedElement,HtmlDeprecatedTag "use strict"; import os from "node:os"; // default-import + destructure: this dependency is CommonJS and some loaders // (tsx) do not expose its named exports to ESM consumers import bonjourService from "bonjour-service"; const { Bonjour } = bonjourService; import DeviceClient from "./DeviceClient.js"; import type { PaperlessConfig } from "./paperless/PaperlessConfig.js"; import type { NextcloudConfig } from "./nextcloud/NextcloudConfig.js"; import type { S3Config } from "./s3/S3Config.js"; import { assertWebhookAuthCredentials } from "./webhook/WebhookConfig.js"; import type { WebhookAuthType, WebhookConfig, WebhookPayload, } from "./webhook/WebhookConfig.js"; import { startHealthCheckServer } from "./healthcheck.js"; import fs from "node:fs"; import { Command, Option } from "@commander-js/extra-typings"; import type { RegistrationConfig } from "./type/scanTargetDefinitions.js"; import { listenCmd } from "./commands/listenCmd.js"; import { adfAutoscanCmd } from "./commands/adfAutoscanCmd.js"; import { singleScanCmd } from "./commands/singleScanCmd.js"; import { clearRegistrationsCmd } from "./commands/clearRegistrationsCmd.js"; import type { DirectoryConfig } from "./type/directoryConfig.js"; import type { AdfAutoScanConfig, ScanConfig, SingleScanConfig, } from "./type/scanConfigs.js"; import { discoverCmd } from "./commands/discoverCmd.js"; import type { FileConfig } from "./type/FileConfig.js"; import { HelpGroupsHeadings } from "./type/helpGroupsHeadings.js"; import type { Server as NetServer } from "node:net"; import { ScanMode } from "./type/scanMode.js"; import { DuplexAssemblyMode } from "./type/DuplexAssemblyMode.js"; import { ScanFormat, parseScanFormat } from "./type/scanFormat.js"; import { validateFilePatternForPlatform } from "./fileNameValidation.js"; import { parsePostCommandTimeoutArg, postCommandArgParser, } from "./postCommand.js"; import { getLoggerForFile, setDebugLevel } from "./logger.js"; const logger = getLoggerForFile(import.meta.url); function findOfficejetIp(deviceNamePrefix: string): Promise { return new Promise((resolve) => { const bonjour = new Bonjour(); logger.info("Searching device..."); const browser = bonjour.find( { type: "http", }, (service) => { if ( service.name.startsWith(deviceNamePrefix) && service.port === 80 && service.type === "http" && service.addresses !== undefined ) { browser.stop(); bonjour.destroy(); logger.info(`Found: ${service.name}`); resolve(service.addresses[0]); } }, ); browser.start(); }); } function setupScanParameters(commandName: string) { return new Command<[], ProgramOption>(commandName) .addOption( new Option( "-d, --directory ", "Directory where scans are saved (default: /tmp/scan-to-pcRANDOM)", ).helpGroup(HelpGroupsHeadings.ouput), ) .addOption( new Option( "-p, --pattern ", 'Pattern for filename (i.e. "scan"_dd.mm.yyyy_HHMMss, default would be scanPageNUMBER), make sure that the pattern is enclosed in extra quotes, avoid ":" as it is invalid on windows', ).helpGroup(HelpGroupsHeadings.ouput), ) .addOption( new Option( "-r, --resolution ", "Resolution in DPI of the scans (default: 200)", ).helpGroup(HelpGroupsHeadings.scan), ) .addOption( new Option("--mode ", "Selects the scan mode (default: Color)") .choices(["Gray", "Color"]) .helpGroup(HelpGroupsHeadings.scan), ) .addOption( new Option( "-w, --width ", "Width in pixels of the scans (default: max)", ) .conflicts("paperSize") .conflicts("paperDim") .helpGroup(HelpGroupsHeadings.scan), ) .addOption( new Option( "-h, --height ", "Height in pixels of the scans (default: max)", ) .conflicts("paperSize") .conflicts("paperDim") .helpGroup(HelpGroupsHeadings.scan), ) .addOption( new Option( "--paper-size ", "Paper size preset: A4 (default), Letter, Legal, A5, B5, or Max (case-insensitive)", ) .conflicts("paperDim") .conflicts("width") .conflicts("height") .helpGroup(HelpGroupsHeadings.scan), ) .addOption( new Option( "--paper-orientation ", "Paper orientation: portrait (default) or landscape. Applied to --paper-size only.", ) .choices(["portrait", "landscape"]) .conflicts("paperDim") .conflicts("width") .conflicts("height") .helpGroup(HelpGroupsHeadings.scan), ) .addOption( new Option( "--paper-dim ", "Custom paper dimensions with unit (e.g., 21x29.7cm, 8.5x11in, 210x297mm). Cannot be used with --paper-size.", ) .conflicts("paperSize") .conflicts("width") .conflicts("height") .helpGroup(HelpGroupsHeadings.scan), ) .addOption( new Option( "-f, --image-format ", "Image format for scans (when not PDF): Jpeg (default) or Bmp", ) .argParser((val) => { const parsed = parseScanFormat(val); if (parsed === undefined) { throw new Error( `Invalid format: ${val}. Expected "Jpeg" or "Bmp" (case-insensitive).`, ); } return parsed; }) .helpGroup(HelpGroupsHeadings.ouput), ) .addOption( new Option( "-t, --temp-directory ", "Temp directory used for processing (default: /tmp/scan-to-pcRANDOM)", ).helpGroup(HelpGroupsHeadings.scan), ) .addOption( new Option( "--prefer-eSCL", "Prefer eSCL protocol if available", ).helpGroup(HelpGroupsHeadings.scan), ) .option( "--device-up-polling-interval ", "Device up polling interval in milliseconds", parseFloat, ) .addOption( new Option( "-s, --paperless-post-document-url ", "The paperless post document url (example: https://domain.tld/api/documents/post_document/)", ).helpGroup(HelpGroupsHeadings.paperless), ) .addOption( new Option( "-o, --paperless-token ", "The paperless token. Either this or paperless-token-file is required for paperless integration.", ).helpGroup(HelpGroupsHeadings.paperless), ) .addOption( new Option( "--paperless-token-file ", "File name that contains the paperless token. Either this or paperless-token is required for paperless integration.", ).helpGroup(HelpGroupsHeadings.paperless), ) .addOption( new Option( "--paperless-group-multi-page-scan-into-a-pdf", "Combine multiple scanned images into a single PDF document", ).helpGroup(HelpGroupsHeadings.paperless), ) .addOption( new Option( "--paperless-always-send-as-pdf-file", "Always convert scan job to pdf before sending to paperless", ).helpGroup(HelpGroupsHeadings.paperless), ) .addOption( new Option( "-k, --keep-files", "Keep the scan files on the file system when sent to external systems for local backup and easy access (default: false)", ).helpGroup(HelpGroupsHeadings.ouput), ) .addOption( new Option( "--post-command-pdf ", "Command run on every generated PDF, given as a program and its arguments ({input} is the file path; when the command contains {output} the output file replaces it, e.g. a Ghostscript PDF/A conversion).", ) .argParser(postCommandArgParser("--post-command-pdf")) .helpGroup(HelpGroupsHeadings.ouput), ) .addOption( new Option( "--post-command-image ", "Command run on every delivered image page, given as a program and its arguments ({input} is the file path; when the command contains {output} the output file replaces it).", ) .argParser(postCommandArgParser("--post-command-image")) .helpGroup(HelpGroupsHeadings.ouput), ) .addOption( new Option( "--post-command-timeout ", "Timeout in milliseconds for the post-command hooks before they are killed (default: 300000)", ) .argParser(parsePostCommandTimeoutArg) .helpGroup(HelpGroupsHeadings.ouput), ) .addOption( new Option( "--reveal", "Open the system file manager on each scan that stays on disk, with the file selected (desktop sessions only; skipped in containers and headless sessions) (default: false)", ).helpGroup(HelpGroupsHeadings.ouput), ) .addOption( new Option( "--nextcloud-url ", "The nextcloud url (example: https://domain.tld)", ).helpGroup(HelpGroupsHeadings.nextcloud), ) .addOption( new Option( "--nextcloud-username ", "The nextcloud username", ).helpGroup(HelpGroupsHeadings.nextcloud), ) .addOption( new Option( "--nextcloud-password ", "The nextcloud app password for username. Either this or nextcloud-password-file is required for nextcloud integration.", ).helpGroup(HelpGroupsHeadings.nextcloud), ) .addOption( new Option( "--nextcloud-password-file ", "File name that contains the nextcloud app password for username. Either this or nextcloud-password is required for nextcloud integration.", ).helpGroup(HelpGroupsHeadings.nextcloud), ) .addOption( new Option( "--nextcloud-upload-folder ", "The upload folder where documents or images are uploaded (default: scan)", ).helpGroup(HelpGroupsHeadings.nextcloud), ) .addOption( new Option( "--s3-url ", "The S3-compatible endpoint url (example: https://s3.us-east-1.amazonaws.com)", ).helpGroup(HelpGroupsHeadings.s3), ) .addOption( new Option( "--s3-region ", "The S3 region used for request signing (default: us-east-1)", ).helpGroup(HelpGroupsHeadings.s3), ) .addOption( new Option( "--s3-access-key-id ", "The S3 access key id", ).helpGroup(HelpGroupsHeadings.s3), ) .addOption( new Option( "--s3-secret-access-key ", "The S3 secret access key. Either this or s3-secret-access-key-file is required for the s3 integration.", ).helpGroup(HelpGroupsHeadings.s3), ) .addOption( new Option( "--s3-secret-access-key-file ", "File name that contains the S3 secret access key. Either this or s3-secret-access-key is required for the s3 integration.", ).helpGroup(HelpGroupsHeadings.s3), ) .addOption( new Option( "--s3-bucket ", "The S3 bucket where scans are uploaded", ).helpGroup(HelpGroupsHeadings.s3), ) .addOption( new Option( "--s3-prefix ", "The folder (prefix) inside the bucket where scans are uploaded (default: bucket root)", ).helpGroup(HelpGroupsHeadings.s3), ) .addOption( new Option( "--s3-force-path-style", "Force path-style addressing (required for MinIO, Cloudflare R2, Wasabi...)", ).helpGroup(HelpGroupsHeadings.s3), ) .addOption( new Option( "--s3-session-token ", "The S3 session token for temporary credentials (optional)", ).helpGroup(HelpGroupsHeadings.s3), ) .addOption( new Option( "--webhook-url ", "The webhook url to POST scan events to (JSON with an idempotency-key header, best-effort delivery)", ).helpGroup(HelpGroupsHeadings.webhook), ) .addOption( new Option( "--webhook-auth ", "Auth scheme for the webhook request: none, hmac, bearer or basic (default: inferred from the configured credentials)", ) .choices(["none", "hmac", "bearer", "basic"]) .helpGroup(HelpGroupsHeadings.webhook), ) .addOption( new Option( "--webhook-auth-header ", "Header name carrying the HMAC signature (default: x-webhook-signature)", ).helpGroup(HelpGroupsHeadings.webhook), ) .addOption( new Option( "--webhook-secret ", "Secret used to sign the payload (HMAC-SHA256, hex) sent in the webhook-auth-header. Either this or webhook-secret-file.", ).helpGroup(HelpGroupsHeadings.webhook), ) .addOption( new Option( "--webhook-secret-file ", "File name that contains the webhook signing secret. Either this or webhook-secret.", ).helpGroup(HelpGroupsHeadings.webhook), ) .addOption( new Option( "--webhook-token ", "Bearer token sent as Authorization: Bearer ", ).helpGroup(HelpGroupsHeadings.webhook), ) .addOption( new Option( "--webhook-username ", "Basic auth username sent as Authorization: Basic", ).helpGroup(HelpGroupsHeadings.webhook), ) .addOption( new Option( "--webhook-password ", "Basic auth password for webhook-username", ).helpGroup(HelpGroupsHeadings.webhook), ) .addOption( new Option( "--webhook-payload ", "What the event carries: full (scanner IP, printer destination label, local file paths) or minimal (no identifying field, never a filesystem path)", ) .choices(["full", "minimal"]) .helpGroup(HelpGroupsHeadings.webhook), ); } async function getDeviceIp( options: ProgramOption, configFile: FileConfig, ): Promise { let ip = getOptConfiguredValue(options.address, configFile.ip); if (ip === undefined) { const name = getConfiguredValue( options.name, configFile.name, "HP Smart Tank Plus 570 series", ); ip = await findOfficejetIp(name); } logger.info(`Using device at IP: ${ip}`); return ip; } function getIsDebug(options: ProgramOption, configFile: FileConfig) { const debug = getConfiguredValue(options.debug, configFile.debug, false); logger.info(`IsDebug: ${debug}`); return debug; } function getPaperlessConfig( options: AdfAutoscanOptions | ListenOptions | SingleScanOptions, fileConfig: FileConfig, ): PaperlessConfig | undefined { const paperlessPostDocumentUrl = getOptConfiguredValue( options.paperlessPostDocumentUrl, fileConfig.paperless_post_document_url, ); const configPaperlessToken = getOptConfiguredValue( options.paperlessToken, fileConfig.paperless_token, ); const configPaperlessTokenFile = getOptConfiguredValue( options.paperlessTokenFile, fileConfig.paperless_token_file, ); if ( paperlessPostDocumentUrl !== undefined && (configPaperlessToken !== undefined || configPaperlessTokenFile !== undefined) ) { const configPaperlessKeepFiles = getConfiguredValue( options.keepFiles, fileConfig.keep_files, false, ); const groupMultiPageScanIntoAPdf = getConfiguredValue( options.paperlessGroupMultiPageScanIntoAPdf, fileConfig.paperless_group_multi_page_scan_into_a_pdf, false, ); const alwaysSendAsPdfFile = getConfiguredValue( options.paperlessAlwaysSendAsPdfFile, fileConfig.paperless_always_send_as_pdf_file, false, ); let paperlessToken: string; if (configPaperlessTokenFile !== undefined) { paperlessToken = fs // NOSONAR: path comes from trusted config/env, not user input. .readFileSync(configPaperlessTokenFile, "utf8") .trimEnd(); } else { paperlessToken = configPaperlessToken ?? ""; } logger.info( `Paperless configuration provided, post document url: ${paperlessPostDocumentUrl}, the token length: ${paperlessToken.length}, keepFiles: ${configPaperlessKeepFiles}`, ); return { postDocumentUrl: paperlessPostDocumentUrl, authToken: paperlessToken, keepFiles: configPaperlessKeepFiles, groupMultiPageScanIntoAPdf: groupMultiPageScanIntoAPdf, alwaysSendAsPdfFile: alwaysSendAsPdfFile, }; } else { return undefined; } } function getNextcloudConfig( options: AdfAutoscanOptions | ListenOptions | SingleScanOptions, fileConfig: FileConfig, ): NextcloudConfig | undefined { const configNextcloudUrl = getOptConfiguredValue( options.nextcloudUrl, fileConfig.nextcloud_url, ); const configNextcloudUsername = getOptConfiguredValue( options.nextcloudUsername, fileConfig.nextcloud_username, ); const configNextcloudPassword = getOptConfiguredValue( options.nextcloudPassword, fileConfig.nextcloud_password, ); const configNextcloudPasswordFile = getOptConfiguredValue( options.nextcloudPasswordFile, fileConfig.nextcloud_password_file, ); if ( configNextcloudUrl !== undefined && configNextcloudUsername !== undefined && (configNextcloudPassword !== undefined || configNextcloudPasswordFile !== undefined) ) { const configNextcloudUploadFolder = getConfiguredValue( options.nextcloudUploadFolder, fileConfig.nextcloud_upload_folder, "scan", ); const configNextcloudKeepFiles: boolean = getConfiguredValue( options.keepFiles, fileConfig.keep_files, false, ); let nextcloudPassword: string; if (configNextcloudPasswordFile !== undefined) { nextcloudPassword = fs // NOSONAR: path comes from trusted config/env, not user input. .readFileSync(configNextcloudPasswordFile, "utf8") .trimEnd(); } else { nextcloudPassword = configNextcloudPassword ?? ""; } const passLength = configNextcloudPassword?.length; const usernameLength = configNextcloudUsername.length; logger.info( `Nextcloud configuration provided, url: ${configNextcloudUrl}, username length: ${usernameLength}, password length: ${passLength}, upload folder: ${configNextcloudUploadFolder}, keepFiles: ${configNextcloudKeepFiles}`, ); return { baseUrl: configNextcloudUrl, username: configNextcloudUsername, password: nextcloudPassword, uploadFolder: configNextcloudUploadFolder, keepFiles: configNextcloudKeepFiles, }; } else { return undefined; } } export function getS3Config( options: AdfAutoscanOptions | ListenOptions | SingleScanOptions, fileConfig: FileConfig, ): S3Config | undefined { const configS3Url = getOptConfiguredValue(options.s3Url, fileConfig.s3_url); const configS3Bucket = getOptConfiguredValue( options.s3Bucket, fileConfig.s3_bucket, ); const configS3AccessKeyId = getOptConfiguredValue( options.s3AccessKeyId, fileConfig.s3_access_key_id, ); const configS3SecretAccessKey = getOptConfiguredValue( options.s3SecretAccessKey, fileConfig.s3_secret_access_key, ); const configS3SecretAccessKeyFile = getOptConfiguredValue( options.s3SecretAccessKeyFile, fileConfig.s3_secret_access_key_file, ); const s3Attempted = configS3Url !== undefined || configS3Bucket !== undefined || configS3AccessKeyId !== undefined || configS3SecretAccessKey !== undefined || configS3SecretAccessKeyFile !== undefined; if (!s3Attempted) { return undefined; } const s3Complete = configS3Url !== undefined && configS3Bucket !== undefined && configS3AccessKeyId !== undefined && (configS3SecretAccessKey !== undefined || configS3SecretAccessKeyFile !== undefined); if (!s3Complete) { const missing: string[] = []; if (configS3Url === undefined) { missing.push("--s3-url"); } if (configS3Bucket === undefined) { missing.push("--s3-bucket"); } if (configS3AccessKeyId === undefined) { missing.push("--s3-access-key-id"); } if ( configS3SecretAccessKey === undefined && configS3SecretAccessKeyFile === undefined ) { missing.push("--s3-secret-access-key or --s3-secret-access-key-file"); } throw new Error( `Incomplete S3 configuration: missing ${missing.join(", ")}. Either provide all the required S3 options or remove them.`, ); } const region = getConfiguredValue( options.s3Region, fileConfig.s3_region, "us-east-1", ); const prefix = getConfiguredValue(options.s3Prefix, fileConfig.s3_prefix, ""); const forcePathStyle = getConfiguredValue( options.s3ForcePathStyle, fileConfig.s3_force_path_style, false, ); const keepFiles: boolean = getConfiguredValue( options.keepFiles, fileConfig.keep_files, false, ); const sessionToken = getOptConfiguredValue( options.s3SessionToken, fileConfig.s3_session_token, ); let secretAccessKey: string; if (configS3SecretAccessKeyFile !== undefined) { secretAccessKey = fs // NOSONAR: path comes from trusted config/env, not user input. .readFileSync(configS3SecretAccessKeyFile, "utf8") .trimEnd(); } else { secretAccessKey = configS3SecretAccessKey ?? ""; } logger.info( `S3 configuration provided, endpoint: ${configS3Url}, bucket: ${configS3Bucket}, region: ${region}, prefix: ${prefix}, forcePathStyle: ${forcePathStyle}, keepFiles: ${keepFiles}`, ); const s3Config: S3Config = { endpointUrl: configS3Url, region, bucket: configS3Bucket, accessKeyId: configS3AccessKeyId, secretAccessKey, prefix, forcePathStyle, keepFiles, }; if (sessionToken !== undefined && sessionToken.trim() !== "") { s3Config.sessionToken = sessionToken; } return s3Config; } /** * Rejects a webhook URL the request could never reach, at startup rather than * once per scan. The URL itself is not echoed: for n8n, Make or Zapier it is * the credential. */ function assertWebhookUrl(url: string): void { let parsed: URL; try { parsed = new URL(url); } catch { throw new Error( "The webhook url is not a valid absolute URL (expected http:// or https://...)", ); } if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { throw new Error("The webhook url must use the http or https scheme"); } } /** * Host of the webhook endpoint, for the startup log. * * The URL itself is never logged: with n8n, Make or Zapier the URL *is* the * credential (the path carries the token), and a log line ends up in * `docker logs`, in log shippers and in bug reports. Only the origin is kept, * which also drops any userinfo. */ function webhookHostForLog(url: string): string { try { return new URL(url).origin; } catch { return "(unparsable url)"; } } export function getWebhookConfig( options: AdfAutoscanOptions | ListenOptions | SingleScanOptions, fileConfig: FileConfig, ): WebhookConfig | undefined { const webhookUrl = getOptConfiguredValue( options.webhookUrl, fileConfig.webhook_url, ); if (webhookUrl === undefined) { return undefined; } assertWebhookUrl(webhookUrl); // A webhook is a notification, not a delivery target: on its own it must // never turn the retention off. Without another target the scan is the only // copy, and the event advertises its local path, which would be deleted // right after being sent. Retention stays decided by the real delivery // targets, or by an explicit `keep_files: false`. const keepFiles: boolean = getConfiguredValue( options.keepFiles, fileConfig.keep_files, true, ); const payload: WebhookPayload = getConfiguredValue( options.webhookPayload, fileConfig.webhook_payload, "full", ); // A blank header name would reach Node as an empty HTTP token and make every // request fail, so it falls back to the default like a blank secret does. const configuredAuthHeader = getConfiguredValue( options.webhookAuthHeader, fileConfig.webhook_auth_header, "x-webhook-signature", ); const authHeader = configuredAuthHeader.trim() === "" ? "x-webhook-signature" : configuredAuthHeader; const configSecret = getOptConfiguredValue( options.webhookSecret, fileConfig.webhook_secret, ); const configSecretFile = getOptConfiguredValue( options.webhookSecretFile, fileConfig.webhook_secret_file, ); const webhookToken = getOptConfiguredValue( options.webhookToken, fileConfig.webhook_token, ); const webhookUsername = getOptConfiguredValue( options.webhookUsername, fileConfig.webhook_username, ); const webhookPassword = getOptConfiguredValue( options.webhookPassword, fileConfig.webhook_password, ); let secret: string | undefined; if (configSecretFile !== undefined) { // NOSONAR: path comes from trusted config/env, not user input. secret = fs.readFileSync(configSecretFile, "utf8").trimEnd(); } else { secret = configSecret; } if (secret?.trim() === "") { secret = undefined; } const explicitAuth = getOptConfiguredValue( options.webhookAuth, fileConfig.webhook_auth, ); let auth: WebhookAuthType; if (explicitAuth !== undefined) { auth = explicitAuth; } else if (secret !== undefined) { auth = "hmac"; } else if (webhookToken !== undefined) { auth = "bearer"; } else if ( webhookUsername !== undefined || webhookPassword !== undefined ) { // Either half of the basic credentials is enough to infer basic auth: // assertWebhookAuthCredentials below then rejects the incomplete pair // instead of silently sending the event unauthenticated. auth = "basic"; } else { auth = "none"; } logger.info( `Webhook configuration provided, host: ${webhookHostForLog(webhookUrl)}, auth: ${auth}, authHeader: ${authHeader}, keepFiles: ${keepFiles}`, ); const webhookConfig: WebhookConfig = { url: webhookUrl, auth, authHeader, keepFiles, payload, }; if (secret !== undefined) { webhookConfig.secret = secret; } if (webhookToken !== undefined) { webhookConfig.token = webhookToken; } if (webhookUsername !== undefined) { webhookConfig.username = webhookUsername; } if (webhookPassword !== undefined) { webhookConfig.password = webhookPassword; } assertWebhookAuthCredentials(webhookConfig); return webhookConfig; } /** * Retrieves the configured value based on the provided options. * This function prioritizes the configuration from the command line if it is provided. * If the command line option is not defined, it checks the value from the config file. * Finally, if neither the command line nor the config file provides a value, * it returns the default value defined in the code. */ function getConfiguredValue( cliOption: undefined | T, fileConfig: undefined | T, defaultValue: T, ): T { if (cliOption !== undefined) { return cliOption; } if (fileConfig !== undefined) { return fileConfig; } return defaultValue; } function getOptConfiguredValue( option: undefined | T, config: undefined | T, ): T | undefined { return getConfiguredValue(option, config, undefined as T | undefined); } function getHealthCheckSetting(options: ProgramOption, configFile: FileConfig) { const healthCheckEnabled: boolean = getConfiguredValue( options.healthCheck, configFile.enableHealthCheck, false, ); const healthCheckPort = parseInt( getConfiguredValue( options.healthCheckPort, configFile.healthCheckPort?.toString(), "3000", ), 10, ); return { isHealthCheckEnabled: healthCheckEnabled, healthCheckPort: healthCheckPort, }; } export function getScanConfiguration( options: AdfAutoscanOptions | ListenOptions | SingleScanOptions, fileConfig: FileConfig, ) { const directoryConfig: DirectoryConfig = { directory: getOptConfiguredValue(options.directory, fileConfig.directory), tempDirectory: getOptConfiguredValue( options.tempDirectory, fileConfig.tempDirectory, ), filePattern: getOptConfiguredValue(options.pattern, fileConfig.pattern), }; if (directoryConfig.filePattern !== undefined) { // Fail early: a pattern producing an invalid file name would otherwise // crash at scan time. validateFilePatternForPlatform(directoryConfig.filePattern); } const paperlessConfig = getPaperlessConfig(options, fileConfig); const nextcloudConfig = getNextcloudConfig(options, fileConfig); const s3Config = getS3Config(options, fileConfig); const webhookConfig = getWebhookConfig(options, fileConfig); const resolution = parseInt( getConfiguredValue( options.resolution, fileConfig.resolution?.toString(), "200", ), 10, ); const mode = getConfiguredValue( options.mode as ScanMode | undefined, fileConfig.mode as ScanMode | undefined, ScanMode.Color, ); const preferEscl = getConfiguredValue( options.preferESCL, fileConfig.prefer_escl, false, ); // Paper size configuration with precedence: CLI > Config > default (A4) const paperSize = getOptConfiguredValue( options.paperSize, fileConfig.paper_size, ); const paperDim = getOptConfiguredValue( options.paperDim, fileConfig.paper_dim, ); const paperOrientation = getOptConfiguredValue( options.paperOrientation, fileConfig.paper_orientation, ); const hasPaperSizeConfig = paperSize !== undefined || paperDim !== undefined; const configWidth = getOptConfiguredValue( options.width, fileConfig.width?.toString(), ); const configHeight = getOptConfiguredValue( options.height, fileConfig.height?.toString(), ); if ( hasPaperSizeConfig && (configWidth !== undefined || configHeight !== undefined) ) { throw new Error( "Cannot specify both width/height and paper size (paper_size/paper_dim). Choose one or the other.", ); } const providedWidth: number | "max" | undefined = configWidth === undefined ? undefined : configWidth.toLowerCase() === "max" ? "max" : parseInt(configWidth, 10); const providedHeight: number | "max" | undefined = configHeight === undefined ? undefined : configHeight.toLowerCase() === "max" ? undefined : parseInt(configHeight, 10); const format = getConfiguredValue( options.imageFormat, fileConfig.image_format, ScanFormat.Jpeg, ); const postCommandImage = getOptConfiguredValue( options.postCommandImage, fileConfig.post_command_image, ); const postCommandPdf = getOptConfiguredValue( options.postCommandPdf, fileConfig.post_command_pdf, ); const postCommandTimeout = getOptConfiguredValue( options.postCommandTimeout, fileConfig.post_command_timeout, ); const reveal = getConfiguredValue(options.reveal, fileConfig.reveal, false); const scanConfig: ScanConfig = { resolution, mode, width: providedWidth, height: providedHeight, paperSize, paperDim, paperOrientation, format, directoryConfig, paperlessConfig, nextcloudConfig, s3Config, webhookConfig, preferEscl, ...(postCommandImage !== undefined && { postCommandImage }), ...(postCommandPdf !== undefined && { postCommandPdf }), ...(postCommandTimeout !== undefined && { postCommandTimeout }), ...(reveal && { reveal }), }; return scanConfig; } function getDeviceUpPollingInterval( options: AdfAutoscanOptions | ListenOptions | SingleScanOptions, configFile: FileConfig, ) { return getConfiguredValue( options.deviceUpPollingInterval, configFile.deviceUpPollingInterval, 1000, ); } export type ListenOptions = ReturnType["opts"]>; function createListenCliCmd(configFile: FileConfig) { return setupScanParameters("listen") .description("Listen the device for new scan job to save to this target") .addOption( new Option( "-l, --label