Skip to content

Build your personal knowledge base with Trilium Notes

fix(import): run OneNote import in the background to avoid client timeout

Elian Dorana3ca0b87552c
diff --git a/apps/client/src/services/onenote_import.ts b/apps/client/src/services/onenote_import.ts
index 3fa90714e1..b7a9daf3a9 100644
--- a/apps/client/src/services/onenote_import.ts
+++ b/apps/client/src/services/onenote_import.ts
@@ -23,6 +23,8 @@ export interface OneNoteSection {
export interface OneNoteNotebook {
id: string;
title: string;
+ createdDateTime?: string;
+ lastModifiedDateTime?: string;
sections: OneNoteSection[];
}
@@ -30,7 +32,10 @@ export interface OneNoteNotebook {
export interface OneNoteSectionSelection {
id: string;
title: string;
+ notebookId: string;
notebookTitle: string;
+ notebookCreatedDateTime?: string;
+ notebookLastModifiedDateTime?: string;
}
function getAuthUrl() {
@@ -49,8 +54,11 @@ function getNotebooks() {
return server.get<{ notebooks: OneNoteNotebook[] }>("onenote-import/notebooks");
}
+// Kicks off the import and returns as soon as the server has accepted it. The import itself runs in the
+// background on the server; progress, completion (navigation to the imported note) and any error all
+// arrive over the WebSocket via the shared "importNotes" toast handlers in import.ts.
function runImport(payload: { parentNoteId: string; sections: OneNoteSectionSelection[]; taskId: string; debug?: boolean }) {
- return server.post<{ noteId: string }>("onenote-import/import", payload);
+ return server.post<void>("onenote-import/import", payload);
}
export default {
diff --git a/apps/client/src/widgets/dialogs/import_providers/onenote.tsx b/apps/client/src/widgets/dialogs/import_providers/onenote.tsx
index f08569d24a..4e733e02af 100644
--- a/apps/client/src/widgets/dialogs/import_providers/onenote.tsx
+++ b/apps/client/src/widgets/dialogs/import_providers/onenote.tsx
@@ -101,7 +101,14 @@ function OneNotePanel({ parentNoteId, closeDialog }: ImportProviderPanelProps) {
for (const notebook of notebooks) {
for (const section of notebook.sections) {
if (selectedIds.has(section.id)) {
- sections.push({ id: section.id, title: section.title, notebookTitle: notebook.title });
+ sections.push({
+ id: section.id,
+ title: section.title,
+ notebookId: notebook.id,
+ notebookTitle: notebook.title,
+ notebookCreatedDateTime: notebook.createdDateTime,
+ notebookLastModifiedDateTime: notebook.lastModifiedDateTime
+ });
}
}
}
@@ -109,8 +116,9 @@ function OneNotePanel({ parentNoteId, closeDialog }: ImportProviderPanelProps) {
return;
}
- // Close immediately and let the shared import toasts report progress and completion. The
- // server request stays open for the whole import, so we don't await before closing.
+ // Close immediately and let the shared import toasts report progress, completion and any error.
+ // The request returns as soon as the server accepts it (the import runs in the background), so
+ // the only errors caught here are upfront ones like a lost connection or an invalid selection.
closeDialog();
try {
await onenoteImport.runImport({ parentNoteId, sections, taskId: randomString(10), debug });
diff --git a/apps/server/src/routes/api/onenote_import.ts b/apps/server/src/routes/api/onenote_import.ts
index 988bd09787..36f666be3a 100644
--- a/apps/server/src/routes/api/onenote_import.ts
+++ b/apps/server/src/routes/api/onenote_import.ts
@@ -94,8 +94,12 @@ async function runImport(req: Request) {
}
becca.getNoteOrThrow(parentNoteId);
- const noteId = await importer.importSelection({ accessToken, parentNoteId, sections, taskId, debug: !!debug });
- return { noteId };
+ // Fire-and-forget: a large notebook can take far longer than the client's HTTP request timeout, so
+ // we return immediately and let the import report progress, completion and any error over the
+ // WebSocket (taskType "importNotes"). importSelection catches and reports its own failures, so the
+ // detached promise never rejects.
+ void importer.importSelection({ accessToken, parentNoteId, sections, taskId, debug: !!debug });
+ return {};
}
function getRedirectUri(req: Request): string {
diff --git a/apps/server/src/services/import/onenote/graph.ts b/apps/server/src/services/import/onenote/graph.ts
index 6b8590f305..b9061cbcb3 100644
--- a/apps/server/src/services/import/onenote/graph.ts
+++ b/apps/server/src/services/import/onenote/graph.ts
@@ -22,6 +22,8 @@ export interface OneNoteSection {
export interface OneNoteNotebook {
id: string;
title: string;
+ createdDateTime?: string;
+ lastModifiedDateTime?: string;
sections: OneNoteSection[];
}
@@ -44,40 +46,50 @@ export async function getAccount(accessToken: string): Promise<GraphAccount> {
/**
* Returns the notebooks with all of their sections, including those nested inside section groups
- * (flattened with a "Group / Subgroup / Section" title). Section groups nest arbitrarily and the
- * notebooks endpoint only reliably $expands one level of them, so instead of a deep nested $expand we
- * walk each section group's `sectionGroupsUrl` recursively (see collectSectionGroupSections).
+ * (flattened with a "Group / Subgroup / Section" title).
+ *
+ * The initial call expands each notebook's sections and whether it has any section groups, so the
+ * common case (no section groups) is a single round-trip. Only notebooks/groups that actually contain
+ * section groups follow their `sectionGroupsUrl`, and those follow-up requests run in parallel —
+ * section groups nest arbitrarily and the notebooks endpoint won't $expand them more than one level.
*/
export async function listNotebooks(accessToken: string): Promise<OneNoteNotebook[]> {
- const url = "/me/onenote/notebooks?$select=id,displayName,sectionGroupsUrl&$expand=sections($select=id,displayName)&$orderby=displayName";
+ const url = "/me/onenote/notebooks?$select=id,displayName,createdDateTime,lastModifiedDateTime,sectionGroupsUrl&$expand=sections($select=id,displayName),sectionGroups($select=id)&$orderby=displayName";
const notebooks = await graphGetAll<RawNotebook>(accessToken, url);
- const result: OneNoteNotebook[] = [];
- for (const notebook of notebooks) {
- const sections: OneNoteSection[] = (notebook.sections ?? []).map((s) => ({ id: s.id, title: s.displayName }));
- await collectSectionGroupSections(accessToken, notebook.sectionGroupsUrl, "", sections);
- result.push({ id: notebook.id, title: notebook.displayName, sections });
- }
- return result;
+ return Promise.all(
+ notebooks.map(async (notebook) => {
+ const direct = (notebook.sections ?? []).map((s) => ({ id: s.id, title: s.displayName }));
+ const grouped = notebook.sectionGroups?.length && notebook.sectionGroupsUrl ? await sectionsFromSectionGroups(accessToken, notebook.sectionGroupsUrl, "") : [];
+ return {
+ id: notebook.id,
+ title: notebook.displayName,
+ createdDateTime: notebook.createdDateTime,
+ lastModifiedDateTime: notebook.lastModifiedDateTime,
+ sections: [...direct, ...grouped]
+ };
+ })
+ );
}
/**
- * Recursively walks the section groups under `sectionGroupsUrl` (a notebook's or section group's link),
- * appending every section to `out` with a "Group / Subgroup / Section" title. Following the link at each
- * level handles arbitrarily nested section groups, which a single one-level $expand misses entirely.
+ * Fetches the section groups under `sectionGroupsUrl` (a notebook's or section group's link) and
+ * returns their sections, recursing into nested groups. Sibling groups are fetched in parallel, and a
+ * further round-trip happens only for groups that actually have children.
*/
-async function collectSectionGroupSections(accessToken: string, sectionGroupsUrl: string | undefined, prefix: string, out: OneNoteSection[]) {
- if (!sectionGroupsUrl) {
- return;
- }
- const url = appendQuery(sectionGroupsUrl, "$select=id,displayName,sectionGroupsUrl&$expand=sections($select=id,displayName)");
- for (const group of await graphGetAll<RawSectionGroup>(accessToken, url)) {
- const path = prefix ? `${prefix} / ${group.displayName}` : group.displayName;
- for (const section of group.sections ?? []) {
- out.push({ id: section.id, title: `${path} / ${section.displayName}` });
- }
- await collectSectionGroupSections(accessToken, group.sectionGroupsUrl, path, out);
- }
+async function sectionsFromSectionGroups(accessToken: string, sectionGroupsUrl: string, prefix: string): Promise<OneNoteSection[]> {
+ const url = appendQuery(sectionGroupsUrl, "$select=id,displayName,sectionGroupsUrl&$expand=sections($select=id,displayName),sectionGroups($select=id)");
+ const groups = await graphGetAll<RawSectionGroup>(accessToken, url);
+
+ const perGroup = await Promise.all(
+ groups.map(async (group) => {
+ const path = prefix ? `${prefix} / ${group.displayName}` : group.displayName;
+ const direct = (group.sections ?? []).map((s) => ({ id: s.id, title: `${path} / ${s.displayName}` }));
+ const nested = group.sectionGroups?.length && group.sectionGroupsUrl ? await sectionsFromSectionGroups(accessToken, group.sectionGroupsUrl, path) : [];
+ return [...direct, ...nested];
+ })
+ );
+ return perGroup.flat();
}
function appendQuery(url: string, query: string): string {
@@ -165,8 +177,12 @@ export async function getResource(accessToken: string, url: string): Promise<{ c
interface RawNotebook {
id: string;
displayName: string;
+ createdDateTime?: string;
+ lastModifiedDateTime?: string;
sectionGroupsUrl?: string;
sections?: { id: string; displayName: string }[];
+ /** id-only, requested just to detect whether the notebook has section groups to follow. */
+ sectionGroups?: { id: string }[];
}
interface RawSectionGroup {
@@ -174,6 +190,8 @@ interface RawSectionGroup {
displayName: string;
sectionGroupsUrl?: string;
sections?: { id: string; displayName: string }[];
+ /** id-only, requested just to detect whether the group has nested section groups to follow. */
+ sectionGroups?: { id: string }[];
}
interface RawPage {
diff --git a/apps/server/src/services/import/onenote/importer.ts b/apps/server/src/services/import/onenote/importer.ts
index 609feae302..9c84670451 100644
--- a/apps/server/src/services/import/onenote/importer.ts
+++ b/apps/server/src/services/import/onenote/importer.ts
@@ -5,7 +5,7 @@
* client-side import toasts apply unchanged.
*/
-import { becca, binary_utils, type BNote, getLog, imageService, note_service as noteService, protected_session as protectedSession, TaskContext } from "@triliumnext/core";
+import { becca, binary_utils, type BNote, date_utils, getLog, imageService, note_service as noteService, protected_session as protectedSession, TaskContext } from "@triliumnext/core";
import { parse } from "node-html-parser";
import sql from "../../sql.js";
@@ -17,7 +17,12 @@ import { type LinkTarget, rewritePageLinks } from "./links.js";
export interface SectionSelection {
id: string;
title: string;
+ notebookId: string;
notebookTitle: string;
+ /** OneNote's notebook creation timestamp (ISO 8601), preserved on the imported notebook folder. */
+ notebookCreatedDateTime?: string;
+ /** OneNote's notebook last-modified timestamp (ISO 8601), preserved on the imported notebook folder. */
+ notebookLastModifiedDateTime?: string;
}
interface FetchedPage {
@@ -51,43 +56,62 @@ interface DownloadedResource {
interface FetchedSection {
title: string;
+ notebookId: string;
notebookTitle: string;
+ notebookCreatedDateTime?: string;
+ notebookLastModifiedDateTime?: string;
pages: FetchedPage[];
}
-export async function importSelection({ accessToken, parentNoteId, sections, taskId, debug = false }: { accessToken: string; parentNoteId: string; sections: SectionSelection[]; taskId: string; debug?: boolean }): Promise<string> {
+/**
+ * Runs the whole import in the background — the caller does not await it, because a large notebook can
+ * take far longer than the client's HTTP request timeout. Progress, completion and failure are all
+ * reported over the WebSocket via the "importNotes" TaskContext, so this never throws to the caller:
+ * any error is caught and surfaced as a task error toast instead.
+ */
+export async function importSelection({ accessToken, parentNoteId, sections, taskId, debug = false }: { accessToken: string; parentNoteId: string; sections: SectionSelection[]; taskId: string; debug?: boolean }): Promise<void> {
const taskContext = TaskContext.getInstance(taskId, "importNotes", { safeImport: true });
- // Phase 1: pull everything over the network first, so note creation can run in a single
- // synchronous transaction afterwards.
+ try {
+ // Phase 1: pull everything over the network first, so note creation can run in a single
+ // synchronous transaction afterwards.
- // 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: SectionSelection; pages: OneNotePage[] }[] = [];
- for (const section of sections) {
- sectionPages.push({ section, pages: await graph.listPages(accessToken, section.id) });
- }
- taskContext.setTotalCount(sectionPages.reduce((total, entry) => total + entry.pages.length, 0));
-
- const fetched: FetchedSection[] = [];
- 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 = await downloadPageResources(accessToken, html);
- fetchedPages.push({ title: page.title, pageId: page.pageId, html, rawHtml, rawInkml: inkml, inkSvg: inkmlToSvg(inkml), resources, createdDateTime: page.createdDateTime, lastModifiedDateTime: page.lastModifiedDateTime });
- taskContext.increaseProgressCount();
+ // 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: SectionSelection; pages: OneNotePage[] }[] = [];
+ for (const section of sections) {
+ sectionPages.push({ section, pages: await graph.listPages(accessToken, section.id) });
+ }
+ taskContext.setTotalCount(sectionPages.reduce((total, entry) => total + entry.pages.length, 0));
+
+ const fetched: FetchedSection[] = [];
+ 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 = await downloadPageResources(accessToken, html);
+ fetchedPages.push({ title: page.title, pageId: page.pageId, html, rawHtml, rawInkml: inkml, inkSvg: inkmlToSvg(inkml), resources, createdDateTime: page.createdDateTime, lastModifiedDateTime: page.lastModifiedDateTime });
+ taskContext.increaseProgressCount();
+ }
+ fetched.push({
+ title: section.title,
+ notebookId: section.notebookId,
+ notebookTitle: section.notebookTitle,
+ notebookCreatedDateTime: section.notebookCreatedDateTime,
+ notebookLastModifiedDateTime: section.notebookLastModifiedDateTime,
+ pages: fetchedPages
+ });
}
- fetched.push({ title: section.title, notebookTitle: section.notebookTitle, pages: fetchedPages });
- }
-
- // Phase 2: create the note tree.
- const rootNoteId = sql.transactional(() => createNotes(parentNoteId, fetched, debug));
- taskContext.taskSucceeded({ parentNoteId, importedNoteId: rootNoteId });
+ // Phase 2: create the note tree.
+ const rootNoteId = sql.transactional(() => createNotes(parentNoteId, fetched, debug));
- return rootNoteId;
+ taskContext.taskSucceeded({ parentNoteId, importedNoteId: rootNoteId });
+ } catch (e: unknown) {
+ getLog().error(`OneNote import failed: ${e instanceof Error ? (e.stack ?? e.message) : e}`);
+ taskContext.reportError(e instanceof Error ? e.message : String(e));
+ }
}
function createNotes(parentNoteId: string, sections: FetchedSection[], debug: boolean): string {
@@ -104,13 +128,17 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], debug: bo
const createdPages: { note: BNote; original: string; content: string; page: FetchedPage }[] = [];
const targetByPageId = new Map<string, LinkTarget>();
- // Group selected sections under a note per notebook so the original hierarchy is preserved.
+ // Group selected sections under a note per notebook so the original hierarchy is preserved. Keyed by
+ // the OneNote notebook id rather than the title, so notebooks that happen to share a title stay apart.
const notebookNotes = new Map<string, string>();
for (const section of sections) {
- let notebookNoteId = notebookNotes.get(section.notebookTitle);
+ let notebookNoteId = notebookNotes.get(section.notebookId);
if (!notebookNoteId) {
- notebookNoteId = createFolder(rootNote.noteId, section.notebookTitle).noteId;
- notebookNotes.set(section.notebookTitle, notebookNoteId);
+ const notebookNote = createFolder(rootNote.noteId, section.notebookTitle);
+ notebookNote.addLabel("iconClass", "bx bx-book");
+ applyOriginalDates(notebookNote, section.notebookCreatedDateTime, section.notebookLastModifiedDateTime);
+ notebookNoteId = notebookNote.noteId;
+ notebookNotes.set(section.notebookId, notebookNoteId);
}
const sectionNote = createFolder(notebookNoteId, section.title);
@@ -174,16 +202,24 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], debug: bo
// Preserve OneNote's original timestamps. Must run after setContent, whose save would otherwise
// re-stamp the modification date with "now".
- const utcDateCreated = toUtcDbDate(page.createdDateTime);
- const utcDateModified = toUtcDbDate(page.lastModifiedDateTime) ?? utcDateCreated;
- if (utcDateCreated || utcDateModified) {
- note.setDateCreatedAndModified(utcDateCreated, utcDateModified);
- }
+ applyOriginalDates(note, page.createdDateTime, page.lastModifiedDateTime);
}
return rootNote.noteId;
}
+/**
+ * Applies OneNote's original created/modified timestamps (ISO 8601) to an imported note, falling back
+ * to the creation date when the modification date is absent. A no-op when neither is available.
+ */
+function applyOriginalDates(note: BNote, createdDateTime?: string, lastModifiedDateTime?: string) {
+ const utcDateCreated = toUtcDbDate(createdDateTime);
+ const utcDateModified = toUtcDbDate(lastModifiedDateTime) ?? utcDateCreated;
+ if (utcDateCreated || utcDateModified) {
+ note.setDateCreatedAndModified(utcDateCreated, utcDateModified);
+ }
+}
+
/** Converts a Graph ISO 8601 timestamp to Trilium's UTC DB format, or undefined if absent/unparseable. */
function toUtcDbDate(isoDateTime: string | undefined): string | undefined {
if (!isoDateTime) {