Skip to content

Build your personal knowledge base with Trilium Notes

feat(import): preserve Google Keep note attachments

Elian Doranfdca9f241261
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Import & Export/Importing data from other applications/Google Keep.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Import & Export/Importing data from other applications/Google Keep.html
index 04ea682f37..4e1f865f45 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Import & Export/Importing data from other applications/Google Keep.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Import & Export/Importing data from other applications/Google Keep.html
@@ -46,15 +46,17 @@
</ul>
</li>
<li>To-do lists</li>
+ <li><a class="reference-link" href="#root/_help_mT0HEkOsz6i1">Images</a>&nbsp;and&nbsp;
+ <a
+ class="reference-link" href="#root/_help_0vhv7lsOLy82">Attachments</a>&nbsp;are
+ preserved: images are embedded inline in the note, while other files are
+ kept as attachments.</li>
<li>Creation and modification dates are preserved.</li>
</ul>
<h2>Limitations</h2>
<p>Currently the following information is not imported:</p>
<ul>
<li>Labels are disregarded.</li>
- <li><a class="reference-link" href="#root/_help_mT0HEkOsz6i1">Images</a>&nbsp;and&nbsp;
- <a
- class="reference-link" href="#root/_help_0vhv7lsOLy82">Attachments</a>&nbsp;are not imported.</li>
<li>Pinned, archived or trashed state is not preserved, all notes are treated
the same.</li>
</ul>
diff --git a/docs/User Guide/User Guide/Basic Concepts and Features/Import & Export/Importing data from other applications/Google Keep.md b/docs/User Guide/User Guide/Basic Concepts and Features/Import & Export/Importing data from other applications/Google Keep.md
index 9fa1bacc44..55a227f7c8 100644
--- a/docs/User Guide/User Guide/Basic Concepts and Features/Import & Export/Importing data from other applications/Google Keep.md
+++ b/docs/User Guide/User Guide/Basic Concepts and Features/Import & Export/Importing data from other applications/Google Keep.md
@@ -34,6 +34,7 @@ Then in Trilium Notes:
* Note titles are maintained, if present.
* In Google Keep it's common for notes not to have a title, case in which the date and time of the note are used as a title.
* To-do lists
+* <a class="reference-link" href="../../../Note%20Types/Text/Images.md">Images</a> and <a class="reference-link" href="../../Notes/Attachments.md">Attachments</a> are preserved: images are embedded inline in the note, while other files are kept as attachments.
* Creation and modification dates are preserved.
## Limitations
@@ -41,7 +42,6 @@ Then in Trilium Notes:
Currently the following information is not imported:
* Labels are disregarded.
-* <a class="reference-link" href="../../../Note%20Types/Text/Images.md">Images</a> and <a class="reference-link" href="../../Notes/Attachments.md">Attachments</a> are not imported.
* Pinned, archived or trashed state is not preserved, all notes are treated the same.
## Reporting issues
diff --git a/packages/trilium-core/src/services/import/keep/importer.integration.spec.ts b/packages/trilium-core/src/services/import/keep/importer.integration.spec.ts
index 19165828ce..7bb1155c6d 100644
--- a/packages/trilium-core/src/services/import/keep/importer.integration.spec.ts
+++ b/packages/trilium-core/src/services/import/keep/importer.integration.spec.ts
@@ -6,6 +6,7 @@ import becca from "../../../becca/becca.js";
import type BNote from "../../../becca/entities/bnote.js";
import { getContext } from "../../context.js";
import TaskContext from "../../task_context.js";
+import { decodeUtf8 } from "../../utils/binary.js";
import keepImporter from "./importer.js";
/** Builds an in-memory zip from a map of entry name -> contents. */
@@ -122,4 +123,75 @@ describe("Google Keep importer — integration", () => {
expect(note.getOwnedLabelValue("color")).toBe("#95d641");
});
+
+ it("preserves an image attachment, embedding it inline as a role:image attachment after the body", async () => {
+ const note = await importSingleNote({
+ "Takeout/Keep/note.json": JSON.stringify({
+ title: "Note with image",
+ textContent: "see below",
+ attachments: [{ filePath: "photo.png", mimetype: "image/png" }]
+ }),
+ "Takeout/Keep/photo.png": Buffer.from("\x89PNG\r\n\x1a\nfake-png-bytes")
+ });
+
+ // The image becomes a role:"image" attachment titled from the file name.
+ const attachments = note.getAttachmentsByRole("image");
+ expect(attachments.map((a) => a.title)).toEqual(["photo.png"]);
+
+ // The body keeps its text and gains an <img> pointing at the attachment URL.
+ const content = decodeUtf8(note.getContent() ?? "");
+ expect(content).toContain("see below");
+ expect(content).toContain(`<img src="api/attachments/${attachments[0].attachmentId}/image/photo.png"`);
+ });
+
+ it("preserves a non-image attachment as a role:file attachment with a reference link in the body", async () => {
+ const note = await importSingleNote({
+ "Takeout/Keep/note.json": JSON.stringify({
+ title: "Note with recording",
+ attachments: [{ filePath: "memo.3gp", mimetype: "audio/3gpp" }]
+ }),
+ "Takeout/Keep/memo.3gp": Buffer.from("fake-audio-bytes")
+ });
+
+ const attachments = note.getAttachmentsByRole("file");
+ expect(attachments.map((a) => a.title)).toEqual(["memo.3gp"]);
+ // The MIME is derived from the extension.
+ expect(attachments[0].mime).toBe("video/3gpp");
+ expect(decodeUtf8(attachments[0].getContent() ?? "")).toBe("fake-audio-bytes");
+
+ const content = decodeUtf8(note.getContent() ?? "");
+ // `&` is HTML-encoded to `&amp;` by the sanitizer in the persisted content.
+ expect(content).toContain(`href="#root/${note.noteId}?viewMode=attachments&amp;attachmentId=${attachments[0].attachmentId}"`);
+ expect(content).toContain(">memo.3gp</a>");
+ });
+
+ it("preserves every attachment when a note has more than one", async () => {
+ const note = await importSingleNote({
+ "Takeout/Keep/note.json": JSON.stringify({
+ attachments: [
+ { filePath: "a.png", mimetype: "image/png" },
+ { filePath: "b.png", mimetype: "image/png" }
+ ]
+ }),
+ "Takeout/Keep/a.png": Buffer.from("\x89PNG\r\n\x1a\na"),
+ "Takeout/Keep/b.png": Buffer.from("\x89PNG\r\n\x1a\nb")
+ });
+
+ expect(note.getAttachmentsByRole("image").map((a) => a.title)).toEqual(["a.png", "b.png"]);
+ });
+
+ it("skips an attachment whose binary is missing from the export, without failing the import", async () => {
+ const note = await importSingleNote({
+ "Takeout/Keep/note.json": JSON.stringify({
+ title: "Broken image",
+ textContent: "body",
+ attachments: [{ filePath: "gone.png", mimetype: "image/png" }]
+ })
+ });
+
+ expect(note.getAttachmentsByRole("image")).toHaveLength(0);
+ // No broken <img> is left behind; the original body is untouched.
+ const content = decodeUtf8(note.getContent() ?? "");
+ expect(content).toBe("<p>body</p>");
+ });
});
diff --git a/packages/trilium-core/src/services/import/keep/importer.spec.ts b/packages/trilium-core/src/services/import/keep/importer.spec.ts
index e2dea44f45..0ea8177a4f 100644
--- a/packages/trilium-core/src/services/import/keep/importer.spec.ts
+++ b/packages/trilium-core/src/services/import/keep/importer.spec.ts
@@ -16,6 +16,7 @@ describe("Google Keep importer — parseNote", () => {
expect(note).toEqual({
title: "Asdf",
content: "<p>Hi there. </p>",
+ attachments: [],
utcDateCreated: "2025-11-13 21:39:26.429Z",
utcDateModified: "2025-11-13 21:39:26.429Z"
});
@@ -131,7 +132,61 @@ describe("Google Keep importer — parseNote", () => {
it("leaves timestamps undefined and content empty for a bare note", () => {
const note = parseNote("empty.json", JSON.stringify({}));
- expect(note).toEqual({ title: "empty", content: "", utcDateCreated: undefined, utcDateModified: undefined });
+ expect(note).toEqual({ title: "empty", content: "", attachments: [], utcDateCreated: undefined, utcDateModified: undefined });
+ });
+
+ it("yields no attachments for a note with an empty (or absent) attachments array", () => {
+ expect(parseNote("n.json", JSON.stringify({ attachments: [] }))?.attachments).toEqual([]);
+ expect(parseNote("n.json", JSON.stringify({}))?.attachments).toEqual([]);
+ });
+
+ it("parses image attachments, deriving the MIME from the file extension", () => {
+ const json = JSON.stringify({
+ title: "With image",
+ textContent: "see below",
+ attachments: [{ filePath: "abc123.png", mimetype: "image/png" }]
+ });
+
+ const note = parseNote("note.json", json);
+
+ expect(note?.attachments).toEqual([{ fileName: "abc123.png", mime: "image/png" }]);
+ });
+
+ it("derives an attachment's MIME from its extension over Keep's declared mimetype", () => {
+ const json = JSON.stringify({
+ attachments: [{ filePath: "recording.3gp", mimetype: "application/octet-stream" }]
+ });
+
+ const note = parseNote("note.json", json);
+
+ // 3gp resolves to video/3gpp by extension, overriding the export's generic octet-stream.
+ expect(note?.attachments).toEqual([{ fileName: "recording.3gp", mime: "video/3gpp" }]);
+ });
+
+ it("falls an attachment's MIME back to Keep's mimetype, then octet-stream, for an unknown extension", () => {
+ const json = JSON.stringify({
+ attachments: [
+ { filePath: "mystery.weird", mimetype: "audio/amr" },
+ { filePath: "nomime.weird" }
+ ]
+ });
+
+ const note = parseNote("note.json", json);
+
+ expect(note?.attachments).toEqual([
+ { fileName: "mystery.weird", mime: "audio/amr" },
+ { fileName: "nomime.weird", mime: "application/octet-stream" }
+ ]);
+ });
+
+ it("uses an attachment's base name, dropping any path, and skips entries with no filePath", () => {
+ const json = JSON.stringify({
+ attachments: [{ filePath: "sub/dir/photo.jpg", mimetype: "image/jpeg" }, { mimetype: "image/png" }]
+ });
+
+ const note = parseNote("note.json", json);
+
+ expect(note?.attachments).toEqual([{ fileName: "photo.jpg", mime: "image/jpeg" }]);
});
it("skips a malformed JSON entry rather than throwing", () => {
diff --git a/packages/trilium-core/src/services/import/keep/importer.ts b/packages/trilium-core/src/services/import/keep/importer.ts
index ed04cb4965..632860b942 100644
--- a/packages/trilium-core/src/services/import/keep/importer.ts
+++ b/packages/trilium-core/src/services/import/keep/importer.ts
@@ -3,10 +3,10 @@
*
* Takeout exports each Keep note as `<title-or-timestamp>.json` (plus a redundant `.html`/`.txt` and any
* attachment files alongside). Keep has no hierarchy — notes are a flat list organised only by labels — so
- * this importer creates every note directly under a single "Google Keep import" root. This first iteration
- * reconstructs only the *basic structure*: each note's title, body (plain text or checklist) and original
- * timestamps. Labels, attachments, colours, pinned/archived/trashed flags and rich-text (the JSON's
- * `textContentHtml`) are deliberately deferred.
+ * this importer creates every note directly under a single "Google Keep import" root. It reconstructs each
+ * note's title, body (plain text, rich text or checklist), colour, original timestamps and any attachments
+ * (Keep stores images/audio/etc. as separate files in the zip, referenced from the note JSON's
+ * `attachments` array). Labels and pinned/archived/trashed flags are deliberately deferred.
*
* Invoked from the shared file-import dispatcher (routes/api/import.ts) when the upload is tagged
* `format=keep`, so progress, completion and failure are reported by that dispatcher's TaskContext — this
@@ -16,12 +16,15 @@
import { t } from "i18next";
import type BNote from "../../../becca/entities/bnote.js";
+import imageService from "../../image.js";
import noteService from "../../notes.js";
import protectedSessionService from "../../protected_session.js";
import { sanitizeHtml } from "../../sanitizer.js";
import type TaskContext from "../../task_context.js";
+import { decodeUtf8 } from "../../utils/binary.js";
import dateUtils from "../../utils/date.js";
import { getZipProvider } from "../../zip_provider.js";
+import mimeService from "../mime.js";
import { convertKeepHtml, convertKeepHtmlInline } from "./converter.js";
/** A checklist row in a Keep note (`listContent`). */
@@ -32,6 +35,14 @@ interface KeepListItem {
isChecked?: boolean;
}
+/** A media file (image, audio, drawing, …) attached to a Keep note; the binary lives alongside in the zip. */
+interface KeepAttachment {
+ /** The attachment's file name within the export (the zip entry's base name), e.g. "abc123.png". */
+ filePath?: string;
+ /** Keep's declared MIME type, e.g. "image/png" — used only as a fallback to the extension. */
+ mimetype?: string;
+}
+
/** The subset of a Keep Takeout note JSON this iteration reads. */
interface KeepNote {
title?: string;
@@ -41,6 +52,8 @@ interface KeepNote {
textContentHtml?: string;
/** Body of a checklist note; mutually exclusive with the text fields. */
listContent?: KeepListItem[];
+ /** Media files (images/audio/…) attached to the note, stored as separate files in the export. */
+ attachments?: KeepAttachment[];
/** Note background colour, one of Keep's named palette entries ("DEFAULT" for none). */
color?: string;
/** Creation/last-edit timestamps, in microseconds since the Unix epoch. */
@@ -48,10 +61,20 @@ interface KeepNote {
userEditedTimestampUsec?: number;
}
+/** A note attachment resolved to its export file name and the MIME we'll persist it with. */
+interface ParsedAttachment {
+ /** The attachment file's base name, used to look its binary up among the zip's non-note entries. */
+ fileName: string;
+ /** MIME derived from the file's extension, falling back to Keep's declared type then octet-stream. */
+ mime: string;
+}
+
interface ParsedNote {
title: string;
/** Body HTML; empty when the note has neither text nor list content. */
content: string;
+ /** Media attachments referenced by the note (images embedded inline, other files as links). */
+ attachments: ParsedAttachment[];
/** Hex colour for Trilium's `#color` label, or undefined for Keep's default (no colour). */
colorHex?: string;
utcDateCreated?: string;
@@ -59,33 +82,43 @@ interface ParsedNote {
}
async function importKeep(taskContext: TaskContext<"importNotes">, fileBuffer: Uint8Array, importRootNote: BNote): Promise<BNote> {
- const notes = await parseNotes(fileBuffer);
+ const { notes, binaries } = await parseNotes(fileBuffer);
taskContext.setTotalCount(notes.length);
- return createNotes(importRootNote, notes, taskContext);
+ return createNotes(importRootNote, notes, binaries, taskContext);
}
-/** Reads every note (.json entry) out of the zip, parsing its title, dates and body. */
-async function parseNotes(fileBuffer: Uint8Array): Promise<ParsedNote[]> {
+/**
+ * Reads the zip in a single pass, parsing each note (.json entry) and collecting every attachment binary
+ * (keyed by its base file name) so notes can later resolve the files they reference. The redundant per-note
+ * `.html`/`.txt` and the `Labels.txt` index are skipped.
+ */
+async function parseNotes(fileBuffer: Uint8Array): Promise<{ notes: ParsedNote[]; binaries: Map<string, Uint8Array> }> {
const provider = getZipProvider();
const filenameEncoding = await provider.detectFilenameEncoding(fileBuffer);
const notes: ParsedNote[] = [];
+ const binaries = new Map<string, Uint8Array>();
await provider.readZipFile(fileBuffer, async (entry, readContent) => {
const path = entry.fileName;
- // Each note is a .json file; the redundant per-note .html/.txt, the Labels.txt index and the
- // attachment binaries are skipped. (Labels.txt also ends in a non-.json extension, so it's covered.)
- if (!path.toLowerCase().endsWith(".json") || isDirectory(path)) {
+ if (isDirectory(path)) {
return;
}
- const parsed = parseNote(path, new TextDecoder().decode(await readContent()));
- if (parsed) {
- notes.push(parsed);
+ const lower = path.toLowerCase();
+ if (lower.endsWith(".json")) {
+ const parsed = parseNote(path, new TextDecoder().decode(await readContent()));
+ if (parsed) {
+ notes.push(parsed);
+ }
+ } else if (!lower.endsWith(".html") && !lower.endsWith(".txt")) {
+ // Everything that isn't a note or a redundant per-note .html/.txt (nor the Labels.txt index, also
+ // .txt) is an attachment binary. Key it by base name to match the note JSON's `filePath`.
+ binaries.set(baseName(path), await readContent());
}
}, filenameEncoding);
- return notes;
+ return { notes, binaries };
}
export function parseNote(path: string, json: string): ParsedNote | null {
@@ -104,12 +137,38 @@ export function parseNote(path: string, json: string): ParsedNote | null {
return {
title,
content: buildContent(note),
+ attachments: parseAttachments(note.attachments),
colorHex: keepColorToHex(note.color),
utcDateCreated: usecToUtc(note.createdTimestampUsec),
utcDateModified: usecToUtc(note.userEditedTimestampUsec)
};
}
+/**
+ * Resolves a note's `attachments` entries to the file name + MIME we'll persist them with. Entries without a
+ * `filePath` (nothing to look up) are dropped. The MIME is derived from the file's extension — Keep's own
+ * `mimetype` is only the fallback, mirroring the other importers, which trust the extension over the export's
+ * declared type.
+ */
+function parseAttachments(attachments: KeepAttachment[] | undefined): ParsedAttachment[] {
+ if (!attachments?.length) {
+ return [];
+ }
+
+ const parsed: ParsedAttachment[] = [];
+ for (const attachment of attachments) {
+ const fileName = attachment.filePath ? baseName(attachment.filePath) : "";
+ if (!fileName) {
+ continue;
+ }
+ parsed.push({
+ fileName,
+ mime: mimeService.getMime(fileName) || attachment.mimetype || "application/octet-stream"
+ });
+ }
+ return parsed;
+}
+
/**
* Builds a note's body HTML from its checklist or text content (whichever is present). For both, Keep's
* rich-text variant (`textHtml`/`textContentHtml`, basic bold/italic/underline formatting) is preferred,
@@ -149,11 +208,12 @@ function buildContent(note: KeepNote): string {
* Creates the (flat) note tree under a fresh "Google Keep import" root — Keep has no page hierarchy, so
* every note is parented directly under that root. Returns the root.
*/
-function createNotes(importRootNote: BNote, notes: ParsedNote[], taskContext: TaskContext<"importNotes">): BNote {
+function createNotes(importRootNote: BNote, notes: ParsedNote[], binaries: Map<string, Uint8Array>, taskContext: TaskContext<"importNotes">): BNote {
// The protected-session branch requires importing into a protected root with an active protected session,
// which the import harness/tests don't exercise.
/* v8 ignore next */
const isProtected = importRootNote.isProtected && protectedSessionService.isProtectedSessionAvailable();
+ const shrinkImages = !!taskContext.data?.shrinkImages;
const rootNote = noteService.createNewNote({ parentNoteId: importRootNote.noteId, title: t("keep_import.root-title"), content: "", type: "text", mime: "text/html", isProtected }).note;
rootNote.addLabel("iconClass", "bx bx-import");
@@ -174,8 +234,12 @@ function createNotes(importRootNote: BNote, notes: ParsedNote[], taskContext: Ta
note.addLabel("color", parsed.colorHex);
}
- // Preserve Keep's original timestamps. Must run after createNewNote's content save, which would
- // otherwise re-stamp the modification date with "now".
+ // Embed the note's attachments (their binaries live elsewhere in the zip). Re-saves the content, so it
+ // must precede the timestamp restore below.
+ appendAttachments(note, parsed.attachments, binaries, shrinkImages);
+
+ // Preserve Keep's original timestamps. Must run after createNewNote's content save (and the attachment
+ // re-save above), which would otherwise re-stamp the modification date with "now".
if (parsed.utcDateCreated || parsed.utcDateModified) {
note.setDateCreatedAndModified(parsed.utcDateCreated ?? parsed.utcDateModified, parsed.utcDateModified ?? parsed.utcDateCreated);
}
@@ -186,6 +250,41 @@ function createNotes(importRootNote: BNote, notes: ParsedNote[], taskContext: Ta
return rootNote;
}
+/**
+ * Persists a note's attachments and appends a reference to each onto the note's body. Keep notes carry no
+ * inline placeholder for their attachments (the JSON lists them separately), so each is appended after the
+ * text body: an image as an inline `<img>` pointing at a `role:"image"` attachment, any other file as a
+ * `role:"file"` attachment reference-link. An attachment whose binary is missing from the export is skipped.
+ * Only re-saves the content when at least one attachment was embedded.
+ */
+function appendAttachments(note: BNote, attachments: ParsedAttachment[], binaries: Map<string, Uint8Array>, shrinkImages: boolean) {
+ const additions: string[] = [];
+
+ for (const attachment of attachments) {
+ const bytes = binaries.get(attachment.fileName);
+ if (!bytes) {
+ continue;
+ }
+
+ if (attachment.mime.startsWith("image/")) {
+ const { attachmentId, title } = imageService.saveImageToAttachment(note.noteId, bytes, attachment.fileName, shrinkImages);
+ // saveImageToAttachment always returns the id of the attachment it just created, so this guard is
+ // never false in practice.
+ /* v8 ignore next */
+ if (attachmentId) {
+ additions.push(`<p><img src="api/attachments/${attachmentId}/image/${encodeURIComponent(title)}"></p>`);
+ }
+ } else {
+ const { attachmentId } = note.saveAttachment({ role: "file", mime: attachment.mime, title: attachment.fileName, content: bytes });
+ additions.push(`<p><a class="reference-link" href="#root/${note.noteId}?viewMode=attachments&attachmentId=${attachmentId}">${escapeHtml(attachment.fileName)}</a></p>`);
+ }
+ }
+
+ if (additions.length) {
+ note.setContent(sanitizeHtml(decodeUtf8(note.getContent()) + additions.join("")));
+ }
+}
+
/**
* Keep's named note colours mapped to their exact palette hex (taken from the colour classes in Keep's own
* exported `.html`). "DEFAULT" (no colour) is intentionally absent.