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): preserve Obsidian note dates from the zip entry mtime
Elian Doran5b58c26f0da7
diff --git a/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts b/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.tsindex 67325477cf..f3052603e3 100644--- a/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts+++ b/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts@@ -10,15 +10,15 @@ import TaskContext from "../../task_context.js";import { decodeUtf8 } from "../../utils/binary.js";import obsidianImporter from "./importer.js";-/** Builds an in-memory zip from a map of entry name -> contents. */-async function createZipBuffer(files: Record<string, string | Buffer>): Promise<Buffer> {+/** Builds an in-memory zip from a map of entry name -> contents, optionally stamping per-entry mtimes. */+async function createZipBuffer(files: Record<string, string | Buffer>, dates: Record<string, Date> = {}): Promise<Buffer> {const archive = new ZipArchive();const chunks: Buffer[] = [];const passthrough = new PassThrough();passthrough.on("data", (chunk: Buffer) => chunks.push(chunk));archive.pipe(passthrough);for (const [name, content] of Object.entries(files)) {- archive.append(content, { name });+ archive.append(content, { name, date: dates[name] });}await archive.finalize();return Buffer.concat(chunks);@@ -31,8 +31,8 @@ function excalidrawFile(scene: object, embeddedFiles = ""): string {}/** Runs the Obsidian importer over `files` and returns the import root note. */-async function importObsidian(files: Record<string, string | Buffer>, fileName?: string): Promise<BNote> {- const buffer = await createZipBuffer(files);+async function importObsidian(files: Record<string, string | Buffer>, fileName?: string, dates?: Record<string, Date>): Promise<BNote> {+ const buffer = await createZipBuffer(files, dates);const taskContext = TaskContext.getInstance("obsidian-integration", "importNotes", { safeImport: true });return new Promise<BNote>((resolve, reject) => {@@ -149,6 +149,21 @@ describe("Obsidian importer — integration", () => {expect(note.getOwnedLabelValue("label:checkboxProp")).toBe("promoted,single,boolean,alias=Checkbox prop");});+ it("preserves a note's modification date from its zip entry, with created falling back to it", async () => {+ const importRoot = await importObsidian({ "Note.md": "Body." }, undefined, { "Note.md": new Date(2020, 5, 15, 12, 30, 0) });++ const note = importRoot.getChildNotes().find((n) => n.title === "Note");+ if (!note) {+ throw new Error("note was not imported");+ }+ // The date comes from the zip entry (2020), not the import time, and created falls back to modified.+ // Exact-instant fidelity isn't asserted: archiver (writing) and yauzl (reading) interpret DOS time+ // zones differently, so this synthetic round-trip skews by the local offset — real OS-written zips+ // store local DOS time that yauzl reads back correctly.+ expect(note.utcDateModified?.startsWith("2020-")).toBe(true);+ expect(note.utcDateCreated).toBe(note.utcDateModified);+ });+it("converts ==highlights== to a coloured span and %%comments%% to dropped HTML comments", async () => {const importRoot = await importObsidian({"Note.md": "A ==highlight== and a %%hidden%% comment."diff --git a/packages/trilium-core/src/services/import/obsidian/importer.ts b/packages/trilium-core/src/services/import/obsidian/importer.tsindex e11b4c2539..3fc36c0efa 100644--- a/packages/trilium-core/src/services/import/obsidian/importer.ts+++ b/packages/trilium-core/src/services/import/obsidian/importer.ts@@ -34,6 +34,7 @@ import noteService from "../../notes.js";import protectedSessionService from "../../protected_session.js";import type TaskContext from "../../task_context.js";import { decodeUtf8 } from "../../utils/binary.js";+import date_utils from "../../utils/date.js";import { basename } from "../../utils/path.js";import { getZipProvider } from "../../zip_provider.js";import { buildPromotedDefinition, toAttributeName } from "../collection_utils.js";@@ -48,6 +49,8 @@ interface VaultNote {path: string;title: string;markdown: string;+ /** The zip entry's modification time, when the reader exposes it (the standalone reader doesn't). */+ modified?: Date;}async function importObsidian(taskContext: TaskContext<"importNotes">, fileBuffer: Uint8Array, importRootNote: BNote, fileName?: string): Promise<BNote> {@@ -66,7 +69,7 @@ async function importObsidian(taskContext: TaskContext<"importNotes">, fileBuffeasync function parseVault(fileBuffer: Uint8Array): Promise<{ notes: VaultNote[]; attachments: Map<string, Uint8Array>; types: Map<string, string>; vaultRoot: string }> {const provider = getZipProvider();const allPaths: string[] = [];- const raw: { path: string; markdown: string }[] = [];+ const raw: { path: string; markdown: string; modified?: Date }[] = [];const rawAttachments: { path: string; bytes: Uint8Array }[] = [];let typesJson = "";const filenameEncoding = await provider.detectFilenameEncoding(fileBuffer);@@ -87,7 +90,7 @@ async function parseVault(fileBuffer: Uint8Array): Promise<{ notes: VaultNote[];return;}if (isMarkdown(path)) {- raw.push({ path, markdown: decodeUtf8(await readContent()) });+ raw.push({ path, markdown: decodeUtf8(await readContent()), modified: entry.lastModified });} else if (!isSpecial(path)) {// A non-Markdown, non-special file is a candidate attachment (`.canvas`/`.base` are handled later).rawAttachments.push({ path, bytes: await readContent() });@@ -95,9 +98,9 @@ async function parseVault(fileBuffer: Uint8Array): Promise<{ notes: VaultNote[];}, filenameEncoding);const vaultRoot = detectVaultRoot(allPaths);- const notes = raw.map(({ path, markdown }) => {+ const notes = raw.map(({ path, markdown, modified }) => {const relative = stripVaultRoot(path, vaultRoot);- return { path: relative, title: noteTitle(relative), markdown };+ return { path: relative, title: noteTitle(relative), markdown, modified };});notes.sort((a, b) => a.path.localeCompare(b.path));@@ -125,7 +128,7 @@ function createNotes(importRootNote: BNote, notes: VaultNote[], attachments: Mapconst shrinkImages = !!taskContext.data?.shrinkImages;// Folder path (POSIX) -> its container note. The empty path maps to the import root.const folderNotes = new Map<string, BNote>();- const created: { note: BNote; path: string; rendered: string; content: string }[] = [];+ const created: { note: BNote; path: string; rendered: string; content: string; modified?: Date }[] = [];// First pass: create every note (so cross-note links can resolve below) with its Markdown rendered and// attachments saved. Content is persisted once, in the link pass, to avoid a second write per note.@@ -138,7 +141,7 @@ function createNotes(importRootNote: BNote, notes: VaultNote[], attachments: Mapif (isExcalidrawPath(vaultNote.path)) {const note = createExcalidrawNote(parent, vaultNote, attachmentIndex, isProtected);if (note) {- created.push({ note, path: vaultNote.path.replace(/\.excalidraw\.md$/i, ""), rendered: "", content: "" });+ created.push({ note, path: vaultNote.path.replace(/\.excalidraw\.md$/i, ""), rendered: "", content: "", modified: vaultNote.modified });taskContext.increaseProgressCount();continue;}@@ -158,14 +161,14 @@ function createNotes(importRootNote: BNote, notes: VaultNote[], attachments: Map// Attachments hang off the note, so this runs after creation; it returns the content with embedded// images/files rewritten to point at the saved attachments.const content = applyAttachments(note, rendered, attachmentIndex, shrinkImages);- created.push({ note, path: vaultNote.path, rendered, content });+ created.push({ note, path: vaultNote.path, rendered, content, modified: vaultNote.modified });taskContext.increaseProgressCount();}// Second pass: now that every note's name -> id is known, resolve wikilinks and note embeds to Trilium// internal links / include-notes, recording the relations that drive backlinks and "what links here".const noteIndex = buildNoteIndex(created);- for (const { note, rendered, content } of created) {+ for (const { note, rendered, content, modified } of created) {const { html, internalLinks, includeLinks } = resolveLinks(content, noteIndex);if (html !== rendered) {note.setContent(html);@@ -176,6 +179,14 @@ function createNotes(importRootNote: BNote, notes: VaultNote[], attachments: Mapfor (const target of includeLinks) {note.addRelation("includeNoteLink", target);}++ // Preserve the file's modification time from the zip. ZIP carries no reliable creation time, so+ // created falls back to it. Runs last, after the content writes above which would re-stamp "now".+ // (Guard the DOS-epoch sentinel a date-less entry yields.)+ if (modified && modified.getFullYear() > 1980) {+ const utc = date_utils.utcDateTimeStr(modified);+ note.setDateCreatedAndModified(utc, utc);+ }}return rootNote;diff --git a/packages/trilium-core/src/services/zip_provider.ts b/packages/trilium-core/src/services/zip_provider.tsindex b59eadfd71..8910cfa43a 100644--- a/packages/trilium-core/src/services/zip_provider.ts+++ b/packages/trilium-core/src/services/zip_provider.ts@@ -1,5 +1,10 @@export interface ZipEntry {fileName: string;+ /**+ * The entry's last-modification time, when the provider can read it (the server's reader does; the+ * standalone/WASM reader currently can't, so it's left undefined). ZIP carries no reliable creation time.+ */+ lastModified?: Date;}export interface ZipArchiveEntryOptions {