/** * Images pasted into Markdown bodies (chat, comments, descriptions): their * records, and binding them to the resource whose body links them, so the * startup purge keeps them. * * @module */ import { db, transaction } from "../db/connection.ts"; import { APIErrorCode } from "../../shared/api.ts"; import { APIException } from "../lib/api-exception.ts"; /** Records the upload of attachment `id`, not yet bound to any resource. */ export function createAttachment(id: string, mime: string): void { db.prepare( "INSERT INTO attachments (id, mime, created_at) VALUES (?, ?, ?)", ).run(id, mime, new Date().toISOString()); } /** * Returns attachment `attachmentId`'s MIME type. * * @throws {APIException} 404 when there is no such attachment. */ export function getAttachment(attachmentId: string): { mime: string } { const row = db.prepare( "SELECT mime FROM attachments WHERE id = ?", ).get(attachmentId) as { mime: string } | undefined; if (!row) { throw new APIException( APIErrorCode.NOT_FOUND, 404, "Attachment not found", ); } return { mime: row.mime }; } /** An attachment URL in a Markdown body, capturing its id. */ const ATTACHMENT_RE = /\/api\/attachments\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/g; /** * Binds the unowned attachments whose URLs appear in `text` to * `resourceId`. Only updates rows where resource_id IS NULL so a user cannot * claim attachments that already belong to another resource. */ export function linkAttachments(text: string, resourceId: string): void { const ids = [...text.matchAll(ATTACHMENT_RE)].map((m) => m[1]); if (ids.length === 0) return; const update = db.prepare( "UPDATE attachments SET resource_id = ? WHERE id = ? AND resource_id IS NULL", ); transaction(() => { for (const id of ids) update.run(resourceId, id); }); }