Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
1051 lines (989 loc) · 43.5 KB
/
Copy pathserver.js
File metadata and controls
1051 lines (989 loc) · 43.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const { randomUUID } = require("crypto");
const fs = require("fs");
const fsp = require("fs/promises");
const os = require("os");
const path = require("path");
const zlib = require("zlib");
const { fileURLToPath, pathToFileURL } = require("url");
const express = require("express");
const mime = require("mime-types");
const { createBudgetedUpload } = require("./upload-budget");
const { createProgressHttpLifecycle, reportConversionProgress } = require("./conversion-progress");
const { cancellationError, throwIfCanceled } = require("./conversion-cancellation");
const sanitize = require("sanitize-filename");
const sharp = require("sharp");
const ExcelJS = require("exceljs");
const yazl = require("yazl");
const yauzl = require("yauzl");
const { PDFDocument } = require("pdf-lib");
const { assertPdfInputHeader } = require("./pdf-input");
const { createTurndownService, htmlToMarkdown, markdownToHtml, csvToJsonObjects, jsonToCsv, csvToMarkdown, csvToHtmlTable } = require("./text-conversion");
const { convertRasterImage } = require("./image-conversion");
const { isBmpFileSync, decodeBmpToRaw } = require("./bmp-input");
const { xmlToJson } = require("./xml-json");
const { convertEbook, convertTextToEpub } = require("./ebook");
const { readTextInput } = require("./text-encoding");
const { pandocPath } = require("./markdown-document");
const yaml = require("js-yaml");
const {
LIMITS,
ResourceLimitError,
assertImageMetadata,
assertImagePdfBudget,
assertBatchBytes,
assertPdfPages
} = require("./resource-policy");
const { buildPdfTableWorkbook, detectTableLinesFromRaw } = require("./pdf-table-runtime");
const { convertOfdToPdf } = require("./ofd-convert");
const { OfficeEngineError, probeLibreOffice, runLibreOffice } = require("./office-engine");
const { getOfficeState, waitForOfficeReady, OfficePreparationError } = require("./office-readiness");
const { getStructuredPdfAvailability } = require("./pdf-structure-engine");
const { inspectXlsxForCsv } = require("./office-quality");
const logger = require("./logger");
// Prefer the Electron main process's debug.log (set via FLYINGMOUSE_LOG_FILE
// or setLogFile); standalone `node server.js` falls back to a temp file.
if (process.env.FLYINGMOUSE_LOG_FILE) {
logger.setLogFile(process.env.FLYINGMOUSE_LOG_FILE);
}
const config = require("./config");
const {
ensureDirs,
run,
commandExists,
extFromName,
decodeUploadFileName,
normalizeExt,
categoryForExt,
targetsForExt,
platformCapabilities,
experimentalInputWarning,
safeBaseName,
outputExtFor,
outputNameFor,
outputPathFor,
registerDownload,
releaseDownloads,
retainDownloadResponse,
escapeHtml
} = require("./utils");
const { convertMedia, probeAudioTrack } = require("./media");
const { convertSubtitle } = require("./subtitles");
const { zipFiles, openZipEntries, readZipEntryToFile, listZipEntries } = require("./zip-util");
const {
convertPdfDecrypt,
assertPdfTableOcrQuality,
convertPdf,
splitPdfToZip,
mergePdfFiles,
renderPdfPages,
emitPdfPageImages,
convertScannedPdfToOcrText,
convertScannedPdfToOcrDocx,
convertScannedPdfToOcrHtml,
ocrScannedPdfPages,
convertPresentationToImages,
convertPresentationToHtml,
convertZipImagesToPdf
} = require("./pdf");
const {
htmlToText,
escapeXml,
mdInlineRuns,
docxRunXml,
docxParagraphXml,
splitHtmlIntoLines,
convertTextToDocx,
parseJsonText,
convertText,
convertCsvToXlsx,
convertCsvToPdf,
parseCsvRecords,
readTabularText
} = require("./text-docx");
const {
libreOfficeFilterFor,
findConvertedFile,
convertWithLibreOffice,
convertDocumentToMarkdown,
convertDocumentToText
} = require("./office-convert");
const {
convertImage,
prepareImageInput,
isHeicFileSync,
inspectImageMetadata,
convertImageToVideo,
pdfAscii,
pdfNumber,
readImageForPdf,
readPngAsPdfImage,
convertImagesToPdf
} = require("./image");
const {
ocrAvailable,
createOcrWorker,
recognizeImageTextWithWorker,
convertImageToOcrText
} = require("./ocr");
const {
normalizePdfjsEntry,
isMissingPdfjsEntry,
resolvePdfjsEntrySpecifiers,
loadPdfjsModule,
createPdfjsLoader,
loadPdfjs
} = require("./pdfjs");
const {
groupPdfItemsIntoRows,
extractPdfRowsByPage,
sheetName,
applyColumnWidths,
renderPdfTablePage,
preparePdfTableOcrImage,
recognizePdfTablePage,
extractComplexPdfTableModel,
addPdfTableNotes,
writePdfTableWorkbook
} = require("./pdf-table");
const {
ROOT,
DEFAULT_PORT,
RUNTIME_DIR,
UPLOAD_DIR,
OUTPUT_DIR,
MAX_UPLOAD_BYTES,
FFMPEG_PATH,
LIBREOFFICE_PATH,
PDFTOPPM_PATH,
TESSDATA_PATH,
DCRAW_PATH,
CR2_DECODER_PATH,
imageInput,
designInput,
rawInput,
imageFormatTargets,
imageVideoTargets,
imageOcrTargets,
imageTargets,
textInput,
textTargets,
documentInput,
documentTargets,
spreadsheetInput,
spreadsheetTargets,
presentationInput,
presentationTargets,
pdfInput,
pdfTextTargets,
pdfImageTargets,
audioInput,
videoInput,
mediaAudioTargets,
mediaVideoTargets,
mediaTargets,
experimentalInputsByCategory,
experimentalInputSet,
allTargets,
downloads,
PRODUCT_EXPIRY_MS
} = require("./config");
const app = express();
const CONTENT_SECURITY_POLICY = [
"default-src 'self'",
"script-src 'self'",
"style-src 'self'",
"img-src 'self' data:",
"connect-src 'self'",
"frame-src 'self'",
"media-src 'self'",
"object-src 'none'",
"base-uri 'none'",
"frame-ancestors 'none'",
"form-action 'self'"
].join("; ");
let cachedTesseract = null;
const upload = createBudgetedUpload({ directory: UPLOAD_DIR, maxFileBytes: MAX_UPLOAD_BYTES });
const conversionProgress = createProgressHttpLifecycle();
// 只清理「孤儿」临时文件:不在 downloads 登记表里、且超过 PRODUCT_EXPIRY_MS 未修改
// 的(上传残留/崩溃残片)。已登记产物在程序运行期间永不过期(2026-09-07 决策:
// 「转换出来的文件放在里面不该过期」),全量清理由退出时 purge + 启动时对历史
// 实例目录的回收负责。dirs/registry 参数化供单测注入。
function registeredFilePaths(registry) {
const paths = new Set();
for (const item of registry.values()) {
if (item.filePath) paths.add(path.resolve(item.filePath));
if (item.assetsDir) paths.add(path.resolve(item.assetsDir));
}
return paths;
}
async function cleanupOldFiles({ dirs = [UPLOAD_DIR, OUTPUT_DIR], registry = downloads } = {}) {
const cutoff = Date.now() - PRODUCT_EXPIRY_MS;
const registered = registeredFilePaths(registry);
for (const dir of dirs) {
const files = await fsp.readdir(dir).catch(() => []);
await Promise.all(files.map(async (file) => {
const filePath = path.join(dir, file);
if (registered.has(path.resolve(filePath))) return;
const stat = await fsp.stat(filePath).catch(() => null);
if (stat && stat.mtimeMs < cutoff) {
await fsp.rm(filePath, { recursive: true, force: true }).catch(() => {});
}
}));
}
}
// 退出前清空本实例的上传/产物目录(downloads 表随进程消失,产物再无保存机会)。
async function purgeRuntimeDirs({ dirs = [UPLOAD_DIR, OUTPUT_DIR] } = {}) {
for (const dir of dirs) {
await fsp.rm(dir, { recursive: true, force: true }).catch(() => {});
await fsp.mkdir(dir, { recursive: true }).catch(() => {});
}
}
// Legacy explicit maintenance helper; desktop shutdown uses bounded async cleanup.
function purgeRuntimeDirsSync({ dirs = [UPLOAD_DIR, OUTPUT_DIR], fsModule = fs } = {}) {
for (const dir of dirs) {
try { fsModule.rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ }
try { fsModule.mkdirSync(dir, { recursive: true }); } catch { /* best effort */ }
}
}
function runtimeProcessIsAlive(pid) {
try {
process.kill(pid, 0);
return true;
} catch (error) {
// Lack of permission is not evidence that another instance has exited.
return error.code !== "ESRCH";
}
}
// Reclaim only old, exactly named PID directories whose process has exited.
// The parent directory timestamp does not track changes to nested output files.
async function purgeStaleRuntimeDirs({ runtimeDir = RUNTIME_DIR } = {}) {
runtimeDir = path.resolve(runtimeDir);
const parent = path.dirname(runtimeDir);
const base = path.basename(runtimeDir);
const currentInstance = /^(.*-)(\d+)$/.exec(base);
if (!currentInstance) return;
const prefix = currentInstance[1];
const cutoff = Date.now() - PRODUCT_EXPIRY_MS;
const entries = await fsp.readdir(parent, { withFileTypes: true }).catch(() => []);
await Promise.all(entries
.filter((entry) => {
if (!entry.isDirectory() || !entry.name.startsWith(prefix)
|| path.join(parent, entry.name) === runtimeDir) return false;
const suffix = entry.name.slice(prefix.length);
const pid = Number(suffix);
return /^\d+$/.test(suffix) && Number.isSafeInteger(pid) && pid > 0 && !runtimeProcessIsAlive(pid);
})
.map(async (entry) => {
const dirPath = path.join(parent, entry.name);
const { PENDING_CLEANUP_FILE, assertRuntimeIdentity, removeMarkedRuntime } = require("./desktop-shutdown");
const stat = await fsp.lstat(dirPath).catch(() => null);
if (!stat?.isDirectory() || stat.isSymbolicLink()) return;
const owner = { runtimeDir: dirPath, identity: stat, realPath: await fsp.realpath(dirPath) };
const pid = Number(entry.name.slice(prefix.length));
const markerPath = path.join(dirPath, PENDING_CLEANUP_FILE);
const markerStat = await fsp.lstat(markerPath).catch(() => null);
let marked = false;
if (markerStat?.isFile() && !markerStat.isSymbolicLink() && markerStat.size <= 256) {
const marker = await fsp.readFile(markerPath, "utf8").then(JSON.parse).catch(() => null);
marked = marker?.schema === 1 && marker.pid === pid && marker.dev === stat.dev && marker.ino === stat.ino;
}
if ((marked || stat.mtimeMs < cutoff) && !runtimeProcessIsAlive(pid)
&& await assertRuntimeIdentity(owner)) {
if (marked) await removeMarkedRuntime(owner);
else await fsp.rm(dirPath, { recursive: true, force: true });
}
}));
}
// Each result owns a unique resource directory, even when download names match.
async function findMarkdownAssetsDir(mdPath) {
const assetsDir = `${mdPath}.assets`;
try {
const stat = await fsp.stat(assetsDir);
if (stat.isDirectory()) return assetsDir;
} catch {
// no assets dir
}
return null;
}
// 列出 assets 目录内的文件,生成相对 md 下载 URL 的资产清单。
async function listDownloadAssets(assetsDir, downloadUrl) {
const names = await fsp.readdir(assetsDir).catch(() => []);
const assets = [];
for (const name of names) {
const filePath = path.join(assetsDir, name);
const stat = await fsp.stat(filePath).catch(() => null);
if (!stat || !stat.isFile()) continue;
assets.push({
name,
url: `${downloadUrl}/asset/${encodeURIComponent(name)}`
});
}
return assets;
}
let cachedTools = null;
let cachedToolDetails = {};
let toolsPromise = null;
let officeProbePromise = null;
async function refreshOfficeCapability() {
const state = getOfficeState();
if (state.status !== "ready") {
cachedToolDetails.libreoffice = {
enabled: false, status: state.status,
...(state.error ? { errorCode: state.error.code, messages: state.error.messages, details: state.error.details } : {})
};
officeProbePromise = null;
return false;
}
if (!officeProbePromise) {
officeProbePromise = probeLibreOffice(LIBREOFFICE_PATH, { runtimeDir: RUNTIME_DIR }).then((probe) => {
cachedToolDetails.libreoffice = { ...probe, status: probe.enabled ? "ready" : "failed" };
return Boolean(probe.enabled);
}).catch((error) => {
cachedToolDetails.libreoffice = { enabled: false, status: "failed",
errorCode: error.code || "OFFICE_ENGINE_START_FAILED", messages: error.messages, details: error.details };
logger.warn("LibreOffice capability probe failed", error);
return false;
});
}
return officeProbePromise;
}
async function getTools({ includeOffice = true } = {}) {
if (!toolsPromise) toolsPromise = (async () => {
const pandocExecutable = pandocPath();
let pandocEnabled = false;
try {
if (!pandocExecutable || !fs.existsSync(pandocExecutable)) throw new Error("missing engine");
const result = await run(pandocExecutable, ["--version"], { timeout: 10000, maxStdoutBytes: 64 * 1024 });
const version = /^pandoc\s+(\S+)/m.exec(result.stdout)?.[1];
if (!version) throw new Error("invalid engine response");
pandocEnabled = true;
cachedToolDetails.pandoc = { enabled: true, version, executable: pandocExecutable };
} catch {
cachedToolDetails.pandoc = {
enabled: false, errorCode: "MARKDOWN_ENGINE_MISSING",
messages: { zhCN: "Markdown 文档引擎缺失或无法启动;Word/PDF 转换暂不可用,请修复安装。", enUS: "The Markdown document engine is missing or cannot start. Repair the installation to enable Word/PDF conversion." }
};
}
cachedToolDetails.pdfStructure = await getStructuredPdfAvailability();
return {
ffmpeg: await commandExists(FFMPEG_PATH),
libreoffice: false,
pandoc: pandocEnabled,
poppler: await commandExists(PDFTOPPM_PATH, ["-v"]),
ocr: ocrAvailable(),
pdf: true,
pdfStructure: Boolean(cachedToolDetails.pdfStructure.enabled),
sharp: true
};
})();
// PDF target discovery has no Office dependency. Leave the shared Office
// probe and its cached diagnostics untouched; full capability/conversion
// requests still await the verified engine result below.
if (!includeOffice) return { ...await toolsPromise };
const [baseTools, officeEnabled] = await Promise.all([toolsPromise, refreshOfficeCapability()]);
cachedTools = { ...baseTools, libreoffice: officeEnabled };
return { ...cachedTools };
}
async function getToolDiagnostics() {
const tools = await getTools();
return {
ffmpeg: { enabled: tools.ffmpeg, executable: FFMPEG_PATH },
libreoffice: { ...cachedToolDetails.libreoffice, executable: LIBREOFFICE_PATH },
pandoc: { ...cachedToolDetails.pandoc },
poppler: { enabled: tools.poppler, executable: PDFTOPPM_PATH },
ocr: { enabled: tools.ocr, version: require("tesseract.js/package.json").version },
pdfjs: { enabled: tools.pdf, version: require("pdfjs-dist/package.json").version },
pdfStructure: { ...cachedToolDetails.pdfStructure },
sharp: { enabled: tools.sharp, version: sharp.versions.sharp },
cr2: { enabled: Boolean(CR2_DECODER_PATH || DCRAW_PATH), executable: CR2_DECODER_PATH || DCRAW_PATH, cameraWhiteBalance: true }
};
}
function isLocalWebOrigin(value, localPort) {
if (!value) return false;
try {
const url = new URL(value);
return !url.username && !url.password
&& url.origin === `http://127.0.0.1:${localPort}`;
} catch {
return false;
}
}
function assertLocalWebRequest(req, res, next) {
const origin = req.headers.origin;
const referer = req.headers.referer;
if (origin && !isLocalWebOrigin(origin, req.socket.localPort)) {
res.status(403).json({ error: "拒绝跨站请求。" });
return;
}
if (referer && !isLocalWebOrigin(referer, req.socket.localPort)) {
res.status(403).json({ error: "拒绝跨站请求。" });
return;
}
next();
}
app.use((_req, res, next) => {
res.setHeader("Content-Security-Policy", CONTENT_SECURITY_POLICY);
next();
});
app.use(express.static(path.join(ROOT, "public")));
app.use(express.json());
function resourceErrorPayload(error) {
return {
error: error.message,
errorCode: error.errorCode,
messages: error.messages,
details: error.details
};
}
function normalizeResourceError(error) {
if (error instanceof ResourceLimitError) return error;
if (/^Input image exceeds pixel limit\b/i.test(String(error?.message || ""))) {
return new ResourceLimitError("IMAGE_PIXELS_EXCEEDED");
}
if (error?.code === "LIMIT_FILE_COUNT") {
return new ResourceLimitError("UPLOAD_FILE_COUNT_EXCEEDED", { limitFiles: LIMITS.maxUploadFiles });
}
if (error?.code === "LIMIT_FILE_SIZE") {
return new ResourceLimitError("UPLOAD_FILE_SIZE_EXCEEDED", { limitGiB: MAX_UPLOAD_BYTES / 1024 ** 3 });
}
return error;
}
function sendResourceError(res, error) {
error = normalizeResourceError(error);
if (!(error instanceof ResourceLimitError)) return false;
res.status(413).json(resourceErrorPayload(error));
return true;
}
app.get("/api/capabilities", async (_req, res) => {
const tools = await getTools();
res.json({
tools,
platform: platformCapabilities(),
toolDetails: cachedToolDetails,
maxUploadBytes: MAX_UPLOAD_BYTES,
limits: LIMITS,
groups: {
image: { inputs: [...imageInput, ...designInput, ...(DCRAW_PATH ? rawInput : [])].sort(), targets: [...imageFormatTargets, ...(tools.ffmpeg ? imageVideoTargets : []), ...(tools.ocr ? imageOcrTargets : [])], experimentalInputs: [...(experimentalInputsByCategory.image || []), ...(DCRAW_PATH ? rawInput : [])].sort() },
text: { inputs: [...textInput].sort(), targets: [...textTargets, ...(tools.libreoffice ? ["pdf"] : []), "docx"] },
subtitle: { inputs: [...config.subtitleInput], targets: config.subtitleTargets },
document: { inputs: [...documentInput].sort(), targets: documentTargets, experimentalInputs: experimentalInputsByCategory.document },
spreadsheet: { inputs: [...spreadsheetInput].sort(), targets: spreadsheetTargets, experimentalInputs: experimentalInputsByCategory.spreadsheet },
presentation: { inputs: [...presentationInput].sort(), targets: presentationTargets, experimentalInputs: experimentalInputsByCategory.presentation },
pdf: { inputs: [...pdfInput].sort(), targets: [...pdfTextTargets, ...(tools.poppler ? [...pdfImageTargets, "pdf"] : [])] },
audio: { inputs: [...audioInput].sort(), targets: mediaAudioTargets, experimentalInputs: experimentalInputsByCategory.audio },
video: { inputs: [...videoInput].sort(), targets: mediaTargets },
any: { inputs: ["*"], targets: [] }
},
optional: [
{ name: "LibreOffice", enabled: tools.libreoffice, formats: ["doc", "docx", "xls", "xlsx", "ppt", "pptx", "wps", "pdf"] },
{ name: "Pandoc Markdown", enabled: tools.pandoc, formats: ["md", "docx", "pdf"] },
{ name: "PDF structure and scanned tables", enabled: tools.pdfStructure, formats: ["pdf", "xlsx", "docx"], limits: cachedToolDetails.pdfStructure?.limits },
{ name: "Poppler PDF renderer", enabled: tools.poppler, formats: ["pdf", "png", "jpg"] },
{ name: "Tesseract OCR", enabled: tools.ocr, formats: ["image", "pdf", "txt"] }
]
});
});
app.post("/api/targets", async (req, res) => {
const ext = normalizeExt(String(req.body?.extension || "").toLowerCase());
const tools = await getTools({ includeOffice: categoryForExt(ext) !== "pdf" });
res.json({ extension: ext, category: categoryForExt(ext), targets: targetsForExt(ext, tools), experimental: experimentalInputSet.has(ext) });
});
app.get("/api/conversion-progress/:id", assertLocalWebRequest, conversionProgress.get);
app.post("/api/convert-images-to-pdf", assertLocalWebRequest, conversionProgress.begin, upload.array("files"), conversionProgress.enter, async (req, res) => {
const files = req.files || [];
try {
assertBatchBytes(files);
} catch (error) {
await Promise.all(files.map((file) => fsp.rm(file.path, { force: true }).catch(() => {})));
if (sendResourceError(res, error)) return;
throw error;
}
if (!files.length) {
res.status(400).json({ error: "请先选择要合并为 PDF 的图片。" });
return;
}
const imageFiles = files.map((file) => {
const originalName = decodeUploadFileName(file.originalname);
return {
inputPath: file.path,
originalName,
category: categoryForExt(normalizeExt(extFromName(originalName)))
};
});
// 空白页:前端队列里插入的空白页条目。blanks=0,3 表示在上传文件流(不含
// 空白页)的第 0 个文件之前、第 3 个文件之后插入空白页;从后往前插入避免
// 索引错位,PDF 生成时空白页输出纯白 A4 页。
const blankAfter = (
String(req.body?.blanks || "")
.split(",")
.map((item) => item.trim())
.filter((item) => item !== "")
.map(Number)
.filter((item) => Number.isInteger(item) && item >= 0 && item <= imageFiles.length)
);
// Equal positions represent consecutive pages and must not be deduplicated.
for (const blankIndex of blankAfter.sort((a, b) => b - a)) {
imageFiles.splice(blankIndex, 0, { inputPath: "", originalName: "", category: "image", blank: true });
}
if (imageFiles.some((file) => file.category !== "image")) {
logger.warn(`Rejected images-to-pdf: non-image file included (${imageFiles.map((f) => f.originalName).join(", ")})`);
await Promise.all(files.map((file) => fsp.rm(file.path, { force: true }).catch(() => {})));
res.status(400).json({ error: "批量合并 PDF 只支持图片文件。请先移除非图片文件。" });
return;
}
const firstBaseName = safeBaseName(imageFiles[0].originalName);
// 拖入文件夹/选择目录转 PDF 时直接用文件夹名命名(folderName 由前端从
// webkitRelativePath 或目录选择器传入),否则沿用「第一个文件等N个文件」。
const folderName = String(req.body?.folderName || "").trim();
const pdfBaseName = folderName ? safeBaseName(folderName) : firstBaseName;
const combinedName = folderName
? `${pdfBaseName}.pdf`
: (imageFiles.length > 1 ? `${firstBaseName}等${imageFiles.length}个文件.pdf` : `${firstBaseName}.pdf`);
const outputPath = outputPathFor(combinedName, "pdf");
const downloadName = outputNameFor(combinedName, "pdf");
logger.info(`Images-to-PDF request: ${imageFiles.length} image(s) -> "${downloadName}"`);
try {
reportConversionProgress({ stage: "merging" });
await withRequestCancellation(req, res, signal => convertImagesToPdf(imageFiles, outputPath, { signal }));
reportConversionProgress({ stage: "validating" });
await Promise.all(files.map((file) => fsp.rm(file.path, { force: true }).catch(() => {})));
const mimeType = "application/pdf";
const previewSize = (await fsp.stat(outputPath)).size;
// A disconnected caller cannot receive or release this result. Complete all
// asynchronous output checks before registering the owned download.
if (req.aborted || res.destroyed) throw cancellationError();
const registered = registerDownload(outputPath, downloadName, mimeType);
logger.info(`Images-to-PDF succeeded: "${downloadName}"`);
conversionProgress.outputReady(req);
res.json({
ok: true,
fileName: downloadName,
category: "image",
mimeType,
...registered,
previewSize
});
} catch (error) {
logger.error(`Images-to-PDF failed: "${combinedName}"`, error);
await Promise.all(files.map((file) => fsp.rm(file.path, { force: true }).catch(() => {})));
await fsp.rm(outputPath, { force: true }).catch(() => {});
if (!sendResourceError(res, error)) res.status(500).json({ error: error.message || "图片合并 PDF 失败。" });
}
});
app.post("/api/merge-pdfs", assertLocalWebRequest, conversionProgress.begin, upload.array("files"), conversionProgress.enter, async (req, res) => {
const files = req.files || [];
try {
assertBatchBytes(files);
} catch (error) {
await Promise.all(files.map((file) => fsp.rm(file.path, { force: true }).catch(() => {})));
if (sendResourceError(res, error)) return;
throw error;
}
if (!files.length) {
res.status(400).json({ error: "请先选择要合并的 PDF 文件。" });
return;
}
const pdfFiles = files.map((file) => ({
inputPath: file.path,
originalName: decodeUploadFileName(file.originalname)
}));
if (pdfFiles.some((file) => normalizeExt(extFromName(file.originalName)) !== "pdf")) {
await Promise.all(files.map((file) => fsp.rm(file.path, { force: true }).catch(() => {})));
res.status(400).json({ error: "批量合并 PDF 只支持 PDF 文件。请先移除非 PDF 文件。" });
return;
}
const firstBaseName = safeBaseName(pdfFiles[0].originalName);
const combinedName = pdfFiles.length > 1 ? `${firstBaseName}等${pdfFiles.length}个文件.pdf` : `${firstBaseName}.pdf`;
const outputPath = outputPathFor(combinedName, "pdf");
const downloadName = outputNameFor(combinedName, "pdf");
logger.info(`Merge-PDFs request: ${pdfFiles.length} PDF(s) -> "${downloadName}"`);
try {
reportConversionProgress({ stage: "merging" });
for (const file of pdfFiles) await assertPdfInputHeader(file.inputPath, file.originalName);
await withRequestCancellation(req, res, signal => mergePdfFiles(pdfFiles, outputPath, { signal }));
reportConversionProgress({ stage: "validating" });
await Promise.all(files.map((file) => fsp.rm(file.path, { force: true }).catch(() => {})));
const mimeType = "application/pdf";
const previewSize = (await fsp.stat(outputPath)).size;
if (req.aborted || res.destroyed) throw cancellationError();
const registered = registerDownload(outputPath, downloadName, mimeType);
logger.info(`Merge-PDFs succeeded: "${downloadName}"`);
conversionProgress.outputReady(req);
res.json({
ok: true,
fileName: downloadName,
category: "pdf",
mimeType,
...registered,
previewSize
});
} catch (error) {
logger.error(`Merge-PDFs failed: "${combinedName}"`, error);
await Promise.all(files.map((file) => fsp.rm(file.path, { force: true }).catch(() => {})));
await fsp.rm(outputPath, { force: true }).catch(() => {});
if (["PDF_ENCRYPTED_INPUT", "PDF_INVALID_INPUT"].includes(error.code)) {
res.status(422).json({ error: error.message, errorCode: error.code, messages: error.messages });
return;
}
if (!sendResourceError(res, error)) res.status(500).json({ error: error.message || "合并 PDF 失败。" });
}
});
async function withRequestCancellation(req, res, operation) {
const controller = new AbortController();
const abort = () => controller.abort();
const closed = () => { if (!res.writableFinished) abort(); };
req.once("aborted", abort);
res.once("close", closed);
if (req.aborted || res.destroyed) abort();
try {
const result = await operation(controller.signal);
throwIfCanceled(controller.signal);
return result;
} finally {
req.removeListener("aborted", abort);
res.removeListener("close", closed);
}
}
app.post("/api/convert", assertLocalWebRequest, conversionProgress.begin, upload.single("file"), conversionProgress.enter, async (req, res) => {
let tools = await getTools();
const file = req.file;
const originalName = decodeUploadFileName(file?.originalname);
const requestedTarget = normalizeExt(String(req.body.targetFormat || "").toLowerCase());
if (!file) {
res.status(400).json({ error: "请先选择一个文件。" });
return;
}
if (!allTargets.has(requestedTarget)) {
logger.warn(`Rejected convert request: unsupported target "${requestedTarget}" for "${originalName}"`);
await fsp.rm(file.path, { force: true }).catch(() => {});
res.status(400).json({ error: "目标格式暂不支持。", errorCode: "UNSUPPORTED_TARGET" });
return;
}
const inputExt = normalizeExt(extFromName(originalName));
const category = categoryForExt(inputExt);
// A queued CLI/API Office conversion may arrive while the first Store launch
// is still preparing its writable engine. Only this conversion waits; normal
// capability requests and all unrelated formats remain responsive.
if (!tools.libreoffice && targetsForExt(inputExt, { ...tools, libreoffice: true }).includes(requestedTarget)
&& !targetsForExt(inputExt, tools).includes(requestedTarget)) {
try {
reportConversionProgress({ stage: "queued" });
await waitForOfficeReady();
reportConversionProgress({ stage: "preparing" });
tools = await getTools();
if (!tools.libreoffice) {
const detail = cachedToolDetails.libreoffice;
throw Object.assign(new Error(detail.messages?.zhCN || "Office 引擎不可用,请修复安装。"), {
code: detail.errorCode || "OFFICE_ENGINE_START_FAILED", messages: detail.messages, details: detail.details
});
}
} catch (error) {
await fsp.rm(file.path, { force: true }).catch(() => {});
res.status(503).json({ error: error.message, errorCode: error.code, messages: error.messages, details: error.details });
return;
}
}
const allowedTargets = targetsForExt(inputExt, tools);
logger.info(`Convert request: "${originalName}" (${inputExt}/${category}) -> ${requestedTarget} (${file.size} bytes)`);
if (!allowedTargets.includes(requestedTarget)) {
logger.warn(`Rejected convert request: ${category} file "${originalName}" cannot target ${requestedTarget}`);
await fsp.rm(file.path, { force: true }).catch(() => {});
res.status(400).json({ error: "这个源文件暂时不能转换成所选格式。", errorCode: "TARGET_UNAVAILABLE_FOR_SOURCE" });
return;
}
const outputExt = outputExtFor(category, requestedTarget);
const pdfAction = String(req.body?.pdfAction || "");
// PDF→PDF 的加密/解密输出单个 .pdf,拆分输出 .pdf.zip(打包多页)
const effectiveOutputExt = (category === "pdf" && requestedTarget === "pdf" && (pdfAction === "encrypt" || pdfAction === "decrypt"))
? "pdf"
: outputExt;
const outputPath = outputPathFor(originalName, requestedTarget, effectiveOutputExt);
let downloadName = outputNameFor(originalName, requestedTarget, effectiveOutputExt);
let conversionResult = { warnings: [] };
try {
reportConversionProgress({ stage: "converting" });
if (category === "pdf") await assertPdfInputHeader(file.path, originalName);
if (category === "image") {
conversionResult = await convertImage(file.path, outputPath, requestedTarget, { inputName: originalName });
} else if (category === "subtitle") {
conversionResult = await convertSubtitle(file.path, outputPath, inputExt, requestedTarget);
} else if (category === "text") {
if (["epub", "mobi"].includes(inputExt)) {
conversionResult = await convertEbook(file.path, outputPath, inputExt, requestedTarget, originalName);
} else if (requestedTarget === "epub") {
await withRequestCancellation(req, res, async signal => {
const text = await readTextInput(file.path, { encoding: req.body?.textEncoding || "auto", signal });
return convertTextToEpub(text, inputExt, originalName, outputPath, { signal });
});
} else {
conversionResult = await convertText(file.path, outputPath, inputExt, requestedTarget, originalName);
}
} else if (category === "pdf") {
conversionResult = await withRequestCancellation(req, res, async signal => {
if (pdfImageTargets.includes(requestedTarget)) {
// 单页直接出图;多页才打包,且包内页图带源文件名前缀,避免解压重名。
const base = safeBaseName(originalName);
const emitted = await emitPdfPageImages(file.path, base, requestedTarget, { signal });
try {
throwIfCanceled(signal);
if (emitted.single) {
await fsp.copyFile(emitted.files[0].filePath, outputPath);
downloadName = `${base}.${requestedTarget}`;
} else {
reportConversionProgress({ stage: "converting" });
await zipFiles(emitted.files.map((item) => ({ inputPath: item.filePath, archiveName: item.name })), outputPath);
downloadName = `${base}.${requestedTarget}.zip`;
}
} finally {
await emitted.cleanup().catch(() => {});
}
return;
}
return convertPdf(file.path, outputPath, requestedTarget, {
signal,
pdfAction,
password: String(req.body?.password || ""),
splitMode: String(req.body?.splitMode || "page"),
groupSize: String(req.body?.groupSize || "1")
});
});
} else if (category === "zip") {
await convertZipImagesToPdf(file.path, outputPath);
} else if (category === "spreadsheet" && ["csv", "tsv"].includes(inputExt) && ["txt", "md", "json"].includes(requestedTarget)) {
conversionResult = await convertText(file.path, outputPath, inputExt, requestedTarget, originalName);
} else if (category === "spreadsheet" && ["csv", "tsv"].includes(inputExt) && ["epub", "xlsx", "html", "pdf"].includes(requestedTarget)) {
// LO 的 csv/tsv 导入过滤器 headless 下假成功(exit 0 零输出),全部用自有实现
if (requestedTarget === "epub") {
await withRequestCancellation(req, res, async signal => {
const tabular = await readTabularText(file.path, inputExt, { encoding: req.body?.textEncoding || "auto", signal });
return convertTextToEpub(tabular, "csv", originalName, outputPath, { signal });
});
} else {
const tabular = await readTabularText(file.path, inputExt);
if (requestedTarget === "xlsx") await convertCsvToXlsx(tabular, outputPath);
else if (requestedTarget === "html") await fsp.writeFile(outputPath, csvToHtmlTable(tabular), "utf8");
else await convertCsvToPdf(tabular, outputPath);
}
} else if (category === "document" || category === "spreadsheet" || category === "presentation") {
if (inputExt === "ofd") {
// OFD(国标 GB/T 33190)走自有链路(ofd-convert.js → PDF),LibreOffice 打不开。
// OFD 仅开放 PDF;校验所有页面后才允许注册下载结果。
// originalName 用于扩展名校验(multer 临时文件无扩展名)。
await withRequestCancellation(req, res, signal => convertOfdToPdf(file.path, outputPath, originalName, { signal }));
} else if (category === "presentation" && ["png", "jpg"].includes(requestedTarget)) {
await convertPresentationToImages(file.path, outputPath, originalName, requestedTarget);
} else if (category === "presentation" && requestedTarget === "html") {
await convertPresentationToHtml(file.path, outputPath, originalName);
} else if (category === "document" && requestedTarget === "md") {
await convertDocumentToMarkdown(file.path, outputPath, inputExt, originalName);
} else if (category === "document" && requestedTarget === "txt") {
await convertDocumentToText(file.path, outputPath, inputExt, originalName);
} else {
if (category === "spreadsheet" && inputExt === "xlsx" && requestedTarget === "csv") {
conversionResult = await inspectXlsxForCsv(file.path);
}
await convertWithLibreOffice(file.path, outputPath, originalName, requestedTarget);
}
} else if (category === "audio" || category === "video") {
const videoCodec = ["h264", "h265", "av1"].includes(String(req.body?.videoCodec || ""))
? String(req.body.videoCodec)
: "h264";
// 透明背景色:white / black / 十六进制色值(白名单在 alphaCompositeArgs 内校验)。
const alphaBackground = String(req.body?.alphaBackground || "").trim() || "white";
conversionResult = await withRequestCancellation(req, res, signal => convertMedia(
file.path, outputPath, requestedTarget, category, { videoCodec, alphaBackground, inputExt, signal }
));
} else {
throw new Error("暂时无法识别这个文件类型。");
}
reportConversionProgress({ stage: "validating" });
await fsp.rm(file.path, { force: true }).catch(() => {});
const mimeType = mime.lookup(downloadName) || "application/octet-stream";
// md 转换产物若带图片外置目录(.assets/),随 downloads 一起注册,
// 保存时主进程按 assets 清单把图片拷到 md 同目录,保证相对引用可用。
let mdAssetsDir = null;
if (requestedTarget === "md" && category === "document") {
mdAssetsDir = await findMarkdownAssetsDir(outputPath);
}
const assets = mdAssetsDir ? await listDownloadAssets(mdAssetsDir, "") : null;
const previewSize = (await fsp.stat(outputPath)).size;
// Finish every asynchronous output check before publication. A closed HTTP
// response has no owner to receive/release a newly registered download.
if (req.aborted || res.destroyed) throw cancellationError();
const registered = registerDownload(outputPath, downloadName, mimeType, { assetsDir: mdAssetsDir });
if (assets) registered.assets = assets.map(asset => ({ ...asset, url: registered.downloadUrl + asset.url }));
const payload = {
ok: true,
fileName: downloadName,
category,
mimeType,
...registered,
previewSize
};
if (Array.isArray(conversionResult?.warnings) && conversionResult.warnings.length) {
payload.warnings = conversionResult.warnings;
}
if (experimentalInputSet.has(inputExt)) {
payload.warnings = [...(payload.warnings || []), experimentalInputWarning(inputExt)];
}
logger.info(`Convert succeeded: "${originalName}" -> ${downloadName} (${requestedTarget})`);
conversionProgress.outputReady(req);
res.json(payload);
} catch (error) {
error = normalizeResourceError(error);
const isClientConversionError = [
"CSV_PARSE_FAILED",
"CONVERSION_CANCELED",
"PDF_TABLE_OCR_REQUIRED",
"PDF_TABLE_OCR_EMPTY",
"PDF_STRUCTURE_MEMORY_INSUFFICIENT",
"MEDIA_NO_AUDIO_TRACK",
"MEDIA_MST_NOT_VIDEO",
"MEDIA_INVALID_TRANSPORT_STREAM",
"PDF_OCR_REQUIRED",
"PDF_NATIVE_MATH_UNVERIFIED",
"PDF_SCAN_COLUMNS_UNVERIFIED",
"XML_JSON_PARSE_FAILED",
"YAML_JSON_PARSE_FAILED",
"PDF_ENCRYPT_UNAVAILABLE",
"PDF_ENCRYPT_NO_PASSWORD",
"PDF_ENCRYPTED_INPUT",
"PDF_INVALID_INPUT",
"PRESENTATION_HTML_EMPTY",
"BMP_UNSUPPORTED_VARIANT",
"JSON_CSV_PATH_COLLISION",
"PDF_TABLE_OCR_LOW_QUALITY"
].includes(error?.code) || /^(?:MARKDOWN|EPUB|MOBI|OFD)_/.test(error?.code || "");
const isResourceLimitError = error instanceof ResourceLimitError;
const isOfficeEngineError = error instanceof OfficeEngineError || error instanceof OfficePreparationError;
if (isClientConversionError || isResourceLimitError) logger.warn(`Convert rejected: "${originalName}" -> ${requestedTarget}`, error);
else logger.error(`Convert failed: "${originalName}" -> ${requestedTarget}`, error);
await fsp.rm(file.path, { force: true }).catch(() => {});
await fsp.rm(outputPath, { force: true }).catch(() => {});
await fsp.rm(`${outputPath}.assets`, { recursive: true, force: true }).catch(() => {});
const payload = isResourceLimitError ? resourceErrorPayload(error) : { error: error.message || "转换失败。" };
if (error?.code) payload.errorCode = error.code;
if (error?.messages) payload.messages = error.messages;
if (isOfficeEngineError) {
payload.messages = error.messages;
payload.details = error.details;
}
res.status(isResourceLimitError ? 413 : (isClientConversionError ? 422 : 500)).json(payload);
}
});
app.post("/api/downloads/release", assertLocalWebRequest, async (req, res) => {
const ids = req.body?.ids;
if (!Array.isArray(ids) || !ids.length || ids.length > 1000
|| ids.some(id => typeof id !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id))) {
res.status(400).json({ error: "Invalid download IDs." });
return;
}
await releaseDownloads([...new Set(ids)]);
res.json({ ok: true });
});
app.get("/downloads/:id", (req, res) => {
const item = downloads.get(req.params.id);
if (!item || item.discarded) {
res.status(404).send("File expired or not found.");
return;
}
retainDownloadResponse(item, res);
res.download(item.filePath, item.downloadName, (error) => {
if (!error) return;
if (!res.headersSent) res.status(500).send(error.message);
});
});
// md 转换产物的图片外置文件下载:/downloads/<id>/asset/<name>。
// 只允许读取该 downloads 条目登记的 assets 目录内的文件,防止路径穿越。
app.get("/downloads/:id/asset/:name", async (req, res) => {
const item = downloads.get(req.params.id);
if (!item || item.discarded || !/^[A-Za-z0-9-]+$/.test(req.params.id)) {
res.status(404).send("File expired or not found.");
return;
}
const assetsDir = item.assetsDir;
if (!assetsDir) {
res.status(404).send("No assets for this download.");
return;
}
const name = String(req.params.name || "");
if (!name || name.includes("\\") || name.includes("/") || name === "." || name === "..") {
res.status(400).send("Invalid asset name.");
return;
}
const filePath = path.join(assetsDir, name);
retainDownloadResponse(item, res);
try {
const stat = await fsp.stat(filePath);
if (!stat.isFile()) throw new Error("not a file");
} catch {
res.status(404).send("Asset not found.");
return;
}
res.download(filePath, name, (error) => {
if (!error) return;
if (!res.headersSent) res.status(500).send(error.message);
});
});
app.get("/previews/:id", (req, res) => {
const item = downloads.get(req.params.id);
if (!item || item.discarded || !/^[A-Za-z0-9-]+$/.test(req.params.id) || req.originalUrl.includes("?")) {
res.status(404).send("File expired or not found.");
return;
}
retainDownloadResponse(item, res);
const inlineName = encodeURIComponent(path.basename(item.downloadName)).replaceAll("'", "%27");
res.setHeader("Content-Type", item.mimeType || "application/octet-stream");
res.setHeader("Content-Disposition", `inline; filename="preview"; filename*=UTF-8''${inlineName}`);
res.setHeader("X-Content-Type-Options", "nosniff");
if (String(item.mimeType).includes("html")) {
res.setHeader("Content-Security-Policy", "default-src 'none'; img-src data:; style-src 'unsafe-inline'; frame-ancestors 'self'; sandbox");
} else {
res.setHeader("Content-Security-Policy", "default-src 'none'; frame-ancestors 'self'");
}
res.sendFile(path.resolve(item.filePath), (error) => {