1// Хранилище презентаций: in-memory Map + персистентность на диск (server/data/presentations.json).
2// Нормализация модели слайдов — единственный источник правды о формате данных.
3const crypto = require('crypto');
4const fs = require('fs');
5const path = require('path');
6
7const DATA_DIR = path.join(__dirname, 'data');
8const DB_FILE = path.join(DATA_DIR, 'presentations.json');
9
10const presentations = new Map();
11
12const uid = (prefix) => `${prefix}_${crypto.randomUUID()}`;
13const num = (value, fallback) => (Number.isFinite(Number(value)) ? Number(value) : fallback);
14const clamp01 = (value, fallback = 0) => Math.max(0, Math.min(1, num(value, fallback)));
15const str = (value, fallback = '') => (typeof value === 'string' ? value : fallback);
16const plainObject = (value) => (value && typeof value === 'object' && !Array.isArray(value) ? value : {});
17
18const DEFAULT_GRADIENT = 'linear-gradient(135deg, #0f172a 0%, #1e1b4b 55%, #312e81 100%)';
19
20const SHAPES = ['rect', 'round', 'ellipse', 'triangle', 'arrow', 'line', 'star', 'hexagon', 'diamond'];
21const FONTS = ['sans', 'serif', 'mono', 'round'];
22const TRANSITIONS = ['none', 'fade', 'slide', 'zoom', 'flip', 'rise'];
23const PASS_THROUGH_KINDS = new Set(['transition', 'anim', 'plugin']);
24
25/* ==================== Персистентность ==================== */
26
27let saveTimer = null;
28
29function loadFromDisk() {
30 try {
31 fs.mkdirSync(DATA_DIR, { recursive: true });
32 const raw = fs.readFileSync(DB_FILE, 'utf8');
33 const arr = JSON.parse(raw);
34 if (!Array.isArray(arr)) return;
35 for (const item of arr) {
36 if (!item || typeof item.id !== 'string') continue;
37 const norm = normalizePresentation(item);
38 presentations.set(item.id, {
39 ...norm,
40 id: item.id,
41 currentSlide: Math.max(0, Math.floor(num(item.currentSlide, 0))),
42 createdAt: num(item.createdAt, Date.now()),
43 updatedAt: num(item.updatedAt, Date.now()),
44 });
45 }
46 console.log(`[store] восстановлено презентаций с диска: ${presentations.size}`);
47 } catch (err) {
48 if (err.code !== 'ENOENT') console.warn('[store] не удалось прочитать БД:', err.message);
49 }
50}
51
52function writeToDisk() {
53 try {
54 fs.mkdirSync(DATA_DIR, { recursive: true });
55 const tmp = `${DB_FILE}.${process.pid}.tmp`;
56 fs.writeFileSync(tmp, JSON.stringify([...presentations.values()]));
57 fs.renameSync(tmp, DB_FILE);
58 } catch (err) {
59 console.error('[store] ошибка записи БД:', err.message);
60 }
61}
62
63function scheduleSave() {
64 if (saveTimer) return;
65 saveTimer = setTimeout(() => {
66 saveTimer = null;
67 writeToDisk();
68 }, 400);
69}
70
71function flushSync() {
72 if (saveTimer) {
73 clearTimeout(saveTimer);
74 saveTimer = null;
75 }
76 writeToDisk();
77}
78
79loadFromDisk();
80process.on('SIGINT', () => { flushSync(); process.exit(0); });
81process.on('SIGTERM', () => { flushSync(); process.exit(0); });
82process.on('exit', () => { try { flushSync(); } catch { /* noop */ } });
83
84/* ==================== Нормализация ==================== */
85
86function normalizeBackground(background) {
87 const bg = plainObject(background);
88 const type = ['color', 'gradient', 'image'].includes(bg.type)
89 ? bg.type
90 : bg.image
91 ? 'image'
92 : bg.gradient
93 ? 'gradient'
94 : 'color';
95 return {
96 type,
97 color: str(bg.color, '#0f172a') || '#0f172a',
98 gradient: str(bg.gradient, DEFAULT_GRADIENT) || DEFAULT_GRADIENT,
99 image: str(bg.image, ''),
100 };
101}
102
103function normalizeAction(action) {
104 const a = plainObject(action);
105 const type = ['none', 'go', 'next', 'prev', 'play', 'stop', 'lua'].includes(a.type) ? a.type : 'next';
106 return {
107 type,
108 slideIndex: Math.max(0, Math.floor(num(a.slideIndex, 0))),
109 audioId: str(a.audioId, ''),
110 code: str(a.code, ''),
111 scriptNodeId: str(a.scriptNodeId, ''),
112 };
113}
114
115function normalizeComputed(computed) {
116 const source = plainObject(computed);
117 const style = {};
118 Object.entries(plainObject(source.style)).forEach(([key, value]) => {
119 if (typeof value === 'string' || typeof value === 'number') style[String(key)] = value;
120 });
121 return {
122 style,
123 css: str(source.css, ''),
124 html: str(source.html, ''),
125 text: str(source.text, ''),
126 at: num(source.at, 0),
127 };
128}
129
130function normalizeElement(element, index) {
131 const el = plainObject(element);
132 const type = ['text', 'image', 'button', 'audio', 'video', 'window', 'shape', 'lua'].includes(el.type) ? el.type : 'text';
133 const base = {
134 id: str(el.id, '') || uid('el'),
135 type,
136 x: num(el.x, 10),
137 y: num(el.y, 10),
138 w: num(el.w, 40),
139 h: num(el.h, 15),
140 z: Math.floor(num(el.z, index + 1)),
141 opacity: clamp01(el.opacity, 1),
142 rotate: num(el.rotate, 0) % 360,
143 };
144
145 if (type === 'text') {
146 return {
147 ...base,
148 text: str(el.text, ''),
149 fontSize: num(el.fontSize, 5),
150 color: str(el.color, '#f8fafc'),
151 weight: Math.floor(num(el.weight, 700)),
152 align: ['left', 'center', 'right'].includes(el.align) ? el.align : 'center',
153 bg: str(el.bg, ''),
154 font: FONTS.includes(el.font) ? el.font : 'sans',
155 italic: !!el.italic,
156 shadow: !!el.shadow,
157 lineHeight: num(el.lineHeight, 1.16),
158 };
159 }
160 if (type === 'image') {
161 return {
162 ...base,
163 src: str(el.src, ''),
164 fit: el.fit === 'contain' ? 'contain' : 'cover',
165 radius: num(el.radius, 14),
166 shadow: !!el.shadow,
167 };
168 }
169 if (type === 'shape') {
170 return {
171 ...base,
172 shape: SHAPES.includes(el.shape) ? el.shape : 'rect',
173 fill: str(el.fill, '#6366f1'),
174 borderColor: str(el.borderColor, ''),
175 borderWidth: num(el.borderWidth, 0),
176 radius: num(el.radius, 12),
177 shadow: !!el.shadow,
178 };
179 }
180 if (type === 'button') {
181 return {
182 ...base,
183 label: str(el.label, 'Кнопка'),
184 bg: str(el.bg, '#6366f1'),
185 color: str(el.color, '#ffffff'),
186 fontSize: num(el.fontSize, 2.2),
187 radius: num(el.radius, 12),
188 shadow: el.shadow !== false,
189 action: normalizeAction(el.action),
190 };
191 }
192 if (type === 'audio') {
193 return {
194 ...base,
195 src: str(el.src, ''),
196 loop: !!el.loop,
197 visible: el.visible !== false,
198 volume: clamp01(el.volume, 0.8),
199 label: str(el.label, 'Аудио'),
200 };
201 }
202 if (type === 'video') {
203 return {
204 ...base,
205 src: str(el.src, ''),
206 poster: str(el.poster, ''),
207 fit: el.fit === 'contain' ? 'contain' : 'cover',
208 radius: num(el.radius, 12),
209 autoplay: el.autoplay !== false,
210 loop: !!el.loop,
211 muted: el.muted !== false,
212 controls: el.controls !== false,
213 label: str(el.label, 'Видео'),
214 };
215 }
216 if (type === 'window') {
217 return {
218 ...base,
219 targetId: str(el.targetId, ''),
220 targetTitle: str(el.targetTitle, ''),
221 targetUrl: str(el.targetUrl, ''),
222 fit: 'contain',
223 radius: num(el.radius, 12),
224 autoStart: el.autoStart !== false,
225 label: str(el.label, 'Окно Chrome'),
226 };
227 }
228 if (type === 'lua') {
229 return {
230 ...base,
231 label: str(el.label, 'Lua-элемент'),
232 code: str(el.code, ''),
233 computed: normalizeComputed(el.computed),
234 };
235 }
236 return {
237 ...base,
238 src: str(el.src, ''),
239 loop: !!el.loop,
240 visible: el.visible !== false,
241 volume: clamp01(el.volume, 0.8),
242 label: str(el.label, 'Аудио'),
243 };
244}
245
246function normalizeSlide(slide, index = 0) {
247 const s = plainObject(slide);
248 let elements = Array.isArray(s.elements) ? s.elements.map(normalizeElement) : [];
249
250 // Совместимость со старым форматом: text + image
251 if (!elements.length) {
252 if (str(s.text).trim()) {
253 elements.push(
254 normalizeElement(
255 { type: 'text', text: s.text, x: 8, y: 34, w: 84, h: 32, fontSize: 6, align: 'center', color: '#f8fafc' },
256 0
257 )
258 );
259 }
260 if (str(s.image).trim()) {
261 elements.push(
262 normalizeElement({ type: 'image', src: s.image, x: 22, y: 18, w: 56, h: 48, fit: 'contain', z: 0 }, 1)
263 );
264 }
265 }
266
267 return {
268 id: str(s.id, '') || uid('slide'),
269 notes: str(s.notes, ''),
270 transition: TRANSITIONS.includes(s.transition) ? s.transition : 'fade',
271 background: normalizeBackground(s.background),
272 lua: str(s.lua, ''),
273 elements,
274 };
275}
276
277function normalizeVariables(variables) {
278 const result = {};
279 for (const [key, value] of Object.entries(plainObject(variables))) {
280 if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
281 result[key] = value;
282 }
283 }
284 return result;
285}
286
287function defaultNodePosition(index) {
288 return { x: 340 + (index % 4) * 320, y: 60 + Math.floor(index / 4) * 300 };
289}
290
291function normalizeGraph(graph, slides) {
292 const g = plainObject(graph);
293 const sourcePositions = plainObject(g.positions);
294 const positions = {};
295 slides.forEach((slide, index) => {
296 const p = plainObject(sourcePositions[slide.id]);
297 const fallback = defaultNodePosition(index);
298 positions[slide.id] = { x: num(p.x, fallback.x), y: num(p.y, fallback.y) };
299 });
300 const scripts = (Array.isArray(g.scripts) ? g.scripts : []).map((node, index) => {
301 const n = plainObject(node);
302 return {
303 id: str(n.id, '') || uid('script'),
304 name: str(n.name, 'Скрипт') || 'Скрипт',
305 code: str(n.code, ''),
306 x: num(n.x, 60 + (index % 3) * 320),
307 y: num(n.y, 520 + Math.floor(index / 3) * 220),
308 slideId: str(n.slideId, ''),
309 elementId: str(n.elementId, ''),
310 };
311 });
312 const audios = (Array.isArray(g.audios) ? g.audios : []).map((node, index) => {
313 const n = plainObject(node);
314 return {
315 id: str(n.id, '') || uid('audio'),
316 name: str(n.name, 'Аудио') || 'Аудио',
317 elementId: str(n.elementId, ''),
318 mode: n.mode === 'stop' ? 'stop' : 'play',
319 x: num(n.x, 60 + (index % 3) * 320),
320 y: num(n.y, 840 + Math.floor(index / 3) * 110),
321 };
322 });
323 const variables = (Array.isArray(g.variables) ? g.variables : []).map((node, index) => {
324 const n = plainObject(node);
325 return {
326 id: str(n.id, '') || uid('var'),
327 name: str(n.name, '') || `var${index + 1}`,
328 x: num(n.x, 40),
329 y: num(n.y, 520 + index * 96),
330 };
331 });
332
333 // Ноды переходов и анимаций: Lua-код, привязанный к слайду (и элементу).
334 const transitions = (Array.isArray(g.transitions) ? g.transitions : []).map((node, index) => {
335 const n = plainObject(node);
336 return {
337 id: str(n.id, '') || uid('trans'),
338 name: str(n.name, 'Переход') || 'Переход',
339 code: str(n.code, ''),
340 slideId: str(n.slideId, ''),
341 x: num(n.x, 60 + (index % 3) * 320),
342 y: num(n.y, 1120 + Math.floor(index / 3) * 200),
343 };
344 });
345 const anims = (Array.isArray(g.anims) ? g.anims : []).map((node, index) => {
346 const n = plainObject(node);
347 return {
348 id: str(n.id, '') || uid('anim'),
349 name: str(n.name, 'Анимация') || 'Анимация',
350 code: str(n.code, ''),
351 slideId: str(n.slideId, ''),
352 elementId: str(n.elementId, ''),
353 x: num(n.x, 140 + (index % 3) * 320),
354 y: num(n.y, 1320 + Math.floor(index / 3) * 200),
355 };
356 });
357
358 // Экземпляры нод из плагинов. Код плагина хранится снимком, чтобы показ
359 // не зависел от того, открыт ли реестр плагинов в текущий момент.
360 const pluginNodes = (Array.isArray(g.plugins) ? g.plugins : []).map((node, index) => {
361 const n = plainObject(node);
362 return {
363 id: str(n.id, '') || uid('plugn'),
364 pluginId: str(n.pluginId, ''),
365 fn: str(n.fn, ''),
366 name: str(n.name, 'Плагин') || 'Плагин',
367 description: str(n.description, ''),
368 color: str(n.color, '#f97316'),
369 code: str(n.code, ''),
370 args: str(n.args, ''),
371 x: num(n.x, 60 + (index % 3) * 320),
372 y: num(n.y, 1440 + Math.floor(index / 3) * 200),
373 };
374 });
375
376 const slideIds = new Set(slides.map((slide) => slide.id));
377 const idsByKind = {
378 slide: slideIds,
379 script: new Set(scripts.map((node) => node.id)),
380 audio: new Set(audios.map((node) => node.id)),
381 variable: new Set(variables.map((node) => node.id)),
382 transition: new Set(transitions.map((node) => node.id)),
383 anim: new Set(anims.map((node) => node.id)),
384 plugin: new Set(pluginNodes.map((node) => node.id)),
385 };
386 const links = (Array.isArray(g.links) ? g.links : []).map((link) => {
387 const l = plainObject(link);
388 const from = plainObject(l.from);
389 const to = plainObject(l.to);
390 if (!from.kind || !to.kind || !Object.prototype.hasOwnProperty.call(idsByKind, from.kind) || !Object.prototype.hasOwnProperty.call(idsByKind, to.kind)) return null;
391 if (!idsByKind[from.kind].has(String(from.id)) || !idsByKind[to.kind].has(String(to.id))) return null;
392 if (!str(from.port, '') || !str(to.port, '')) return null;
393 return {
394 id: str(l.id, '') || uid('link'),
395 from: { kind: from.kind, id: String(from.id), port: String(from.port) },
396 to: { kind: to.kind, id: String(to.id), port: String(to.port) },
397 };
398 }).filter(Boolean);
399
400 const jumps = deriveJumps(links);
401
402 return { positions, scripts, audios, variables, transitions, anims, plugins: pluginNodes, links, jumps };
403}
404
405// Кнопки с Lua из старых версий получают отдельную ноду в графе.
406function migrateLuaScripts(slides, graph) {
407 slides.forEach((slide) => {
408 (slide.elements || []).forEach((element) => {
409 if (element.type !== 'button' || !element.action || element.action.type !== 'lua') return;
410 const action = element.action;
411 let node = graph.scripts.find(
412 (item) => item.id === action.scriptNodeId || (item.elementId === element.id && item.slideId === slide.id)
413 );
414 if (!node) {
415 const base = graph.positions[slide.id] || { x: 60, y: 60 };
416 node = {
417 id: uid('script'),
418 name: `Lua · ${element.label || 'Кнопка'}`,
419 code: action.code || '',
420 x: base.x + 330,
421 y: base.y + 20,
422 slideId: slide.id,
423 elementId: element.id,
424 };
425 graph.scripts.push(node);
426 } else if (!node.code && action.code) {
427 node.code = action.code;
428 }
429 if (!node.elementId) {
430 node.elementId = element.id;
431 node.slideId = slide.id;
432 }
433 action.scriptNodeId = node.id;
434 if (node.code) action.code = node.code;
435 });
436 });
437}
438
439function normalizeCommands(commands) {
440 return (Array.isArray(commands) ? commands : []).map((item) => {
441 const command = plainObject(item);
442 return {
443 id: str(command.id, '') || uid('cmd'),
444 label: str(command.label, 'Команда') || 'Команда',
445 description: str(command.description, ''),
446 code: str(command.code, ''),
447 };
448 });
449}
450
451// Переходы «дальше/назад» — это не только прямые связи slide → slide.
452// Цепь может проходить через анимации, переходы и ноды плагинов (у них порты in/out).
453function deriveJumps(links) {
454 const outgoing = new Map();
455 links.forEach((link) => {
456 const key = `${link.from.kind}|${link.from.id}`;
457 if (!outgoing.has(key)) outgoing.set(key, []);
458 outgoing.get(key).push(link);
459 });
460
461 const jumps = {};
462 links.forEach((link) => {
463 if (link.from.kind !== 'slide' || !['next', 'prev'].includes(link.from.port)) return;
464 const port = link.from.port;
465 let current = link;
466 const visited = new Set();
467 for (let step = 0; current && step < 32; step += 1) {
468 const key = `${current.to.kind}|${current.to.id}`;
469 if (visited.has(key)) break;
470 visited.add(key);
471 if (current.to.kind === 'slide' && current.to.port === 'in') {
472 jumps[link.from.id] = jumps[link.from.id] || {};
473 if (!jumps[link.from.id][port]) jumps[link.from.id][port] = current.to.id;
474 break;
475 }
476 if (PASS_THROUGH_KINDS.has(current.to.kind) && current.to.port === 'in') {
477 current = (outgoing.get(key) || []).find((item) => item.from.port === 'out');
478 continue;
479 }
480 break;
481 }
482 });
483 return jumps;
484}
485
486function normalizePresentation(input = {}) {
487 const data = plainObject(input);
488 const slides = Array.isArray(data.slides) ? data.slides.map(normalizeSlide) : [];
489 const finalSlides = slides.length ? slides : [normalizeSlide({})];
490 const graph = normalizeGraph(data.graph, finalSlides);
491 migrateLuaScripts(finalSlides, graph);
492 return {
493 title: str(data.title, '').trim() || 'Без названия',
494 variables: normalizeVariables(data.variables),
495 music: {
496 src: str(data.music && data.music.src, ''),
497 volume: clamp01(data.music && data.music.volume, 0.5),
498 },
499 lua: str(data.lua, ''),
500 commands: normalizeCommands(data.commands),
501 graph,
502 slides: finalSlides,
503 };
504}
505
506/* ==================== CRUD ==================== */
507
508function createPresentation(input = {}) {
509 const id = uid('pres');
510 const presentation = {
511 id,
512 ...normalizePresentation(input),
513 currentSlide: 0,
514 createdAt: Date.now(),
515 updatedAt: Date.now(),
516 };
517 presentations.set(id, presentation);
518 scheduleSave();
519 return presentation;
520}
521
522function getPresentation(id) {
523 return presentations.get(id);
524}
525
526function updatePresentation(id, input = {}) {
527 const presentation = presentations.get(id);
528 if (!presentation) return null;
529 const normalized = normalizePresentation({
530 title: input.title ?? presentation.title,
531 variables: input.variables ?? presentation.variables,
532 music: input.music ?? presentation.music,
533 lua: input.lua ?? presentation.lua,
534 commands: input.commands ?? presentation.commands,
535 graph: input.graph ?? presentation.graph,
536 slides: input.slides ?? presentation.slides,
537 });
538 Object.assign(presentation, normalized, { updatedAt: Date.now() });
539 scheduleSave();
540 return presentation;
541}
542
543function savePresentation(presentation) {
544 presentations.set(presentation.id, presentation);
545 scheduleSave();
546 return presentation;
547}
548
549function deletePresentation(id) {
550 const ok = presentations.delete(id);
551 if (ok) scheduleSave();
552 return ok;
553}
554
555function listPresentations() {
556 return [...presentations.values()].map((p) => ({
557 id: p.id,
558 title: p.title,
559 slides: p.slides,
560 variables: p.variables,
561 music: p.music,
562 lua: p.lua,
563 commands: p.commands,
564 graph: p.graph,
565 currentSlide: p.currentSlide,
566 createdAt: p.createdAt,
567 updatedAt: p.updatedAt,
568 }));
569}
570
571module.exports = {
572 createPresentation,
573 getPresentation,
574 updatePresentation,
575 savePresentation,
576 deletePresentation,
577 listPresentations,
578 flushSync,
579 SHAPES,
580 FONTS,
581 TRANSITIONS,
582};