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
fix(onenote): import the authored page creation date, not the storage object's
Elian Doran6c7230541e83
diff --git a/apps/server/src/services/import/onenote/converter.spec.ts b/apps/server/src/services/import/onenote/converter.spec.tsindex 89a826db9d..60678edb08 100644--- a/apps/server/src/services/import/onenote/converter.spec.ts+++ b/apps/server/src/services/import/onenote/converter.spec.ts@@ -791,3 +791,17 @@ describe("convertPageHtml", () => {expect(out).toContain("<code>Code</code>");});});++describe("extractPageCreatedDate", () => {+ it("returns the authored timestamp from the document's created meta header", () => {+ expect(converter.extractPageCreatedDate(SAMPLE)).toBe("2020-09-02T09:37:00.0000000");+ });++ it("returns undefined when the meta is absent, empty or unparseable", () => {+ // A body-only document (as placeholder-adjacent captures can be) has no head to read.+ expect(converter.extractPageCreatedDate(FORMATTING_SAMPLE)).toBeUndefined();+ expect(converter.extractPageCreatedDate(`<html><head><meta name="created" content="" /></head><body></body></html>`)).toBeUndefined();+ expect(converter.extractPageCreatedDate(`<html><head><meta name="created" content="not a date" /></head><body></body></html>`)).toBeUndefined();+ expect(converter.extractPageCreatedDate(`<html><head><meta name="created" /></head><body></body></html>`)).toBeUndefined();+ });+});diff --git a/apps/server/src/services/import/onenote/converter.ts b/apps/server/src/services/import/onenote/converter.tsindex cc1eb2d1f3..de6c9b0e68 100644--- a/apps/server/src/services/import/onenote/converter.ts+++ b/apps/server/src/services/import/onenote/converter.ts@@ -123,6 +123,22 @@ export function convertPageHtml(rawHtml: string): string {return sanitize.sanitizeHtml(scope.innerHTML);}+/**+ * Extracts the page's authored creation timestamp from the Graph page document's+ * `<meta name="created">` header, or undefined when the meta is absent or unparseable.+ *+ * This is the creation date OneNote displays under the page title: it lives in the page *content*+ * and survives moves, copies and notebook migrations, whereas the page object's `createdDateTime`+ * metadata is re-stamped by them (a moved page can report an object date years after the authored+ * one). Graph emits the value without a UTC offset (e.g. "2026-07-23T21:28:00.0000000"), i.e. as+ * wall-clock time, so `new Date()` parses it as server-local time — exact when the server runs in+ * the notebook owner's timezone, and still the right day otherwise.+ */+export function extractPageCreatedDate(rawHtml: string): string | undefined {+ const content = parse(rawHtml).querySelector('meta[name="created"]')?.getAttribute("content");+ return content && !Number.isNaN(Date.parse(content)) ? content : undefined;+}+/*** A OneNote page is a free-form canvas of absolutely-positioned text boxes (the top-level outline* <div>s). Their document order need not match their visual order, so reorder them top-to-bottom then@@ -721,4 +737,4 @@ function removeBlockLevelBreaks(scope: HTMLElement) {}}-export default { convertPageHtml };+export default { convertPageHtml, extractPageCreatedDate };diff --git a/apps/server/src/services/import/onenote/importer.spec.ts b/apps/server/src/services/import/onenote/importer.spec.tsindex f94763a970..654c60e09e 100644--- a/apps/server/src/services/import/onenote/importer.spec.ts+++ b/apps/server/src/services/import/onenote/importer.spec.ts@@ -1,4 +1,4 @@-import { becca, cls, note_service as noteService } from "@triliumnext/core";+import { becca, cls, date_utils, note_service as noteService } from "@triliumnext/core";import { beforeAll, describe, expect, it, vi } from "vitest";import sqlInit from "../../sql_init.js";@@ -301,4 +301,38 @@ describe("importSelection (real DB)", () => {expect([...pages.values()].every((note) => note.hasOwnedLabel("oneNoteImportFailed"))).toBe(true);expect([...pages.values()][0]?.getContent()).toContain("could not be imported");});++ it("prefers the authored created date from the page HTML over the Graph object's metadata", async () => {+ // A moved/copied/migrated page: the Graph page *object*'s createdDateTime is re-stamped to the+ // time of the move, while the date OneNote actually displays under the title lives in the page+ // HTML's `<meta name="created">`. The authored date must win; the object date remains the+ // fallback for pages whose HTML carries no meta.+ graphMock.listPages.mockResolvedValue([+ { id: "1-meta", title: "Authored Date Page", level: 0, createdDateTime: "2020-10-20T10:00:00Z", lastModifiedDateTime: "2021-03-04T05:06:07Z" },+ { id: "1-nometa", title: "Fallback Date Page", level: 0, createdDateTime: "2020-10-20T10:00:00Z" }+ ]);+ graphMock.getPageContent.mockImplementation(async (_token, pageId) => ({+ html: pageId === "1-meta"+ ? `<html><head><title>Authored Date Page</title><meta name="created" content="2019-01-19T20:24:00.0000000" /></head><body><p>hi</p></body></html>`+ : "<p>hi</p>",+ inkml: ""+ }));++ await cls.init(() => importSelection({+ getAccessToken: () => Promise.resolve("token"),+ parentNoteId: "root",+ sections: [{ id: "sec-dates", title: "Date Section", groupPath: [], notebookId: "nb-dates", notebookTitle: "Date Notebook" }],+ taskId: "task-authored-dates"+ }));++ const authored = Object.values(becca.notes).find((note) => note.title === "Authored Date Page");+ // The meta value is offset-less wall-clock time and is parsed as server-local, so the expected+ // value goes through the same Date conversion to stay timezone-independent.+ expect(authored?.utcDateCreated).toBe(date_utils.utcDateTimeStr(new Date("2019-01-19T20:24:00.0000000")));+ // The modification date has no in-content counterpart and stays the Graph object's value.+ expect(authored?.utcDateModified).toBe("2021-03-04 05:06:07.000Z");++ const fallback = Object.values(becca.notes).find((note) => note.title === "Fallback Date Page");+ expect(fallback?.utcDateCreated).toBe("2020-10-20 10:00:00.000Z");+ });});diff --git a/apps/server/src/services/import/onenote/importer.ts b/apps/server/src/services/import/onenote/importer.tsindex a4d176f48f..a94533d06f 100644--- a/apps/server/src/services/import/onenote/importer.ts+++ b/apps/server/src/services/import/onenote/importer.ts@@ -40,7 +40,13 @@ interface FetchedPage {resources: DownloadedResource[];/** How many of the page's resources failed to download (skipped, reported in the import report). */failedResourceCount: number;- /** OneNote's page creation timestamp (ISO 8601), preserved on the imported note. */+ /**+ * OneNote's page creation timestamp (ISO 8601), preserved on the imported note. The authored+ * date from the page HTML's `<meta name="created">` when available — the date OneNote itself+ * displays, which survives page moves/copies and notebook migrations — otherwise the Graph+ * page object's `createdDateTime` (re-stamped by those operations; placeholder pages have no+ * HTML to read the authored date from).+ */createdDateTime?: string;/** OneNote's last-modified timestamp (ISO 8601), preserved on the imported note. */lastModifiedDateTime?: string;@@ -134,7 +140,7 @@ export async function importSelection({ getAccessToken, parentNoteId, sections,try {const html = converter.convertPageHtml(rawHtml);const { resources, failedResourceCount } = await downloadPageResources(getAccessToken, page.title, html);- fetchedPages.push({ id: page.id, title: page.title, level: page.level, pageId: page.pageId, html, rawHtml, rawInkml: inkml, inkSvg: inkmlToSvg(inkml), resources, failedResourceCount, createdDateTime: page.createdDateTime, lastModifiedDateTime: page.lastModifiedDateTime });+ fetchedPages.push({ id: page.id, title: page.title, level: page.level, pageId: page.pageId, html, rawHtml, rawInkml: inkml, inkSvg: inkmlToSvg(inkml), resources, failedResourceCount, createdDateTime: converter.extractPageCreatedDate(rawHtml) ?? page.createdDateTime, lastModifiedDateTime: page.lastModifiedDateTime });} catch (e: unknown) {const message = e instanceof Error ? e.message : String(e);getLog().error(`OneNote import: fetched page '${page.title}' (${page.id}) but could not process its content; a placeholder note will be imported instead: ${message}`);