OrbiSubs panel: channel list, add/edit modal, live status (phase 1, start/stop off)
This commit is contained in:
@@ -0,0 +1,195 @@
|
||||
'use strict';
|
||||
// validate.js — normaliza y valida la configuración de un canal. Lo usa la API
|
||||
// (la que manda) y lo replica a mano el modal (defense in depth, como en v1:
|
||||
// la regla crítica se chequea en cada camino por el que puede entrar).
|
||||
//
|
||||
// Puertos: cada salida SRT listener reserva su puerto y el siguiente (la 078 usa
|
||||
// SRT_PORT para clientes y SRT_PORT_TEST = +1 para el HLS de prueba interno).
|
||||
|
||||
const SLUG_RE = /^[a-z0-9][a-z0-9-]{0,30}$/;
|
||||
// Puertos del CT que no puede tomar ningún canal (ssh, smtp local, nginx, este panel).
|
||||
const RESERVED = new Set([22, 25, 80, 443, Number(process.env.PORT) || 4700]);
|
||||
const CC608 = ['CC1', 'CC2', 'CC3', 'CC4'];
|
||||
const LANGS = ['es', 'en', 'pt'];
|
||||
|
||||
class ValidationError extends Error {
|
||||
constructor(msg, field) { super(msg); this.field = field; this.status = 400; }
|
||||
}
|
||||
const bad = (msg, field) => { throw new ValidationError(msg, field); };
|
||||
|
||||
const str = v => (v == null ? '' : String(v).trim());
|
||||
function int(v, field, min, max, label, { optional = false } = {}) {
|
||||
if (v === '' || v == null) {
|
||||
if (optional) return null;
|
||||
bad(`Falta ${label}`, field);
|
||||
}
|
||||
const n = Number(v);
|
||||
if (!Number.isInteger(n) || n < min || n > max) bad(`${label}: tiene que ser un entero entre ${min} y ${max}`, field);
|
||||
return n;
|
||||
}
|
||||
function num(v, field, min, max, label) {
|
||||
const n = Number(v);
|
||||
if (v === '' || v == null || !Number.isFinite(n) || n < min || n > max) bad(`${label}: tiene que ser un número entre ${min} y ${max}`, field);
|
||||
return n;
|
||||
}
|
||||
function httpUrl(v, field, label) {
|
||||
const s = str(v);
|
||||
let u;
|
||||
try { u = new URL(s); } catch { bad(`${label}: URL mal armada`, field); }
|
||||
if (!/^https?:$/.test(u.protocol)) bad(`${label}: tiene que empezar con http:// o https://`, field);
|
||||
return s.replace(/\/+$/, '');
|
||||
}
|
||||
function host(v, field, label) {
|
||||
const s = str(v);
|
||||
if (!/^[A-Za-z0-9.-]{1,253}$/.test(s) && !/^\[[0-9a-fA-F:]+\]$/.test(s)) bad(`${label}: host mal armado`, field);
|
||||
return s;
|
||||
}
|
||||
function passphrase(v, field) {
|
||||
const s = str(v);
|
||||
if (s && (s.length < 10 || s.length > 79)) bad('La passphrase SRT tiene que tener entre 10 y 79 caracteres', field);
|
||||
return s;
|
||||
}
|
||||
|
||||
function input(i = {}) {
|
||||
const kind = str(i.kind);
|
||||
if (kind === 'srt') {
|
||||
const mode = str(i.mode) === 'listener' ? 'listener' : 'caller';
|
||||
const out = {
|
||||
kind, mode,
|
||||
host: mode === 'caller' ? host(i.host, 'in_host', 'Entrada SRT') : (str(i.host) || '0.0.0.0'),
|
||||
port: int(i.port, 'in_port', 1, 65535, 'Puerto de la entrada'),
|
||||
latency_ms: int(i.latency_ms === '' || i.latency_ms == null ? 200 : i.latency_ms, 'in_latency', 20, 8000, 'Latency de la entrada (ms)'),
|
||||
streamid: str(i.streamid),
|
||||
passphrase: passphrase(i.passphrase, 'in_passphrase'),
|
||||
};
|
||||
if (out.streamid.length > 512 || /[\s&]/.test(out.streamid)) bad('streamid: sin espacios ni &, hasta 512 caracteres', 'in_streamid');
|
||||
if (mode === 'listener' && RESERVED.has(out.port)) bad(`El puerto ${out.port} lo usa el sistema`, 'in_port');
|
||||
return Object.assign(out, avPick(i));
|
||||
}
|
||||
if (kind === 'udp') {
|
||||
const s = str(i.url);
|
||||
const m = /^udp:\/\/(@?)([0-9.]+|[A-Za-z0-9.-]+)?:(\d{1,5})(\?.*)?$/.exec(s);
|
||||
if (!m || Number(m[3]) < 1 || Number(m[3]) > 65535) bad('Entrada UDP: tiene que ser udp://ip:puerto (o udp://@239.x.x.x:puerto)', 'in_url');
|
||||
return Object.assign({ kind, url: s }, avPick(i));
|
||||
}
|
||||
if (kind === 'hls') {
|
||||
const url = httpUrl(i.url, 'in_url', 'Entrada HLS');
|
||||
if (!/\.m3u8/i.test(url)) bad('Entrada HLS: la URL tiene que apuntar a una lista .m3u8', 'in_url');
|
||||
return Object.assign({ kind, url }, avPick(i));
|
||||
}
|
||||
bad('Tipo de entrada desconocido (SRT, UDP o HLS)', 'in_kind');
|
||||
}
|
||||
// Programa y PID de audio: opcionales, para fuentes con más de un servicio o audio.
|
||||
function avPick(i) {
|
||||
return {
|
||||
program: int(i.program, 'in_program', 1, 65535, 'Programa', { optional: true }),
|
||||
audio_pid: int(i.audio_pid, 'in_audio_pid', 16, 8190, 'PID de audio', { optional: true }),
|
||||
};
|
||||
}
|
||||
|
||||
// Toma el JSON que manda el modal (o la API) y devuelve el canal normalizado.
|
||||
function channel(body = {}) {
|
||||
const name = str(body.name);
|
||||
if (!name || name.length > 80) bad('Falta el nombre (hasta 80 caracteres)', 'name');
|
||||
const slug = str(body.slug).toLowerCase();
|
||||
if (!SLUG_RE.test(slug)) bad('Id corto: minúsculas, números y guiones, hasta 31, empezando con letra o número', 'slug');
|
||||
// <slug>-cc es la carpeta del HLS de prueba de la salida SRT (078): no puede ser otro canal.
|
||||
if (/-cc$/.test(slug)) bad('El id corto no puede terminar en "-cc" (lo usa la prueba de la salida SRT)', 'slug');
|
||||
|
||||
const c = body.cfg || body;
|
||||
const asr = c.asr || {};
|
||||
const tr = c.tr || {};
|
||||
const hls = c.hls || {};
|
||||
const srt = c.srt || {};
|
||||
|
||||
const cfg = {
|
||||
input: input(c.input),
|
||||
asr: {
|
||||
lang: LANGS.includes(str(asr.lang)) ? str(asr.lang) : 'es',
|
||||
url: httpUrl(asr.url || 'http://192.168.2.10:8004', 'asr_url', 'URL del motor de reconocimiento'),
|
||||
prompt: str(asr.prompt).slice(0, 500),
|
||||
},
|
||||
tr: {
|
||||
langs: [...new Set((Array.isArray(tr.langs) ? tr.langs : []).map(str))].filter(l => l === 'en'),
|
||||
url: httpUrl(tr.url || 'http://192.168.2.10:8001', 'tr_url', 'URL del LLM'),
|
||||
model: str(tr.model) || 'qwen2.5-7b-instruct',
|
||||
},
|
||||
hls: {
|
||||
enabled: hls.enabled !== false,
|
||||
seg_s: int(hls.seg_s ?? 6, 'hls_seg', 2, 10, 'Largo de segmento HLS (s)'),
|
||||
list_size: int(hls.list_size ?? 10, 'hls_list', 3, 30, 'Segmentos en la lista'),
|
||||
},
|
||||
srt: { enabled: !!srt.enabled },
|
||||
};
|
||||
if (cfg.tr.langs.length && cfg.asr.lang === 'en') bad('El audio ya es inglés: no hace falta traducir a inglés', 'tr_langs');
|
||||
|
||||
if (cfg.srt.enabled) {
|
||||
const mode = str(srt.mode) === 'caller' ? 'caller' : 'listener';
|
||||
Object.assign(cfg.srt, {
|
||||
mode,
|
||||
host: mode === 'caller' ? host(srt.host, 'srt_host', 'Destino de la salida SRT') : '',
|
||||
port: int(srt.port, 'srt_port', 1024, 65534, 'Puerto de la salida SRT'),
|
||||
latency_ms: int(srt.latency_ms === '' || srt.latency_ms == null ? 200 : srt.latency_ms, 'srt_latency', 20, 8000, 'Latency de la salida (ms)'),
|
||||
passphrase: passphrase(srt.passphrase, 'srt_passphrase'),
|
||||
delay_s: num(srt.delay_s ?? 24, 'srt_delay', 5, 60, 'Retraso fijo del video (s)'),
|
||||
cc608: {}, cc708: {},
|
||||
});
|
||||
// Qué idioma va en cada canal 608 y servicio 708. Vacío = ese idioma no va.
|
||||
const langsOut = [cfg.asr.lang, ...cfg.tr.langs];
|
||||
const used608 = new Set(), used708 = new Set();
|
||||
for (const l of langsOut) {
|
||||
const v608 = str((srt.cc608 || {})[l]);
|
||||
if (v608) {
|
||||
if (!CC608.includes(v608)) bad(`608 de ${l}: CC1 a CC4`, 'srt_cc608');
|
||||
if (used608.has(v608)) bad(`${v608} está repetido entre idiomas`, 'srt_cc608');
|
||||
used608.add(v608); cfg.srt.cc608[l] = v608;
|
||||
}
|
||||
const v708 = (srt.cc708 || {})[l];
|
||||
if (v708 !== '' && v708 != null) {
|
||||
const n = int(v708, 'srt_cc708', 1, 6, `Servicio 708 de ${l}`);
|
||||
if (used708.has(n)) bad(`El servicio 708 ${n} está repetido entre idiomas`, 'srt_cc708');
|
||||
used708.add(n); cfg.srt.cc708[l] = n;
|
||||
}
|
||||
}
|
||||
if (mode === 'listener' && (RESERVED.has(cfg.srt.port) || RESERVED.has(cfg.srt.port + 1))) {
|
||||
bad(`El puerto ${cfg.srt.port} (o el siguiente) lo usa el sistema`, 'srt_port');
|
||||
}
|
||||
}
|
||||
if (!cfg.hls.enabled && !cfg.srt.enabled) bad('El canal necesita al menos una salida (HLS o SRT)', 'hls_enabled');
|
||||
|
||||
return { name, slug, enabled: body.enabled !== false, cfg };
|
||||
}
|
||||
|
||||
// Puertos UDP que el canal toma en este CT (listeners SRT de entrada y salida).
|
||||
function portsOf(cfg) {
|
||||
const out = [];
|
||||
if (cfg.input && cfg.input.kind === 'srt' && cfg.input.mode === 'listener') out.push({ port: cfg.input.port, what: 'entrada SRT' });
|
||||
if (cfg.srt && cfg.srt.enabled && cfg.srt.mode === 'listener') {
|
||||
out.push({ port: cfg.srt.port, what: 'salida SRT' }, { port: cfg.srt.port + 1, what: 'prueba interna de la salida SRT' });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Choque de puertos o de id contra los otros canales (others = filas de la base).
|
||||
function conflicts(ch, others) {
|
||||
for (const o of others) {
|
||||
if (o.slug === ch.slug) bad(`Ya hay un canal con el id corto "${ch.slug}"`, 'slug');
|
||||
}
|
||||
const mine = portsOf(ch.cfg);
|
||||
const seen = new Map();
|
||||
for (const p of mine) {
|
||||
if (seen.has(p.port)) bad(`El puerto ${p.port} se usa dos veces en este canal (${seen.get(p.port)} y ${p.what})`, p.what.includes('entrada') ? 'in_port' : 'srt_port');
|
||||
seen.set(p.port, p.what);
|
||||
}
|
||||
for (const o of others) {
|
||||
for (const q of portsOf(o.cfg)) {
|
||||
for (const p of mine) {
|
||||
if (p.port === q.port) {
|
||||
bad(`El puerto ${p.port} (${p.what}) ya lo usa el canal "${o.name}" (${q.what})`, p.what.includes('entrada') ? 'in_port' : 'srt_port');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { channel, conflicts, portsOf, ValidationError, SLUG_RE };
|
||||
Reference in New Issue
Block a user