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): skip sections that can't be listed instead of aborting the import
Elian Doran5c1585288a7a
diff --git a/apps/server/src/services/import/onenote/importer.spec.ts b/apps/server/src/services/import/onenote/importer.spec.tsindex 654c60e09e..98f83c1794 100644--- a/apps/server/src/services/import/onenote/importer.spec.ts+++ b/apps/server/src/services/import/onenote/importer.spec.ts@@ -198,6 +198,48 @@ describe("importSelection (real DB)", () => {expect(content).toContain(`href="#root/${badNote?.noteId}"`);});+ it("skips a section whose pages can't be listed, imports the rest, and reports the skip", async () => {+ // One section's page list fails (e.g. it's encrypted/password-protected); the other succeeds.+ graphMock.listPages.mockImplementation(async (_token, sectionId) => {+ if (sectionId === "sec-locked") {+ throw new Error("Microsoft Graph request failed (HTTP 403: 20185: Encrypted sections are not accessible.)");+ }+ return [{ id: "1-ok", title: "Readable Page", level: 0 }];+ });+ graphMock.getPageContent.mockResolvedValue({ html: "<p>hi</p>", inkml: "" });++ const parent = cls.init(() => noteService.createNewNote({+ parentNoteId: "root",+ title: "skip parent",+ content: "",+ type: "text",+ mime: "text/html"+ }).note);++ await cls.init(() => importSelection({+ getAccessToken: () => Promise.resolve("token"),+ parentNoteId: parent.noteId,+ sections: [+ { id: "sec-locked", title: "Locked Section", groupPath: [], notebookId: "nb-skip", notebookTitle: "Skip Notebook" },+ { id: "sec-open", title: "Open Section", groupPath: [], notebookId: "nb-skip", notebookTitle: "Skip Notebook" }+ ],+ taskId: "task-skip"+ }));++ // The readable section still imports: one bad section must not abort the whole import.+ expect(Object.values(becca.notes).find((note) => note.title === "Readable Page")).toBeDefined();+ expect(Object.values(becca.notes).find((note) => note.title === "Open Section")).toBeDefined();+ // The locked section is skipped entirely — no section note, no placeholder.+ expect(Object.values(becca.notes).find((note) => note.title === "Locked Section")).toBeUndefined();++ // The report records the skip (imported/total section count + a dedicated table) and surfaces+ // the Graph error verbatim so the user can see why.+ const content = parent.getChildNotes()[0]?.getContent() as string;+ expect(content).toContain('<tr><th scope="row">Sections imported</th><td>1/2</td></tr>');+ expect(content).toContain("Sections that could not be imported");+ expect(content).toContain("Encrypted sections are not accessible.");+ });+it("preserves the OneNote page order even when #newNotesOnTop is inherited onto the target", async () => {graphMock.listPages.mockResolvedValue([{ id: "1-ord-a", title: "Order Page A", level: 0 },diff --git a/apps/server/src/services/import/onenote/importer.ts b/apps/server/src/services/import/onenote/importer.tsindex a94533d06f..a05a476ca8 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 AccessTokenProvider, type OneNotePage, sanitizeGraphUrl } from "./graph.js";import { inkmlToSvg } from "./inkml.js";import { type LinkTarget, rewritePageLinks } from "./links.js";-import { type FailedPageReport, type ImportReportData, renderImportReport } from "./report.js";+import { type FailedPageReport, type FailedSectionReport, type ImportReportData, renderImportReport } from "./report.js";interface FetchedPage {/**@@ -105,8 +105,19 @@ export async function importSelection({ getAccessToken, parentNoteId, sections,// Enumerate every selected section's pages up front so the total page count is known before// any content is fetched — this lets the client show a real progress bar rather than a bare count.const sectionPages: { section: OneNoteSectionSelection; pages: OneNotePage[] }[] = [];+ const failedSections: FailedSectionReport[] = [];for (const section of sections) {- sectionPages.push({ section, pages: await graph.listPages(getAccessToken, section.id) });+ // A section whose page list can't be fetched is skipped rather than aborting the whole+ // import: the remaining sections still import, and the skipped section is recorded in the+ // import report. This covers e.g. encrypted/password-protected sections — which Graph+ // rejects outright — as well as any other per-section Graph failure.+ try {+ sectionPages.push({ section, pages: await graph.listPages(getAccessToken, section.id) });+ } catch (e: unknown) {+ const message = e instanceof Error ? e.message : String(e);+ getLog().error(`OneNote import: could not list the pages of section '${section.title}' (${section.id}); skipping the section: ${message}`);+ failedSections.push({ title: section.title, notebookTitle: section.notebookTitle, error: message });+ }}taskContext.setTotalCount(sectionPages.reduce((total, entry) => total + entry.pages.length, 0));@@ -162,7 +173,7 @@ export async function importSelection({ getAccessToken, parentNoteId, sections,}// Phase 2: create the note tree.- const rootNoteId = sql.transactional(() => createNotes(parentNoteId, fetched, debug, shrinkImages, startedAtMs));+ const rootNoteId = sql.transactional(() => createNotes(parentNoteId, fetched, failedSections, debug, shrinkImages, startedAtMs));taskContext.taskSucceeded({ parentNoteId, importedNoteId: rootNoteId });} catch (e: unknown) {@@ -177,7 +188,7 @@ function buildPlaceholderPage(page: OneNotePage, error: string): FetchedPage {return { id: page.id, title: page.title, level: page.level, pageId: page.pageId, html: "", rawHtml: "", rawInkml: "", inkSvg: null, resources: [], failedResourceCount: 0, fetchError: error, createdDateTime: page.createdDateTime, lastModifiedDateTime: page.lastModifiedDateTime };}-function createNotes(parentNoteId: string, sections: FetchedSection[], debug: boolean, shrinkImages: boolean, startedAtMs: number): string {+function createNotes(parentNoteId: string, sections: FetchedSection[], failedSections: FailedSectionReport[], debug: boolean, shrinkImages: boolean, startedAtMs: number): string {const parentNote = becca.getNoteOrThrow(parentNoteId);const isProtected = parentNote.isProtected && protectedSession.isProtectedSessionAvailable();@@ -335,6 +346,7 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], debug: bounresolvedLinkCount,throttledRequestCount: throttleStats.requestCount,throttleWaitMs: throttleStats.waitMs,+ failedSections,failedPages,failedResources: allPages.filter(({ page }) => page.failedResourceCount > 0)diff --git a/apps/server/src/services/import/onenote/report.spec.ts b/apps/server/src/services/import/onenote/report.spec.tsindex 1483f4ebb6..b802233780 100644--- a/apps/server/src/services/import/onenote/report.spec.ts+++ b/apps/server/src/services/import/onenote/report.spec.ts@@ -20,6 +20,7 @@ function reportData(overrides: Partial<ImportReportData> = {}): ImportReportDatathrottleWaitMs: 3 * 60_000,failedPages: [],failedResources: [],+ failedSections: [],...overrides};}@@ -99,6 +100,22 @@ describe("renderImportReport", () => {expect(html).toContain("HTTP 504");});+ it("lists skipped sections and shows the section count as imported/total", () => {+ const html = renderImportReport(reportData({+ sectionCount: 2,+ failedSections: [+ { title: "Secret <plans>", notebookTitle: "Work & Home", error: "Microsoft Graph request failed (HTTP 403: 20185: Encrypted sections are not accessible.)" }+ ]+ }));++ // 2 imported of 3 selected: the skipped section is folded into the denominator.+ expect(html).toContain('<tr><th scope="row">Sections imported</th><td>2/3</td></tr>');+ expect(html).toContain("Sections that could not be imported");+ expect(html).toContain("<td>Secret <plans></td>");+ expect(html).toContain("<td>Work & Home</td>");+ expect(html).toContain("Encrypted sections are not accessible.");+ });+it("lists pages with failed resource downloads, with per-page counts", () => {const html = renderImportReport(reportData({failedResources: [diff --git a/apps/server/src/services/import/onenote/report.ts b/apps/server/src/services/import/onenote/report.tsindex 5ffe069db4..ebe3a287f1 100644--- a/apps/server/src/services/import/onenote/report.ts+++ b/apps/server/src/services/import/onenote/report.ts@@ -16,6 +16,17 @@ export interface FailedPageReport {error: string;}+/**+ * A section whose page list could not be fetched, so the whole section was skipped (no notes created+ * for it). Unlike a failed page there is no placeholder note to link to — the section left no trace in+ * the tree — so only its title, notebook (for disambiguation) and the error are recorded.+ */+export interface FailedSectionReport {+ title: string;+ notebookTitle: string;+ error: string;+}+/** A page for which one or more image/attachment downloads failed (the page itself was imported). */export interface FailedResourceReport {pageTitle: string;@@ -42,6 +53,8 @@ export interface ImportReportData {throttleWaitMs: number;failedPages: FailedPageReport[];failedResources: FailedResourceReport[];+ /** Sections skipped entirely because their page list could not be fetched. */+ failedSections: FailedSectionReport[];}export function renderImportReport(data: ImportReportData): string {@@ -49,6 +62,14 @@ export function renderImportReport(data: ImportReportData): string {parts.push(renderSummaryTable(data));+ if (data.failedSections.length > 0) {+ const rows = data.failedSections.map((section) =>+ `<tr><td>${utils.escapeHtml(section.title)}</td><td>${utils.escapeHtml(section.notebookTitle)}</td><td>${utils.escapeHtml(section.error)}</td></tr>`);+ parts.push(`<h2>${t("onenote_import.report.skipped-sections-title")}</h2>`+ + `<figure class="table"><table><thead><tr><th>${t("onenote_import.report.skipped-sections-section")}</th><th>${t("onenote_import.report.skipped-sections-notebook")}</th><th>${t("onenote_import.report.skipped-sections-error")}</th></tr></thead>`+ + `<tbody>${rows.join("")}</tbody></table></figure>`);+ }+if (data.failedPages.length > 0) {const rows = data.failedPages.map((page) =>`<tr><td>${noteLink(page.noteId, page.title)}</td><td>${utils.escapeHtml(page.sectionTitle)}</td><td>${utils.escapeHtml(page.error)}</td></tr>`);@@ -79,7 +100,7 @@ function renderSummaryTable(data: ImportReportData): string {const rows: [string, string | number][] = [[t("onenote_import.report.row-pages"), `${data.importedPageCount}/${totalPageCount} (${successPercent}%)`],[t("onenote_import.report.row-notebooks"), data.notebookCount],- [t("onenote_import.report.row-sections"), data.sectionCount],+ [t("onenote_import.report.row-sections"), data.failedSections.length > 0 ? `${data.sectionCount}/${data.sectionCount + data.failedSections.length}` : data.sectionCount],[t("onenote_import.report.row-duration"), formatDuration(data.durationMs)]];if (data.imageCount > 0) {