98 lines
4.9 KiB
JavaScript
98 lines
4.9 KiB
JavaScript
import fs from "node:fs";
|
||
import path from "node:path";
|
||
|
||
// Библиотека материалов (BRM-29, сущность content_assets). Привязка — к идеям банка;
|
||
// идея с датой — это запись календаря, поэтому отдельной связи с календарём нет.
|
||
export const KINDS = ["image", "text", "video", "link"];
|
||
export const LINK_FILTERS = ["linked", "unlinked"];
|
||
export const LIMITS = { image: 2 * 1024 * 1024, text: 200 * 1024 };
|
||
const IMAGE_TYPES = { "image/png": "png", "image/jpeg": "jpg", "image/gif": "gif", "image/webp": "webp" };
|
||
|
||
const str = (v) => (v == null ? "" : String(v).trim());
|
||
export const isUrl = (s) => {
|
||
if (!/^https?:\/\/[^\s]+$/i.test(s)) return false;
|
||
try { return !!new URL(s).hostname.includes("."); } catch { return false; }
|
||
};
|
||
|
||
// Возвращает { asset, file } или { err } (ключ текста из locales).
|
||
export function normalize(b) {
|
||
const kind = str(b.kind);
|
||
const title = str(b.title);
|
||
if (!KINDS.includes(kind)) return { err: "err.asset.kind" };
|
||
if (!title) return { err: "err.asset.title" };
|
||
const asset = { kind, title };
|
||
if (kind === "video" || kind === "link") {
|
||
const url = str(b.url);
|
||
if (!url) return { err: "err.asset.urlEmpty" };
|
||
if (!isUrl(url)) return { err: "err.asset.urlBad" };
|
||
return { asset: { ...asset, url } };
|
||
}
|
||
if (kind === "text") {
|
||
const content = typeof b.content === "string" ? b.content : "";
|
||
if (!content.trim()) return { err: "err.asset.textEmpty" };
|
||
if (Buffer.byteLength(content) > LIMITS.text) return { err: "err.asset.tooBig" };
|
||
return { asset: { ...asset, content } };
|
||
}
|
||
// image: файл (base64 / data URL) или ссылка на картинку
|
||
if (b.data) {
|
||
const m = String(b.data).match(/^data:([\w/+.-]+);base64,(.*)$/s);
|
||
const mime = m ? m[1] : str(b.mime);
|
||
const ext = IMAGE_TYPES[mime];
|
||
if (!ext) return { err: "err.asset.imageType" };
|
||
const buf = Buffer.from(m ? m[2] : String(b.data), "base64");
|
||
if (!buf.length) return { err: "err.asset.imageEmpty" };
|
||
if (buf.length > LIMITS.image) return { err: "err.asset.tooBig" };
|
||
return { asset: { ...asset, mime, ext }, file: buf };
|
||
}
|
||
const url = str(b.url);
|
||
if (!url) return { err: "err.asset.imageEmpty" };
|
||
if (!isUrl(url)) return { err: "err.asset.urlBad" };
|
||
return { asset: { ...asset, url } };
|
||
}
|
||
|
||
export function createAssetStore(file) {
|
||
const dir = path.join(path.dirname(file), "asset-files");
|
||
let data;
|
||
try { data = JSON.parse(fs.readFileSync(file, "utf8")); } catch { data = { nextId: 1, assets: [] }; }
|
||
const save = () => {
|
||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||
fs.writeFileSync(file + ".tmp", JSON.stringify(data, null, 2));
|
||
fs.renameSync(file + ".tmp", file);
|
||
};
|
||
const get = (id) => data.assets.find((a) => a.id === id);
|
||
const filePath = (a) => path.join(dir, `${a.id}.${a.ext}`);
|
||
return {
|
||
get,
|
||
list({ q = "", kind = "", link = "" } = {}) {
|
||
const needle = q.trim().toLowerCase();
|
||
return data.assets.filter((a) =>
|
||
(!kind || a.kind === kind) &&
|
||
(!needle || a.title.toLowerCase().includes(needle)) &&
|
||
(!link || (link === "linked") === (a.ideaIds.length > 0)));
|
||
},
|
||
forIdea: (ideaId) => data.assets.filter((a) => a.ideaIds.includes(ideaId)),
|
||
create(b, now) {
|
||
const r = normalize(b);
|
||
if (r.err) return r;
|
||
const a = { id: data.nextId++, ...r.asset, addedAt: now, ideaIds: [] };
|
||
if (r.file) { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(filePath(a), r.file); }
|
||
data.assets.push(a); save();
|
||
return { asset: a };
|
||
},
|
||
attach(id, ideaId) { const a = get(id); if (!a) return false; if (!a.ideaIds.includes(ideaId)) a.ideaIds.push(ideaId); save(); return a; },
|
||
detach(id, ideaId) { const a = get(id); if (!a) return false; a.ideaIds = a.ideaIds.filter((x) => x !== ideaId); save(); return a; },
|
||
// Идея удалена: материалы остаются в библиотеке, но уже не привязаны к ней.
|
||
dropIdea(ideaId) { let ch = false; for (const a of data.assets) if (a.ideaIds.includes(ideaId)) { a.ideaIds = a.ideaIds.filter((x) => x !== ideaId); ch = true; } if (ch) save(); },
|
||
remove(id) {
|
||
const a = get(id); if (!a) return false;
|
||
data.assets = data.assets.filter((x) => x !== a);
|
||
if (a.ext) fs.rmSync(filePath(a), { force: true });
|
||
save(); return true;
|
||
},
|
||
readFile(id) { const a = get(id); if (!a?.ext) return null; try { return { mime: a.mime, buf: fs.readFileSync(filePath(a)) }; } catch { return null; } },
|
||
};
|
||
}
|
||
|
||
// Краткий вид для карточки идеи: название, вид, предпросмотр или ссылка.
|
||
export const brief = (a) => ({ id: a.id, title: a.title, kind: a.kind, url: a.url ?? null, preview: a.kind === "image" ? (a.url ?? `/api/assets/${a.id}/file`) : null });
|