chore(core): integrate notes route

This commit is contained in:
Elian Doran
2026-01-07 12:00:38 +02:00
parent dd58eac4b0
commit ab0800a9f3
3 changed files with 31 additions and 27 deletions

View File

@@ -1,380 +0,0 @@
import type { AttributeRow, CreateChildrenResponse, DeleteNotesPreview, MetadataResponse } from "@triliumnext/commons";
import { blob as blobService, erase as eraseService, ValidationError } from "@triliumnext/core";
import type { Request } from "express";
import becca from "../../becca/becca.js";
import type BBranch from "../../becca/entities/bbranch.js";
import log from "../../services/log.js";
import noteService from "../../services/notes.js";
import sql from "../../services/sql.js";
import TaskContext from "../../services/task_context.js";
import treeService from "../../services/tree.js";
import utils from "../../services/utils.js";
/**
* @swagger
* /api/notes/{noteId}:
* get:
* summary: Retrieve note metadata
* operationId: notes-get
* parameters:
* - name: noteId
* in: path
* required: true
* schema:
* $ref: "#/components/schemas/NoteId"
* responses:
* '200':
* description: Note metadata
* content:
* application/json:
* schema:
* allOf:
* - $ref: '#/components/schemas/Note'
* - $ref: "#/components/schemas/Timestamps"
* security:
* - session: []
* tags: ["data"]
*/
function getNote(req: Request) {
return becca.getNoteOrThrow(req.params.noteId);
}
/**
* @swagger
* /api/notes/{noteId}/blob:
* get:
* summary: Retrieve note content
* operationId: notes-blob
* parameters:
* - name: noteId
* in: path
* required: true
* schema:
* $ref: "#/components/schemas/NoteId"
* responses:
* '304':
* description: Note content
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Blob'
* security:
* - session: []
* tags: ["data"]
*/
function getNoteBlob(req: Request) {
return blobService.getBlobPojo("notes", req.params.noteId);
}
/**
* @swagger
* /api/notes/{noteId}/metadata:
* get:
* summary: Retrieve note metadata (limited to timestamps)
* operationId: notes-metadata
* parameters:
* - name: noteId
* in: path
* required: true
* schema:
* $ref: "#/components/schemas/NoteId"
* responses:
* '200':
* description: Note metadata
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Timestamps"
* security:
* - session: []
* tags: ["data"]
*/
function getNoteMetadata(req: Request) {
const note = becca.getNoteOrThrow(req.params.noteId);
return {
dateCreated: note.dateCreated,
utcDateCreated: note.utcDateCreated,
dateModified: note.dateModified,
utcDateModified: note.utcDateModified
} satisfies MetadataResponse;
}
function createNote(req: Request) {
const params = Object.assign({}, req.body); // clone
params.parentNoteId = req.params.parentNoteId;
const { target, targetBranchId } = req.query;
if (target !== "into" && target !== "after" && target !== "before") {
throw new ValidationError("Invalid target type.");
}
if (targetBranchId && typeof targetBranchId !== "string") {
throw new ValidationError("Missing or incorrect type for target branch ID.");
}
const { note, branch } = noteService.createNewNoteWithTarget(target, String(targetBranchId), params);
return {
note,
branch
} satisfies CreateChildrenResponse;
}
function updateNoteData(req: Request) {
const { content, attachments } = req.body;
const { noteId } = req.params;
return noteService.updateNoteData(noteId, content, attachments);
}
/**
* @swagger
* /api/notes/{noteId}:
* delete:
* summary: Delete note
* operationId: notes-delete
* parameters:
* - name: noteId
* in: path
* required: true
* schema:
* $ref: "#/components/schemas/NoteId"
* - name: taskId
* in: query
* required: true
* schema:
* type: string
* description: Task group identifier
* - name: eraseNotes
* in: query
* schema:
* type: boolean
* required: false
* description: Whether to erase the note immediately
* - name: last
* in: query
* schema:
* type: boolean
* required: true
* description: Whether this is the last request of this task group
* responses:
* '200':
* description: Note successfully deleted
* security:
* - session: []
* tags: ["data"]
*/
function deleteNote(req: Request) {
const noteId = req.params.noteId;
const taskId = req.query.taskId;
const eraseNotes = req.query.eraseNotes === "true";
const last = req.query.last === "true";
// note how deleteId is separate from taskId - single taskId produces separate deleteId for each "top level" deleted note
const deleteId = utils.randomString(10);
const note = becca.getNoteOrThrow(noteId);
if (typeof taskId !== "string") {
throw new ValidationError("Missing or incorrect type for task ID.");
}
const taskContext = TaskContext.getInstance(taskId, "deleteNotes", null);
note.deleteNote(deleteId, taskContext);
if (eraseNotes) {
eraseService.eraseNotesWithDeleteId(deleteId);
}
if (last) {
taskContext.taskSucceeded(null);
}
}
function undeleteNote(req: Request) {
const taskContext = TaskContext.getInstance(utils.randomString(10), "undeleteNotes", null);
noteService.undeleteNote(req.params.noteId, taskContext);
taskContext.taskSucceeded(null);
}
function sortChildNotes(req: Request) {
const noteId = req.params.noteId;
const { sortBy, sortDirection, foldersFirst, sortNatural, sortLocale } = req.body;
log.info(`Sorting '${noteId}' children with ${sortBy} ${sortDirection}, foldersFirst=${foldersFirst}, sortNatural=${sortNatural}, sortLocale=${sortLocale}`);
const reverse = sortDirection === "desc";
treeService.sortNotes(noteId, sortBy, reverse, foldersFirst, sortNatural, sortLocale);
}
function protectNote(req: Request) {
const noteId = req.params.noteId;
const note = becca.notes[noteId];
const protect = !!parseInt(req.params.isProtected);
const includingSubTree = !!parseInt(req.query?.subtree as string);
const taskContext = new TaskContext(utils.randomString(10), "protectNotes", { protect });
noteService.protectNoteRecursively(note, protect, includingSubTree, taskContext);
taskContext.taskSucceeded(null);
}
function setNoteTypeMime(req: Request) {
// can't use [] destructuring because req.params is not iterable
const { noteId } = req.params;
const { type, mime } = req.body;
const note = becca.getNoteOrThrow(noteId);
note.type = type;
note.mime = mime;
note.save();
}
function changeTitle(req: Request) {
const noteId = req.params.noteId;
const title = req.body.title;
const note = becca.getNoteOrThrow(noteId);
if (!note.isContentAvailable()) {
throw new ValidationError(`Note '${noteId}' is not available for change`);
}
const noteTitleChanged = note.title !== title;
if (noteTitleChanged) {
noteService.saveRevisionIfNeeded(note);
}
note.title = title;
note.save();
if (noteTitleChanged) {
noteService.triggerNoteTitleChanged(note);
}
return note;
}
function duplicateSubtree(req: Request) {
const { noteId, parentNoteId } = req.params;
return noteService.duplicateSubtree(noteId, parentNoteId);
}
function eraseDeletedNotesNow() {
eraseService.eraseDeletedNotesNow();
}
function eraseUnusedAttachmentsNow() {
eraseService.eraseUnusedAttachmentsNow();
}
function getDeleteNotesPreview(req: Request) {
const { branchIdsToDelete, deleteAllClones } = req.body;
const noteIdsToBeDeleted = new Set<string>();
const strongBranchCountToDelete: Record<string, number> = {}; // noteId => count
function branchPreviewDeletion(branch: BBranch) {
if (branch.isWeak || !branch.branchId) {
return;
}
strongBranchCountToDelete[branch.branchId] = strongBranchCountToDelete[branch.branchId] || 0;
strongBranchCountToDelete[branch.branchId]++;
const note = branch.getNote();
if (deleteAllClones || note.getStrongParentBranches().length <= strongBranchCountToDelete[branch.branchId]) {
noteIdsToBeDeleted.add(note.noteId);
for (const childBranch of note.getChildBranches()) {
branchPreviewDeletion(childBranch);
}
}
}
for (const branchId of branchIdsToDelete) {
const branch = becca.getBranch(branchId);
if (!branch) {
log.error(`Branch ${branchId} was not found and delete preview can't be calculated for this note.`);
continue;
}
branchPreviewDeletion(branch);
}
let brokenRelations: AttributeRow[] = [];
if (noteIdsToBeDeleted.size > 0) {
sql.fillParamList(noteIdsToBeDeleted);
// FIXME: No need to do this in database, can be done with becca data
brokenRelations = sql
.getRows<AttributeRow>(
`
SELECT attr.noteId, attr.name, attr.value
FROM attributes attr
JOIN param_list ON param_list.paramId = attr.value
WHERE attr.isDeleted = 0
AND attr.type = 'relation'`
)
.filter((attr) => attr.noteId && !noteIdsToBeDeleted.has(attr.noteId));
}
return {
noteIdsToBeDeleted: Array.from(noteIdsToBeDeleted),
brokenRelations
} satisfies DeleteNotesPreview;
}
function forceSaveRevision(req: Request) {
const { noteId } = req.params;
const note = becca.getNoteOrThrow(noteId);
if (!note.isContentAvailable()) {
throw new ValidationError(`Note revision of a protected note cannot be created outside of a protected session.`);
}
note.saveRevision();
}
function convertNoteToAttachment(req: Request) {
const { noteId } = req.params;
const note = becca.getNoteOrThrow(noteId);
return {
attachment: note.convertToParentAttachment()
};
}
export default {
getNote,
getNoteBlob,
getNoteMetadata,
updateNoteData,
deleteNote,
undeleteNote,
createNote,
sortChildNotes,
protectNote,
setNoteTypeMime,
changeTitle,
duplicateSubtree,
eraseDeletedNotesNow,
eraseUnusedAttachmentsNow,
getDeleteNotesPreview,
forceSaveRevision,
convertNoteToAttachment
};

View File

@@ -37,7 +37,6 @@ import llmRoute from "./api/llm.js";
import loginApiRoute from "./api/login.js";
import metricsRoute from "./api/metrics.js";
import noteMapRoute from "./api/note_map.js";
import notesApiRoute from "./api/notes.js";
import ollamaRoute from "./api/ollama.js";
import openaiRoute from "./api/openai.js";
import otherRoute from "./api/other.js";
@@ -105,19 +104,6 @@ function register(app: express.Application) {
routes.buildSharedApiRoutes(apiRoute);
apiRoute(GET, "/api/notes/:noteId", notesApiRoute.getNote);
apiRoute(GET, "/api/notes/:noteId/blob", notesApiRoute.getNoteBlob);
apiRoute(GET, "/api/notes/:noteId/metadata", notesApiRoute.getNoteMetadata);
apiRoute(PUT, "/api/notes/:noteId/data", notesApiRoute.updateNoteData);
apiRoute(DEL, "/api/notes/:noteId", notesApiRoute.deleteNote);
apiRoute(PUT, "/api/notes/:noteId/undelete", notesApiRoute.undeleteNote);
apiRoute(PST, "/api/notes/:noteId/revision", notesApiRoute.forceSaveRevision);
apiRoute(PST, "/api/notes/:parentNoteId/children", notesApiRoute.createNote);
apiRoute(PUT, "/api/notes/:noteId/sort-children", notesApiRoute.sortChildNotes);
apiRoute(PUT, "/api/notes/:noteId/protect/:isProtected", notesApiRoute.protectNote);
apiRoute(PUT, "/api/notes/:noteId/type", notesApiRoute.setNoteTypeMime);
apiRoute(PUT, "/api/notes/:noteId/title", notesApiRoute.changeTitle);
apiRoute(PST, "/api/notes/:noteId/duplicate/:parentNoteId", notesApiRoute.duplicateSubtree);
apiRoute(PUT, "/api/notes/:noteId/clone-to-branch/:parentBranchId", cloningApiRoute.cloneNoteToBranch);
apiRoute(PUT, "/api/notes/:noteId/toggle-in-parent/:parentNoteId/:present", cloningApiRoute.toggleNoteInParent);
apiRoute(PUT, "/api/notes/:noteId/clone-to-note/:parentNoteId", cloningApiRoute.cloneNoteToParentNote);
@@ -139,7 +125,6 @@ function register(app: express.Application) {
route(GET, "/api/notes/download/:noteId", [auth.checkApiAuthOrElectron], filesRoute.downloadFile);
apiRoute(PST, "/api/notes/:noteId/save-to-tmp-dir", filesRoute.saveNoteToTmpDir);
apiRoute(PST, "/api/notes/:noteId/upload-modified-file", filesRoute.uploadModifiedFileToNote);
apiRoute(PST, "/api/notes/:noteId/convert-to-attachment", notesApiRoute.convertNoteToAttachment);
apiRoute(PUT, "/api/branches/:branchId/move-to/:parentBranchId", branchesApiRoute.moveBranchToParent);
apiRoute(PUT, "/api/branches/:branchId/move-before/:beforeBranchId", branchesApiRoute.moveBranchBeforeNote);
@@ -322,13 +307,10 @@ function register(app: express.Application) {
asyncRoute(PST, "/api/sender/note", [auth.checkEtapiToken], senderRoute.saveNote, apiResultHandler);
apiRoute(PST, "/api/relation-map", relationMapApiRoute.getRelationMap);
apiRoute(PST, "/api/notes/erase-deleted-notes-now", notesApiRoute.eraseDeletedNotesNow);
apiRoute(PST, "/api/notes/erase-unused-attachments-now", notesApiRoute.eraseUnusedAttachmentsNow);
asyncApiRoute(GET, "/api/similar-notes/:noteId", similarNotesRoute.getSimilarNotes);
asyncApiRoute(GET, "/api/backend-log", backendLogRoute.getBackendLog);
apiRoute(GET, "/api/stats/note-size/:noteId", statsRoute.getNoteSize);
apiRoute(GET, "/api/stats/subtree-size/:noteId", statsRoute.getSubtreeSize);
apiRoute(PST, "/api/delete-notes-preview", notesApiRoute.getDeleteNotesPreview);
route(GET, "/api/fonts", [auth.checkApiAuthOrElectron], fontsRoute.getFontCss);
apiRoute(GET, "/api/other/icon-usage", otherRoute.getIconUsage);
apiRoute(PST, "/api/other/render-markdown", otherRoute.renderMarkdown);