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(import): import Anytype file objects that are collection members
Elian Doran4191f911cc54
diff --git a/packages/trilium-core/src/services/import/anytype/importer.integration.spec.ts b/packages/trilium-core/src/services/import/anytype/importer.integration.spec.tsindex 44b9d2c890..35c1f40225 100644--- a/packages/trilium-core/src/services/import/anytype/importer.integration.spec.ts+++ b/packages/trilium-core/src/services/import/anytype/importer.integration.spec.ts@@ -764,6 +764,60 @@ describe("Anytype importer — integration", () => {expect(content).toContain(">log.txt</a>");});+ it("imports a file object that's a collection member as a file note under the collection", async () => {+ // A file dropped into a collection is listed in its membership (details.links) as a FileObject id, not+ // a page — so it must still become a (file) note beneath the collection rather than being dropped.+ const fileCid = "bafyreifilemember";+ const importRoot = await importAnytype({+ "objects/coll.pb.json": collectionObject("coll", "Docs", [fileCid], []),+ "filesObjects/f1.pb.json": fileObjectJson(fileCid, "report", "pdf", "application/pdf", "files\\report.pdf"),+ "files/report.pdf": Buffer.from("%PDF-1.4 hi")+ });++ const collection = importRoot.getChildNotes()[0];+ expect(collection.title).toBe("Docs");+ const members = collection.getChildNotes();+ expect(members.map((n) => n.title)).toEqual(["report.pdf"]);+ const fileNote = members[0];+ expect(fileNote.type).toBe("file");+ expect(fileNote.mime).toBe("application/pdf");+ expect(decodeUtf8(fileNote.getContent() ?? "")).toBe("%PDF-1.4 hi");+ expect(fileNote.getOwnedLabelValue("originalFileName")).toBe("report.pdf");+ });++ it("imports an image object that's a collection member as an image note", async () => {+ const imgCid = "bafyreiimagemember";+ const importRoot = await importAnytype({+ "objects/coll.pb.json": collectionObject("coll", "Gallery", [imgCid], []),+ "filesObjects/f1.pb.json": fileObjectJson(imgCid, "pic", "png", "image/png", "files\\pic.png"),+ "files/pic.png": Buffer.from("\x89PNG\r\n\x1a\nfake-png")+ });++ const members = importRoot.getChildNotes()[0].getChildNotes();+ expect(members.map((n) => n.type)).toEqual(["image"]);+ expect(members[0].title).toBe("pic.png");+ });++ it("clones a file member into every collection that lists it", async () => {+ // The same file is a member of two collections — its primary parent is the first, and it's cloned into+ // the second (same as a page member).+ const fileCid = "bafyreisharedfile";+ const importRoot = await importAnytype({+ "objects/c1.pb.json": collectionObject("c1", "First", [fileCid], []),+ "objects/c2.pb.json": collectionObject("c2", "Second", [fileCid], []),+ "filesObjects/f1.pb.json": fileObjectJson(fileCid, "shared", "txt", "text/plain", "files\\shared.txt"),+ "files/shared.txt": Buffer.from("shared bytes")+ });++ const collections = importRoot.getChildNotes();+ expect(collections.map((n) => n.title).sort()).toEqual(["First", "Second"]);+ // The very same note (one noteId) appears under both collections.+ const firstMember = collections.find((n) => n.title === "First")?.getChildNotes()[0];+ const secondMember = collections.find((n) => n.title === "Second")?.getChildNotes()[0];+ expect(firstMember?.noteId).toBe(secondMember?.noteId);+ expect(firstMember?.title).toBe("shared.txt");+ });+it("imports an inline image block as a role:image attachment, rewriting the <img src> to point at it", async () => {// An Image file block in the body references a FileObject (its `targetObjectId`), whose bytes ship under files/.const imageCid = "bafyreiimage";diff --git a/packages/trilium-core/src/services/import/anytype/importer.ts b/packages/trilium-core/src/services/import/anytype/importer.tsindex 5b632567fd..c238a5e2c6 100644--- a/packages/trilium-core/src/services/import/anytype/importer.ts+++ b/packages/trilium-core/src/services/import/anytype/importer.ts@@ -343,6 +343,21 @@ function createNotes(importRootNote: BNote, pages: ParsedObject[], targets: Map<taskContext.increaseProgressCount();}+ // A collection can list a *file object* directly as a member (a file dropped into the collection). It's+ // not a page, so no note was created for it above — create one now, a `file`/`image` note under its+ // owning collection, so the member shows up. The membership pass below then clones it into any further+ // collections. Done after the page loop so the owning collection note already exists.+ for (const fileId of fileMemberIds(pages, notesByPageId, fileObjects)) {+ const info = fileObjects.get(fileId);+ const bytes = info ? files.get(normalizePath(info.source)) : undefined;+ if (!info || !bytes) {+ continue;+ }+ const primaryCollectionId = primaryCollectionByMember.get(fileId);+ const parentNoteId = (primaryCollectionId ? notesByPageId.get(primaryCollectionId)?.noteId : undefined) ?? rootNote.noteId;+ notesByPageId.set(fileId, createFileMemberNote(parentNoteId, info, bytes, isProtected));+ }+// Membership: clone a member into every collection that isn't already its (primary) parent.for (const page of pages) {const collectionNote = page.collection ? notesByPageId.get(page.id) : undefined;@@ -367,6 +382,31 @@ function createNotes(importRootNote: BNote, pages: ParsedObject[], targets: Map<return rootNote;}+/** The file-object ids a collection lists as members that no page note was created for — i.e. files dropped+ * directly into a collection (resolvable to bytes via the file map). De-duplicated across collections. */+function fileMemberIds(pages: ParsedObject[], notesByPageId: Map<string, BNote>, fileObjects: Map<string, FileObjectInfo>): Set<string> {+ const ids = new Set<string>();+ for (const page of pages) {+ for (const memberId of page.collection?.memberIds ?? []) {+ if (!notesByPageId.has(memberId) && fileObjects.has(memberId)) {+ ids.add(memberId);+ }+ }+ }+ return ids;+}++/** Creates a Trilium note for a file dropped into a collection: an `image` note for an image (so it renders+ * inline), otherwise a `file` note holding the raw bytes — both children of the owning collection. */+function createFileMemberNote(parentNoteId: string, info: FileObjectInfo, bytes: Uint8Array, isProtected: boolean | undefined): BNote {+ if (info.mime.startsWith("image/")) {+ return imageService.saveImage(parentNoteId, bytes, info.title, false).note;+ }+ const { note } = noteService.createNewNote({ parentNoteId, title: info.title, content: bytes, type: "file", mime: info.mime || "application/octet-stream", isProtected });+ note.addLabel("originalFileName", info.title);+ return note;+}+/*** Resolves the inline file/media placeholders a page's body carries ({@link ./content.js} emits each* `file` block as an `<img>` / `<a class="anytype-file">` whose `src`/`href` is the linked `FileObject`'s