Skip to content

Build your personal knowledge base with Trilium Notes

feat(server): import a placeholder note for OneNote pages that fail to fetch

Elian Doran70f17a24683d
diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.json
index c5d1497713..79888af14c 100644
--- a/apps/server/src/assets/translations/en/server.json
+++ b/apps/server/src/assets/translations/en/server.json
@@ -330,6 +330,7 @@
},
"onenote_import": {
"root-title": "OneNote import",
+ "failed-page-placeholder": "This page could not be imported from OneNote. Error: {{error}}",
"report": {
"row-pages": "Pages imported successfully",
"row-notebooks": "Notebooks imported",
diff --git a/apps/server/src/services/import/onenote/importer.spec.ts b/apps/server/src/services/import/onenote/importer.spec.ts
index 4fcce24536..ee752f4d56 100644
--- a/apps/server/src/services/import/onenote/importer.spec.ts
+++ b/apps/server/src/services/import/onenote/importer.spec.ts
@@ -137,4 +137,81 @@ describe("importSelection (real DB)", () => {
expect(content).not.toContain("could not be");
expect(content).not.toContain("Images");
});
+
+ it("imports a placeholder note when a page's content cannot be fetched, keeping the tree intact", async () => {
+ graphMock.listPages.mockResolvedValue([
+ { id: "1-good", title: "Ph Good", level: 0 },
+ { id: "1-bad", title: "Ph Bad", level: 0 },
+ { id: "1-sub", title: "Ph Sub", level: 1 }
+ ]);
+ graphMock.getPageContent.mockImplementation(async (_token, pageId) => {
+ if (pageId === "1-bad") {
+ throw new Error("Failed to fetch OneNote page content (HTTP 504)");
+ }
+ return { html: "<p>ok</p>", inkml: "" };
+ });
+
+ const parent = cls.init(() => noteService.createNewNote({
+ parentNoteId: "root",
+ title: "placeholder parent",
+ content: "",
+ type: "text",
+ mime: "text/html"
+ }).note);
+
+ await cls.init(() => importSelection({
+ accessToken: "token",
+ parentNoteId: parent.noteId,
+ sections: [{ id: "sec-3", title: "Ph Section", groupPath: [], notebookId: "nb-3", notebookTitle: "Ph Notebook" }],
+ taskId: "task-placeholder"
+ }));
+
+ // The failed page becomes a placeholder note: findable by label, explains itself, and keeps
+ // the page id so a later retry pass can re-fetch it.
+ const badNote = Object.values(becca.notes).find((note) => note.title === "Ph Bad");
+ expect(badNote?.hasOwnedLabel("oneNoteImportFailed")).toBe(true);
+ expect(badNote?.getOwnedLabelValue("oneNotePageId")).toBe("1-bad");
+ expect(badNote?.getContent()).toContain("could not be imported");
+ expect(badNote?.getContent()).toContain("HTTP 504");
+
+ // Subpage nesting resolves by index, so the placeholder must hold its parent spot in the tree.
+ const subNote = Object.values(becca.notes).find((note) => note.title === "Ph Sub");
+ expect(subNote?.getParentNotes()[0]?.noteId).toBe(badNote?.noteId);
+
+ // The report counts the loss and links to the placeholder.
+ const content = parent.getChildNotes()[0]?.getContent() as string;
+ expect(content).toContain('<tr><th scope="row">Pages imported successfully</th><td>2/3 (66%)</td></tr>');
+ expect(content).toContain("Pages that could not be imported");
+ expect(content).toContain(`href="#root/${badNote?.noteId}"`);
+ });
+
+ it("aborts the import when too many consecutive pages fail (systemic failure)", async () => {
+ graphMock.listPages.mockResolvedValue(
+ Array.from({ length: 8 }, (_, i) => ({ id: `1-cb${i}`, title: `CB Page ${i}`, level: 0 }))
+ );
+ graphMock.getPageContent.mockClear();
+ graphMock.getPageContent.mockImplementation(async () => {
+ throw new Error("Failed to fetch OneNote page content (HTTP 504)");
+ });
+
+ const parent = cls.init(() => noteService.createNewNote({
+ parentNoteId: "root",
+ title: "circuit breaker parent",
+ content: "",
+ type: "text",
+ mime: "text/html"
+ }).note);
+
+ await cls.init(() => importSelection({
+ accessToken: "token",
+ parentNoteId: parent.noteId,
+ sections: [{ id: "sec-4", title: "CB Section", groupPath: [], notebookId: "nb-4", notebookTitle: "CB Notebook" }],
+ taskId: "task-circuit-breaker"
+ }));
+
+ // Six consecutive failures trip the breaker: the remaining pages are never fetched and the
+ // import aborts without creating any notes (a placeholder-only tree would be worthless).
+ expect(graphMock.getPageContent).toHaveBeenCalledTimes(6);
+ expect(parent.getChildNotes()).toHaveLength(0);
+ });
});
diff --git a/apps/server/src/services/import/onenote/importer.ts b/apps/server/src/services/import/onenote/importer.ts
index 3f7d38f72c..ca45d7eecd 100644
--- a/apps/server/src/services/import/onenote/importer.ts
+++ b/apps/server/src/services/import/onenote/importer.ts
@@ -15,7 +15,7 @@ import converter, { ONENOTE_ATTACHMENT_CLASS } from "./converter.js";
import graph, { type OneNotePage } from "./graph.js";
import { inkmlToSvg } from "./inkml.js";
import { type LinkTarget, rewritePageLinks } from "./links.js";
-import { type ImportReportData, renderImportReport } from "./report.js";
+import { type FailedPageReport, type ImportReportData, renderImportReport } from "./report.js";
interface FetchedPage {
/**
@@ -44,8 +44,21 @@ interface FetchedPage {
createdDateTime?: string;
/** OneNote's last-modified timestamp (ISO 8601), preserved on the imported note. */
lastModifiedDateTime?: string;
+ /**
+ * Set when the page's content could not be fetched (after retries). The page is imported as a
+ * placeholder note carrying this error instead of aborting the whole import: one poisoned page
+ * must not cost the user hours of already-fetched work.
+ */
+ fetchError?: string;
}
+/**
+ * Aborts the import once this many pages in a row fail to fetch. A streak this long means the
+ * failure is systemic (expired token, service outage) rather than page-specific, and failing fast
+ * beats producing a tree of nothing but placeholders. Mirrors the Obsidian importer's threshold.
+ */
+const MAX_CONSECUTIVE_PAGE_FAILURES = 5;
+
interface DownloadedResource {
/** The Graph resource URL as it still appears in the converted HTML; used to match references. */
url: string;
@@ -92,13 +105,25 @@ export async function importSelection({ accessToken, parentNoteId, sections, tas
taskContext.setTotalCount(sectionPages.reduce((total, entry) => total + entry.pages.length, 0));
const fetched: FetchedSection[] = [];
+ let consecutivePageFailures = 0;
for (const { section, pages } of sectionPages) {
const fetchedPages: FetchedPage[] = [];
for (const page of pages) {
- const { html: rawHtml, inkml } = await graph.getPageContent(accessToken, page.id);
- const html = converter.convertPageHtml(rawHtml);
- const { resources, failedResourceCount } = await downloadPageResources(accessToken, 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 });
+ try {
+ const { html: rawHtml, inkml } = await graph.getPageContent(accessToken, page.id);
+ const html = converter.convertPageHtml(rawHtml);
+ const { resources, failedResourceCount } = await downloadPageResources(accessToken, 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 });
+ consecutivePageFailures = 0;
+ } catch (e: unknown) {
+ consecutivePageFailures++;
+ const message = e instanceof Error ? e.message : String(e);
+ getLog().error(`OneNote import: could not fetch page '${page.title}' (${page.id}); a placeholder note will be imported instead: ${message}`);
+ if (consecutivePageFailures > MAX_CONSECUTIVE_PAGE_FAILURES) {
+ throw new Error(`Aborting the OneNote import: ${consecutivePageFailures} pages in a row failed to fetch, which points to a systemic problem rather than individual broken pages. Last error: ${message}`);
+ }
+ fetchedPages.push({ id: page.id, title: page.title, level: page.level, pageId: page.pageId, html: "", rawHtml: "", rawInkml: "", inkSvg: null, resources: [], failedResourceCount: 0, fetchError: message, createdDateTime: page.createdDateTime, lastModifiedDateTime: page.lastModifiedDateTime });
+ }
taskContext.increaseProgressCount();
}
fetched.push({
@@ -138,6 +163,7 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], debug: bo
// page's OneNote page-id GUID to its imported note (and title) — both feed the link-resolution pass.
const createdPages: { note: BNote; original: string; content: string; page: FetchedPage }[] = [];
const targetByPageId = new Map<string, LinkTarget>();
+ const failedPages: FailedPageReport[] = [];
// Recreate the OneNote hierarchy as folder notes: a folder per notebook, then a folder per section
// group on the path down to the section, then the section itself. Folders are keyed by their OneNote
@@ -178,13 +204,27 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], debug: bo
const { note: pageNote } = noteService.createNewNote({
parentNoteId: parentIndex >= 0 ? (pageNoteIds[parentIndex] ?? sectionNote.noteId) : sectionNote.noteId,
title: page.title,
- content: page.html,
+ content: page.fetchError === undefined ? page.html : renderFailedPagePlaceholder(page.fetchError),
type: "text",
mime: "text/html",
isProtected
});
pageNoteIds[index] = pageNote.noteId;
pageNote.addLabel("oneNotePageId", page.id);
+ if (page.pageId) {
+ // Registered for placeholders too, so other pages' links to a failed page resolve to it.
+ targetByPageId.set(page.pageId, { noteId: pageNote.noteId, title: page.title });
+ }
+
+ if (page.fetchError !== undefined) {
+ // A placeholder rather than a gap: it holds the page's spot in the tree (subpages
+ // resolve their parent by index), keeps the OneNote timestamps, and is findable by
+ // label. The dates are applied here because placeholders skip the second pass below.
+ pageNote.addLabel("oneNoteImportFailed");
+ failedPages.push({ title: page.title, sectionTitle: section.title, noteId: pageNote.noteId, error: page.fetchError });
+ applyOriginalDates(pageNote, page.createdDateTime, page.lastModifiedDateTime);
+ continue;
+ }
// Resources and ink both need the page note to exist (attachments hang off it), so build
// the per-page content now: swap Graph URLs for local attachment references, then append
@@ -199,9 +239,6 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], debug: bo
}
createdPages.push({ note: pageNote, original: page.html, content, page });
- if (page.pageId) {
- targetByPageId.set(page.pageId, { noteId: pageNote.noteId, title: page.title });
- }
// Debug aid: keep the unmodified Graph HTML (and InkML, when present) alongside the
// converted note so the two can be compared when diagnosing conversion issues.
@@ -266,8 +303,7 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], debug: bo
unresolvedLinkCount,
throttledRequestCount: throttleStats.requestCount,
throttleWaitMs: throttleStats.waitMs,
- // Filled in once fetch failures skip the page instead of aborting the import.
- failedPages: [],
+ failedPages,
failedResources: allPages
.filter(({ page }) => page.failedResourceCount > 0)
.map(({ note, page }) => ({ pageTitle: page.title, pageNoteId: note.noteId, failedCount: page.failedResourceCount }))
@@ -277,6 +313,11 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], debug: bo
return rootNote.noteId;
}
+/** The body of a placeholder note standing in for a page whose content could not be fetched. */
+function renderFailedPagePlaceholder(error: string): string {
+ return `<p>${t("onenote_import.failed-page-placeholder", { error })}</p>`;
+}
+
/** Totals `value` over every downloaded page resource of the given kind. */
function sumResources(pages: { page: FetchedPage }[], kind: DownloadedResource["kind"], value: (resource: DownloadedResource) => number): number {
let sum = 0;