1const express = require('express');
2const crypto = require('crypto');
3const fs = require('fs');
4const path = require('path');
5const store = require('./store');
6const hub = require('./hub');
7const cdp = require('./cdp');
8const plugins = require('./plugins');
9
10const router = express.Router();
11
12const UPLOAD_DIR = path.join(__dirname, '..', 'public', 'uploads');
13fs.mkdirSync(UPLOAD_DIR, { recursive: true });
14
15function safeFileName(raw, fallbackExt = '') {
16 const base = String(raw || 'file')
17 .replace(/\\/g, '/')
18 .split('/')
19 .pop();
20 const extMatch = base.match(/\.([a-zA-Z0-9]{1,12})$/);
21 const ext = extMatch ? `.${extMatch[1].toLowerCase()}` : fallbackExt;
22 const stem = base
23 .slice(0, extMatch ? -extMatch[0].length : undefined)
24 .toLowerCase()
25 .replace(/[^a-z0-9._-]+/g, '-')
26 .replace(/^-+|-+$/g, '')
27 .slice(0, 48) || 'file';
28 const suffix = crypto.randomBytes(4).toString('hex');
29 return `${stem}-${Date.now().toString(36)}-${suffix}${ext}`;
30}
31
32// ---- Презентации ----
33
34router.get('/presentations', (req, res) => {
35 res.json({ presentations: store.listPresentations() });
36});
37
38router.post('/presentations', (req, res) => {
39 const presentation = store.createPresentation(req.body || {});
40 hub.broadcastPresentations();
41 res.status(201).json(presentation);
42});
43
44router.get('/presentations/:id', (req, res) => {
45 const presentation = store.getPresentation(req.params.id);
46 if (!presentation) {
47 return res.status(404).json({ error: 'not_found' });
48 }
49 res.json(presentation);
50});
51
52// Дублировать презентацию
53router.post('/presentations/:id/duplicate', (req, res) => {
54 const source = store.getPresentation(req.params.id);
55 if (!source) {
56 return res.status(404).json({ error: 'not_found' });
57 }
58 const copy = store.createPresentation({
59 title: `${source.title} (копия)`,
60 slides: source.slides,
61 variables: source.variables,
62 music: source.music,
63 lua: source.lua,
64 commands: source.commands,
65 graph: source.graph,
66 });
67 hub.broadcastPresentations();
68 res.status(201).json(copy);
69});
70
71router.put('/presentations/:id', (req, res) => {
72 const presentation = store.getPresentation(req.params.id);
73 if (!presentation) {
74 return res.status(404).json({ error: 'not_found' });
75 }
76 const body = req.body || {};
77 if (body.slides !== undefined && !Array.isArray(body.slides)) {
78 return res.status(400).json({ error: 'bad_slides' });
79 }
80
81 const updated = store.updatePresentation(req.params.id, body);
82
83 // Обновляем открытые демонстрации «на лету»
84 hub.broadcastRoom(updated.id, {
85 type: 'sync',
86 presentationId: updated.id,
87 title: updated.title,
88 slides: updated.slides,
89 slideIndex: updated.currentSlide,
90 variables: updated.variables,
91 music: updated.music,
92 lua: updated.lua,
93 commands: updated.commands,
94 graph: updated.graph,
95 });
96 hub.broadcastPresentations();
97 hub.broadcastSessions();
98 res.json(updated);
99});
100
101router.delete('/presentations/:id', (req, res) => {
102 hub.endSession(req.params.id, 'deleted');
103 store.deletePresentation(req.params.id);
104 hub.broadcastPresentations();
105 hub.broadcastSessions();
106 res.json({ ok: true });
107});
108
109// ---- Реестр Lua-плагинов ----
110
111const broadcastPlugins = () => hub.broadcastAll({ type: 'plugins', plugins: plugins.listPlugins() });
112
113router.get('/plugins', (req, res) => {
114 res.json({ plugins: plugins.listPlugins() });
115});
116
117router.get('/plugins/:id', (req, res) => {
118 const plugin = plugins.getPlugin(req.params.id);
119 if (!plugin) return res.status(404).json({ error: 'not_found' });
120 res.json(plugin);
121});
122
123router.post('/plugins', (req, res) => {
124 const plugin = plugins.createPlugin(req.body || {});
125 broadcastPlugins();
126 res.status(201).json(plugin);
127});
128
129router.put('/plugins/:id', (req, res) => {
130 const plugin = plugins.updatePlugin(req.params.id, req.body || {});
131 if (!plugin) return res.status(404).json({ error: 'not_found' });
132 broadcastPlugins();
133 res.json(plugin);
134});
135
136router.delete('/plugins/:id', (req, res) => {
137 const removed = plugins.deletePlugin(req.params.id);
138 if (!removed) return res.status(404).json({ error: 'not_found' });
139 broadcastPlugins();
140 res.json({ ok: true });
141});
142
143// ---- Загрузка медиа ----
144
145// Файл передаётся сырым телом запроса, чтобы не тянуть multipart-зависимость.
146router.post(
147 '/uploads',
148 express.raw({ type: () => true, limit: '512mb' }),
149 (req, res) => {
150 if (!req.body || !Buffer.isBuffer(req.body) || !req.body.length) {
151 return res.status(400).json({ error: 'empty_file' });
152 }
153 const original = req.query.name || req.get('x-file-name') || 'file';
154 const fallbackExt = String(req.get('content-type') || '').includes('video') ? '.mp4' : '';
155 const fileName = safeFileName(original, fallbackExt);
156 try {
157 fs.writeFileSync(path.join(UPLOAD_DIR, fileName), req.body);
158 } catch (error) {
159 return res.status(500).json({ error: 'write_failed', message: String(error.message || error) });
160 }
161 const url = `/uploads/${fileName}`;
162 res.status(201).json({ url, name: original, size: req.body.length });
163 }
164);
165
166// ---- Окна Chrome для трансляции ----
167
168router.get('/windows', async (req, res) => {
169 const targets = await cdp.listTargets(true);
170 res.json({
171 endpoint: cdp.ENDPOINT,
172 targets: targets.map(({ id, title, url }) => ({ id, title, url })),
173 });
174});
175
176// ---- Сессии демонстраций ----
177
178router.get('/sessions', (req, res) => {
179 res.json({ sessions: hub.listSessions() });
180});
181
182router.delete('/sessions/:presentationId', (req, res) => {
183 const stopped = hub.endSession(req.params.presentationId, 'stopped');
184 res.json({ ok: stopped });
185});
186
187module.exports = router;