Skip to content

Build your personal knowledge base with Trilium Notes

5.1 KB
Raw Blame
import {
    ConvertAttachmentToNoteResponse, getAttachedFileMime, isAcceptedImageMime
} from "@triliumnext/commons";
import { ValidationError } from "../../errors";
import type { Request } from "../../http_interface";

import becca from "../../becca/becca.js";
import blobService from "../../services/blob.js";
import imageService from "../../services/image.js";
import { wrapStringOrBuffer } from "../../services/utils/binary.js";

function getAttachmentBlob(req: Request<{ attachmentId: string }>) {
    const preview = req.query.preview === "true";

    return blobService.getBlobPojo("attachments", req.params.attachmentId, { preview });
}

function getAttachments(req: Request<{ noteId: string }>) {
    const note = becca.getNoteOrThrow(req.params.noteId);

    return note.getAttachments();
}

function getAttachment(req: Request<{ attachmentId: string }>) {
    const { attachmentId } = req.params;

    return becca.getAttachmentOrThrow(attachmentId);
}

function getAllAttachments(req: Request<{ attachmentId: string }>) {
    const { attachmentId } = req.params;
    // one particular attachment is requested, but return all note's attachments

    const attachment = becca.getAttachmentOrThrow(attachmentId);
    return attachment.getNote()?.getAttachments() || [];
}

function saveAttachment(req: Request<{ noteId: string }>) {
    const { noteId } = req.params;
    const { attachmentId, role, mime, title, content } = req.body;
    const matchByQuery = req.query.matchBy;
    const isValidMatchBy = (typeof matchByQuery === "string") && (matchByQuery === "attachmentId" || matchByQuery === "title");
    const matchBy = isValidMatchBy ? matchByQuery : undefined;

    const note = becca.getNoteOrThrow(noteId);
    note.saveAttachment({ attachmentId, role, mime, title, content }, matchBy);
}

async function uploadAttachment(req: Request<{ noteId: string }>) {
    const { noteId } = req.params;
    const { file } = req;

    if (!file) {
        return {
            uploaded: false,
            message: `Missing attachment data.`
        };
    }

    const note = becca.getNoteOrThrow(noteId);
    let url;

    // Convert buffer to Uint8Array (Buffer extends Uint8Array, string needs encoding)
    const buffer = wrapStringOrBuffer(file.buffer as string | Uint8Array);

    // With `link=true`, the response links to the attachment and a picture is stored as uploaded.
    const isLinkRequested = req.query.link === "true";

    if (isAcceptedImageMime(file.mimetype)) {
        // Always the user's own image: the pictures the app fetches for itself — a link preview's
        // favicon and cover — are stored by the code that fetched them, never uploaded through here.
        const attachment = imageService.saveImageToAttachment(
            noteId,
            buffer,
            file.originalname,
            !isLinkRequested,
            !isLinkRequested
        );

        // The URL below is fetched the moment this answers — the editor puts it straight into the
        // document as the source of an image. Answering before the bytes are stored hands it the
        // address of an empty attachment, which draws as a broken image and stays broken until
        // something reloads the note. So this one image is waited for; nothing else is.
        await imageService.awaitImageWrite(attachment.attachmentId);

        const { attachmentId, title } = attachment;
        url = isLinkRequested
            ? getAttachmentLinkUrl(noteId, attachmentId)
            : `api/attachments/${attachmentId}/image/${encodeURIComponent(title)}`;
    } else {
        const attachment = note.saveAttachment({
            role: "file",
            mime: getAttachedFileMime(file.originalname, file.mimetype),
            title: file.originalname,
            content: file.buffer
        });

        url = getAttachmentLinkUrl(noteId, attachment.attachmentId);
    }

    return {
        uploaded: true,
        url
    };
}

function getAttachmentLinkUrl(noteId: string, attachmentId: string | undefined) {
    return `#root/${noteId}?viewMode=attachments&attachmentId=${attachmentId}`;
}

function renameAttachment(req: Request<{ attachmentId: string }>) {
    const { title } = req.body;
    const { attachmentId } = req.params;

    const attachment = becca.getAttachmentOrThrow(attachmentId);

    if (!title?.trim()) {
        throw new ValidationError("Title must not be empty");
    }

    attachment.title = title;
    attachment.save();
}

function deleteAttachment(req: Request<{ attachmentId: string }>) {
    const { attachmentId } = req.params;

    const attachment = becca.getAttachment(attachmentId);

    if (attachment) {
        attachment.markAsDeleted();
    }
}

function convertAttachmentToNote(req: Request<{ attachmentId: string }>) {
    const { attachmentId } = req.params;

    const attachment = becca.getAttachmentOrThrow(attachmentId);
    return attachment.convertToNote() satisfies ConvertAttachmentToNoteResponse;
}

export default {
    getAttachmentBlob,
    getAttachments,
    getAttachment,
    getAllAttachments,
    saveAttachment,
    uploadAttachment,
    renameAttachment,
    deleteAttachment,
    convertAttachmentToNote
};