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(onenote): import unreadable sections as placeholder folders instead of dropping them
Elian Doranad8286d1b660
diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.jsonindex 18573c384f..536b59c458 100644--- a/apps/server/src/assets/translations/en/server.json+++ b/apps/server/src/assets/translations/en/server.json@@ -331,6 +331,7 @@"onenote_import": {"root-title": "OneNote import","failed-page-placeholder": "This page could not be imported from OneNote. Error: {{error}}",+ "failed-section-placeholder": "This section could not be imported from OneNote, so it was created empty. This often means the section is password-protected — unlock it in OneNote and import again. 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.tsindex 98f83c1794..8ce1e389de 100644--- a/apps/server/src/services/import/onenote/importer.spec.ts+++ b/apps/server/src/services/import/onenote/importer.spec.ts@@ -198,8 +198,10 @@ 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.+ it("imports a placeholder folder for a section whose pages can't be listed, keeping order and the rest", async () => {+ // The first (locked) section's page list fails, e.g. it's encrypted/password-protected; the+ // second succeeds. The locked section is ordered first to prove it doesn't abort the rest and+ // that its placeholder keeps its position.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.)");@@ -228,15 +230,32 @@ describe("importSelection (real DB)", () => {// 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.+ // The locked section becomes an empty placeholder folder: self-explaining, labeled, and keeping+ // the section id so a later retry pass can re-fetch it.+ const lockedNote = Object.values(becca.notes).find((note) => note.title === "Locked Section");+ expect(lockedNote?.hasOwnedLabel("oneNoteImportFailed")).toBe(true);+ expect(lockedNote?.getOwnedLabelValue("oneNoteSectionId")).toBe("sec-locked");+ expect(lockedNote?.getContent()).toContain("could not be imported");+ expect(lockedNote?.getContent()).toContain("Encrypted sections are not accessible.");+ expect(lockedNote?.getChildNotes()).toHaveLength(0);++ // Order is preserved: both sections share a notebook folder, and the locked placeholder keeps+ // its selected position ahead of the readable section.+ const notebookNote = lockedNote?.getParentNotes()[0];+ const orderedSectionTitles = notebookNote+ ?.getChildBranches()+ .slice()+ .sort((a, b) => a.notePosition - b.notePosition)+ .map((branch) => branch.getNote().title);+ expect(orderedSectionTitles).toEqual(["Locked Section", "Open Section"]);++ // The report records it (imported/total section count + a dedicated table linking to the+ // placeholder) and surfaces the Graph error verbatim.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(`href="#root/${lockedNote?.noteId}"`);expect(content).toContain("Encrypted sections are not accessible.");});diff --git a/apps/server/src/services/import/onenote/importer.ts b/apps/server/src/services/import/onenote/importer.tsindex a05a476ca8..8d99d5df38 100644--- a/apps/server/src/services/import/onenote/importer.ts+++ b/apps/server/src/services/import/onenote/importer.ts@@ -76,6 +76,9 @@ interface DownloadedResource {}interface FetchedSection {+ /** The Graph API section id, preserved on the section note (as `#oneNoteSectionId`) when the+ * section is imported as a placeholder, so a later "retry failed sections" pass can re-fetch it. */+ id: string;title: string;createdDateTime?: string;lastModifiedDateTime?: string;@@ -85,6 +88,13 @@ interface FetchedSection {notebookCreatedDateTime?: string;notebookLastModifiedDateTime?: string;pages: FetchedPage[];+ /**+ * Set when the section's page list could not be fetched (e.g. an encrypted/password-protected+ * section, which Graph rejects). The section is imported as an empty placeholder folder carrying+ * this error — holding its place in the tree so import order is preserved — rather than skipped,+ * so the user sees where it belongs and can unlock and re-import it.+ */+ fetchError?: string;}/**@@ -104,26 +114,31 @@ 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[] = [];+ const sectionPages: { section: OneNoteSectionSelection; pages: OneNotePage[]; error?: string }[] = [];for (const section of sections) {- // 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.+ // A section whose page list can't be fetched doesn't abort the whole import: it is tagged+ // with the error here and imported as a placeholder folder below, holding its place so the+ // rest of the selection still imports in order. 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 });+ getLog().error(`OneNote import: could not list the pages of section '${section.title}' (${section.id}); it will be imported as a placeholder: ${message}`);+ sectionPages.push({ section, pages: [], error: message });}}taskContext.setTotalCount(sectionPages.reduce((total, entry) => total + entry.pages.length, 0));const fetched: FetchedSection[] = [];let consecutivePageFailures = 0;- for (const { section, pages } of sectionPages) {+ for (const { section, pages, error } of sectionPages) {+ // A section whose pages couldn't be listed keeps its slot in `fetched` (so import order is+ // preserved) but carries the error instead of pages — createNotes renders it as a placeholder.+ if (error !== undefined) {+ fetched.push(toFetchedSection(section, [], error));+ continue;+ }const fetchedPages: FetchedPage[] = [];for (const page of pages) {// The Graph fetch and the local processing (HTML/InkML conversion, resource discovery)@@ -159,21 +174,11 @@ export async function importSelection({ getAccessToken, parentNoteId, sections,}taskContext.increaseProgressCount();}- fetched.push({- title: section.title,- createdDateTime: section.createdDateTime,- lastModifiedDateTime: section.lastModifiedDateTime,- groupPath: section.groupPath,- notebookId: section.notebookId,- notebookTitle: section.notebookTitle,- notebookCreatedDateTime: section.notebookCreatedDateTime,- notebookLastModifiedDateTime: section.notebookLastModifiedDateTime,- pages: fetchedPages- });+ fetched.push(toFetchedSection(section, fetchedPages));}// Phase 2: create the note tree.- const rootNoteId = sql.transactional(() => createNotes(parentNoteId, fetched, failedSections, debug, shrinkImages, startedAtMs));+ const rootNoteId = sql.transactional(() => createNotes(parentNoteId, fetched, debug, shrinkImages, startedAtMs));taskContext.taskSucceeded({ parentNoteId, importedNoteId: rootNoteId });} catch (e: unknown) {@@ -182,13 +187,31 @@ export async function importSelection({ getAccessToken, parentNoteId, sections,}}+/** Copies a selected section's metadata into a {@link FetchedSection}, attaching its fetched pages and+ * (when its page list couldn't be loaded) the error that turns it into a placeholder folder. */+function toFetchedSection(section: OneNoteSectionSelection, pages: FetchedPage[], fetchError?: string): FetchedSection {+ return {+ id: section.id,+ title: section.title,+ createdDateTime: section.createdDateTime,+ lastModifiedDateTime: section.lastModifiedDateTime,+ groupPath: section.groupPath,+ notebookId: section.notebookId,+ notebookTitle: section.notebookTitle,+ notebookCreatedDateTime: section.notebookCreatedDateTime,+ notebookLastModifiedDateTime: section.notebookLastModifiedDateTime,+ pages,+ fetchError+ };+}+/** A content-less stand-in for a page that could not be fetched or processed; imported so the tree and* cross-page links stay intact and the failure is reported (see {@link FetchedPage.fetchError}). */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[], failedSections: FailedSectionReport[], debug: boolean, shrinkImages: boolean, startedAtMs: number): string {+function createNotes(parentNoteId: string, sections: FetchedSection[], debug: boolean, shrinkImages: boolean, startedAtMs: number): string {const parentNote = becca.getNoteOrThrow(parentNoteId);const isProtected = parentNote.isProtected && protectedSession.isProtectedSessionAvailable();@@ -207,6 +230,7 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], failedSecconst createdPages: { note: BNote; original: string; content: string; page: FetchedPage }[] = [];const targetByPageId = new Map<string, LinkTarget>();const failedPages: FailedPageReport[] = [];+ const failedSections: FailedSectionReport[] = [];// 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@@ -234,6 +258,20 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], failedSec}const sectionNote = createFolder(containerNoteId, section.title);++ if (section.fetchError !== undefined) {+ // A section whose pages couldn't be listed becomes an empty placeholder folder: it holds the+ // section's place in the tree (so order and hierarchy are preserved), explains itself, and is+ // findable/retryable by label + section id. The report links to this note.+ sectionNote.setContent(renderFailedSectionPlaceholder(section.fetchError));+ sectionNote.addLabel("oneNoteImportFailed");+ sectionNote.addLabel("oneNoteSectionId", section.id);+ // Applied after setContent, whose save would otherwise re-stamp the modification date.+ applyOriginalDates(sectionNote, section.createdDateTime, section.lastModifiedDateTime);+ failedSections.push({ title: section.title, notebookTitle: section.notebookTitle, noteId: sectionNote.noteId, error: section.fetchError });+ continue;+ }+applyOriginalDates(sectionNote, section.createdDateTime, section.lastModifiedDateTime);// OneNote pages carry an indentation level (subpages); preserve it by parenting each page under@@ -335,7 +373,8 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], failedSecconst reportData: ImportReportData = {importedPageCount: createdPages.length,notebookCount: new Set(sections.map((section) => section.notebookId)).size,- sectionCount: sections.length,+ // Successfully imported sections; the placeholder (failed) ones are counted via failedSections.+ sectionCount: sections.length - failedSections.length,durationMs: Date.now() - startedAtMs,imageCount: sumResources(allPages, "image", () => 1),imageBytes: sumResources(allPages, "image", (resource) => resource.content.length),@@ -362,6 +401,11 @@ function renderFailedPagePlaceholder(error: string): string {return `<p>${t("onenote_import.failed-page-placeholder", { error })}</p>`;}+/** The body of a placeholder folder standing in for a section whose page list could not be fetched. */+function renderFailedSectionPlaceholder(error: string): string {+ return `<p>${t("onenote_import.failed-section-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;diff --git a/apps/server/src/services/import/onenote/report.spec.ts b/apps/server/src/services/import/onenote/report.spec.tsindex b802233780..a79d38e030 100644--- a/apps/server/src/services/import/onenote/report.spec.ts+++ b/apps/server/src/services/import/onenote/report.spec.ts@@ -100,18 +100,18 @@ describe("renderImportReport", () => {expect(html).toContain("HTTP 504");});- it("lists skipped sections and shows the section count as imported/total", () => {+ it("lists placeholder sections with reference links 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.)" }+ { title: "Secret <plans>", notebookTitle: "Work & Home", noteId: "ps1", 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.+ // 2 imported of 3 selected: the placeholder 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('<a class="reference-link" href="#root/ps1">Secret <plans></a>');expect(html).toContain("<td>Work & Home</td>");expect(html).toContain("Encrypted sections are not accessible.");});diff --git a/apps/server/src/services/import/onenote/report.ts b/apps/server/src/services/import/onenote/report.tsindex ebe3a287f1..aa6714b569 100644--- a/apps/server/src/services/import/onenote/report.ts+++ b/apps/server/src/services/import/onenote/report.ts@@ -17,13 +17,13 @@ export interface FailedPageReport {}/**- * 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.+ * A section whose page list could not be fetched; `noteId` is the empty placeholder folder created in+ * its stead. The notebook title is kept for disambiguation when several notebooks share a section name.*/export interface FailedSectionReport {title: string;notebookTitle: string;+ noteId: string;error: string;}@@ -64,7 +64,7 @@ export function renderImportReport(data: ImportReportData): string {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>`);+ `<tr><td>${noteLink(section.noteId, 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>`);