// Хранилище презентаций: in-memory Map + персистентность на диск (server/data/presentations.json). // Нормализация модели слайдов — единственный источник правды о формате данных. const crypto = require('crypto'); const fs = require('fs'); const path = require('path'); const DATA_DIR = path.join(__dirname, 'data'); const DB_FILE = path.join(DATA_DIR, 'presentations.json'); const presentations = new Map(); const uid = (prefix) => `${prefix}_${crypto.randomUUID()}`; const num = (value, fallback) => (Number.isFinite(Number(value)) ? Number(value) : fallback); const clamp01 = (value, fallback = 0) => Math.max(0, Math.min(1, num(value, fallback))); const str = (value, fallback = '') => (typeof value === 'string' ? value : fallback); const plainObject = (value) => (value && typeof value === 'object' && !Array.isArray(value) ? value : {}); const DEFAULT_GRADIENT = 'linear-gradient(135deg, #0f172a 0%, #1e1b4b 55%, #312e81 100%)'; const SHAPES = ['rect', 'round', 'ellipse', 'triangle', 'arrow', 'line', 'star', 'hexagon', 'diamond']; const FONTS = ['sans', 'serif', 'mono', 'round']; const TRANSITIONS = ['none', 'fade', 'slide', 'zoom', 'flip', 'rise']; const PASS_THROUGH_KINDS = new Set(['transition', 'anim', 'plugin']); /* ==================== Персистентность ==================== */ let saveTimer = null; function loadFromDisk() { try { fs.mkdirSync(DATA_DIR, { recursive: true }); const raw = fs.readFileSync(DB_FILE, 'utf8'); const arr = JSON.parse(raw); if (!Array.isArray(arr)) return; for (const item of arr) { if (!item || typeof item.id !== 'string') continue; const norm = normalizePresentation(item); presentations.set(item.id, { ...norm, id: item.id, currentSlide: Math.max(0, Math.floor(num(item.currentSlide, 0))), createdAt: num(item.createdAt, Date.now()), updatedAt: num(item.updatedAt, Date.now()), }); } console.log(`[store] восстановлено презентаций с диска: ${presentations.size}`); } catch (err) { if (err.code !== 'ENOENT') console.warn('[store] не удалось прочитать БД:', err.message); } } function writeToDisk() { try { fs.mkdirSync(DATA_DIR, { recursive: true }); const tmp = `${DB_FILE}.${process.pid}.tmp`; fs.writeFileSync(tmp, JSON.stringify([...presentations.values()])); fs.renameSync(tmp, DB_FILE); } catch (err) { console.error('[store] ошибка записи БД:', err.message); } } function scheduleSave() { if (saveTimer) return; saveTimer = setTimeout(() => { saveTimer = null; writeToDisk(); }, 400); } function flushSync() { if (saveTimer) { clearTimeout(saveTimer); saveTimer = null; } writeToDisk(); } loadFromDisk(); process.on('SIGINT', () => { flushSync(); process.exit(0); }); process.on('SIGTERM', () => { flushSync(); process.exit(0); }); process.on('exit', () => { try { flushSync(); } catch { /* noop */ } }); /* ==================== Нормализация ==================== */ function normalizeBackground(background) { const bg = plainObject(background); const type = ['color', 'gradient', 'image'].includes(bg.type) ? bg.type : bg.image ? 'image' : bg.gradient ? 'gradient' : 'color'; return { type, color: str(bg.color, '#0f172a') || '#0f172a', gradient: str(bg.gradient, DEFAULT_GRADIENT) || DEFAULT_GRADIENT, image: str(bg.image, ''), }; } function normalizeAction(action) { const a = plainObject(action); const type = ['none', 'go', 'next', 'prev', 'play', 'stop', 'lua'].includes(a.type) ? a.type : 'next'; return { type, slideIndex: Math.max(0, Math.floor(num(a.slideIndex, 0))), audioId: str(a.audioId, ''), code: str(a.code, ''), scriptNodeId: str(a.scriptNodeId, ''), }; } function normalizeComputed(computed) { const source = plainObject(computed); const style = {}; Object.entries(plainObject(source.style)).forEach(([key, value]) => { if (typeof value === 'string' || typeof value === 'number') style[String(key)] = value; }); return { style, css: str(source.css, ''), html: str(source.html, ''), text: str(source.text, ''), at: num(source.at, 0), }; } function normalizeElement(element, index) { const el = plainObject(element); const type = ['text', 'image', 'button', 'audio', 'video', 'window', 'shape', 'lua'].includes(el.type) ? el.type : 'text'; const base = { id: str(el.id, '') || uid('el'), type, x: num(el.x, 10), y: num(el.y, 10), w: num(el.w, 40), h: num(el.h, 15), z: Math.floor(num(el.z, index + 1)), opacity: clamp01(el.opacity, 1), rotate: num(el.rotate, 0) % 360, }; if (type === 'text') { return { ...base, text: str(el.text, ''), fontSize: num(el.fontSize, 5), color: str(el.color, '#f8fafc'), weight: Math.floor(num(el.weight, 700)), align: ['left', 'center', 'right'].includes(el.align) ? el.align : 'center', bg: str(el.bg, ''), font: FONTS.includes(el.font) ? el.font : 'sans', italic: !!el.italic, shadow: !!el.shadow, lineHeight: num(el.lineHeight, 1.16), }; } if (type === 'image') { return { ...base, src: str(el.src, ''), fit: el.fit === 'contain' ? 'contain' : 'cover', radius: num(el.radius, 14), shadow: !!el.shadow, }; } if (type === 'shape') { return { ...base, shape: SHAPES.includes(el.shape) ? el.shape : 'rect', fill: str(el.fill, '#6366f1'), borderColor: str(el.borderColor, ''), borderWidth: num(el.borderWidth, 0), radius: num(el.radius, 12), shadow: !!el.shadow, }; } if (type === 'button') { return { ...base, label: str(el.label, 'Кнопка'), bg: str(el.bg, '#6366f1'), color: str(el.color, '#ffffff'), fontSize: num(el.fontSize, 2.2), radius: num(el.radius, 12), shadow: el.shadow !== false, action: normalizeAction(el.action), }; } if (type === 'audio') { return { ...base, src: str(el.src, ''), loop: !!el.loop, visible: el.visible !== false, volume: clamp01(el.volume, 0.8), label: str(el.label, 'Аудио'), }; } if (type === 'video') { return { ...base, src: str(el.src, ''), poster: str(el.poster, ''), fit: el.fit === 'contain' ? 'contain' : 'cover', radius: num(el.radius, 12), autoplay: el.autoplay !== false, loop: !!el.loop, muted: el.muted !== false, controls: el.controls !== false, label: str(el.label, 'Видео'), }; } if (type === 'window') { return { ...base, targetId: str(el.targetId, ''), targetTitle: str(el.targetTitle, ''), targetUrl: str(el.targetUrl, ''), fit: 'contain', radius: num(el.radius, 12), autoStart: el.autoStart !== false, label: str(el.label, 'Окно Chrome'), }; } if (type === 'lua') { return { ...base, label: str(el.label, 'Lua-элемент'), code: str(el.code, ''), computed: normalizeComputed(el.computed), }; } return { ...base, src: str(el.src, ''), loop: !!el.loop, visible: el.visible !== false, volume: clamp01(el.volume, 0.8), label: str(el.label, 'Аудио'), }; } function normalizeSlide(slide, index = 0) { const s = plainObject(slide); let elements = Array.isArray(s.elements) ? s.elements.map(normalizeElement) : []; // Совместимость со старым форматом: text + image if (!elements.length) { if (str(s.text).trim()) { elements.push( normalizeElement( { type: 'text', text: s.text, x: 8, y: 34, w: 84, h: 32, fontSize: 6, align: 'center', color: '#f8fafc' }, 0 ) ); } if (str(s.image).trim()) { elements.push( normalizeElement({ type: 'image', src: s.image, x: 22, y: 18, w: 56, h: 48, fit: 'contain', z: 0 }, 1) ); } } return { id: str(s.id, '') || uid('slide'), notes: str(s.notes, ''), transition: TRANSITIONS.includes(s.transition) ? s.transition : 'fade', background: normalizeBackground(s.background), lua: str(s.lua, ''), elements, }; } function normalizeVariables(variables) { const result = {}; for (const [key, value] of Object.entries(plainObject(variables))) { if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { result[key] = value; } } return result; } function defaultNodePosition(index) { return { x: 340 + (index % 4) * 320, y: 60 + Math.floor(index / 4) * 300 }; } function normalizeGraph(graph, slides) { const g = plainObject(graph); const sourcePositions = plainObject(g.positions); const positions = {}; slides.forEach((slide, index) => { const p = plainObject(sourcePositions[slide.id]); const fallback = defaultNodePosition(index); positions[slide.id] = { x: num(p.x, fallback.x), y: num(p.y, fallback.y) }; }); const scripts = (Array.isArray(g.scripts) ? g.scripts : []).map((node, index) => { const n = plainObject(node); return { id: str(n.id, '') || uid('script'), name: str(n.name, 'Скрипт') || 'Скрипт', code: str(n.code, ''), x: num(n.x, 60 + (index % 3) * 320), y: num(n.y, 520 + Math.floor(index / 3) * 220), slideId: str(n.slideId, ''), elementId: str(n.elementId, ''), }; }); const audios = (Array.isArray(g.audios) ? g.audios : []).map((node, index) => { const n = plainObject(node); return { id: str(n.id, '') || uid('audio'), name: str(n.name, 'Аудио') || 'Аудио', elementId: str(n.elementId, ''), mode: n.mode === 'stop' ? 'stop' : 'play', x: num(n.x, 60 + (index % 3) * 320), y: num(n.y, 840 + Math.floor(index / 3) * 110), }; }); const variables = (Array.isArray(g.variables) ? g.variables : []).map((node, index) => { const n = plainObject(node); return { id: str(n.id, '') || uid('var'), name: str(n.name, '') || `var${index + 1}`, x: num(n.x, 40), y: num(n.y, 520 + index * 96), }; }); // Ноды переходов и анимаций: Lua-код, привязанный к слайду (и элементу). const transitions = (Array.isArray(g.transitions) ? g.transitions : []).map((node, index) => { const n = plainObject(node); return { id: str(n.id, '') || uid('trans'), name: str(n.name, 'Переход') || 'Переход', code: str(n.code, ''), slideId: str(n.slideId, ''), x: num(n.x, 60 + (index % 3) * 320), y: num(n.y, 1120 + Math.floor(index / 3) * 200), }; }); const anims = (Array.isArray(g.anims) ? g.anims : []).map((node, index) => { const n = plainObject(node); return { id: str(n.id, '') || uid('anim'), name: str(n.name, 'Анимация') || 'Анимация', code: str(n.code, ''), slideId: str(n.slideId, ''), elementId: str(n.elementId, ''), x: num(n.x, 140 + (index % 3) * 320), y: num(n.y, 1320 + Math.floor(index / 3) * 200), }; }); // Экземпляры нод из плагинов. Код плагина хранится снимком, чтобы показ // не зависел от того, открыт ли реестр плагинов в текущий момент. const pluginNodes = (Array.isArray(g.plugins) ? g.plugins : []).map((node, index) => { const n = plainObject(node); return { id: str(n.id, '') || uid('plugn'), pluginId: str(n.pluginId, ''), fn: str(n.fn, ''), name: str(n.name, 'Плагин') || 'Плагин', description: str(n.description, ''), color: str(n.color, '#f97316'), code: str(n.code, ''), args: str(n.args, ''), x: num(n.x, 60 + (index % 3) * 320), y: num(n.y, 1440 + Math.floor(index / 3) * 200), }; }); const slideIds = new Set(slides.map((slide) => slide.id)); const idsByKind = { slide: slideIds, script: new Set(scripts.map((node) => node.id)), audio: new Set(audios.map((node) => node.id)), variable: new Set(variables.map((node) => node.id)), transition: new Set(transitions.map((node) => node.id)), anim: new Set(anims.map((node) => node.id)), plugin: new Set(pluginNodes.map((node) => node.id)), }; const links = (Array.isArray(g.links) ? g.links : []).map((link) => { const l = plainObject(link); const from = plainObject(l.from); const to = plainObject(l.to); if (!from.kind || !to.kind || !Object.prototype.hasOwnProperty.call(idsByKind, from.kind) || !Object.prototype.hasOwnProperty.call(idsByKind, to.kind)) return null; if (!idsByKind[from.kind].has(String(from.id)) || !idsByKind[to.kind].has(String(to.id))) return null; if (!str(from.port, '') || !str(to.port, '')) return null; return { id: str(l.id, '') || uid('link'), from: { kind: from.kind, id: String(from.id), port: String(from.port) }, to: { kind: to.kind, id: String(to.id), port: String(to.port) }, }; }).filter(Boolean); const jumps = deriveJumps(links); return { positions, scripts, audios, variables, transitions, anims, plugins: pluginNodes, links, jumps }; } // Кнопки с Lua из старых версий получают отдельную ноду в графе. function migrateLuaScripts(slides, graph) { slides.forEach((slide) => { (slide.elements || []).forEach((element) => { if (element.type !== 'button' || !element.action || element.action.type !== 'lua') return; const action = element.action; let node = graph.scripts.find( (item) => item.id === action.scriptNodeId || (item.elementId === element.id && item.slideId === slide.id) ); if (!node) { const base = graph.positions[slide.id] || { x: 60, y: 60 }; node = { id: uid('script'), name: `Lua · ${element.label || 'Кнопка'}`, code: action.code || '', x: base.x + 330, y: base.y + 20, slideId: slide.id, elementId: element.id, }; graph.scripts.push(node); } else if (!node.code && action.code) { node.code = action.code; } if (!node.elementId) { node.elementId = element.id; node.slideId = slide.id; } action.scriptNodeId = node.id; if (node.code) action.code = node.code; }); }); } function normalizeCommands(commands) { return (Array.isArray(commands) ? commands : []).map((item) => { const command = plainObject(item); return { id: str(command.id, '') || uid('cmd'), label: str(command.label, 'Команда') || 'Команда', description: str(command.description, ''), code: str(command.code, ''), }; }); } // Переходы «дальше/назад» — это не только прямые связи slide → slide. // Цепь может проходить через анимации, переходы и ноды плагинов (у них порты in/out). function deriveJumps(links) { const outgoing = new Map(); links.forEach((link) => { const key = `${link.from.kind}|${link.from.id}`; if (!outgoing.has(key)) outgoing.set(key, []); outgoing.get(key).push(link); }); const jumps = {}; links.forEach((link) => { if (link.from.kind !== 'slide' || !['next', 'prev'].includes(link.from.port)) return; const port = link.from.port; let current = link; const visited = new Set(); for (let step = 0; current && step < 32; step += 1) { const key = `${current.to.kind}|${current.to.id}`; if (visited.has(key)) break; visited.add(key); if (current.to.kind === 'slide' && current.to.port === 'in') { jumps[link.from.id] = jumps[link.from.id] || {}; if (!jumps[link.from.id][port]) jumps[link.from.id][port] = current.to.id; break; } if (PASS_THROUGH_KINDS.has(current.to.kind) && current.to.port === 'in') { current = (outgoing.get(key) || []).find((item) => item.from.port === 'out'); continue; } break; } }); return jumps; } function normalizePresentation(input = {}) { const data = plainObject(input); const slides = Array.isArray(data.slides) ? data.slides.map(normalizeSlide) : []; const finalSlides = slides.length ? slides : [normalizeSlide({})]; const graph = normalizeGraph(data.graph, finalSlides); migrateLuaScripts(finalSlides, graph); return { title: str(data.title, '').trim() || 'Без названия', variables: normalizeVariables(data.variables), music: { src: str(data.music && data.music.src, ''), volume: clamp01(data.music && data.music.volume, 0.5), }, lua: str(data.lua, ''), commands: normalizeCommands(data.commands), graph, slides: finalSlides, }; } /* ==================== CRUD ==================== */ function createPresentation(input = {}) { const id = uid('pres'); const presentation = { id, ...normalizePresentation(input), currentSlide: 0, createdAt: Date.now(), updatedAt: Date.now(), }; presentations.set(id, presentation); scheduleSave(); return presentation; } function getPresentation(id) { return presentations.get(id); } function updatePresentation(id, input = {}) { const presentation = presentations.get(id); if (!presentation) return null; const normalized = normalizePresentation({ title: input.title ?? presentation.title, variables: input.variables ?? presentation.variables, music: input.music ?? presentation.music, lua: input.lua ?? presentation.lua, commands: input.commands ?? presentation.commands, graph: input.graph ?? presentation.graph, slides: input.slides ?? presentation.slides, }); Object.assign(presentation, normalized, { updatedAt: Date.now() }); scheduleSave(); return presentation; } function savePresentation(presentation) { presentations.set(presentation.id, presentation); scheduleSave(); return presentation; } function deletePresentation(id) { const ok = presentations.delete(id); if (ok) scheduleSave(); return ok; } function listPresentations() { return [...presentations.values()].map((p) => ({ id: p.id, title: p.title, slides: p.slides, variables: p.variables, music: p.music, lua: p.lua, commands: p.commands, graph: p.graph, currentSlide: p.currentSlide, createdAt: p.createdAt, updatedAt: p.updatedAt, })); } module.exports = { createPresentation, getPresentation, updatePresentation, savePresentation, deletePresentation, listPresentations, flushSync, SHAPES, FONTS, TRANSITIONS, };