Notes/src/becca/entities/abstract_becca_entity.ts

325 lines
12 KiB
TypeScript
Raw Normal View History

"use strict";
import utils from "../../services/utils.js";
import sql from "../../services/sql.js";
import entityChangesService from "../../services/entity_changes.js";
import eventService from "../../services/events.js";
import dateUtils from "../../services/date_utils.js";
import cls from "../../services/cls.js";
import log from "../../services/log.js";
import protectedSessionService from "../../services/protected_session.js";
import blobService from "../../services/blob.js";
import Becca, { type ConstructorData } from "../becca-interface.js";
2024-07-19 00:49:56 +03:00
import becca from "../becca.js";
2021-04-25 21:19:18 +02:00
interface ContentOpts {
forceSave?: boolean;
forceFrontendReload?: boolean;
}
2022-04-16 00:17:32 +02:00
/**
* Base class for all backend entities.
2024-12-22 15:45:54 +02:00
*
2024-03-30 10:49:40 +02:00
* @type T the same entity type needed for self-reference in {@link ConstructorData}.
2022-04-16 00:17:32 +02:00
*/
abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {
2024-02-19 23:08:43 +02:00
utcDateModified?: string;
2024-04-06 21:55:27 +03:00
dateCreated?: string;
dateModified?: string;
2024-12-22 15:45:54 +02:00
2024-02-17 20:55:36 +02:00
utcDateCreated!: string;
2024-02-17 19:44:46 +02:00
isProtected?: boolean;
2024-03-30 10:49:40 +02:00
isSynced?: boolean;
blobId?: string;
protected beforeSaving(opts?: {}) {
2025-01-09 18:07:02 +02:00
const constructorData = this.constructor as unknown as ConstructorData<T>;
if (!(this as any)[constructorData.primaryKeyName]) {
(this as any)[constructorData.primaryKeyName] = utils.newEntityId();
}
}
2024-03-30 10:49:40 +02:00
getUtcDateChanged() {
return this.utcDateModified || this.utcDateCreated;
}
protected get becca(): Becca {
return becca;
2021-04-30 22:13:13 +02:00
}
protected putEntityChange(isDeleted: boolean) {
2025-01-09 18:07:02 +02:00
const constructorData = this.constructor as unknown as ConstructorData<T>;
2023-07-29 23:25:02 +02:00
entityChangesService.putEntityChange({
entityName: constructorData.entityName,
entityId: (this as any)[constructorData.primaryKeyName],
2021-05-08 21:10:58 +02:00
hash: this.generateHash(isDeleted),
isErased: false,
utcDateChanged: this.getUtcDateChanged(),
2025-01-09 18:07:02 +02:00
isSynced: constructorData.entityName !== "options" || !!this.isSynced
2021-05-08 21:10:58 +02:00
});
}
2024-03-30 10:49:40 +02:00
generateHash(isDeleted?: boolean): string {
2025-01-09 18:07:02 +02:00
const constructorData = this.constructor as unknown as ConstructorData<T>;
2023-09-28 00:24:53 +02:00
let contentToHash = "";
for (const propertyName of constructorData.hashedProperties) {
contentToHash += `|${(this as any)[propertyName]}`;
2023-09-28 00:24:53 +02:00
}
if (isDeleted) {
contentToHash += "|deleted";
}
return utils.hash(contentToHash).substr(0, 10);
}
protected getPojoToSave() {
return this.getPojo();
}
hasStringContent(): boolean {
2024-02-18 20:29:23 +02:00
// TODO: Not sure why some entities don't implement it.
return true;
}
abstract getPojo(): {};
2023-09-28 00:24:53 +02:00
init() {
// Do nothing by default, can be overriden in derived classes.
}
abstract updateFromRow(row: unknown): void;
get isDeleted(): boolean {
2024-02-18 20:29:23 +02:00
// TODO: Not sure why some entities don't implement it.
return false;
}
2024-02-17 10:56:27 +02:00
2022-04-16 00:17:32 +02:00
/**
2025-01-09 18:07:02 +02:00
* Saves entity - executes SQL, but doesn't commit the transaction on its own
*/
save(opts?: {}): this {
2025-01-09 18:07:02 +02:00
const constructorData = this.constructor as unknown as ConstructorData<T>;
const entityName = constructorData.entityName;
const primaryKeyName = constructorData.primaryKeyName;
2021-05-08 21:10:58 +02:00
const isNewEntity = !(this as any)[primaryKeyName];
2024-12-22 15:45:54 +02:00
this.beforeSaving(opts);
2021-05-08 21:10:58 +02:00
const pojo = this.getPojoToSave();
2021-05-08 21:10:58 +02:00
sql.transactional(() => {
sql.upsert(entityName, primaryKeyName, pojo);
2025-01-09 18:07:02 +02:00
if (entityName === "recent_notes") {
2021-05-08 21:10:58 +02:00
return;
}
2023-09-28 00:24:53 +02:00
this.putEntityChange(!!this.isDeleted);
2021-05-08 21:10:58 +02:00
if (!cls.isEntityEventsDisabled()) {
const eventPayload = {
entityName,
entity: this
};
if (isNewEntity) {
eventService.emit(eventService.ENTITY_CREATED, eventPayload);
}
eventService.emit(eventService.ENTITY_CHANGED, eventPayload);
}
});
return this;
}
2021-05-08 21:10:58 +02:00
protected _setContent(content: string | Buffer, opts: ContentOpts = {}) {
2023-03-16 16:37:31 +01:00
// client code asks to save entity even if blobId didn't change (something else was changed)
opts.forceSave = !!opts.forceSave;
2023-05-03 10:23:20 +02:00
opts.forceFrontendReload = !!opts.forceFrontendReload;
2023-03-16 16:37:31 +01:00
if (content === null || content === undefined) {
2025-01-09 18:07:02 +02:00
const constructorData = this.constructor as unknown as ConstructorData<T>;
throw new Error(`Cannot set null content to ${constructorData.primaryKeyName} '${(this as any)[constructorData.primaryKeyName]}'`);
}
2023-05-05 16:37:39 +02:00
if (this.hasStringContent()) {
content = content.toString();
2023-07-27 23:22:08 +02:00
} else {
content = Buffer.isBuffer(content) ? content : Buffer.from(content);
}
const unencryptedContentForHashCalculation = this.getUnencryptedContentForHashCalculation(content);
2023-04-25 00:01:58 +02:00
if (this.isProtected) {
if (protectedSessionService.isProtectedSessionAvailable()) {
const encryptedContent = protectedSessionService.encrypt(content);
if (!encryptedContent) {
2024-12-22 15:45:54 +02:00
throw new Error(`Unable to encrypt the content of the entity.`);
}
content = encryptedContent;
2023-06-04 20:51:08 +02:00
} else {
throw new Error(`Cannot update content of blob since protected session is not available.`);
}
}
sql.transactional(() => {
const newBlobId = this.saveBlob(content, unencryptedContentForHashCalculation, opts);
const oldBlobId = this.blobId;
if (newBlobId !== oldBlobId || opts.forceSave) {
this.blobId = newBlobId;
this.save();
if (oldBlobId && newBlobId !== oldBlobId) {
this.deleteBlobIfNotUsed(oldBlobId);
}
}
});
}
private deleteBlobIfNotUsed(oldBlobId: string) {
2023-07-27 23:22:08 +02:00
if (sql.getValue("SELECT 1 FROM notes WHERE blobId = ? LIMIT 1", [oldBlobId])) {
return;
}
2023-07-27 23:22:08 +02:00
if (sql.getValue("SELECT 1 FROM attachments WHERE blobId = ? LIMIT 1", [oldBlobId])) {
return;
}
2023-07-27 23:22:08 +02:00
if (sql.getValue("SELECT 1 FROM revisions WHERE blobId = ? LIMIT 1", [oldBlobId])) {
return;
}
2023-07-27 23:22:08 +02:00
sql.execute("DELETE FROM blobs WHERE blobId = ?", [oldBlobId]);
// blobs are not marked as erased in entity_changes, they are just purged completely
// this is because technically every keystroke can create a new blob, and there would be just too many
2023-07-27 23:22:08 +02:00
sql.execute("DELETE FROM entity_changes WHERE entityName = 'blobs' AND entityId = ?", [oldBlobId]);
}
private getUnencryptedContentForHashCalculation(unencryptedContent: Buffer | string) {
2023-06-04 20:51:08 +02:00
if (this.isProtected) {
2023-07-27 23:22:08 +02:00
// a "random" prefix makes sure that the calculated hash/blobId is different for a decrypted/encrypted content
2023-06-04 20:51:08 +02:00
const encryptedPrefixSuffix = "t$[nvQg7q)&_ENCRYPTED_?M:Bf&j3jr_";
2025-01-09 18:07:02 +02:00
return Buffer.isBuffer(unencryptedContent) ? Buffer.concat([Buffer.from(encryptedPrefixSuffix), unencryptedContent]) : `${encryptedPrefixSuffix}${unencryptedContent}`;
2023-06-04 20:51:08 +02:00
} else {
return unencryptedContent;
}
}
private saveBlob(content: string | Buffer, unencryptedContentForHashCalculation: string | Buffer, opts: ContentOpts = {}) {
/*
2025-01-09 18:07:02 +02:00
* We're using the unencrypted blob for the hash calculation, because otherwise the random IV would
* cause every content blob to be unique which would balloon the database size (esp. with revisioning).
* This has minor security implications (it's easy to infer that given content is shared between different
* notes/attachments), but the trade-off comes out clearly positive.
*/
const newBlobId = utils.hashedBlobId(unencryptedContentForHashCalculation);
2025-01-09 18:07:02 +02:00
const blobNeedsInsert = !sql.getValue("SELECT 1 FROM blobs WHERE blobId = ?", [newBlobId]);
if (!blobNeedsInsert) {
return newBlobId;
}
const pojo = {
blobId: newBlobId,
content: content,
dateModified: dateUtils.localNowDateTime(),
utcDateModified: dateUtils.utcNowDateTime()
};
sql.upsert("blobs", "blobId", pojo);
2023-07-27 23:22:08 +02:00
// we can't reuse blobId as an entity_changes hash, because this one has to be calculatable without having
// access to the decrypted content
const hash = blobService.calculateContentHash(pojo);
2023-07-29 23:25:02 +02:00
entityChangesService.putEntityChange({
2025-01-09 18:07:02 +02:00
entityName: "blobs",
entityId: newBlobId,
hash: hash,
isErased: false,
utcDateChanged: pojo.utcDateModified,
isSynced: true,
// overriding componentId will cause the frontend to think the change is coming from a different component
// and thus reload
componentId: opts.forceFrontendReload ? utils.randomString(10) : null
});
eventService.emit(eventService.ENTITY_CHANGED, {
2025-01-09 18:07:02 +02:00
entityName: "blobs",
entity: this
});
return newBlobId;
}
2024-12-22 15:45:54 +02:00
protected _getContent(): string | Buffer {
const row = sql.getRow<{ content: string | Buffer }>(`SELECT content FROM blobs WHERE blobId = ?`, [this.blobId]);
if (!row) {
2025-01-09 18:07:02 +02:00
const constructorData = this.constructor as unknown as ConstructorData<T>;
throw new Error(`Cannot find content for ${constructorData.primaryKeyName} '${(this as any)[constructorData.primaryKeyName]}', blobId '${this.blobId}'`);
}
return blobService.processContent(row.content, this.isProtected || false, this.hasStringContent());
}
2022-04-16 00:17:32 +02:00
/**
2025-01-09 18:07:02 +02:00
* Mark the entity as (soft) deleted. It will be completely erased later.
*
* This is a low-level method, for notes and branches use `note.deleteNote()` and 'branch.deleteBranch()` instead.
*/
markAsDeleted(deleteId: string | null = null) {
2025-01-09 18:07:02 +02:00
const constructorData = this.constructor as unknown as ConstructorData<T>;
const entityId = (this as any)[constructorData.primaryKeyName];
const entityName = constructorData.entityName;
2021-05-08 21:10:58 +02:00
this.utcDateModified = dateUtils.utcNowDateTime();
2025-01-09 18:07:02 +02:00
sql.execute(
`UPDATE ${entityName} SET isDeleted = 1, deleteId = ?, utcDateModified = ?
2024-12-22 15:45:54 +02:00
WHERE ${constructorData.primaryKeyName} = ?`,
2025-01-09 18:07:02 +02:00
[deleteId, this.utcDateModified, entityId]
);
2021-05-09 11:12:53 +02:00
if (this.dateModified) {
this.dateModified = dateUtils.localNowDateTime();
2025-01-09 18:07:02 +02:00
sql.execute(`UPDATE ${entityName} SET dateModified = ? WHERE ${constructorData.primaryKeyName} = ?`, [this.dateModified, entityId]);
2021-05-09 11:12:53 +02:00
}
2021-05-08 21:10:58 +02:00
2022-01-31 21:25:18 +01:00
log.info(`Marking ${entityName} ${entityId} as deleted`);
2023-07-29 23:25:02 +02:00
this.putEntityChange(true);
2021-05-08 21:10:58 +02:00
eventService.emit(eventService.ENTITY_DELETED, { entityName, entityId, entity: this });
2021-05-08 21:10:58 +02:00
}
2022-01-10 17:09:20 +01:00
markAsDeletedSimple() {
2025-01-09 18:07:02 +02:00
const constructorData = this.constructor as unknown as ConstructorData<T>;
const entityId = (this as any)[constructorData.primaryKeyName];
const entityName = constructorData.entityName;
2022-01-10 17:09:20 +01:00
2022-01-31 21:25:18 +01:00
this.utcDateModified = dateUtils.utcNowDateTime();
2025-01-09 18:07:02 +02:00
sql.execute(
`UPDATE ${entityName} SET isDeleted = 1, utcDateModified = ?
2024-12-22 15:45:54 +02:00
WHERE ${constructorData.primaryKeyName} = ?`,
2025-01-09 18:07:02 +02:00
[this.utcDateModified, entityId]
);
2022-01-31 21:25:18 +01:00
log.info(`Marking ${entityName} ${entityId} as deleted`);
2022-01-10 17:09:20 +01:00
2023-07-29 23:25:02 +02:00
this.putEntityChange(true);
2022-01-10 17:09:20 +01:00
eventService.emit(eventService.ENTITY_DELETED, { entityName, entityId, entity: this });
}
}
export default AbstractBeccaEntity;