Files
2026-10-30 17:43:26 +07:00

188 lines
5.7 KiB
JavaScript

const express = require('express');
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const store = require('./store');
const hub = require('./hub');
const cdp = require('./cdp');
const plugins = require('./plugins');
const router = express.Router();
const UPLOAD_DIR = path.join(__dirname, '..', 'public', 'uploads');
fs.mkdirSync(UPLOAD_DIR, { recursive: true });
function safeFileName(raw, fallbackExt = '') {
const base = String(raw || 'file')
.replace(/\\/g, '/')
.split('/')
.pop();
const extMatch = base.match(/\.([a-zA-Z0-9]{1,12})$/);
const ext = extMatch ? `.${extMatch[1].toLowerCase()}` : fallbackExt;
const stem = base
.slice(0, extMatch ? -extMatch[0].length : undefined)
.toLowerCase()
.replace(/[^a-z0-9._-]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 48) || 'file';
const suffix = crypto.randomBytes(4).toString('hex');
return `${stem}-${Date.now().toString(36)}-${suffix}${ext}`;
}
// ---- Презентации ----
router.get('/presentations', (req, res) => {
res.json({ presentations: store.listPresentations() });
});
router.post('/presentations', (req, res) => {
const presentation = store.createPresentation(req.body || {});
hub.broadcastPresentations();
res.status(201).json(presentation);
});
router.get('/presentations/:id', (req, res) => {
const presentation = store.getPresentation(req.params.id);
if (!presentation) {
return res.status(404).json({ error: 'not_found' });
}
res.json(presentation);
});
// Дублировать презентацию
router.post('/presentations/:id/duplicate', (req, res) => {
const source = store.getPresentation(req.params.id);
if (!source) {
return res.status(404).json({ error: 'not_found' });
}
const copy = store.createPresentation({
title: `${source.title} (копия)`,
slides: source.slides,
variables: source.variables,
music: source.music,
lua: source.lua,
commands: source.commands,
graph: source.graph,
});
hub.broadcastPresentations();
res.status(201).json(copy);
});
router.put('/presentations/:id', (req, res) => {
const presentation = store.getPresentation(req.params.id);
if (!presentation) {
return res.status(404).json({ error: 'not_found' });
}
const body = req.body || {};
if (body.slides !== undefined && !Array.isArray(body.slides)) {
return res.status(400).json({ error: 'bad_slides' });
}
const updated = store.updatePresentation(req.params.id, body);
// Обновляем открытые демонстрации «на лету»
hub.broadcastRoom(updated.id, {
type: 'sync',
presentationId: updated.id,
title: updated.title,
slides: updated.slides,
slideIndex: updated.currentSlide,
variables: updated.variables,
music: updated.music,
lua: updated.lua,
commands: updated.commands,
graph: updated.graph,
});
hub.broadcastPresentations();
hub.broadcastSessions();
res.json(updated);
});
router.delete('/presentations/:id', (req, res) => {
hub.endSession(req.params.id, 'deleted');
store.deletePresentation(req.params.id);
hub.broadcastPresentations();
hub.broadcastSessions();
res.json({ ok: true });
});
// ---- Реестр Lua-плагинов ----
const broadcastPlugins = () => hub.broadcastAll({ type: 'plugins', plugins: plugins.listPlugins() });
router.get('/plugins', (req, res) => {
res.json({ plugins: plugins.listPlugins() });
});
router.get('/plugins/:id', (req, res) => {
const plugin = plugins.getPlugin(req.params.id);
if (!plugin) return res.status(404).json({ error: 'not_found' });
res.json(plugin);
});
router.post('/plugins', (req, res) => {
const plugin = plugins.createPlugin(req.body || {});
broadcastPlugins();
res.status(201).json(plugin);
});
router.put('/plugins/:id', (req, res) => {
const plugin = plugins.updatePlugin(req.params.id, req.body || {});
if (!plugin) return res.status(404).json({ error: 'not_found' });
broadcastPlugins();
res.json(plugin);
});
router.delete('/plugins/:id', (req, res) => {
const removed = plugins.deletePlugin(req.params.id);
if (!removed) return res.status(404).json({ error: 'not_found' });
broadcastPlugins();
res.json({ ok: true });
});
// ---- Загрузка медиа ----
// Файл передаётся сырым телом запроса, чтобы не тянуть multipart-зависимость.
router.post(
'/uploads',
express.raw({ type: () => true, limit: '512mb' }),
(req, res) => {
if (!req.body || !Buffer.isBuffer(req.body) || !req.body.length) {
return res.status(400).json({ error: 'empty_file' });
}
const original = req.query.name || req.get('x-file-name') || 'file';
const fallbackExt = String(req.get('content-type') || '').includes('video') ? '.mp4' : '';
const fileName = safeFileName(original, fallbackExt);
try {
fs.writeFileSync(path.join(UPLOAD_DIR, fileName), req.body);
} catch (error) {
return res.status(500).json({ error: 'write_failed', message: String(error.message || error) });
}
const url = `/uploads/${fileName}`;
res.status(201).json({ url, name: original, size: req.body.length });
}
);
// ---- Окна Chrome для трансляции ----
router.get('/windows', async (req, res) => {
const targets = await cdp.listTargets(true);
res.json({
endpoint: cdp.ENDPOINT,
targets: targets.map(({ id, title, url }) => ({ id, title, url })),
});
});
// ---- Сессии демонстраций ----
router.get('/sessions', (req, res) => {
res.json({ sessions: hub.listSessions() });
});
router.delete('/sessions/:presentationId', (req, res) => {
const stopped = hub.endSession(req.params.presentationId, 'stopped');
res.json({ ok: stopped });
});
module.exports = router;