Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(import/zip): support GBK encoding (closes #9678)
Elian Doran36ea6c5f594e
diff --git a/apps/server/src/services/import/samples/gbk-support.zip b/apps/server/src/services/import/samples/gbk-support.zipnew file mode 100644index 0000000000..6dd9ff7b74Binary files /dev/null and b/apps/server/src/services/import/samples/gbk-support.zip differdiff --git a/apps/server/src/services/import/zip.spec.ts b/apps/server/src/services/import/zip.spec.tsindex 21e4b19e14..6c2cd3a86a 100644--- a/apps/server/src/services/import/zip.spec.ts+++ b/apps/server/src/services/import/zip.spec.ts@@ -76,6 +76,15 @@ describe("processNoteContent", () => {expect(importedNote.title).toBe("测试");});+ it("can import ZIP with GBK-encoded filenames (Chinese Windows)", async () => {+ const { rootNote } = await testImport("gbk-support.zip");+ const children = rootNote.getChildNotes().map((n) => n.title);+ expect(children).toContain("测试文件.txt");+ expect(children).toContain("中文目录");+ const dirNote = rootNote.getChildNotes().find((n) => n.title === "中文目录")!;+ expect(dirNote.getChildNotes().map((n) => n.title)).toContain("子文件.txt");+ });+it("can import old geomap notes", async () => {const { importedNote } = await testImport("geomap.zip");expect(importedNote.type).toBe("book");diff --git a/apps/server/src/services/import/zip.ts b/apps/server/src/services/import/zip.tsindex e4a0dfbd98..0d759f6fb4 100644--- a/apps/server/src/services/import/zip.ts+++ b/apps/server/src/services/import/zip.ts@@ -3,6 +3,7 @@import { ALLOWED_NOTE_TYPES, type NoteType } from "@triliumnext/commons";import path from "path";import type { Stream } from "stream";+import chardet from "chardet";import yauzl from "yauzl";import becca from "../../becca/becca.js";@@ -560,6 +561,9 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: Bu}}+ // Detect filename encoding once for the whole ZIP (e.g. GBK for Chinese Windows ZIPs)+ const filenameEncoding = await detectZipFilenameEncoding(fileBuffer);+// we're running two passes in order to obtain critical information first (meta file and root)const topLevelItems = new Set<string>();await readZipFile(fileBuffer, async (zipfile: yauzl.ZipFile, entry: yauzl.Entry) => {@@ -578,7 +582,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: ButopLevelItems.add(topLevelPath);zipfile.readEntry();- });+ }, filenameEncoding);topLevelPath = (topLevelItems.size > 1 ? "" : topLevelItems.values().next().value ?? "");@@ -595,7 +599,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: ButaskContext.increaseProgressCount();zipfile.readEntry();- });+ }, filenameEncoding);for (const noteId of createdNoteIds) {const note = becca.getNote(noteId);@@ -661,7 +665,39 @@ export function readContent(zipfile: yauzl.ZipFile, entry: yauzl.Entry): Promise});}-export function readZipFile(buffer: Buffer, processEntryCallback: (zipfile: yauzl.ZipFile, entry: yauzl.Entry) => Promise<void>) {+/**+ * Detects the filename encoding used in a ZIP file by collecting all+ * non-UTF-8-flagged entry names and running charset detection on them.+ * Returns the detected encoding label (usable with TextDecoder), or "utf-8" as fallback.+ */+function detectZipFilenameEncoding(buffer: Buffer): Promise<string> {+ return new Promise<string>((res, rej) => {+ yauzl.fromBuffer(buffer, { lazyEntries: true, validateEntrySizes: false, decodeStrings: false }, (err, zipfile) => {+ if (err) return rej(err);+ if (!zipfile) return rej(new Error("Unable to read zip file."));++ const samples: Buffer[] = [];+ zipfile.readEntry();+ zipfile.on("entry", (entry) => {+ const isUtf8Flagged = !!(entry.generalPurposeBitFlag & 0x800);+ if (!isUtf8Flagged && Buffer.isBuffer(entry.fileName)) {+ samples.push(entry.fileName as Buffer);+ }+ zipfile.readEntry();+ });+ zipfile.on("end", () => {+ if (samples.length === 0) {+ return res("utf-8");+ }+ const combined = Buffer.concat(samples);+ const detected = chardet.detect(combined);+ res(detected || "utf-8");+ });+ });+ });+}++export function readZipFile(buffer: Buffer, processEntryCallback: (zipfile: yauzl.ZipFile, entry: yauzl.Entry) => Promise<void>, filenameEncoding?: string) {return new Promise<void>((res, rej) => {yauzl.fromBuffer(buffer, { lazyEntries: true, validateEntrySizes: false, decodeStrings: false }, (err, zipfile) => {if (err) rej(err);@@ -670,11 +706,10 @@ export function readZipFile(buffer: Buffer, processEntryCallback: (zipfile: yauzzipfile.readEntry();zipfile.on("entry", async (entry) => {try {- // yauzl with decodeStrings: false returns fileName as a Buffer.- // We decode as UTF-8 to handle ZIP files that use UTF-8 filenames- // without setting the general purpose bit flag 11 (language encoding flag).if (Buffer.isBuffer(entry.fileName)) {- entry.fileName = (entry.fileName as Buffer).toString("utf-8");+ const isUtf8Flagged = !!(entry.generalPurposeBitFlag & 0x800);+ const encoding = isUtf8Flagged ? "utf-8" : (filenameEncoding || "utf-8");+ entry.fileName = decodeBuffer(entry.fileName as Buffer, encoding);}await processEntryCallback(zipfile, entry);@@ -687,6 +722,15 @@ export function readZipFile(buffer: Buffer, processEntryCallback: (zipfile: yauz});}+function decodeBuffer(buf: Buffer, encoding: string): string {+ try {+ return new TextDecoder(encoding).decode(buf);+ } catch {+ // Fallback if the encoding label isn't supported by TextDecoder+ return buf.toString("utf-8");+ }+}+function resolveNoteType(type: string | undefined): NoteType {// BC for ZIPs created in Trilium 0.57 and olderswitch (type) {