Skip to content

Build your personal knowledge base with Trilium Notes

feat(ocr): keep extracted text when a note is protected or unprotected

Elian Dorane66667c054e2
diff --git a/apps/server/src/services/ocr/ocr_service.spec.ts b/apps/server/src/services/ocr/ocr_service.spec.ts
index 791fe861fd..ef6773f320 100644
--- a/apps/server/src/services/ocr/ocr_service.spec.ts
+++ b/apps/server/src/services/ocr/ocr_service.spec.ts
@@ -35,18 +35,16 @@ const mockSql = {
const mockBecca = {
getNote: vi.fn(),
- getAttachment: vi.fn(),
- getBlob: vi.fn()
+ getAttachment: vi.fn()
};
const mockBlobService = {
- calculateContentHash: vi.fn().mockReturnValue('hash123'),
// Stands in for the real encryption: distinguishable from the plain text, and reversible by eye.
encryptTextRepresentation: vi.fn((text: string, isProtected: boolean) => (isProtected ? `encrypted(${text})` : text))
};
const mockEntityChangesService = {
- putEntityChange: vi.fn()
+ putBlobEntityChange: vi.fn()
};
vi.mock('../sql.js', () => ({
@@ -86,14 +84,6 @@ beforeEach(async () => {
mockSql.getRows.mockReturnValue([]);
mockSql.getColumn.mockReturnValue([]);
- // Mock getBlob for putBlobEntityChange
- mockBecca.getBlob.mockReturnValue({
- blobId: 'blob123',
- content: Buffer.from('data'),
- textRepresentation: null,
- utcDateModified: '2025-01-01'
- });
-
mockTesseract.createWorker.mockImplementation(async () => {
return mockWorker;
});
@@ -459,9 +449,8 @@ describe('OCRService', () => {
(mockNote as any).blobId = 'blob123';
});
- it('skips storing the blob entity change when blob is missing', async () => {
+ it('has the stored blob re-hashed for sync, since the text is not part of its identity', async () => {
mockSql.getRow.mockReturnValue(null);
- mockBecca.getBlob.mockReturnValue(null);
mockWorker.recognize.mockResolvedValue({
data: { text: 'text', confidence: 90, words: [] }
});
@@ -469,7 +458,7 @@ describe('OCRService', () => {
const result = await ocrService.processNoteOCR('note123');
expect(result?.text).toBe('text');
- expect(mockEntityChangesService.putEntityChange).not.toHaveBeenCalled();
+ expect(mockEntityChangesService.putBlobEntityChange).toHaveBeenCalledWith('blob123');
});
});
diff --git a/apps/server/src/services/ocr/ocr_service.ts b/apps/server/src/services/ocr/ocr_service.ts
index ce9581a006..4e5bd4f2f6 100644
--- a/apps/server/src/services/ocr/ocr_service.ts
+++ b/apps/server/src/services/ocr/ocr_service.ts
@@ -242,7 +242,7 @@ class OCRService {
WHERE blobId = ?
`, [textRepresentation, blobId]);
- this.putBlobEntityChange(blobId);
+ entityChangesService.putBlobEntityChange(blobId);
getLog().info(`Stored OCR result for blob ${blobId}`);
} catch (error) {
@@ -382,28 +382,6 @@ class OCRService {
/**
* Get processor for a given MIME type
*/
- /**
- * Notifies the sync system that a blob has changed, without modifying the blob's identity.
- */
- private putBlobEntityChange(blobId: string): void {
- const blob = becca.getBlob({ blobId });
- if (!blob || !blob.blobId) return;
-
- const hash = blobService.calculateContentHash({
- blobId: blob.blobId,
- content: blob.content,
- textRepresentation: blob.textRepresentation
- });
- entityChangesService.putEntityChange({
- entityName: "blobs",
- entityId: blobId,
- hash,
- isErased: false,
- utcDateChanged: blob.utcDateModified,
- isSynced: true
- });
- }
-
private getProcessorForMimeType(mimeType: string): FileProcessor | null {
for (const processor of this.processors.values()) {
if (processor.canProcess(mimeType)) {
diff --git a/packages/trilium-core/src/services/entity_changes.ts b/packages/trilium-core/src/services/entity_changes.ts
index 7ad3c75f76..49d1173341 100644
--- a/packages/trilium-core/src/services/entity_changes.ts
+++ b/packages/trilium-core/src/services/entity_changes.ts
@@ -46,6 +46,34 @@ function putEntityChange(origEntityChange: EntityChange) {
cls.putEntityChange(ec);
}
+/**
+ * Re-records a blob's entity change from what is stored on it now, leaving the blob itself alone.
+ *
+ * A blob is identified by a hash of its content, so it is normally recorded once, when it is written,
+ * and never again. Its text representation is not part of that identity and is filled in afterwards —
+ * by OCR, or by carrying the text across a change of protection — which leaves the recorded hash
+ * describing a row that no longer matches, and sync comparing against something that was never stored.
+ */
+function putBlobEntityChange(blobId: string) {
+ const blob = getSql().getRowOrNull<Pick<BlobRow, "blobId" | "content" | "utcDateModified" | "textRepresentation">>(
+ /*sql*/`SELECT blobId, content, textRepresentation, utcDateModified FROM blobs WHERE blobId = ?`,
+ [blobId]
+ );
+
+ if (!blob) {
+ return;
+ }
+
+ putEntityChange({
+ entityName: "blobs",
+ entityId: blobId,
+ hash: blobService.calculateContentHash(blob),
+ isErased: false,
+ utcDateChanged: blob.utcDateModified,
+ isSynced: true // blobs are always synced
+ } as EntityChange);
+}
+
function putNoteReorderingEntityChange(parentNoteId: string, componentId?: string) {
putEntityChange({
entityName: "note_reordering",
@@ -199,6 +227,7 @@ function recalculateMaxEntityChangeId() {
}
export default {
+ putBlobEntityChange,
putNoteReorderingEntityChange,
putEntityChangeForOtherInstances,
putEntityChangeWithForcedChange,
diff --git a/packages/trilium-core/src/services/notes.spec.ts b/packages/trilium-core/src/services/notes.spec.ts
index 3d3fa8cb26..6197ff0f22 100644
--- a/packages/trilium-core/src/services/notes.spec.ts
+++ b/packages/trilium-core/src/services/notes.spec.ts
@@ -1,15 +1,19 @@
-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import becca from "../becca/becca.js";
import type BBranch from "../becca/entities/bbranch.js";
import type BNote from "../becca/entities/bnote.js";
+import blobService from "./blob.js";
import { disableEntityEvents, getContext } from "./context.js";
import { getLog } from "./log.js";
import noteService, { prepareTitle, saveLinks } from "./notes.js";
import optionService from "./options.js";
+import protectedSessionService from "./protected_session.js";
import { fakeRequestProvider } from "../test/request_provider.js";
import { initRequest } from "./request.js";
import { getSql } from "./sql/index.js";
+import TaskContext from "./task_context.js";
+import { encodeUtf8 } from "./utils/binary.js";
/**
* The pure link-extraction helpers (findBookmarks, findLlmChatLinks) and the
@@ -41,6 +45,70 @@ function createNote(parentNoteId: string, overrides: Partial<Parameters<typeof n
);
}
+describe("OCR text across (un)protection", () => {
+ const PROTECTED_KEY = encodeUtf8("0123456789abcdef"); // exactly 16 bytes
+
+ /** The text as it is stored on the blob right now, without decrypting it. */
+ function storedText(blobId: string | undefined) {
+ return getSql().getValue<string | null>("SELECT textRepresentation FROM blobs WHERE blobId = ?", [blobId ?? ""]);
+ }
+
+ function setStoredText(blobId: string | undefined, text: string) {
+ getSql().execute("UPDATE blobs SET textRepresentation = ? WHERE blobId = ?", [text, blobId ?? ""]);
+ }
+
+ function protect(note: BNote, value: boolean) {
+ getContext().init(() =>
+ noteService.protectNoteRecursively(note, value, false, new TaskContext("spec-protect", "protectNotes", { protect: value }))
+ );
+ }
+
+ afterEach(() => protectedSessionService.resetDataKey());
+
+ it("carries a note's extracted text onto the blob the re-save produces, encrypting it", () => {
+ const { note } = createNote("root", { title: "spec-ocr-carry", content: "image-bytes-carry", type: "image", mime: "image/png" });
+ setStoredText(note.blobId, "text read out of the picture");
+ const unprotectedBlobId = note.blobId;
+
+ protectedSessionService.setDataKey(PROTECTED_KEY);
+ protect(note, true);
+
+ // A new blob, since protection is part of a blob's identity — and the text came with it.
+ expect(note.blobId).not.toBe(unprotectedBlobId);
+ expect(storedText(note.blobId)).not.toBe("text read out of the picture");
+ expect(blobService.decryptTextRepresentation(storedText(note.blobId), true)).toBe("text read out of the picture");
+
+ // And back again, readable without a key once the note no longer needs one.
+ protect(note, false);
+ expect(storedText(note.blobId)).toBe("text read out of the picture");
+ });
+
+ it("carries an attachment's extracted text too", () => {
+ const { note } = createNote("root", { title: "spec-ocr-carry-attachment" });
+ const attachment = getContext().init(() =>
+ note.saveAttachment({ role: "image", mime: "image/png", title: "scan.png", content: "attachment-bytes-carry" })
+ );
+ setStoredText(attachment.blobId, "text read out of the attachment");
+
+ protectedSessionService.setDataKey(PROTECTED_KEY);
+ protect(note, true);
+
+ const protectedAttachment = becca.getAttachmentOrThrow(attachment.attachmentId);
+ expect(protectedAttachment.isProtected).toBe(true);
+ expect(blobService.decryptTextRepresentation(storedText(protectedAttachment.blobId), true))
+ .toBe("text read out of the attachment");
+ });
+
+ it("leaves a note that never had extracted text without any", () => {
+ const { note } = createNote("root", { title: "spec-ocr-carry-none", content: "image-bytes-none", type: "image", mime: "image/png" });
+
+ protectedSessionService.setDataKey(PROTECTED_KEY);
+ protect(note, true);
+
+ expect(storedText(note.blobId)).toBeNull();
+ });
+});
+
describe("notes service (real DB)", () => {
beforeAll(() => {
// The in-memory fixture DB and initializeCore are booted by the
diff --git a/packages/trilium-core/src/services/notes.ts b/packages/trilium-core/src/services/notes.ts
index 8afc458e43..f4ae5813af 100644
--- a/packages/trilium-core/src/services/notes.ts
+++ b/packages/trilium-core/src/services/notes.ts
@@ -10,6 +10,7 @@ import BNote from "../becca/entities/bnote.js";
import { ValidationError } from "../errors.js";
import { getLog } from "../services/log.js";
import protectedSessionService from "../services/protected_session.js";
+import blobService from "./blob.js";
import * as cls from "./context.js";
import entityChangesService from "./entity_changes.js";
import eventService from "./events.js";
@@ -414,9 +415,12 @@ function protectNote(note: BNote, protect: boolean) {
try {
if (protect !== note.isProtected) {
const content = note.getContent();
+ const extractedText = readExtractedText(note.blobId, note.isProtected);
note.isProtected = protect;
note.setContent(content, { forceSave: true });
+
+ writeExtractedText(note.blobId, extractedText, protect);
}
revisionService.protectRevisions(note);
@@ -425,9 +429,12 @@ function protectNote(note: BNote, protect: boolean) {
if (protect !== attachment.isProtected) {
try {
const content = attachment.getContent();
+ const extractedText = readExtractedText(attachment.blobId, attachment.isProtected);
attachment.isProtected = protect;
attachment.setContent(content, { forceSave: true });
+
+ writeExtractedText(attachment.blobId, extractedText, protect);
} catch (e) {
log.error(`Could not un/protect attachment '${attachment.attachmentId}'`);
@@ -442,6 +449,41 @@ function protectNote(note: BNote, protect: boolean) {
}
}
+/**
+ * The text OCR pulled out of a file, read off the blob holding it.
+ *
+ * (Un)protecting re-saves content that has not changed a byte, but a blob's identity takes its
+ * protection into account, so the re-save lands on a different row — one with no extracted text on it.
+ * The text describes the same file either way, so it is read here while the old state still says how
+ * it is stored, and put back by {@link writeExtractedText} once the new state does.
+ */
+function readExtractedText(blobId: string | undefined, isProtected: boolean | undefined): string {
+ if (!blobId) {
+ return "";
+ }
+
+ const row = getSql().getRowOrNull<{ textRepresentation: string | null }>(
+ /*sql*/`SELECT textRepresentation FROM blobs WHERE blobId = ?`,
+ [blobId]
+ );
+
+ return blobService.decryptTextRepresentation(row?.textRepresentation, !!isProtected);
+}
+
+/** Puts {@link readExtractedText}'s text back, on the blob the re-save produced and in its terms. */
+function writeExtractedText(blobId: string | undefined, extractedText: string, isProtected: boolean) {
+ if (!blobId || !extractedText) {
+ return;
+ }
+
+ getSql().execute(
+ /*sql*/`UPDATE blobs SET textRepresentation = ? WHERE blobId = ?`,
+ [blobService.encryptTextRepresentation(extractedText, isProtected), blobId]
+ );
+
+ entityChangesService.putBlobEntityChange(blobId);
+}
+
export function checkImageAttachments(note: BNote, content: string) {
// Canvas references images by the Excalidraw fileId stored as the attachment *title* in its
// scene JSON, so orphans are detected by title; every other type references them by attachmentId
diff --git a/packages/trilium-core/src/services/sql/sql.spec.ts b/packages/trilium-core/src/services/sql/sql.spec.ts
index 6bf5a22016..f6a05052ce 100644
--- a/packages/trilium-core/src/services/sql/sql.spec.ts
+++ b/packages/trilium-core/src/services/sql/sql.spec.ts
@@ -90,15 +90,12 @@ describe("SqlService (real DB)", () => {
getSql().insert(table, { name: "b", val: 2 });
expect(getSql().getValue<number>(`SELECT COUNT(*) FROM "${table}"`)).toBe(2);
- // Distinct query strings: getColumn pluck-mode and getRows row-mode
- // share the statement cache by query text, so reusing the exact same
- // string would leave the cached statement stuck in pluck mode.
expect(
- getSql().getColumn<string>(`SELECT name FROM "${table}" /*col*/ ORDER BY val`)
+ getSql().getColumn<string>(`SELECT name FROM "${table}" ORDER BY val`)
).toEqual(["a", "b"]);
const all = getSql().getRows<{ name: string }>(
- `SELECT name FROM "${table}" /*rows*/ ORDER BY val`
+ `SELECT name FROM "${table}" ORDER BY val`
);
expect(all.map((r) => r.name)).toEqual(["a", "b"]);
@@ -114,6 +111,27 @@ describe("SqlService (real DB)", () => {
expect(single).toEqual({ name: "b" });
});
+ it("keeps a plucking reader from changing what the same query returns to a row reader", () => {
+ // The statement cache is keyed by query text and both pluck and raw stick to a statement
+ // once set, so a plucking read used to leave every later read of the byte-identical query
+ // returning bare values instead of rows — for the rest of the process, and wherever in the
+ // codebase that query happened to be repeated.
+ const table = createTempTable();
+ getSql().insert(table, { name: "a", val: 1 });
+ const query = `SELECT name FROM "${table}" WHERE val = ?`;
+
+ expect(getSql().getValue<string>(query, [1])).toBe("a");
+ expect(getSql().getRow<{ name: string }>(query, [1])).toEqual({ name: "a" });
+ expect(getSql().getRowOrNull<{ name: string }>(query, [1])).toEqual({ name: "a" });
+ expect(getSql().getRows<{ name: string }>(query, [1])).toEqual([{ name: "a" }]);
+
+ // ...and in the other order, so neither mode is merely winning by going first.
+ const reverse = `SELECT name FROM "${table}" WHERE val = ? /* reverse */`;
+ expect(getSql().getRows<{ name: string }>(reverse, [1])).toEqual([{ name: "a" }]);
+ expect(getSql().getColumn<string>(reverse, [1])).toEqual(["a"]);
+ expect(getSql().getRow<{ name: string }>(reverse, [1])).toEqual({ name: "a" });
+ });
+
it("getRowOrNull returns null when no rows match", () => {
const table = createTempTable();
expect(getSql().getRowOrNull(`SELECT name FROM "${table}" WHERE val = ?`, [999])).toBeNull();
@@ -159,15 +177,20 @@ describe("SqlService (real DB)", () => {
expect(a).toBe(b);
});
- // Node's better-sqlite3 provider prepares a fresh statement object per
- // cache key, so raw vs non-raw yield distinct instances. The WASM
- // (sql.js) provider may hand back the same object for identical SQL, so
- // this distinctness is a Node-provider impl detail, not a portable contract.
- it.skipIf(isBrowserRuntime)("keeps raw and non-raw statements as distinct cache entries", () => {
- const sql = getSql();
- const plain = sql.stmt("SELECT 2");
- const raw = sql.stmt("SELECT 2", true);
- expect(plain).not.toBe(raw);
+ it("reads one query in every shape, whichever was asked for first", () => {
+ // Statements are shared and their output mode sticks, so the shape a read gets has to come
+ // from the read rather than from whatever the last one left behind. Keeping the modes in
+ // separate cache entries was not enough: the browser provider caches by query text too, and
+ // handed both entries the same statement.
+ const table = createTempTable();
+ getSql().insert(table, { name: "a", val: 1 });
+ const query = `SELECT name, val FROM "${table}"`;
+
+ expect(getSql().getColumn<string>(query)).toEqual(["a"]);
+ expect(getSql().getRawRows<[string, number]>(query)).toEqual([["a", 1]]);
+ expect(getSql().getRows<{ name: string; val: number }>(query)).toEqual([{ name: "a", val: 1 }]);
+ expect(getSql().getValue<string>(query)).toBe("a");
+ expect(getSql().getRow<{ name: string; val: number }>(query)).toEqual({ name: "a", val: 1 });
});
});
diff --git a/packages/trilium-core/src/services/sql/sql.ts b/packages/trilium-core/src/services/sql/sql.ts
index 95c1d5d153..22b5515244 100644
--- a/packages/trilium-core/src/services/sql/sql.ts
+++ b/packages/trilium-core/src/services/sql/sql.ts
@@ -7,6 +7,12 @@ const LOG_ALL_QUERIES = false;
// smaller values can result in better performance due to better usage of statement cache
const PARAM_LIMIT = 100;
+/**
+ * The output shapes a prepared statement can return: rows as objects, rows as arrays (`raw`), or the
+ * first column alone (`pluck`). Each sticks to the statement once set, so a reader always names one.
+ */
+type StatementMode = "row" | "raw" | "pluck";
+
export interface SqlServiceParams {
provider: DatabaseProvider;
onTransactionRollback: () => void;
@@ -133,18 +139,32 @@ export class SqlService {
/**
* For the given SQL query, returns a prepared statement. For the same query (string comparison), the same statement is returned.
*
+ * The statement carries its output mode, and the mode sticks to it: a `pluck()` or `raw()` set for
+ * one read stays set for every later read of the same query. Since the statement is shared — by
+ * this cache, and again by the browser provider's own — a read never inherits a mode. Every reader
+ * states the shape it wants through {@link applyMode()} instead.
+ *
* @param sql the SQL query for which to return a prepared statement.
- * @param isRaw indicates whether `.raw()` is going to be called on the prepared statement in order to return the raw rows (e.g. via {@link getRawRows()}). The reason is that the raw state is preserved in the saved statement and would break non-raw calls for the same query.
* @returns the corresponding {@link Statement}.
*/
- stmt(sql: string, isRaw?: boolean) {
- const key = (isRaw ? `raw/${sql}` : sql);
-
- if (!(key in this.statementCache)) {
- this.statementCache[key] = this.dbConnection.prepare(sql);
+ stmt(sql: string) {
+ if (!(sql in this.statementCache)) {
+ this.statementCache[sql] = this.dbConnection.prepare(sql);
}
- return this.statementCache[key];
+ return this.statementCache[sql];
+ }
+
+ /**
+ * Puts a statement into the output mode a reader wants, turning the other modes off.
+ *
+ * Only for statements that return data: better-sqlite3 rejects both calls on one that does not.
+ */
+ private applyMode(statement: Statement, mode: StatementMode): Statement {
+ statement.raw(mode === "raw");
+ statement.pluck(mode === "pluck");
+
+ return statement;
}
/**
@@ -155,7 +175,7 @@ export class SqlService {
* @returns - map of column name to column value
*/
getRow<T>(query: string, params: Params = []): T {
- return this.wrap(query, (s) => s.get(params)) as T;
+ return this.wrap(query, (s) => s.get(params), "row") as T;
}
getRowOrNull<T>(query: string, params: Params = []): T | null {
@@ -175,7 +195,7 @@ export class SqlService {
* @returns single value
*/
getValue<T>(query: string, params: Params = []): T {
- return this.wrap(query, (s) => s.pluck().get(params)) as T;
+ return this.wrap(query, (s) => s.get(params), "pluck") as T;
}
getManyRows<T>(query: string, params: Params): T[] {
@@ -198,7 +218,7 @@ export class SqlService {
const statement = curParams.length === PARAM_LIMIT ? this.stmt(curQuery) : this.dbConnection.prepare(curQuery);
- const subResults = statement.all(curParamsObj);
+ const subResults = this.applyMode(statement, "row").all(curParamsObj);
results = results.concat(subResults);
}
@@ -213,11 +233,11 @@ export class SqlService {
* @returns - array of all rows, each row is a map of column name to column value
*/
getRows<T>(query: string, params: Params = []): T[] {
- return this.wrap(query, (s) => s.all(params)) as T[];
+ return this.wrap(query, (s) => s.all(params), "row") as T[];
}
getRawRows<T extends {} | unknown[]>(query: string, params: Params = []): T[] {
- return (this.wrap(query, (s) => s.raw().all(params), true) as T[]) || [];
+ return (this.wrap(query, (s) => s.all(params), "raw") as T[]) || [];
}
iterateRows<T>(query: string, params: Params = []): IterableIterator<T> {
@@ -225,7 +245,7 @@ export class SqlService {
console.log(query);
}
- return this.stmt(query).iterate(params) as IterableIterator<T>;
+ return this.applyMode(this.stmt(query), "row").iterate(params) as IterableIterator<T>;
}
/**
@@ -254,7 +274,7 @@ export class SqlService {
* @returns array of first column of all returned rows
*/
getColumn<T>(query: string, params: Params = []): T[] {
- return this.wrap(query, (s) => s.pluck().all(params)) as T[];
+ return this.wrap(query, (s) => s.all(params), "pluck") as T[];
}
/**
@@ -307,9 +327,10 @@ export class SqlService {
}
/**
- * @param isRaw indicates whether `.raw()` is going to be called on the prepared statement in order to return the raw rows (e.g. via {@link getRawRows()}). The reason is that the raw state is preserved in the saved statement and would break non-raw calls for the same query.
+ * @param mode the output shape `func` reads the statement in. Omitted for a statement that returns
+ * no data, which cannot be put into a mode at all. See {@link stmt()} for why a reader names one.
*/
- wrap(query: string, func: (statement: Statement) => unknown, isRaw?: boolean): unknown {
+ wrap(query: string, func: (statement: Statement) => unknown, mode?: StatementMode): unknown {
const startTimestamp = Date.now();
let result;
@@ -318,7 +339,9 @@ export class SqlService {
}
try {
- result = func(this.stmt(query, isRaw));
+ const statement = this.stmt(query);
+
+ result = func(mode ? this.applyMode(statement, mode) : statement);
} catch (e: any) {
if (e.message.includes("The database connection is not open")) {
// this often happens on killing the app which puts these alerts in front of user