OrbiSubs panel: channel list, add/edit modal, live status (phase 1, start/stop off)
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
[Unit]
|
||||
Description=OrbiSubs panel web (canales, alta y edición, estado)
|
||||
After=network-online.target
|
||||
# Throttle: como mucho 5 arranques en 10 min (caso TVR-hls de v1: loops de restarts).
|
||||
StartLimitIntervalSec=600
|
||||
StartLimitBurst=5
|
||||
|
||||
[Service]
|
||||
# Node propio en /opt/node (Debian 12 trae Node 18 y better-sqlite3 12 pide >= 20).
|
||||
Environment=PATH=/opt/node/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
||||
Environment=PORT=4700
|
||||
Environment=DATA_DIR=/var/lib/orbisubs-panel
|
||||
WorkingDirectory=/opt/orbisubs-panel
|
||||
ExecStart=/opt/node/bin/node /opt/orbisubs-panel/src/server.js
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,2 @@
|
||||
node_modules/
|
||||
data/
|
||||
Generated
+1270
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "orbisubs-panel",
|
||||
"version": "0.1.0",
|
||||
"description": "OrbiSubs - panel web para configurar los canales con subtítulos en vivo",
|
||||
"main": "src/server.js",
|
||||
"type": "commonjs",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"start": "node src/server.js",
|
||||
"test": "node --test test/*.test.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"better-sqlite3": "^12.2.0",
|
||||
"express": "^4.21.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
'use strict';
|
||||
// db.js — base SQLite del panel: usuarios, sesiones, canales y eventos.
|
||||
// La configuración de cada canal va como JSON en una columna: son pocos canales,
|
||||
// sin relaciones, y así sumar un campo no pide migración.
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const Database = require('better-sqlite3');
|
||||
|
||||
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, '..', 'data');
|
||||
fs.mkdirSync(DATA_DIR, { recursive: true });
|
||||
|
||||
const db = new Database(path.join(DATA_DIR, 'orbisubs-panel.db'));
|
||||
db.pragma('journal_mode = WAL');
|
||||
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
username TEXT PRIMARY KEY,
|
||||
salt TEXT NOT NULL,
|
||||
iter INTEGER NOT NULL,
|
||||
hash TEXT NOT NULL,
|
||||
role TEXT NOT NULL DEFAULT 'admin',
|
||||
must_change INTEGER NOT NULL DEFAULT 0,
|
||||
sver INTEGER NOT NULL DEFAULT 1
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL REFERENCES users(username) ON DELETE CASCADE,
|
||||
sver INTEGER NOT NULL,
|
||||
expires INTEGER NOT NULL -- epoch ms
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS channels (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
slug TEXT NOT NULL UNIQUE, -- id corto: rutas /hls/<slug>/ y orbisubs-*@<slug>
|
||||
name TEXT NOT NULL,
|
||||
enabled INTEGER NOT NULL DEFAULT 1,
|
||||
cfg TEXT NOT NULL, -- JSON: input, asr, tr, hls, srt
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS events (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
ts TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
level TEXT NOT NULL DEFAULT 'info',
|
||||
channel TEXT,
|
||||
username TEXT,
|
||||
message TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_events_ts ON events(ts);
|
||||
`);
|
||||
|
||||
function event(level, message, { channel = null, username = null } = {}) {
|
||||
db.prepare('INSERT INTO events (level, message, channel, username) VALUES (?, ?, ?, ?)').run(level, message, channel, username);
|
||||
// Tope: el panel es de prueba, no hace falta historia larga.
|
||||
db.prepare('DELETE FROM events WHERE id <= (SELECT MAX(id) - 2000 FROM events)').run();
|
||||
}
|
||||
|
||||
module.exports = { db, DATA_DIR, event };
|
||||
@@ -0,0 +1,158 @@
|
||||
'use strict';
|
||||
// status.js — estado real de cada canal: lo que dice systemd de sus instancias
|
||||
// orbisubs-*@<slug> y lo que escriben los procesos en /var/log/orbisubs (las
|
||||
// métricas por segmento de orbisubs.py, orbisubs_tr.py y orbisubs_srt.py).
|
||||
// Solo lee: no arranca ni para nada.
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { execFile } = require('child_process');
|
||||
|
||||
const LOG_DIR = process.env.LOG_DIR || '/var/log/orbisubs';
|
||||
const HLS_DIR = process.env.HLS_DIR || '/var/www/hls';
|
||||
const STALE_S = 60; // métricas más viejas que esto: el proceso no está produciendo
|
||||
|
||||
function sh(cmd, args, timeout = 5000) {
|
||||
return new Promise(resolve => {
|
||||
execFile(cmd, args, { timeout, maxBuffer: 4 << 20 }, (err, stdout) => resolve(err && !stdout ? '' : String(stdout)));
|
||||
});
|
||||
}
|
||||
|
||||
// Instancias systemd que forman el canal, según su configuración.
|
||||
function unitsOf(ch) {
|
||||
const u = ['ingest', 'asr'];
|
||||
if (ch.cfg.tr && ch.cfg.tr.langs && ch.cfg.tr.langs.length) u.push('tr');
|
||||
if (ch.cfg.srt && ch.cfg.srt.enabled) u.push('srt');
|
||||
return u.map(k => ({ key: k, unit: `orbisubs-${k}@${ch.slug}.service` }));
|
||||
}
|
||||
|
||||
// Un solo `systemctl show` para todas las unidades de todos los canales.
|
||||
async function systemdState(units) {
|
||||
if (!units.length) return {};
|
||||
const out = await sh('systemctl', ['show', '--no-pager', '-p', 'Id,LoadState,ActiveState,SubState,NRestarts,Result,UnitFileState', ...units]);
|
||||
const res = {};
|
||||
for (const block of out.split(/\n\s*\n/)) {
|
||||
const o = {};
|
||||
for (const line of block.split('\n')) {
|
||||
const i = line.indexOf('=');
|
||||
if (i > 0) o[line.slice(0, i)] = line.slice(i + 1);
|
||||
}
|
||||
if (o.Id) res[o.Id] = { load: o.LoadState, active: o.ActiveState, sub: o.SubState, restarts: Number(o.NRestarts || 0), result: o.Result, file: o.UnitFileState };
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
// Últimas líneas JSON de un .jsonl, leyendo solo la cola del archivo.
|
||||
function tailJsonl(file, maxBytes = 256 * 1024) {
|
||||
let fd;
|
||||
try {
|
||||
fd = fs.openSync(file, 'r');
|
||||
const st = fs.fstatSync(fd);
|
||||
const len = Math.min(st.size, maxBytes);
|
||||
const buf = Buffer.alloc(len);
|
||||
fs.readSync(fd, buf, 0, len, st.size - len);
|
||||
const lines = buf.toString('utf8').split('\n');
|
||||
if (st.size > len) lines.shift(); // la primera puede venir cortada
|
||||
const rows = [];
|
||||
for (const l of lines) { if (l.trim()) { try { rows.push(JSON.parse(l)); } catch { /* línea a medias */ } } }
|
||||
return { rows, mtime: st.mtimeMs };
|
||||
} catch { return { rows: [], mtime: 0 }; }
|
||||
finally { if (fd !== undefined) fs.closeSync(fd); }
|
||||
}
|
||||
|
||||
const median = a => {
|
||||
if (!a.length) return null;
|
||||
const s = [...a].sort((x, y) => x - y), m = s.length >> 1;
|
||||
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
|
||||
};
|
||||
const round = (v, d = 2) => (v == null ? null : Math.round(v * 10 ** d) / 10 ** d);
|
||||
|
||||
function metrics(ch, { last = 1 } = {}) {
|
||||
const now = Date.now();
|
||||
const asr = tailJsonl(path.join(LOG_DIR, `${ch.slug}.jsonl`));
|
||||
const segs = asr.rows.filter(r => r.seq != null && r.dur != null);
|
||||
const lastSeg = segs[segs.length - 1];
|
||||
const fresh = asr.mtime && now - asr.mtime < STALE_S * 1000;
|
||||
const m = {
|
||||
fresh: !!fresh,
|
||||
age_s: asr.mtime ? Math.round((now - asr.mtime) / 1000) : null,
|
||||
delay_s: fresh && lastSeg ? lastSeg.channel_extra_s : null,
|
||||
held_segments: fresh && lastSeg ? lastSeg.held_segments : null,
|
||||
pending_s: fresh && lastSeg ? lastSeg.pending_s : null,
|
||||
last: {},
|
||||
recent: {},
|
||||
};
|
||||
const conTexto = segs.filter(r => r.text);
|
||||
if (conTexto.length) m.last[ch.cfg.asr.lang] = conTexto[conTexto.length - 1].text.replace(/ \| /g, ' ');
|
||||
m.recent[ch.cfg.asr.lang] = conTexto.slice(-last).map(r => ({ seq: r.seq, text: r.text.replace(/ \| /g, ' ') }));
|
||||
// Pedidos al motor de reconocimiento (gpu02 :8004): los últimos 100 segmentos.
|
||||
const asrT = segs.slice(-100).map(r => r.http_s ?? r.asr_s).filter(v => typeof v === 'number');
|
||||
m.asr = { n: asrT.length, median_s: round(median(asrT)) };
|
||||
|
||||
if (ch.cfg.tr.langs.length) {
|
||||
const tr = tailJsonl(path.join(LOG_DIR, `${ch.slug}-en.jsonl`));
|
||||
const frases = tr.rows.filter(r => 'en' in r);
|
||||
const lags = tr.rows.filter(r => r.en_lag_vs_es_s != null).slice(-100).map(r => r.en_lag_vs_es_s);
|
||||
const okT = frases.slice(-100).map(r => r.qwen_s).filter(v => typeof v === 'number');
|
||||
const conEn = frases.filter(r => r.en);
|
||||
if (conEn.length) m.last.en = conEn[conEn.length - 1].en;
|
||||
m.recent.en = conEn.slice(-last).map(r => ({ text: r.en, es: r.es }));
|
||||
m.tr = { n: okT.length, median_s: round(median(okT)), lag_median_s: round(median(lags)), fresh: !!(tr.mtime && now - tr.mtime < STALE_S * 1000) };
|
||||
}
|
||||
|
||||
if (ch.cfg.srt.enabled) {
|
||||
const s = tailJsonl(path.join(LOG_DIR, `${ch.slug}-srt.jsonl`), 64 * 1024);
|
||||
const r = s.rows[s.rows.length - 1];
|
||||
if (r) {
|
||||
const pick = k => (r[k] ? { cues: r[k].cues, tarde: r[k].tarde, perdidos: r[k].perdidos, tarde_max_s: r[k].tarde_max_s ?? null } : null);
|
||||
m.srt = {
|
||||
fresh: !!(s.mtime && now - s.mtime < STALE_S * 1000),
|
||||
delay_s: r.retraso_fijo_s, send_lag_s: r.atraso_envio_s,
|
||||
es608: pick('es608'), en608: pick('en608'), es708: pick('es708'), en708: pick('en708'),
|
||||
};
|
||||
}
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
// Fallas de los pedidos a gpu02 en la última hora, contadas en el journal
|
||||
// (orbisubs.py escribe asr_error y orbisubs_tr.py translate_error).
|
||||
async function failures(ch) {
|
||||
const count = async (unit, word) => {
|
||||
const out = await sh('journalctl', ['-u', unit, '--since', '-1h', '-o', 'cat', '--no-pager', '-q'], 8000);
|
||||
return out.split('\n').filter(l => l.includes(`"${word}"`)).length;
|
||||
};
|
||||
const r = { asr_errors_1h: await count(`orbisubs-asr@${ch.slug}.service`, 'asr_error') };
|
||||
if (ch.cfg.tr.langs.length) r.tr_errors_1h = await count(`orbisubs-tr@${ch.slug}.service`, 'translate_error');
|
||||
return r;
|
||||
}
|
||||
|
||||
// Resume las unidades en un estado del canal: corriendo, parado, error, arrancando.
|
||||
function summarize(ch, sd) {
|
||||
const units = unitsOf(ch).map(u => ({ ...u, ...(sd[u.unit] || { load: 'not-found', active: 'inactive' }) }));
|
||||
const act = units.map(u => u.active);
|
||||
let state;
|
||||
if (act.every(a => a === 'active')) state = 'running';
|
||||
else if (act.some(a => a === 'failed')) state = 'error';
|
||||
else if (act.every(a => a === 'inactive')) state = 'stopped';
|
||||
else if (act.some(a => a === 'activating' || a === 'reloading')) state = 'connecting';
|
||||
else state = 'error'; // a medias: algunas andan y otras no
|
||||
const notes = units.filter(u => u.active !== 'active' && state !== 'stopped').map(u => `${u.key}: ${u.active}${u.result && u.result !== 'success' ? ` (${u.result})` : ''}`);
|
||||
return { state, units, notes, managed: units.some(u => u.load === 'loaded') };
|
||||
}
|
||||
|
||||
async function all(channels) {
|
||||
const sd = await systemdState(channels.flatMap(ch => unitsOf(ch).map(u => u.unit)));
|
||||
const res = {};
|
||||
for (const ch of channels) {
|
||||
const s = summarize(ch, sd);
|
||||
const m = metrics(ch);
|
||||
// Corriendo según systemd pero sin producir subtítulos: se muestra como error.
|
||||
if (s.state === 'running' && !m.fresh && m.age_s !== null && m.age_s > STALE_S * 2) {
|
||||
s.state = 'error'; s.notes.push(`sin subtítulos nuevos hace ${m.age_s} s`);
|
||||
}
|
||||
res[ch.id] = { ...s, metrics: m };
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
module.exports = { all, metrics, failures, unitsOf, systemdState, summarize, LOG_DIR, HLS_DIR };
|
||||
@@ -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 };
|
||||
@@ -0,0 +1,465 @@
|
||||
/* app.js — panel de OrbiSubs. Sin framework, como OrbiStream. */
|
||||
'use strict';
|
||||
const $ = s => document.querySelector(s);
|
||||
const $$ = s => [...document.querySelectorAll(s)];
|
||||
const t = (s, v) => OrbiLang.t(s, v);
|
||||
const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
// El HLS y el player los sirve el nginx del CT (puerto 80), no este panel.
|
||||
const MEDIA = `${location.protocol}//${location.hostname}`;
|
||||
|
||||
let me = null, channels = [], control = false, controlMsg = '';
|
||||
let pollTimer = null;
|
||||
|
||||
OrbiLang.apply(document);
|
||||
OrbiLang.mount($('#login-lang'));
|
||||
|
||||
/* ---------------- API ---------------- */
|
||||
async function api(method, url, body) {
|
||||
let r;
|
||||
try {
|
||||
r = await fetch(url, { method, headers: body ? { 'Content-Type': 'application/json' } : {}, body: body ? JSON.stringify(body) : undefined, credentials: 'same-origin' });
|
||||
} catch (e) {
|
||||
$('#api-banner').classList.remove('hidden');
|
||||
throw new Error(t('Sin conexión con la API'));
|
||||
}
|
||||
$('#api-banner').classList.add('hidden');
|
||||
let data = null;
|
||||
try { data = await r.json(); } catch { /* sin cuerpo */ }
|
||||
if (r.status === 401 && !url.startsWith('/api/auth/')) { showLogin(); throw new Error(t('No autenticado')); }
|
||||
if (!r.ok) { const e = new Error(t((data && data.error) || `HTTP ${r.status}`)); e.field = data && data.field; e.status = r.status; throw e; }
|
||||
return data;
|
||||
}
|
||||
|
||||
/* ---------------- Login ---------------- */
|
||||
let changeToken = null;
|
||||
function showLogin(msg) {
|
||||
me = null;
|
||||
clearInterval(pollTimer);
|
||||
$('#login-overlay').classList.remove('hidden');
|
||||
$('#login-form').classList.remove('hidden');
|
||||
$('#first-form').classList.add('hidden');
|
||||
setLoginMsg(msg);
|
||||
setTimeout(() => $('#login-form [name=username]').focus(), 50);
|
||||
}
|
||||
function setLoginMsg(msg) {
|
||||
$('#login-msg').textContent = msg || '';
|
||||
$('#login-msg').classList.toggle('hidden', !msg);
|
||||
}
|
||||
function loggedIn(user) {
|
||||
me = user;
|
||||
$('#login-overlay').classList.add('hidden');
|
||||
$('#user-name').textContent = user.username;
|
||||
$('#user-role').textContent = user.role;
|
||||
$('#user-box').classList.remove('hidden');
|
||||
route();
|
||||
}
|
||||
$('#login-form').addEventListener('submit', async e => {
|
||||
e.preventDefault();
|
||||
const f = e.target;
|
||||
try {
|
||||
const r = await api('POST', '/api/auth/login', { username: f.username.value.trim(), password: f.password.value });
|
||||
f.password.value = '';
|
||||
if (r.must_change) {
|
||||
changeToken = r.token;
|
||||
$('#login-form').classList.add('hidden');
|
||||
$('#first-form').classList.remove('hidden');
|
||||
$('#first-hint').innerHTML = t('La cuenta <b>{u}</b> tiene la clave inicial. Elige una nueva para seguir (mínimo {n} caracteres).', { u: esc(r.username), n: r.min });
|
||||
setLoginMsg('');
|
||||
$('#first-form [name=password]').focus();
|
||||
return;
|
||||
}
|
||||
loggedIn(r.user);
|
||||
} catch (err) { setLoginMsg(err.message); }
|
||||
});
|
||||
$('#first-form').addEventListener('submit', async e => {
|
||||
e.preventDefault();
|
||||
const f = e.target;
|
||||
try {
|
||||
const r = await api('POST', '/api/auth/first-password', { token: changeToken, password: f.password.value, password2: f.password2.value });
|
||||
f.reset();
|
||||
loggedIn(r.user);
|
||||
} catch (err) { setLoginMsg(err.message); }
|
||||
});
|
||||
$('#btn-logout').addEventListener('click', async () => {
|
||||
try { await api('POST', '/api/auth/logout'); } catch { /* igual */ }
|
||||
$('#user-box').classList.add('hidden');
|
||||
showLogin();
|
||||
});
|
||||
|
||||
/* ---------------- Navegación ---------------- */
|
||||
function route() {
|
||||
if (!me) return;
|
||||
const r = (location.hash || '#channels').slice(1);
|
||||
$$('.view').forEach(v => v.classList.toggle('hidden', v.id !== `view-${r}`));
|
||||
$$('.nav a').forEach(a => a.classList.toggle('active', a.dataset.route === r));
|
||||
clearInterval(pollTimer);
|
||||
if (r === 'events') { loadEvents(); pollTimer = setInterval(loadEvents, 10000); }
|
||||
else { loadChannels(); pollTimer = setInterval(loadChannels, 5000); }
|
||||
}
|
||||
window.addEventListener('hashchange', route);
|
||||
|
||||
/* ---------------- Canales ---------------- */
|
||||
const STATE = {
|
||||
running: ['running', 'corriendo'], stopped: ['stopped', 'parado'],
|
||||
error: ['error', 'error'], connecting: ['connecting', 'arrancando'],
|
||||
};
|
||||
const LANG_NAME = { es: 'Español', en: 'English', pt: 'Português' };
|
||||
|
||||
function inputText(i) {
|
||||
if (i.kind === 'srt') return i.mode === 'listener' ? `srt://:${i.port} (listener)` : `srt://${i.host}:${i.port}`;
|
||||
if (i.kind === 'hls') { try { return `HLS ${new URL(i.url).host}`; } catch { return i.url; } }
|
||||
return i.url;
|
||||
}
|
||||
function outputsText(c) {
|
||||
const o = [];
|
||||
if (c.cfg.hls.enabled) o.push('<span class="chip">HLS</span>');
|
||||
if (c.cfg.srt.enabled) o.push(`<span class="chip">SRT ${c.cfg.srt.mode === 'listener' ? ':' + c.cfg.srt.port : '→ ' + esc(c.cfg.srt.host) + ':' + c.cfg.srt.port}</span>`);
|
||||
return o.join('');
|
||||
}
|
||||
function langsText(c) {
|
||||
return [c.cfg.asr.lang, ...c.cfg.tr.langs].map(l => `<span class="chip">${l}</span>`).join('');
|
||||
}
|
||||
|
||||
async function loadChannels() {
|
||||
try {
|
||||
const r = await api('GET', '/api/channels');
|
||||
channels = r.channels; control = r.control; controlMsg = r.control_msg;
|
||||
renderChannels();
|
||||
} catch { /* banner o login */ }
|
||||
}
|
||||
function renderChannels() {
|
||||
$('#control-banner').classList.toggle('hidden', control);
|
||||
$('#control-banner').textContent = control ? '' : t(controlMsg || '');
|
||||
$('#channels-empty').classList.toggle('hidden', channels.length > 0);
|
||||
const offTitle = control ? '' : ` — ${t(controlMsg)}`;
|
||||
$('#tbl-channels tbody').innerHTML = channels.map(c => {
|
||||
const st = c.status || {};
|
||||
const [cls, label] = STATE[st.state] || STATE.stopped;
|
||||
const m = st.metrics || {};
|
||||
const lastLines = Object.entries(m.last || {}).map(([l, txt]) => `<div class="ch-sub"><span class="chip">${l}</span> ${esc(txt)}</div>`).join('');
|
||||
const notes = (st.notes || []).join(' · ');
|
||||
return `<tr data-id="${c.id}">
|
||||
<td><span class="badge ${cls}" title="${esc(notes)}">${t(label)}</span>${c.enabled ? '' : `<div class="muted small">${t('deshabilitado')}</div>`}</td>
|
||||
<td><b>${esc(c.name)}</b><div class="mono">${esc(c.slug)}</div></td>
|
||||
<td class="mono" title="${esc(c.cfg.input.url || '')}">${esc(inputText(c.cfg.input))}</td>
|
||||
<td>${langsText(c)}</td>
|
||||
<td>${outputsText(c)}</td>
|
||||
<td class="num">${m.delay_s != null ? `${m.delay_s.toFixed(1)} s` : '—'}${m.held_segments != null ? `<div class="muted small">${t('{n} seg. sostenidos', { n: m.held_segments })}</div>` : ''}</td>
|
||||
<td class="c-sub">${lastLines || '<span class="muted">—</span>'}</td>
|
||||
<td><div class="actions">
|
||||
<button class="btn-ico" data-act="start" title="${t('Iniciar')}${offTitle}" ${control ? '' : 'disabled'}>▶</button>
|
||||
<button class="btn-ico" data-act="stop" title="${t('Parar')}${offTitle}" ${control ? '' : 'disabled'}>■</button>
|
||||
<button class="btn-ico" data-act="edit" title="${t('Editar')}">✎</button>
|
||||
<button class="btn-ico" data-act="view" title="${t('Ver')}">👁</button>
|
||||
<button class="btn-ico danger" data-act="delete" title="${t('Eliminar')}">🗑</button>
|
||||
</div></td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
}
|
||||
$('#tbl-channels').addEventListener('click', async e => {
|
||||
const b = e.target.closest('button[data-act]');
|
||||
if (!b) return;
|
||||
const c = channels.find(x => x.id === Number(b.closest('tr').dataset.id));
|
||||
if (!c) return;
|
||||
const act = b.dataset.act;
|
||||
if (act === 'edit') return openModal(c);
|
||||
if (act === 'view') return openView(c);
|
||||
if (act === 'delete') {
|
||||
if (!confirm(t('¿Borrar el canal «{n}»?', { n: c.name }))) return;
|
||||
try { await api('DELETE', `/api/channels/${c.id}`); loadChannels(); } catch (err) { alert(err.message); }
|
||||
return;
|
||||
}
|
||||
try { await api('POST', `/api/channels/${c.id}/${act}`); loadChannels(); } catch (err) { alert(err.message); }
|
||||
});
|
||||
|
||||
/* ---------------- Modal alta / edición ---------------- */
|
||||
let editing = null;
|
||||
const F = () => $('#channel-form');
|
||||
function fillCC() {
|
||||
const f = F();
|
||||
const o608 = ['', 'CC1', 'CC2', 'CC3', 'CC4'].map(v => `<option value="${v}">${v || t('(no va)')}</option>`).join('');
|
||||
const o708 = ['', 1, 2, 3, 4, 5, 6].map(v => `<option value="${v}">${v || t('(no va)')}</option>`).join('');
|
||||
f.cc608_main.innerHTML = o608; f.cc608_en.innerHTML = o608;
|
||||
f.cc708_main.innerHTML = o708; f.cc708_en.innerHTML = o708;
|
||||
}
|
||||
function openModal(c) {
|
||||
editing = c || null;
|
||||
const f = F();
|
||||
f.reset(); fillCC();
|
||||
$('#form-error').classList.add('hidden');
|
||||
$('#paste-msg').classList.add('hidden');
|
||||
$$('#channel-form .field-bad').forEach(x => x.classList.remove('field-bad'));
|
||||
$('#modal-title').textContent = c ? t('Editar canal: {n}', { n: c.name }) : t('Nuevo canal');
|
||||
const d = c ? c.cfg : {
|
||||
input: { kind: 'srt', mode: 'caller', latency_ms: 200 },
|
||||
asr: { lang: 'es', url: 'http://192.168.2.10:8004', prompt: '' },
|
||||
tr: { langs: [], url: 'http://192.168.2.10:8001' },
|
||||
hls: { enabled: true, seg_s: 6, list_size: 10 },
|
||||
srt: { enabled: false, mode: 'listener', latency_ms: 200, delay_s: 24, cc608: { es: 'CC1', en: 'CC3' }, cc708: { es: 1, en: 2 } },
|
||||
};
|
||||
f.name.value = c ? c.name : '';
|
||||
f.slug.value = c ? c.slug : '';
|
||||
f.enabled.checked = c ? c.enabled : true;
|
||||
const i = d.input;
|
||||
f.in_kind.value = i.kind;
|
||||
f.in_mode.value = i.mode || 'caller';
|
||||
f.in_host.value = i.kind === 'srt' && i.mode === 'caller' ? (i.host || '') : '';
|
||||
f.in_port.value = i.port ?? '';
|
||||
f.in_latency.value = i.latency_ms ?? 200;
|
||||
f.in_passphrase.value = i.passphrase || '';
|
||||
f.in_streamid.value = i.streamid || '';
|
||||
f.in_url.value = i.url || '';
|
||||
f.in_program.value = i.program ?? '';
|
||||
f.in_audio_pid.value = i.audio_pid ?? '';
|
||||
f.asr_lang.value = d.asr.lang;
|
||||
f.asr_url.value = d.asr.url;
|
||||
f.asr_prompt.value = d.asr.prompt || '';
|
||||
f.tr_en.checked = d.tr.langs.includes('en');
|
||||
f.tr_url.value = d.tr.url || 'http://192.168.2.10:8001';
|
||||
f.hls_enabled.checked = d.hls.enabled;
|
||||
f.hls_seg.value = d.hls.seg_s;
|
||||
f.hls_list.value = d.hls.list_size;
|
||||
const s = d.srt;
|
||||
f.srt_enabled.checked = s.enabled;
|
||||
f.srt_mode.value = s.mode || 'listener';
|
||||
f.srt_host.value = s.host || '';
|
||||
f.srt_port.value = s.port ?? suggestPort();
|
||||
f.srt_latency.value = s.latency_ms ?? 200;
|
||||
f.srt_passphrase.value = s.passphrase || '';
|
||||
f.srt_delay.value = s.delay_s ?? 24;
|
||||
const cc608 = s.cc608 || { es: 'CC1', en: 'CC3' }, cc708 = s.cc708 || { es: 1, en: 2 };
|
||||
f.cc608_main.value = cc608[d.asr.lang] || ''; f.cc608_en.value = cc608.en || '';
|
||||
f.cc708_main.value = cc708[d.asr.lang] ?? ''; f.cc708_en.value = cc708.en ?? '';
|
||||
syncForm();
|
||||
$('#modal').classList.remove('hidden');
|
||||
f.name.focus();
|
||||
}
|
||||
// Puerto libre sugerido para la salida SRT: el primero par desde 9000 que no use nadie.
|
||||
function suggestPort() {
|
||||
const used = new Set(channels.flatMap(c => usedPorts(c.cfg)));
|
||||
for (let p = 9000; p < 9900; p += 2) if (!used.has(p) && !used.has(p + 1)) return p;
|
||||
return '';
|
||||
}
|
||||
function usedPorts(cfg) {
|
||||
const u = [];
|
||||
if (cfg.input.kind === 'srt' && cfg.input.mode === 'listener') u.push(cfg.input.port);
|
||||
if (cfg.srt.enabled && cfg.srt.mode === 'listener') u.push(cfg.srt.port, cfg.srt.port + 1);
|
||||
return u;
|
||||
}
|
||||
function syncForm() {
|
||||
const f = F();
|
||||
const k = f.in_kind.value;
|
||||
$$('.in-srt').forEach(x => x.classList.toggle('hidden', k !== 'srt'));
|
||||
$$('.in-srt-caller').forEach(x => x.classList.toggle('hidden', k !== 'srt' || f.in_mode.value !== 'caller'));
|
||||
$$('.in-url').forEach(x => x.classList.toggle('hidden', k === 'srt'));
|
||||
$('.in-hls-hint').classList.toggle('hidden', k !== 'hls');
|
||||
f.in_url.placeholder = k === 'hls' ? 'https://cdn.ejemplo/canal/playlist.m3u8' : 'udp://@239.1.1.1:5000';
|
||||
$$('.srt-on').forEach(x => x.classList.toggle('hidden', !f.srt_enabled.checked));
|
||||
$$('.srt-caller').forEach(x => x.classList.toggle('hidden', !f.srt_enabled.checked || f.srt_mode.value !== 'caller'));
|
||||
f.cc608_en.disabled = f.cc708_en.disabled = !f.tr_en.checked;
|
||||
const slug = f.slug.value.trim() || '<id>';
|
||||
$('#hls-urls').innerHTML = f.hls_enabled.checked
|
||||
? urlLine(t('Master HLS'), `${MEDIA}/hls/${slug}/master.m3u8`) + urlLine(t('Player'), `${MEDIA}/player.html?u=/hls/${slug}/master.m3u8`)
|
||||
: '';
|
||||
$('#srt-url').innerHTML = f.srt_enabled.checked && f.srt_mode.value === 'listener' && f.srt_port.value
|
||||
? urlLine(t('Salida SRT'), `srt://${location.hostname}:${f.srt_port.value}`) : '';
|
||||
}
|
||||
function urlLine(label, url) {
|
||||
return `<div class="url-line"><span class="muted">${esc(label)}</span> <span class="mono out-url">${esc(url)}</span><button type="button" class="out-copy" data-url="${esc(url)}" title="${t('Copiar URL')}">📋</button></div>`;
|
||||
}
|
||||
document.addEventListener('click', e => {
|
||||
const b = e.target.closest('.out-copy');
|
||||
if (!b) return;
|
||||
navigator.clipboard?.writeText(b.dataset.url).then(() => { b.classList.add('copied'); setTimeout(() => b.classList.remove('copied'), 1200); });
|
||||
});
|
||||
F().addEventListener('input', syncForm);
|
||||
F().addEventListener('change', syncForm);
|
||||
$('#modal-close').onclick = $('#btn-cancel').onclick = () => $('#modal').classList.add('hidden');
|
||||
|
||||
// Pegado rápido: el parser de OrbiStream (url-parse.js) reparte la URL en los campos.
|
||||
$('#btn-paste-fill').addEventListener('click', () => {
|
||||
const f = F();
|
||||
const r = parseMediaUrl($('#in-paste').value);
|
||||
const box = $('#paste-msg');
|
||||
box.classList.remove('hidden', 'ok', 'bad');
|
||||
if (r.error) { box.classList.add('bad'); box.textContent = r.error; return; }
|
||||
if (r.kind === 'rtmp') { box.classList.add('bad'); box.textContent = t('RTMP no está soportado como entrada (SRT, UDP o HLS).'); return; }
|
||||
if (r.kind === 'srt_listener' || r.kind === 'srt_caller') {
|
||||
f.in_kind.value = 'srt';
|
||||
f.in_mode.value = r.kind === 'srt_listener' ? 'listener' : 'caller';
|
||||
const m = /^srt:\/\/([^:/?]+|\[[^\]]+\]):(\d+)(?:\?(.*))?$/.exec(r.url);
|
||||
if (m) {
|
||||
f.in_host.value = r.kind === 'srt_caller' ? m[1] : '';
|
||||
f.in_port.value = m[2];
|
||||
const q = new URLSearchParams(m[3] || '');
|
||||
f.in_streamid.value = q.get('streamid') || '';
|
||||
}
|
||||
if (r.latency_ms != null) f.in_latency.value = r.latency_ms;
|
||||
f.in_passphrase.value = r.passphrase || '';
|
||||
} else {
|
||||
f.in_kind.value = r.kind;
|
||||
f.in_url.value = r.url;
|
||||
}
|
||||
box.classList.add('ok');
|
||||
box.innerHTML = t('Campos rellenados.') + (r.avisos.length ? `<ul>${r.avisos.map(a => `<li>${esc(a)}</li>`).join('')}</ul>` : '');
|
||||
syncForm();
|
||||
});
|
||||
|
||||
function collect() {
|
||||
const f = F();
|
||||
const lang = f.asr_lang.value;
|
||||
const cc608 = {}, cc708 = {};
|
||||
if (f.cc608_main.value) cc608[lang] = f.cc608_main.value;
|
||||
if (f.cc708_main.value) cc708[lang] = Number(f.cc708_main.value);
|
||||
if (f.tr_en.checked) {
|
||||
if (f.cc608_en.value) cc608.en = f.cc608_en.value;
|
||||
if (f.cc708_en.value) cc708.en = Number(f.cc708_en.value);
|
||||
}
|
||||
const k = f.in_kind.value;
|
||||
return {
|
||||
name: f.name.value.trim(), slug: f.slug.value.trim().toLowerCase(), enabled: f.enabled.checked,
|
||||
cfg: {
|
||||
input: k === 'srt'
|
||||
? { kind: k, mode: f.in_mode.value, host: f.in_host.value.trim(), port: f.in_port.value, latency_ms: f.in_latency.value,
|
||||
passphrase: f.in_passphrase.value.trim(), streamid: f.in_streamid.value.trim(), program: f.in_program.value, audio_pid: f.in_audio_pid.value }
|
||||
: { kind: k, url: f.in_url.value.trim(), program: f.in_program.value, audio_pid: f.in_audio_pid.value },
|
||||
asr: { lang, url: f.asr_url.value.trim(), prompt: f.asr_prompt.value.trim() },
|
||||
tr: { langs: f.tr_en.checked ? ['en'] : [], url: f.tr_url.value.trim(), model: editing ? editing.cfg.tr.model : undefined },
|
||||
hls: { enabled: f.hls_enabled.checked, seg_s: f.hls_seg.value, list_size: f.hls_list.value },
|
||||
srt: { enabled: f.srt_enabled.checked, mode: f.srt_mode.value, host: f.srt_host.value.trim(), port: f.srt_port.value,
|
||||
latency_ms: f.srt_latency.value, passphrase: f.srt_passphrase.value.trim(), delay_s: f.srt_delay.value, cc608, cc708 },
|
||||
},
|
||||
};
|
||||
}
|
||||
// Chequeos del modal antes de mandar (la API los repite y es la que manda).
|
||||
function checkLocal(b) {
|
||||
if (!b.name) return ['name', t('Falta el nombre')];
|
||||
if (!/^[a-z0-9][a-z0-9-]{0,30}$/.test(b.slug)) return ['slug', t('Id corto: minúsculas, números y guiones, hasta 31, empezando con letra o número')];
|
||||
const others = channels.filter(c => !editing || c.id !== editing.id);
|
||||
if (others.some(c => c.slug === b.slug)) return ['slug', t('Ya hay un canal con el id corto "{s}"', { s: b.slug })];
|
||||
const i = b.cfg.input;
|
||||
if (i.kind === 'srt') {
|
||||
if (i.mode === 'caller' && !i.host) return ['in_host', t('Falta el host de la entrada SRT')];
|
||||
if (!(Number(i.port) >= 1 && Number(i.port) <= 65535)) return ['in_port', t('Falta el puerto de la entrada')];
|
||||
} else if (i.kind === 'hls' && !/^https?:\/\/[^/\s]+\/\S*\.m3u8/i.test(i.url)) return ['in_url', t('Entrada HLS: la URL tiene que apuntar a una lista .m3u8')];
|
||||
else if (i.kind === 'udp' && !/^udp:\/\/@?[^:\s]*:\d{1,5}(\?\S*)?$/.test(i.url)) return ['in_url', t('Entrada UDP: tiene que ser udp://ip:puerto (o udp://@239.x.x.x:puerto)')];
|
||||
const mine = [];
|
||||
if (i.kind === 'srt' && i.mode === 'listener') mine.push(['in_port', Number(i.port)]);
|
||||
if (b.cfg.srt.enabled && b.cfg.srt.mode === 'listener') mine.push(['srt_port', Number(b.cfg.srt.port)], ['srt_port', Number(b.cfg.srt.port) + 1]);
|
||||
for (const [field, p] of mine) {
|
||||
const o = others.find(c => usedPorts(c.cfg).includes(p));
|
||||
if (o) return [field, t('El puerto {p} ya lo usa el canal "{n}"', { p, n: o.name })];
|
||||
}
|
||||
if (!b.cfg.hls.enabled && !b.cfg.srt.enabled) return ['hls_enabled', t('El canal necesita al menos una salida (HLS o SRT)')];
|
||||
return null;
|
||||
}
|
||||
function showFormError(field, msg) {
|
||||
$$('#channel-form .field-bad').forEach(x => x.classList.remove('field-bad'));
|
||||
const el = field && F()[field] || (field === 'srt_cc608' && F().cc608_main) || (field === 'srt_cc708' && F().cc708_main);
|
||||
if (el) { el.classList.add('field-bad'); el.focus(); }
|
||||
$('#form-error').textContent = msg;
|
||||
$('#form-error').classList.remove('hidden');
|
||||
}
|
||||
F().addEventListener('submit', async e => {
|
||||
e.preventDefault();
|
||||
const b = collect();
|
||||
const bad = checkLocal(b);
|
||||
if (bad) return showFormError(bad[0], bad[1]);
|
||||
$('#btn-save').disabled = true;
|
||||
try {
|
||||
if (editing) await api('PUT', `/api/channels/${editing.id}`, b);
|
||||
else await api('POST', '/api/channels', b);
|
||||
$('#modal').classList.add('hidden');
|
||||
loadChannels();
|
||||
} catch (err) { showFormError(err.field, err.message); }
|
||||
finally { $('#btn-save').disabled = false; }
|
||||
});
|
||||
|
||||
/* ---------------- Ver canal ---------------- */
|
||||
let hls = null, viewTimer = null, viewing = null;
|
||||
function openView(c) {
|
||||
viewing = c;
|
||||
$('#view-title').textContent = c.name;
|
||||
$('#view-modal').classList.remove('hidden');
|
||||
const v = $('#view-video'), sel = $('#view-track');
|
||||
sel.innerHTML = `<option value="-1">${t('Apagados')}</option>`;
|
||||
if (hls) { hls.destroy(); hls = null; }
|
||||
const src = `${MEDIA}/hls/${c.slug}/master.m3u8`;
|
||||
if (c.cfg.hls.enabled && window.Hls && Hls.isSupported()) {
|
||||
// Mismo player que la 076: 3 segmentos detrás del borde (así el inglés llega a tiempo).
|
||||
hls = new Hls({ liveSyncDurationCount: 3 });
|
||||
hls.on(Hls.Events.ERROR, (ev, d) => { if (!d.fatal) return; if (d.type === Hls.ErrorTypes.MEDIA_ERROR) hls.recoverMediaError(); else hls.startLoad(); });
|
||||
hls.loadSource(src); hls.attachMedia(v);
|
||||
hls.on(Hls.Events.SUBTITLE_TRACKS_UPDATED, () => {
|
||||
sel.innerHTML = `<option value="-1">${t('Apagados')}</option>` + hls.subtitleTracks.map((tr, i) => `<option value="${i}">${esc(tr.name)}</option>`).join('');
|
||||
const want = OrbiLang.lang === 'en' ? 'en' : c.cfg.asr.lang;
|
||||
const i = Math.max(0, hls.subtitleTracks.findIndex(tr => tr.lang === want));
|
||||
sel.value = i; hls.subtitleTrack = i; hls.subtitleDisplay = true;
|
||||
});
|
||||
} else if (c.cfg.hls.enabled && v.canPlayType('application/vnd.apple.mpegurl')) v.src = src;
|
||||
sel.onchange = () => { if (hls) { hls.subtitleTrack = +sel.value; hls.subtitleDisplay = +sel.value >= 0; } };
|
||||
const urls = [];
|
||||
if (c.cfg.hls.enabled) urls.push(urlLine(t('Master HLS'), src), urlLine(t('Player'), `${MEDIA}/player.html?u=/hls/${c.slug}/master.m3u8`));
|
||||
if (c.cfg.srt.enabled) {
|
||||
urls.push(c.cfg.srt.mode === 'listener'
|
||||
? urlLine(t('Salida SRT'), `srt://${location.hostname}:${c.cfg.srt.port}`)
|
||||
: urlLine(t('Salida SRT (caller a)'), `srt://${c.cfg.srt.host}:${c.cfg.srt.port}`));
|
||||
}
|
||||
$('#view-urls').innerHTML = urls.join('');
|
||||
loadView();
|
||||
clearInterval(viewTimer);
|
||||
viewTimer = setInterval(() => {
|
||||
loadView();
|
||||
$('#view-lat').textContent = hls && hls.latency ? t('Detrás del borde: {s} s', { s: hls.latency.toFixed(1) }) : '';
|
||||
}, 5000);
|
||||
}
|
||||
function kpi(label, value, sub) {
|
||||
return `<div class="kpi-card"><div class="kpi-label">${esc(label)}</div><div class="kpi-value">${value}</div>${sub ? `<div class="muted small">${sub}</div>` : ''}</div>`;
|
||||
}
|
||||
async function loadView() {
|
||||
if (!viewing) return;
|
||||
let r;
|
||||
try { r = await api('GET', `/api/channels/${viewing.id}/view`); } catch { return; }
|
||||
const m = r.status.metrics, fl = r.failures, c = r.channel;
|
||||
const [cls, label] = STATE[r.status.state] || STATE.stopped;
|
||||
const k = [
|
||||
kpi(t('Estado'), `<span class="badge ${cls}">${t(label)}</span>`, esc((r.status.notes || []).join(' · '))),
|
||||
kpi(t('Retraso del canal'), m.delay_s != null ? `${m.delay_s.toFixed(1)} s` : '—', m.held_segments != null ? t('{n} seg. sostenidos', { n: m.held_segments }) : ''),
|
||||
kpi(t('Whisper (gpu02)'), m.asr.median_s != null ? `${m.asr.median_s} s` : '—', t('mediana de {n} pedidos · {f} fallas en 1 h', { n: m.asr.n, f: fl.asr_errors_1h })),
|
||||
];
|
||||
if (m.tr) k.push(kpi(t('Traducción (gpu02)'), m.tr.median_s != null ? `${m.tr.median_s} s` : '—', t('mediana de {n} pedidos · {f} fallas en 1 h', { n: m.tr.n, f: fl.tr_errors_1h ?? 0 }) + (m.tr.lag_median_s != null ? ` · ${t('inglés {s} s detrás', { s: m.tr.lag_median_s })}` : '')));
|
||||
if (c.cfg.srt.enabled) {
|
||||
const s = m.srt;
|
||||
if (s) {
|
||||
const part = (n, x) => (x ? `${n}: ${x.tarde} ${t('tarde')}, ${x.perdidos} ${t('perdidos')} / ${x.cues}` : '');
|
||||
k.push(kpi(t('Salida SRT'), `${s.delay_s ?? '—'} s`, [t('retraso fijo'), part('608 ' + c.cfg.asr.lang, s.es608), part('608 en', s.en608), part('708 ' + c.cfg.asr.lang, s.es708), part('708 en', s.en708)].filter(Boolean).join('<br>')));
|
||||
} else k.push(kpi(t('Salida SRT'), '—', t('sin métricas')));
|
||||
}
|
||||
$('#view-kpis').innerHTML = k.join('');
|
||||
$('#view-subs').innerHTML = Object.entries(m.recent || {}).map(([l, rows]) => `
|
||||
<div class="panel sub-panel"><div class="panel-head"><h2>${esc(t(LANG_NAME[l] || l))}</h2></div>
|
||||
${rows.length ? `<ol class="sub-list">${rows.slice().reverse().map(x => `<li>${esc(x.text)}</li>`).join('')}</ol>` : `<div class="muted">${t('sin subtítulos todavía')}</div>`}
|
||||
</div>`).join('');
|
||||
}
|
||||
$('#view-close').onclick = () => {
|
||||
$('#view-modal').classList.add('hidden');
|
||||
clearInterval(viewTimer); viewing = null;
|
||||
if (hls) { hls.destroy(); hls = null; }
|
||||
$('#view-video').removeAttribute('src');
|
||||
};
|
||||
|
||||
/* ---------------- Eventos ---------------- */
|
||||
async function loadEvents() {
|
||||
let rows;
|
||||
try { rows = await api('GET', '/api/events'); } catch { return; }
|
||||
$('#events-empty').classList.toggle('hidden', rows.length > 0);
|
||||
$('#tbl-events tbody').innerHTML = rows.map(e => `<tr>
|
||||
<td class="mono">${esc(new Date(e.ts.replace(' ', 'T') + 'Z').toLocaleString(OrbiLang.locale()))}</td>
|
||||
<td><span class="lvl ${esc(e.level)}">${esc(e.level)}</span></td>
|
||||
<td>${esc(e.channel || '—')}</td><td>${esc(e.username || '—')}</td><td>${esc(t(e.message))}</td></tr>`).join('');
|
||||
}
|
||||
|
||||
/* ---------------- Arranque ---------------- */
|
||||
window.addEventListener('orbi-lang', () => { if (me) { renderChannels(); syncForm(); } });
|
||||
fetch('/api/system/nodo').then(r => r.json()).then(n => { $('#brand-ver').textContent = `v${n.version}`; }).catch(() => {});
|
||||
api('GET', '/api/auth/me').then(r => loggedIn(r.user)).catch(() => showLogin());
|
||||
@@ -0,0 +1,168 @@
|
||||
/* i18n.js — textos en inglés del panel OrbiSubs (orbi-lang.js).
|
||||
*
|
||||
* Igual que en OrbiStream: la clave es el texto en español tal como está en
|
||||
* index.html (data-i18n) o en t('…') de app.js / url-parse.js. {x} son valores
|
||||
* que pone el código.
|
||||
*/
|
||||
OrbiLang.add({ en: {
|
||||
// ---- General ----
|
||||
'OrbiSubs — Subtítulos en vivo': 'OrbiSubs — Live subtitles',
|
||||
'Subtítulos en vivo': 'Live subtitles',
|
||||
'Sin conexión con la API — reintentando…': 'No connection to the API — retrying…',
|
||||
'Sin conexión con la API': 'No connection to the API',
|
||||
'No autenticado': 'Not authenticated',
|
||||
'Navegación principal': 'Main navigation',
|
||||
'Canales': 'Channels',
|
||||
'Eventos': 'Events',
|
||||
'⎋ Salir': '⎋ Log out',
|
||||
'Cerrar sesión': 'Log out',
|
||||
'Cerrar': 'Close',
|
||||
'Cancelar': 'Cancel',
|
||||
'Editar': 'Edit',
|
||||
'Eliminar': 'Delete',
|
||||
'Iniciar': 'Start',
|
||||
'Parar': 'Stop',
|
||||
'Ver': 'View',
|
||||
'Copiar URL': 'Copy URL',
|
||||
// ---- Login ----
|
||||
'Usuario': 'User',
|
||||
'Contraseña': 'Password',
|
||||
'Entrar': 'Sign in',
|
||||
'Clave nueva': 'New password',
|
||||
'Repetir la clave nueva': 'Repeat the new password',
|
||||
'Guardar y entrar': 'Save and sign in',
|
||||
'La cuenta <b>{u}</b> tiene la clave inicial. Elige una nueva para seguir (mínimo {n} caracteres).': 'The account <b>{u}</b> still has the initial password. Choose a new one to continue (at least {n} characters).',
|
||||
'Usuario o contraseña incorrectos': 'Wrong user or password',
|
||||
'Demasiados intentos. Prueba de nuevo en unos minutos.': 'Too many attempts. Try again in a few minutes.',
|
||||
'El pase venció: vuelve a entrar con la clave inicial': 'The pass expired: sign in again with the initial password',
|
||||
'Las dos claves no coinciden': 'The two passwords do not match',
|
||||
'La contraseña tiene que tener al menos 8 caracteres': 'The password must have at least 8 characters',
|
||||
'La clave nueva no puede ser la inicial ni el nombre de usuario': 'The new password cannot be the initial one or the user name',
|
||||
// ---- Lista ----
|
||||
'Subtítulos automáticos en vivo · actualización 5 s': 'Automatic live subtitles · refresh 5 s',
|
||||
'+ Nuevo canal': '+ New channel',
|
||||
'Estado': 'Status',
|
||||
'Nombre': 'Name',
|
||||
'Entrada': 'Input',
|
||||
'Idiomas': 'Languages',
|
||||
'Salidas': 'Outputs',
|
||||
'Retraso': 'Delay',
|
||||
'Último subtítulo': 'Last subtitle',
|
||||
'Acciones': 'Actions',
|
||||
'corriendo': 'running',
|
||||
'parado': 'stopped',
|
||||
'error': 'error',
|
||||
'arrancando': 'starting',
|
||||
'deshabilitado': 'disabled',
|
||||
'{n} seg. sostenidos': '{n} seg. held',
|
||||
'No hay canales configurados. Crea el primero con «+ Nuevo canal».': 'No channels configured. Create the first one with «+ New channel».',
|
||||
'Como máximo <b>2 canales andando a la vez</b>: el reconocimiento y la traducción corren en gpu02, que es compartido.': 'At most <b>2 channels running at the same time</b>: recognition and translation run on gpu02, which is shared.',
|
||||
'Iniciar y parar: disponible al cerrar la 078': 'Start and stop: available once task 078 is closed',
|
||||
'¿Borrar el canal «{n}»?': 'Delete channel «{n}»?',
|
||||
'El canal está andando: detenlo antes de borrarlo': 'The channel is running: stop it before deleting it',
|
||||
// ---- Modal ----
|
||||
'Nuevo canal': 'New channel',
|
||||
'Editar canal: {n}': 'Edit channel: {n}',
|
||||
'Nombre visible del canal en el panel.': 'Channel name shown in the panel.',
|
||||
'Id corto': 'Short id',
|
||||
'Minúsculas, números y guiones. Se usa en las rutas (/hls/<id>/) y en los servicios.': 'Lowercase, digits and dashes. Used in the paths (/hls/<id>/) and in the services.',
|
||||
'Canal habilitado': 'Channel enabled',
|
||||
'Pegado rápido': 'Quick paste',
|
||||
'srt://origen:10013?latency=200&streamid=… — se reparte solo en los campos de abajo': 'srt://source:10013?latency=200&streamid=… — it is split into the fields below',
|
||||
'Rellenar': 'Fill in',
|
||||
'Campos rellenados.': 'Fields filled in.',
|
||||
'RTMP no está soportado como entrada (SRT, UDP o HLS).': 'RTMP is not supported as input (SRT, UDP or HLS).',
|
||||
'Tipo': 'Type',
|
||||
'Modo': 'Mode',
|
||||
'Caller (marca al origen)': 'Caller (calls the source)',
|
||||
'Listener (espera al origen)': 'Listener (waits for the source)',
|
||||
'Puerto': 'Port',
|
||||
'(opcional)': '(optional)',
|
||||
'Lista .m3u8 de la fuente (http o https).': 'Source .m3u8 playlist (http or https).',
|
||||
'Programa': 'Program',
|
||||
'(el primero)': '(the first one)',
|
||||
'Solo si la fuente trae más de un servicio (MPTS).': 'Only if the source carries more than one service (MPTS).',
|
||||
'PID de audio': 'Audio PID',
|
||||
'Solo si hay más de un audio (por ejemplo, SAP).': 'Only if there is more than one audio (for example, SAP).',
|
||||
'Reconocimiento': 'Recognition',
|
||||
'Idioma del audio': 'Audio language',
|
||||
'Español': 'Spanish',
|
||||
'Inglés': 'English',
|
||||
'Portugués': 'Portuguese',
|
||||
'URL del motor (whisper.cpp)': 'Engine URL (whisper.cpp)',
|
||||
'gpu02 :8004 por defecto. Solo se usa POST /inference, de a un pedido.': 'gpu02 :8004 by default. Only POST /inference is used, one request at a time.',
|
||||
'Prompt fijo (opcional)': 'Fixed prompt (optional)',
|
||||
'Noticias de Chile. Nombres: Coyhaique, Boric…': 'Chilean news. Names: Coyhaique, Boric…',
|
||||
'Ayuda con nombres propios y siglas. Vacío = el prompt con puntuación de siempre.': 'Helps with proper names and acronyms. Empty = the usual punctuated prompt.',
|
||||
'Traducción': 'Translation',
|
||||
'Inglés (English)': 'English',
|
||||
'URL del LLM': 'LLM URL',
|
||||
'gpu02 :8001 por defecto (Qwen).': 'gpu02 :8001 by default (Qwen).',
|
||||
'Salida HLS': 'HLS output',
|
||||
'Habilitada': 'Enabled',
|
||||
'Largo de segmento (s)': 'Segment length (s)',
|
||||
'Segmentos en la lista': 'Segments in the playlist',
|
||||
'Master HLS': 'HLS master',
|
||||
'Player': 'Player',
|
||||
'Salida SRT': 'SRT output',
|
||||
'Salida SRT (caller a)': 'SRT output (caller to)',
|
||||
'Listener (los clientes marcan acá)': 'Listener (clients call here)',
|
||||
'Caller (marca a un destino)': 'Caller (calls a destination)',
|
||||
'Destino (host)': 'Destination (host)',
|
||||
'En listener toma también el siguiente (prueba interna).': 'As listener it also takes the next one (internal test).',
|
||||
'Retraso fijo del video (s)': 'Fixed video delay (s)',
|
||||
'Lo justo para que el subtítulo (y el inglés, que llega después) caiga a tiempo.': 'Just enough for the subtitle (and the English one, which comes later) to land on time.',
|
||||
'608 (idioma del audio / inglés)': '608 (audio language / English)',
|
||||
'708 servicio (idioma del audio / inglés)': '708 service (audio language / English)',
|
||||
'(no va)': '(none)',
|
||||
'Guardar canal': 'Save channel',
|
||||
'Falta el nombre': 'The name is missing',
|
||||
'Falta el host de la entrada SRT': 'The SRT input host is missing',
|
||||
'Falta el puerto de la entrada': 'The input port is missing',
|
||||
'Id corto: minúsculas, números y guiones, hasta 31, empezando con letra o número': 'Short id: lowercase, digits and dashes, up to 31, starting with a letter or digit',
|
||||
'Ya hay un canal con el id corto "{s}"': 'There is already a channel with the short id "{s}"',
|
||||
'El puerto {p} ya lo usa el canal "{n}"': 'Port {p} is already used by channel "{n}"',
|
||||
'Entrada HLS: la URL tiene que apuntar a una lista .m3u8': 'HLS input: the URL must point to an .m3u8 playlist',
|
||||
'Entrada UDP: tiene que ser udp://ip:puerto (o udp://@239.x.x.x:puerto)': 'UDP input: it must be udp://ip:port (or udp://@239.x.x.x:port)',
|
||||
'El canal necesita al menos una salida (HLS o SRT)': 'The channel needs at least one output (HLS or SRT)',
|
||||
'Detén el canal antes de cambiarle el id corto': 'Stop the channel before changing its short id',
|
||||
// ---- Ver canal ----
|
||||
'Subtítulos': 'Subtitles',
|
||||
'Apagados': 'Off',
|
||||
'Detrás del borde: {s} s': 'Behind the live edge: {s} s',
|
||||
'Retraso del canal': 'Channel delay',
|
||||
'Whisper (gpu02)': 'Whisper (gpu02)',
|
||||
'Traducción (gpu02)': 'Translation (gpu02)',
|
||||
'mediana de {n} pedidos · {f} fallas en 1 h': 'median of {n} requests · {f} failures in 1 h',
|
||||
'inglés {s} s detrás': 'English {s} s behind',
|
||||
'retraso fijo': 'fixed delay',
|
||||
'tarde': 'late',
|
||||
'perdidos': 'lost',
|
||||
'sin métricas': 'no metrics',
|
||||
'sin subtítulos todavía': 'no subtitles yet',
|
||||
'Spanish': 'Spanish',
|
||||
// ---- Eventos ----
|
||||
'Últimos 200 eventos del panel': 'Last 200 panel events',
|
||||
'Fecha': 'Date',
|
||||
'Nivel': 'Level',
|
||||
'Canal': 'Channel',
|
||||
'Mensaje': 'Message',
|
||||
'Sin eventos registrados.': 'No events recorded.',
|
||||
'Login fallido': 'Failed login',
|
||||
'Ingreso al panel': 'Signed in',
|
||||
'Clave inicial cambiada': 'Initial password changed',
|
||||
'Clave cambiada': 'Password changed',
|
||||
// ---- url-parse.js (copia de OrbiStream) ----
|
||||
'Pega una URL.': 'Paste a URL.',
|
||||
'Se extrajo la URL del texto pegado.': 'The URL was extracted from the pasted text.',
|
||||
'No parece una URL: falta el esquema (srt://, udp://, rtmp://, http://).': 'This does not look like a URL: the scheme is missing (srt://, udp://, rtmp://, http://).',
|
||||
'La URL no termina en .m3u8; verifica que sea realmente HLS.': 'The URL does not end in .m3u8; check that it really is HLS.',
|
||||
'Falta el puerto en "srt://{x}".': 'The port is missing in "srt://{x}".',
|
||||
'mode=rendezvous no está soportado; se dejó como SRT Caller.': 'mode=rendezvous is not supported; it was set to SRT Caller.',
|
||||
'Sin mode= en la URL: se dedujo {k} por el host.': 'No mode= in the URL: {k} was inferred from the host.',
|
||||
'Latencia ilegible ("{v}"): se ignoró.': 'Unreadable latency ("{v}"): ignored.',
|
||||
'La latencia venía en microsegundos ({n}); se convirtió a {ms} ms.': 'The latency was in microseconds ({n}); it was converted to {ms} ms.',
|
||||
'La passphrase tenía un %-escape inválido; se copió tal cual.': 'The passphrase had an invalid %-escape; it was copied as is.',
|
||||
'La passphrase tiene {n} caracteres; SRT exige entre 10 y 79.': 'The passphrase has {n} characters; SRT requires between 10 and 79.',
|
||||
'Se dejaron en la URL: {list}.': 'Left in the URL: {list}.',
|
||||
} });
|
||||
@@ -0,0 +1,297 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title data-i18n>OrbiSubs — Subtítulos en vivo</title>
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
<link rel="stylesheet" href="node-foot.css">
|
||||
<link rel="stylesheet" href="subs.css">
|
||||
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'><circle cx='16' cy='16' r='13' fill='none' stroke='%23e8a838' stroke-width='3'/><circle cx='16' cy='16' r='5' fill='%23e8a838'/></svg>">
|
||||
</head>
|
||||
<body>
|
||||
<div id="api-banner" class="api-banner hidden" role="alert">
|
||||
<span class="dot-pulse"></span>
|
||||
<span data-i18n>Sin conexión con la API — reintentando…</span>
|
||||
</div>
|
||||
|
||||
<!-- ================= LOGIN ================= -->
|
||||
<!-- Como toda caja Orbi: admin/admin y cambio de clave obligatorio en el primer ingreso. -->
|
||||
<div id="login-overlay" class="login-overlay hidden">
|
||||
<div class="login-card">
|
||||
<div class="login-brand">
|
||||
<svg viewBox="0 0 32 32" width="42" height="42" aria-hidden="true">
|
||||
<circle cx="16" cy="16" r="13" fill="none" stroke="#e8a838" stroke-width="3"/>
|
||||
<circle cx="16" cy="16" r="5" fill="#e8a838"/>
|
||||
</svg>
|
||||
<div>
|
||||
<div class="brand-name">Orbi<span>Subs</span></div>
|
||||
<div class="brand-sub" data-i18n>Subtítulos en vivo</div>
|
||||
</div>
|
||||
</div>
|
||||
<form id="login-form" autocomplete="on">
|
||||
<label><span data-i18n>Usuario</span> <input name="username" autocomplete="username" required autofocus></label>
|
||||
<label><span data-i18n>Contraseña</span> <input name="password" type="password" autocomplete="current-password" required></label>
|
||||
<button type="submit" class="btn btn-amber login-btn" data-i18n>Entrar</button>
|
||||
</form>
|
||||
<form id="first-form" class="hidden" autocomplete="off">
|
||||
<p class="hint" id="first-hint"></p>
|
||||
<label><span data-i18n>Clave nueva</span> <input name="password" type="password" autocomplete="new-password" required minlength="8"></label>
|
||||
<label><span data-i18n>Repetir la clave nueva</span> <input name="password2" type="password" autocomplete="new-password" required minlength="8"></label>
|
||||
<button type="submit" class="btn btn-amber login-btn" data-i18n>Guardar y entrar</button>
|
||||
</form>
|
||||
<div id="login-msg" class="form-error hidden"></div>
|
||||
<div class="login-lang" id="login-lang"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="layout">
|
||||
<aside class="sidebar">
|
||||
<div class="brand">
|
||||
<svg viewBox="0 0 32 32" width="28" height="28" aria-hidden="true">
|
||||
<circle cx="16" cy="16" r="13" fill="none" stroke="#e8a838" stroke-width="3"/>
|
||||
<circle cx="16" cy="16" r="5" fill="#e8a838"/>
|
||||
</svg>
|
||||
<div>
|
||||
<div class="brand-name">Orbi<span>Subs</span></div>
|
||||
<div class="brand-sub" data-i18n>Subtítulos en vivo</div>
|
||||
<div class="brand-ver" id="brand-ver"></div>
|
||||
</div>
|
||||
</div>
|
||||
<nav class="nav" aria-label="Navegación principal" data-i18n="aria-label">
|
||||
<a href="#channels" data-route="channels"><span class="nav-ico">▶</span> <span data-i18n>Canales</span></a>
|
||||
<a href="#events" data-route="events"><span class="nav-ico">≡</span> <span data-i18n>Eventos</span></a>
|
||||
</nav>
|
||||
<div class="sidebar-foot" id="orbi-foot" data-api="/api/system/nodo" data-me="off" data-logo="logo-orbitv.png">
|
||||
<div id="user-box" class="user-box hidden">
|
||||
<span class="user-ico" aria-hidden="true">●</span>
|
||||
<span id="user-name" class="user-name">—</span>
|
||||
<span id="user-role" class="chip user-role">—</span>
|
||||
<button class="btn-ico user-logout" id="btn-logout" title="Cerrar sesión" data-i18n="text title">⎋ Salir</button>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<main class="main">
|
||||
<div id="control-banner" class="info-banner hidden"></div>
|
||||
<!-- ================= CANALES ================= -->
|
||||
<section id="view-channels" class="view">
|
||||
<header class="view-head">
|
||||
<h1 data-i18n>Canales</h1>
|
||||
<span class="view-sub" data-i18n>Subtítulos automáticos en vivo · actualización 5 s</span>
|
||||
<button class="btn btn-amber" id="btn-new-channel" data-i18n>+ Nuevo canal</button>
|
||||
</header>
|
||||
<div class="panel">
|
||||
<div class="table-wrap">
|
||||
<table class="tbl" id="tbl-channels">
|
||||
<thead><tr>
|
||||
<th data-i18n>Estado</th><th data-i18n>Nombre</th><th data-i18n>Entrada</th><th data-i18n>Idiomas</th>
|
||||
<th data-i18n>Salidas</th><th data-i18n>Retraso</th><th data-i18n>Último subtítulo</th><th class="ta-r" data-i18n>Acciones</th>
|
||||
</tr></thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div id="channels-empty" class="empty hidden" data-i18n>No hay canales configurados. Crea el primero con «+ Nuevo canal».</div>
|
||||
</div>
|
||||
<p class="hint" data-i18n="html">Como máximo <b>2 canales andando a la vez</b>: el reconocimiento y la traducción corren en gpu02, que es compartido.</p>
|
||||
</section>
|
||||
<!-- ================= EVENTOS ================= -->
|
||||
<section id="view-events" class="view hidden">
|
||||
<header class="view-head">
|
||||
<h1 data-i18n>Eventos</h1>
|
||||
<span class="view-sub" data-i18n>Últimos 200 eventos del panel</span>
|
||||
</header>
|
||||
<div class="panel">
|
||||
<div class="table-wrap">
|
||||
<table class="tbl" id="tbl-events">
|
||||
<thead><tr><th data-i18n>Fecha</th><th data-i18n>Nivel</th><th data-i18n>Canal</th><th data-i18n>Usuario</th><th data-i18n>Mensaje</th></tr></thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div id="events-empty" class="empty hidden" data-i18n>Sin eventos registrados.</div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<!-- ================= MODAL ALTA / EDICIÓN DE CANAL ================= -->
|
||||
<div id="modal" class="modal-backdrop hidden">
|
||||
<div class="modal" role="dialog" aria-modal="true" aria-labelledby="modal-title">
|
||||
<div class="modal-head">
|
||||
<h2 id="modal-title">Nuevo canal</h2>
|
||||
<button class="btn-close" id="modal-close" aria-label="Cerrar" data-i18n="aria-label">✕</button>
|
||||
</div>
|
||||
<form id="channel-form" class="modal-body" novalidate>
|
||||
<fieldset>
|
||||
<legend>General</legend>
|
||||
<div class="grid-3">
|
||||
<label><span data-i18n>Nombre</span> <input name="name" required maxlength="80" placeholder="Canal 13">
|
||||
<span class="field-hint" data-i18n>Nombre visible del canal en el panel.</span>
|
||||
</label>
|
||||
<label><span data-i18n>Id corto</span> <input name="slug" required maxlength="31" placeholder="c13" pattern="[a-z0-9][a-z0-9-]*">
|
||||
<span class="field-hint" data-i18n>Minúsculas, números y guiones. Se usa en las rutas (/hls/<id>/) y en los servicios.</span>
|
||||
</label>
|
||||
<label class="chk-wrap"><input type="checkbox" name="enabled" checked> <span data-i18n>Canal habilitado</span></label>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset>
|
||||
<legend data-i18n>Entrada</legend>
|
||||
<label class="paste-url"><span data-i18n>Pegado rápido</span>
|
||||
<span class="paste-row">
|
||||
<input id="in-paste" type="text" autocomplete="off" spellcheck="false"
|
||||
placeholder="srt://origen:10013?latency=200&streamid=… — se reparte solo en los campos de abajo" data-i18n="placeholder">
|
||||
<button type="button" class="btn btn-sm" id="btn-paste-fill" data-i18n>Rellenar</button>
|
||||
</span>
|
||||
</label>
|
||||
<div id="paste-msg" class="paste-msg hidden"></div>
|
||||
<div class="grid-3">
|
||||
<label><span data-i18n>Tipo</span>
|
||||
<select name="in_kind">
|
||||
<option value="srt">SRT</option>
|
||||
<option value="udp">UDP / multicast</option>
|
||||
<option value="hls">HLS (http)</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="in-srt"><span data-i18n>Modo</span>
|
||||
<select name="in_mode">
|
||||
<option value="caller" data-i18n>Caller (marca al origen)</option>
|
||||
<option value="listener" data-i18n>Listener (espera al origen)</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="in-srt in-srt-caller">Host <input name="in_host" placeholder="192.168.10.40"></label>
|
||||
</div>
|
||||
<div class="grid-3 in-srt">
|
||||
<label><span data-i18n>Puerto</span> <input name="in_port" type="number" min="1" max="65535" placeholder="10013"></label>
|
||||
<label>Latency (ms) <input name="in_latency" type="number" min="20" max="8000" step="10" value="200"></label>
|
||||
<label>Passphrase <input name="in_passphrase" autocomplete="off" placeholder="(opcional)" data-i18n="placeholder"></label>
|
||||
</div>
|
||||
<label class="in-srt">streamid <input name="in_streamid" autocomplete="off" placeholder="(opcional)" data-i18n="placeholder"></label>
|
||||
<label class="in-url">URL <input name="in_url" placeholder="udp://@239.1.1.1:5000">
|
||||
<span class="field-hint in-hls-hint" data-i18n>Lista .m3u8 de la fuente (http o https).</span>
|
||||
</label>
|
||||
<div class="grid-2">
|
||||
<label><span data-i18n>Programa</span> <input name="in_program" type="number" min="1" placeholder="(el primero)" data-i18n="placeholder">
|
||||
<span class="field-hint" data-i18n>Solo si la fuente trae más de un servicio (MPTS).</span>
|
||||
</label>
|
||||
<label><span data-i18n>PID de audio</span> <input name="in_audio_pid" type="number" min="16" max="8190" placeholder="(el primero)" data-i18n="placeholder">
|
||||
<span class="field-hint" data-i18n>Solo si hay más de un audio (por ejemplo, SAP).</span>
|
||||
</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset>
|
||||
<legend data-i18n>Reconocimiento</legend>
|
||||
<div class="grid-2">
|
||||
<label><span data-i18n>Idioma del audio</span>
|
||||
<select name="asr_lang">
|
||||
<option value="es" data-i18n>Español</option>
|
||||
<option value="en" data-i18n>Inglés</option>
|
||||
<option value="pt" data-i18n>Portugués</option>
|
||||
</select>
|
||||
</label>
|
||||
<label><span data-i18n>URL del motor (whisper.cpp)</span> <input name="asr_url" value="http://192.168.2.10:8004">
|
||||
<span class="field-hint" data-i18n>gpu02 :8004 por defecto. Solo se usa POST /inference, de a un pedido.</span>
|
||||
</label>
|
||||
</div>
|
||||
<label><span data-i18n>Prompt fijo (opcional)</span> <input name="asr_prompt" maxlength="500" placeholder="Noticias de Chile. Nombres: Coyhaique, Boric…" data-i18n="placeholder">
|
||||
<span class="field-hint" data-i18n>Ayuda con nombres propios y siglas. Vacío = el prompt con puntuación de siempre.</span>
|
||||
</label>
|
||||
</fieldset>
|
||||
|
||||
<fieldset>
|
||||
<legend data-i18n>Traducción</legend>
|
||||
<div class="grid-2">
|
||||
<label class="chk-wrap"><input type="checkbox" name="tr_en"> <span data-i18n>Inglés (English)</span></label>
|
||||
<label><span data-i18n>URL del LLM</span> <input name="tr_url" value="http://192.168.2.10:8001">
|
||||
<span class="field-hint" data-i18n>gpu02 :8001 por defecto (Qwen).</span>
|
||||
</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset>
|
||||
<legend data-i18n>Salida HLS</legend>
|
||||
<div class="grid-3">
|
||||
<label class="chk-wrap"><input type="checkbox" name="hls_enabled" checked> <span data-i18n>Habilitada</span></label>
|
||||
<label><span data-i18n>Largo de segmento (s)</span> <input name="hls_seg" type="number" min="2" max="10" value="6"></label>
|
||||
<label><span data-i18n>Segmentos en la lista</span> <input name="hls_list" type="number" min="3" max="30" value="10"></label>
|
||||
</div>
|
||||
<div class="url-box" id="hls-urls"></div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset>
|
||||
<legend data-i18n>Salida SRT</legend>
|
||||
<div class="grid-3">
|
||||
<label class="chk-wrap"><input type="checkbox" name="srt_enabled"> <span data-i18n>Habilitada</span></label>
|
||||
<label class="srt-on"><span data-i18n>Modo</span>
|
||||
<select name="srt_mode">
|
||||
<option value="listener" data-i18n>Listener (los clientes marcan acá)</option>
|
||||
<option value="caller" data-i18n>Caller (marca a un destino)</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="srt-on srt-caller"><span data-i18n>Destino (host)</span> <input name="srt_host" placeholder="10.100.101.211"></label>
|
||||
</div>
|
||||
<div class="grid-3 srt-on">
|
||||
<label><span data-i18n>Puerto</span> <input name="srt_port" type="number" min="1024" max="65534" placeholder="9002">
|
||||
<span class="field-hint" data-i18n>En listener toma también el siguiente (prueba interna).</span>
|
||||
</label>
|
||||
<label>Latency (ms) <input name="srt_latency" type="number" min="20" max="8000" step="10" value="200"></label>
|
||||
<label>Passphrase <input name="srt_passphrase" autocomplete="off" placeholder="(opcional)" data-i18n="placeholder"></label>
|
||||
</div>
|
||||
<div class="grid-3 srt-on">
|
||||
<label><span data-i18n>Retraso fijo del video (s)</span> <input name="srt_delay" type="number" min="5" max="60" step="0.5" value="24">
|
||||
<span class="field-hint" data-i18n>Lo justo para que el subtítulo (y el inglés, que llega después) caiga a tiempo.</span>
|
||||
</label>
|
||||
<label><span data-i18n>608 (idioma del audio / inglés)</span>
|
||||
<span class="pair"><select name="cc608_main"></select><select name="cc608_en"></select></span>
|
||||
</label>
|
||||
<label><span data-i18n>708 servicio (idioma del audio / inglés)</span>
|
||||
<span class="pair"><select name="cc708_main"></select><select name="cc708_en"></select></span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="url-box srt-on" id="srt-url"></div>
|
||||
</fieldset>
|
||||
|
||||
<div id="form-error" class="form-error hidden"></div>
|
||||
<div class="modal-foot">
|
||||
<button type="button" class="btn" id="btn-cancel" data-i18n>Cancelar</button>
|
||||
<button type="submit" class="btn btn-amber" id="btn-save" data-i18n>Guardar canal</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ================= MODAL VER CANAL ================= -->
|
||||
<div id="view-modal" class="modal-backdrop hidden">
|
||||
<div class="modal modal-wide" role="dialog" aria-modal="true" aria-labelledby="view-title">
|
||||
<div class="modal-head">
|
||||
<h2 id="view-title">Canal</h2>
|
||||
<button class="btn-close" id="view-close" aria-label="Cerrar" data-i18n="aria-label">✕</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="view-grid">
|
||||
<div>
|
||||
<video id="view-video" controls muted autoplay playsinline></video>
|
||||
<div class="player-bar">
|
||||
<label class="inline"><span data-i18n>Subtítulos</span> <select id="view-track"><option value="-1" data-i18n>Apagados</option></select></label>
|
||||
<span class="mono" id="view-lat"></span>
|
||||
</div>
|
||||
<div class="url-box" id="view-urls"></div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="kpi-row kpi-sm" id="view-kpis"></div>
|
||||
<div id="view-subs"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/hls.js@1.5.20/dist/hls.min.js"></script>
|
||||
<script src="orbi-lang.js"></script>
|
||||
<script src="i18n.js"></script>
|
||||
<script src="url-parse.js"></script>
|
||||
<script src="app.js"></script>
|
||||
<script src="node-foot.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 28 KiB |
@@ -0,0 +1,26 @@
|
||||
/* node-foot.css — estilos del pie común (ver node-foot.js). Copia de referencia
|
||||
en orbiadmin/src/common/; usa las variables de styles.css de cada panel. */
|
||||
.ofoot .hidden{display:none}
|
||||
.ofoot .user-box{display:flex;align-items:center;gap:6px;margin-bottom:8px;flex-wrap:wrap}
|
||||
.ofoot .user-ico{color:var(--amber);font-size:10px}
|
||||
.ofoot .user-name{font-weight:600;color:var(--text);max-width:90px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.ofoot .user-role{text-transform:capitalize}
|
||||
.ofoot .user-logout{margin-left:auto;font-size:11px;padding:2px 6px;text-decoration:none;color:var(--text-dim)}
|
||||
.ofoot .user-logout:hover{color:var(--red)}
|
||||
.ofoot .conn-status{display:flex;align-items:center;gap:7px;margin-bottom:4px}
|
||||
.ofoot-clock{color:var(--text);font-variant-numeric:tabular-nums;margin-bottom:4px}
|
||||
.ofoot-prod{color:var(--text);font-weight:600}
|
||||
.ofoot-node{margin-bottom:6px}
|
||||
.ofoot-ips{display:grid;grid-template-columns:auto 1fr;gap:2px 10px;margin:0 0 8px}
|
||||
.ofoot-ips dt{color:var(--text-dim)}
|
||||
.ofoot-ips dd{margin:0;text-align:right;font-family:var(--mono,ui-monospace,monospace);font-size:11.5px}
|
||||
/* Logo del pie: acá y no solo en styles.css, porque no todos los paneles lo traían
|
||||
(OrbiCache lo mostraba a tamaño natural, 2026-10-17). */
|
||||
#orbi-foot .host-logo{height:18px;width:auto;max-width:120px;display:block;margin:8px 0 2px;opacity:.9}
|
||||
/* Selector de idioma ES | EN (orbi-lang.js) */
|
||||
.ofoot-lang{margin:2px 0 8px}
|
||||
.orbi-lang{display:inline-flex;border:1px solid var(--border);border-radius:6px;overflow:hidden}
|
||||
.orbi-lang-opt{padding:3px 10px;font:600 11px system-ui,sans-serif;color:var(--text-dim);background:transparent;border:none;cursor:pointer}
|
||||
.orbi-lang-opt+.orbi-lang-opt{border-left:1px solid var(--border)}
|
||||
.orbi-lang-opt:hover{color:var(--text)}
|
||||
.orbi-lang-opt.on{background:var(--amber-dim,rgba(232,168,56,.15));color:var(--amber)}
|
||||
@@ -0,0 +1,129 @@
|
||||
/* node-foot.js — pie del sidebar común a todos los paneles OrbiTV.
|
||||
*
|
||||
* Copia de referencia: orbiadmin/src/common/. Cada panel la copia tal cual
|
||||
* (como styles.css). Pedido de Jorge (2026-10-17): el mismo pie en todos los
|
||||
* nodos, con usuario y rol, API, hora del nodo, producto, CT e IPs por función.
|
||||
*
|
||||
* Uso:
|
||||
* <div class="sidebar-foot" id="orbi-foot"
|
||||
* data-api="/api/nodo" ← JSON del nodo (ver orbitv_node.py)
|
||||
* data-me="/_orbiauth/me" ← {user, role} | {username, role}; "off" = lo maneja el panel
|
||||
* data-logout="/_orbiauth/logout?rd=/"
|
||||
* data-logo="logo-orbitv.png"></div>
|
||||
* <script src="node-foot.js"></script>
|
||||
* Lo que ya haya dentro del div (extras del panel, p.ej. el badge de ACL del
|
||||
* edge) queda debajo del pie común.
|
||||
*
|
||||
* Idioma: si el panel carga orbi-lang.js antes, el pie dibuja el selector ES | EN
|
||||
* y traduce lo suyo (OrbiLang.t); sin orbi-lang.js queda en español.
|
||||
*/
|
||||
(function () {
|
||||
const root = document.getElementById('orbi-foot');
|
||||
if (!root) return;
|
||||
const cfg = root.dataset;
|
||||
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||
const L = window.OrbiLang;
|
||||
const t = L ? L.t : (s => s);
|
||||
const locale = () => (L ? L.locale() : 'es-CL');
|
||||
if (L) L.add({ en: {
|
||||
'API conectada': 'API connected', 'API sin respuesta': 'API not responding',
|
||||
'Cerrar sesión': 'Sign out', 'Salir': 'Sign out', 'Idioma': 'Language',
|
||||
// Funciones de las redes (RED_* en /etc/orbitv/nodo.conf)
|
||||
'adquisición': 'acquisition', 'gestión': 'management', 'video': 'video',
|
||||
'clientes': 'customers', 'modulador': 'modulator',
|
||||
} });
|
||||
|
||||
const box = document.createElement('div');
|
||||
box.className = 'ofoot';
|
||||
box.innerHTML = `
|
||||
<div class="user-box hidden" id="ofoot-user"></div>
|
||||
<div id="conn-status" class="conn-status"><span class="status-dot"></span> API …</div>
|
||||
<div class="ofoot-clock" id="ofoot-clock">--:--:--</div>
|
||||
<div class="ofoot-prod" id="ofoot-prod"></div>
|
||||
<div class="ofoot-node" id="ofoot-node"></div>
|
||||
<dl class="ofoot-ips" id="ofoot-ips"></dl>
|
||||
<div class="ofoot-lang" id="ofoot-lang" title="Idioma"></div>`;
|
||||
// Si el panel maneja su propio usuario (data-me="off", p.ej. OrbiStream con su
|
||||
// login local + SSO) su .user-box queda primero y el pie común va debajo.
|
||||
const own = cfg.me === 'off' && root.querySelector(':scope > .user-box');
|
||||
if (own) own.after(box); else root.prepend(box);
|
||||
const langEl = document.getElementById('ofoot-lang');
|
||||
if (L) { L.mount(langEl); langEl.title = t('Idioma'); } else langEl.remove();
|
||||
if (cfg.logo && !root.querySelector('.host-logo')) {
|
||||
const img = document.createElement('img');
|
||||
img.className = 'host-logo'; img.src = cfg.logo; img.alt = 'OrbiTV';
|
||||
root.append(img);
|
||||
}
|
||||
|
||||
// Hora del nodo: se toma la del servidor (no la del navegador) y se avanza
|
||||
// localmente, en la zona horaria del nodo. Si un nodo tiene la hora corrida, se ve.
|
||||
let offset = 0, tz = null, tzLabel = '';
|
||||
function tick() {
|
||||
const d = new Date(Date.now() + offset);
|
||||
let t;
|
||||
try { t = d.toLocaleTimeString(locale(), { hour12: false, timeZone: tz || undefined }); }
|
||||
catch { t = d.toLocaleTimeString(locale(), { hour12: false }); }
|
||||
document.getElementById('ofoot-clock').textContent = tzLabel ? `${t} · ${tzLabel}` : t;
|
||||
}
|
||||
|
||||
let conn = null, lastNode = null, lastMe = null;
|
||||
function setConn(ok) {
|
||||
conn = ok;
|
||||
const el = document.getElementById('conn-status');
|
||||
el.innerHTML = `<span class="status-dot ${ok ? 'ok' : 'err'}"></span> ${t(ok ? 'API conectada' : 'API sin respuesta')}`;
|
||||
}
|
||||
function showIps() {
|
||||
document.getElementById('ofoot-ips').innerHTML = ((lastNode && lastNode.ips) || [])
|
||||
.map(i => `<dt>${esc(t(i.role))}</dt><dd class="mono">${esc(i.ip)}</dd>`).join('');
|
||||
}
|
||||
|
||||
async function loadNode() {
|
||||
try {
|
||||
const r = await fetch(cfg.api || '/api/nodo', { cache: 'no-store' });
|
||||
if (!r.ok) throw new Error(r.status);
|
||||
const n = await r.json();
|
||||
setConn(true);
|
||||
if (n.now) offset = n.now - Date.now();
|
||||
tz = n.tz || null;
|
||||
tzLabel = tz ? tz.split('/').pop().replace(/_/g, ' ') : '';
|
||||
document.getElementById('ofoot-prod').textContent = [n.product, n.version].filter(Boolean).join(' ');
|
||||
document.getElementById('ofoot-node').textContent =
|
||||
[n.ct_id ? `CT ${n.ct_id}` : null, n.pve, n.hostname].filter(Boolean).join(' · ');
|
||||
lastNode = n; showIps();
|
||||
tick();
|
||||
} catch { setConn(false); }
|
||||
}
|
||||
|
||||
async function loadMe() {
|
||||
if (cfg.me === 'off') return;
|
||||
try {
|
||||
const r = await fetch(cfg.me || '/_orbiauth/me', { cache: 'no-store', credentials: 'same-origin' });
|
||||
if (!r.ok) return;
|
||||
const me = await r.json();
|
||||
const user = me.user || me.username;
|
||||
if (!user) return;
|
||||
lastMe = me; showMe();
|
||||
} catch { /* sin login común: no se muestra el usuario */ }
|
||||
}
|
||||
function showMe() {
|
||||
const me = lastMe; if (!me) return;
|
||||
const user = me.user || me.username;
|
||||
const el = document.getElementById('ofoot-user');
|
||||
el.innerHTML = `<span class="user-ico" aria-hidden="true">●</span>
|
||||
<span class="user-name" title="${esc(user)}">${esc(user)}</span>
|
||||
<span class="chip user-role">${esc(me.role || '')}</span>
|
||||
<a class="btn-ico user-logout" href="${esc(cfg.logout || '/_orbiauth/logout?rd=/')}" title="${esc(t('Cerrar sesión'))}">⎋ ${esc(t('Salir'))}</a>`;
|
||||
el.classList.remove('hidden');
|
||||
}
|
||||
|
||||
// Cambio de idioma: se redibuja lo que ya se cargó, sin volver a pedirlo
|
||||
window.addEventListener('orbi-lang', () => {
|
||||
if (conn !== null) setConn(conn);
|
||||
showIps(); showMe(); tick();
|
||||
langEl.title = t('Idioma');
|
||||
});
|
||||
|
||||
loadMe(); loadNode();
|
||||
setInterval(tick, 1000);
|
||||
setInterval(loadNode, 30000);
|
||||
})();
|
||||
@@ -0,0 +1,158 @@
|
||||
/* orbi-lang.js — idioma común de OrbiTV (es / en): selector y traducción.
|
||||
*
|
||||
* Copia de referencia: orbimanual/assets/. Cada panel la copia tal cual (como
|
||||
* node-foot.js). El español es el idioma del código: el texto en español ES la
|
||||
* clave, y el diccionario de cada panel solo trae el inglés.
|
||||
*
|
||||
* OrbiLang.lang idioma actual
|
||||
* OrbiLang.get(['es','en']) idioma elegido: ?lang= > guardado > navegador > el primero
|
||||
* OrbiLang.set('en') lo cambia, lo guarda (localStorage 'orbi.lang'), traduce
|
||||
* la página y avisa con el evento 'orbi-lang' en window
|
||||
* OrbiLang.add({en: {'Guardar': 'Save', 'Hace {n} s': '{n} s ago'}})
|
||||
* OrbiLang.t('Hace {n} s', {n: 5}) texto en el idioma actual ({x} se reemplaza)
|
||||
* OrbiLang.apply(root) traduce lo marcado con data-i18n dentro de root:
|
||||
* data-i18n el texto (textContent)
|
||||
* data-i18n="html" el innerHTML (texto con <b>, <kbd>…)
|
||||
* data-i18n="title placeholder" esos atributos
|
||||
* data-i18n="text title" texto y atributo
|
||||
* El original en español queda guardado en el elemento:
|
||||
* lo que el JS cambia después va con t(), no con data-i18n.
|
||||
* OrbiLang.locale() 'es-CL' | 'en-US', para fechas y números
|
||||
* OrbiLang.url(u) u con ?lang=<actual> (enlaces e iframes a otro panel)
|
||||
* OrbiLang.mount(el, {href}) dibuja el selector "ES | EN" dentro de el. Con href(l)
|
||||
* cada idioma es un enlace (el manual: otra carpeta); sin
|
||||
* href cambia el idioma en el lugar.
|
||||
* OrbiLang.missing textos sin traducción vistos en esta página (para revisar)
|
||||
*
|
||||
* localStorage es por origen (cada IP:puerto el suyo). Para que los paneles se sigan:
|
||||
* el shell de OrbiAdmin pasa ?lang= a cada iframe, y entre la página y sus iframes el
|
||||
* cambio viaja por postMessage ({orbiLang: 'en'}).
|
||||
*/
|
||||
(function () {
|
||||
var KEY = 'orbi.lang';
|
||||
var LIST = ['es', 'en'];
|
||||
var NAMES = { es: 'ES', en: 'EN' };
|
||||
var TITLES = { es: 'Español', en: 'English' };
|
||||
var LOCALES = { es: 'es-CL', en: 'en-US' };
|
||||
var dicts = {};
|
||||
var mounted = [];
|
||||
function stored() { try { return localStorage.getItem(KEY); } catch (e) { return null; } }
|
||||
function store(l) { try { localStorage.setItem(KEY, l); } catch (e) {} }
|
||||
function norm(s) { return String(s).replace(/\s+/g, ' ').trim(); }
|
||||
function query() { try { return new URLSearchParams(location.search).get('lang'); } catch (e) { return null; } }
|
||||
|
||||
var OrbiLang = {
|
||||
missing: new Set(),
|
||||
get: function (list) {
|
||||
list = list || LIST;
|
||||
var cands = [query(), stored()].concat((navigator.languages || [navigator.language || '']).map(function (l) { return String(l).slice(0, 2); }));
|
||||
for (var i = 0; i < cands.length; i++) if (cands[i] && list.indexOf(cands[i]) >= 0) return cands[i];
|
||||
return list[0];
|
||||
},
|
||||
add: function (d) {
|
||||
for (var l in d) {
|
||||
var to = dicts[l] = dicts[l] || {};
|
||||
for (var k in d[l]) to[norm(k)] = d[l][k];
|
||||
}
|
||||
},
|
||||
t: function (s, vars) {
|
||||
if (s == null) return '';
|
||||
var d = dicts[OrbiLang.lang], v = d && (d[s] != null ? d[s] : d[norm(s)]);
|
||||
if (v == null) {
|
||||
v = String(s);
|
||||
if (OrbiLang.lang !== 'es' && norm(s)) OrbiLang.missing.add(norm(s));
|
||||
}
|
||||
if (vars) v = v.replace(/\{(\w+)\}/g, function (m, n) { return n in vars ? vars[n] : m; });
|
||||
return v;
|
||||
},
|
||||
apply: function (root) {
|
||||
root = root || document;
|
||||
var els = Array.prototype.slice.call(root.querySelectorAll('[data-i18n]'));
|
||||
if (root.matches && root.matches('[data-i18n]')) els.unshift(root);
|
||||
els.forEach(function (el) {
|
||||
var o = el._i18n || (el._i18n = {});
|
||||
(el.getAttribute('data-i18n') || 'text').split(/\s+/).forEach(function (what) {
|
||||
if (what === 'text') {
|
||||
if (o.text == null) o.text = norm(el.textContent);
|
||||
el.textContent = OrbiLang.t(o.text);
|
||||
} else if (what === 'html') {
|
||||
if (o.html == null) o.html = norm(el.innerHTML);
|
||||
el.innerHTML = OrbiLang.t(o.html);
|
||||
} else if (el.hasAttribute(what)) {
|
||||
if (o[what] == null) o[what] = el.getAttribute(what);
|
||||
el.setAttribute(what, OrbiLang.t(o[what]));
|
||||
}
|
||||
});
|
||||
});
|
||||
if (root === document) document.documentElement.lang = OrbiLang.lang;
|
||||
},
|
||||
locale: function () { return LOCALES[OrbiLang.lang] || OrbiLang.lang; },
|
||||
url: function (u) {
|
||||
try {
|
||||
var x = new URL(u, location.href);
|
||||
x.searchParams.set('lang', OrbiLang.lang);
|
||||
return x.href;
|
||||
} catch (e) { return u; }
|
||||
},
|
||||
set: function (l, quiet) {
|
||||
if (LIST.indexOf(l) < 0) return;
|
||||
store(l);
|
||||
if (l === OrbiLang.lang) return;
|
||||
OrbiLang.lang = l;
|
||||
// Si la página vino con ?lang=, que una recarga no vuelva al idioma anterior
|
||||
if (query()) { try { var u = new URL(location.href); u.searchParams.set('lang', l); history.replaceState(history.state, '', u.href); } catch (e) {} }
|
||||
OrbiLang.apply(document);
|
||||
mounted.forEach(function (m) { m.el.setAttribute('data-orbi-lang', l); OrbiLang.mount(m.el, m.opts); });
|
||||
try { window.dispatchEvent(new CustomEvent('orbi-lang', { detail: l })); } catch (e) {}
|
||||
if (!quiet) post(l);
|
||||
},
|
||||
mount: function (el, opts) {
|
||||
if (!el) return;
|
||||
opts = opts || {};
|
||||
var cur = el.getAttribute('data-orbi-lang') || OrbiLang.lang;
|
||||
var list = (el.getAttribute('data-orbi-lang-list') || LIST.join(',')).split(',');
|
||||
if (opts.href) store(cur); // quien llega a una página en un idioma lo deja elegido
|
||||
else if (!mounted.some(function (m) { return m.el === el; })) mounted.push({ el: el, opts: opts });
|
||||
el.innerHTML = '';
|
||||
el.classList.add('orbi-lang');
|
||||
list.forEach(function (l) {
|
||||
var a = document.createElement(opts.href ? 'a' : 'button');
|
||||
a.textContent = NAMES[l] || l.toUpperCase();
|
||||
a.title = TITLES[l] || l;
|
||||
a.className = 'orbi-lang-opt' + (l === cur ? ' on' : '');
|
||||
if (opts.href) a.href = opts.href(l); else a.type = 'button';
|
||||
a.addEventListener('click', function (ev) {
|
||||
if (opts.href) { store(l); return; }
|
||||
ev.preventDefault();
|
||||
OrbiLang.set(l);
|
||||
});
|
||||
el.appendChild(a);
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
// Entre la página y sus iframes (otros orígenes): solo viaja el idioma. Nunca se
|
||||
// devuelve a quien avisó: si dos ventanas cambian a la vez, no quedan rebotando.
|
||||
function post(l, except) {
|
||||
var msg = { orbiLang: l };
|
||||
try { if (window.parent !== window && window.parent !== except) window.parent.postMessage(msg, '*'); } catch (e) {}
|
||||
for (var i = 0; i < window.frames.length; i++) {
|
||||
if (window.frames[i] === except) continue;
|
||||
try { window.frames[i].postMessage(msg, '*'); } catch (e) {}
|
||||
}
|
||||
}
|
||||
window.addEventListener('message', function (e) {
|
||||
var l = e.data && e.data.orbiLang;
|
||||
if (!l || LIST.indexOf(l) < 0) return;
|
||||
var known = e.source === window.parent;
|
||||
for (var i = 0; !known && i < window.frames.length; i++) known = e.source === window.frames[i];
|
||||
if (!known || l === OrbiLang.lang) return;
|
||||
OrbiLang.set(l, true);
|
||||
post(l, e.source); // a los demás, no al que avisó
|
||||
});
|
||||
|
||||
OrbiLang.lang = OrbiLang.get();
|
||||
if (query() === OrbiLang.lang) store(OrbiLang.lang); // llegó por ?lang=: queda elegido
|
||||
// <html lang> lo pone apply(document): el manual (un idioma por carpeta) no lo llama
|
||||
window.OrbiLang = OrbiLang;
|
||||
})();
|
||||
@@ -0,0 +1,430 @@
|
||||
/* OrbiStream — Obsidian & Amber */
|
||||
:root{
|
||||
--bg:#0c0e14;
|
||||
--surface:#141821;
|
||||
--surface-2:#1a1f2b;
|
||||
--border:#242a38;
|
||||
--amber:#e8a838;
|
||||
--amber-dim:rgba(232,168,56,.15);
|
||||
--text:#e6e9f0;
|
||||
--text-dim:#8b93a5;
|
||||
--green:#3ecf6e;
|
||||
--red:#e85555;
|
||||
--gray:#6b7280;
|
||||
--blue:#4aa3e8;
|
||||
font-size:14px;
|
||||
}
|
||||
*{box-sizing:border-box;margin:0;padding:0}
|
||||
body{background:var(--bg);color:var(--text);font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;line-height:1.45}
|
||||
.hidden{display:none!important}
|
||||
a{color:inherit;text-decoration:none}
|
||||
|
||||
/* Layout */
|
||||
.layout{display:flex;min-height:100vh}
|
||||
.sidebar{width:220px;background:var(--surface);border-right:1px solid var(--border);display:flex;flex-direction:column;position:sticky;top:0;height:100vh;flex-shrink:0}
|
||||
.main{flex:1;padding:22px 28px;min-width:0}
|
||||
|
||||
/* Sidebar */
|
||||
.brand{display:flex;align-items:flex-start;gap:10px;padding:18px 16px;border-bottom:1px solid var(--border)}
|
||||
/* Logo frente al nombre y el subtítulo, no centrado en todo el bloque (con versión/badge debajo quedaba abajo) */
|
||||
.brand>svg,.brand>img{flex:none;margin-top:6px}
|
||||
.brand-name{font-weight:700;font-size:16px}
|
||||
.brand-name span{color:var(--amber)}
|
||||
.brand-sub{font-size:11px;color:var(--text-dim)}
|
||||
.brand-ver{font-size:10.5px;color:var(--amber);font-weight:600;letter-spacing:.02em;margin-top:1px}
|
||||
.nav{display:flex;flex-direction:column;padding:12px 8px;gap:2px}
|
||||
.nav a{display:flex;align-items:center;gap:10px;padding:9px 12px;border-radius:6px;color:var(--text-dim);font-weight:500}
|
||||
.nav a:hover{background:var(--surface-2);color:var(--text)}
|
||||
.nav a.active{background:var(--amber-dim);color:var(--amber)}
|
||||
.nav-ico{width:16px;text-align:center;opacity:.9}
|
||||
.sidebar-foot{margin-top:auto;padding:14px 16px;border-top:1px solid var(--border);font-size:12px;color:var(--text-dim)}
|
||||
.conn-status{display:flex;align-items:center;gap:7px;margin-bottom:4px}
|
||||
.status-dot{width:8px;height:8px;border-radius:50%;display:inline-block}
|
||||
.status-dot.ok{background:var(--green);box-shadow:0 0 6px var(--green)}
|
||||
.status-dot.down{background:var(--red);box-shadow:0 0 6px var(--red)}
|
||||
|
||||
/* Banner API caída */
|
||||
.api-banner{position:fixed;top:0;left:0;right:0;z-index:200;background:#3a1717;border-bottom:1px solid var(--red);color:#ffb4b4;padding:8px 16px;text-align:center;font-weight:600;display:flex;align-items:center;justify-content:center;gap:10px}
|
||||
.dot-pulse{width:9px;height:9px;border-radius:50%;background:var(--red);animation:pulse 1s infinite}
|
||||
@keyframes pulse{0%,100%{opacity:1}50%{opacity:.3}}
|
||||
|
||||
/* Views */
|
||||
.view-head{display:flex;align-items:baseline;gap:14px;margin-bottom:18px;flex-wrap:wrap}
|
||||
.view-head h1{font-size:20px;font-weight:700}
|
||||
.view-sub{color:var(--text-dim);font-size:12px}
|
||||
.view-head .btn{margin-left:auto}
|
||||
|
||||
/* Panels & KPIs */
|
||||
.panel{background:var(--surface);border:1px solid var(--border);border-radius:10px;padding:16px;margin-bottom:18px}
|
||||
.panel-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:12px}
|
||||
.panel-head h2{font-size:14px;font-weight:600;color:var(--text)}
|
||||
.kpi-row{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:12px;margin-bottom:18px}
|
||||
.kpi-card{background:var(--surface);border:1px solid var(--border);border-radius:10px;padding:12px 16px}
|
||||
.kpi-label{font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--text-dim)}
|
||||
.kpi-value{font-size:22px;font-weight:700;margin-top:2px;font-variant-numeric:tabular-nums}
|
||||
.kpi-value.amber{color:var(--amber)}
|
||||
|
||||
/* Chart */
|
||||
.chart-wrap{width:100%;overflow:hidden}
|
||||
#rt-chart{width:100%;display:block}
|
||||
.legend{display:flex;gap:16px;font-size:12px;color:var(--text-dim)}
|
||||
.legend-item{display:flex;align-items:center;gap:6px}
|
||||
.swatch{width:14px;height:8px;border-radius:2px;display:inline-block}
|
||||
.swatch.line{background:var(--green)}
|
||||
.swatch.area{background:var(--amber)}
|
||||
.swatch.rtt{background:#4ea3f0}
|
||||
.swatch.fanout{background:#f0683c}
|
||||
.enc-chip{display:inline-block;margin-left:6px;padding:0 6px;border-radius:4px;font-size:10px;font-weight:700;vertical-align:middle}
|
||||
.enc-chip.hw{background:rgba(62,207,110,.16);color:#3ecf6e;border:1px solid rgba(62,207,110,.4)}
|
||||
.enc-chip.sw{background:rgba(232,168,56,.14);color:#e8a838;border:1px solid rgba(232,168,56,.35)}
|
||||
.enc-chip.copy{background:#2a2e37;color:#aab3c2;border:1px solid #3a3f4b}
|
||||
.o-port.port-ok{border-color:#3ecf6e}
|
||||
.o-port.port-bad{border-color:#e85555}
|
||||
.out-line{display:flex;gap:6px;align-items:baseline;white-space:nowrap}
|
||||
.out-kind{color:var(--muted);font-size:11px;min-width:64px}
|
||||
.out-url{cursor:pointer;font-size:11px}
|
||||
.out-url:hover{color:var(--amber);text-decoration:underline}
|
||||
.out-url.copied{color:var(--green)}
|
||||
.out-copy{background:none;border:none;cursor:pointer;font-size:12px;padding:0 3px;vertical-align:middle;opacity:.65}
|
||||
.out-copy:hover{opacity:1}
|
||||
.out-copy.copied{color:var(--green);opacity:1}
|
||||
.sv-rtt{color:#4ea3f0}
|
||||
|
||||
/* Badge srt-mux (multipoint) en salidas */
|
||||
.mux-badge{display:inline-flex;align-items:center;gap:4px;padding:1px 7px;border-radius:20px;font-size:10px;font-weight:700;font-variant-numeric:tabular-nums;vertical-align:middle}
|
||||
.mux-badge.on{color:var(--green);background:rgba(62,207,110,.12)}
|
||||
.mux-badge.off{color:var(--gray);background:rgba(107,114,128,.15)}
|
||||
.mux-badge.down{color:var(--red);background:rgba(232,85,85,.12);padding:3px 6px}
|
||||
.mux-dot{width:7px;height:7px;border-radius:50%;background:var(--red);box-shadow:0 0 5px var(--red);display:inline-block}
|
||||
|
||||
/* Vista ISPs */
|
||||
.info-banner{background:var(--amber-dim);border:1px solid var(--amber);border-left-width:4px;color:var(--text);padding:10px 14px;border-radius:8px;margin-bottom:16px;font-size:13px}
|
||||
.chip{display:inline-block;background:var(--surface-2);border:1px solid var(--border);border-radius:20px;padding:2px 9px;font-size:11px;margin:1px 2px 1px 0}
|
||||
.isp-outputs-list{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:10px}
|
||||
.isp-out-group{background:var(--surface-2);border:1px solid var(--border);border-radius:8px;padding:10px 12px}
|
||||
.isp-out-group-name{font-weight:700;font-size:12px;margin-bottom:6px;color:var(--amber)}
|
||||
.isp-out-chk{margin:0 0 4px;font-weight:500}
|
||||
.isp-out-chk input{width:auto}
|
||||
|
||||
/* Tables */
|
||||
.table-wrap{overflow-x:auto}
|
||||
.tbl{width:100%;border-collapse:collapse;font-size:13px;white-space:nowrap}
|
||||
.tbl th{text-align:left;padding:8px 10px;color:var(--text-dim);font-weight:600;font-size:11px;text-transform:uppercase;letter-spacing:.05em;border-bottom:1px solid var(--border)}
|
||||
.tbl td{padding:9px 10px;border-bottom:1px solid var(--border);vertical-align:middle}
|
||||
.tbl tbody tr:hover{background:var(--surface-2)}
|
||||
.ta-r{text-align:right}
|
||||
.empty{padding:24px;text-align:center;color:var(--text-dim)}
|
||||
.mono{font-family:ui-monospace,Consolas,monospace;font-size:12px;color:var(--text-dim)}
|
||||
.num{font-variant-numeric:tabular-nums}
|
||||
|
||||
/* Badges */
|
||||
.badge{display:inline-flex;align-items:center;gap:6px;padding:3px 9px;border-radius:20px;font-size:11px;font-weight:600}
|
||||
.badge::before{content:"";width:7px;height:7px;border-radius:50%;background:currentColor}
|
||||
.badge.running{color:var(--green);background:rgba(62,207,110,.12)}
|
||||
.badge.error{color:var(--red);background:rgba(232,85,85,.12)}
|
||||
.badge.stopped{color:var(--gray);background:rgba(107,114,128,.15)}
|
||||
.badge.connecting{color:var(--amber);background:var(--amber-dim)}
|
||||
.lvl{font-weight:700;font-size:11px;text-transform:uppercase}
|
||||
.lvl.error,.lvl.critical{color:var(--red)}
|
||||
.lvl.warn,.lvl.warning{color:var(--amber)}
|
||||
.lvl.info{color:var(--blue)}
|
||||
.lvl.debug{color:var(--gray)}
|
||||
|
||||
/* Buttons */
|
||||
.btn{background:var(--surface-2);border:1px solid var(--border);color:var(--text);padding:7px 14px;border-radius:7px;cursor:pointer;font-size:13px;font-weight:600}
|
||||
.btn:hover{border-color:var(--amber);color:var(--amber)}
|
||||
.btn-amber{background:var(--amber);border-color:var(--amber);color:#14100a}
|
||||
.btn-amber:hover{background:#f0b850;color:#14100a}
|
||||
.btn-sm{padding:3px 10px;font-size:12px;margin-left:8px}
|
||||
.btn-ico{background:none;border:1px solid transparent;color:var(--text-dim);cursor:pointer;padding:4px 6px;border-radius:5px;font-size:14px}
|
||||
.btn-ico:hover{background:var(--surface-2);color:var(--amber)}
|
||||
.btn-ico.danger:hover{color:var(--red)}
|
||||
.actions{display:flex;gap:2px;justify-content:flex-end}
|
||||
|
||||
/* Dashboard mini-channels */
|
||||
.mini-channels{display:grid;grid-template-columns:repeat(auto-fill,minmax(230px,1fr));gap:10px}
|
||||
.mini-ch{background:var(--surface-2);border:1px solid var(--border);border-radius:8px;padding:10px 12px}
|
||||
.mini-ch .mc-top{display:flex;justify-content:space-between;align-items:center;margin-bottom:4px}
|
||||
.mini-ch .mc-name{font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.mini-ch .mc-meta{font-size:11px;color:var(--text-dim)}
|
||||
|
||||
/* Preview de canal */
|
||||
.preview-cell{width:104px}
|
||||
.ch-preview{position:relative;width:96px;height:54px;border-radius:6px;overflow:hidden;background:var(--surface-2);border:1px solid var(--border);cursor:pointer;padding:0;display:block}
|
||||
.ch-preview img{width:100%;height:100%;object-fit:cover;display:block}
|
||||
.ch-preview .preview-ph{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;color:var(--gray);font-size:18px;background:var(--surface-2)}
|
||||
.ch-preview.has-img .preview-ph{display:none}
|
||||
.ch-preview:hover{border-color:var(--amber)}
|
||||
.preview-modal{background:var(--surface);border:1px solid var(--border);border-radius:12px;width:100%;max-width:700px;box-shadow:0 20px 60px rgba(0,0,0,.5)}
|
||||
.preview-modal-body{padding:16px;display:flex;justify-content:center}
|
||||
.preview-modal-body img{max-width:640px;width:100%;border-radius:8px;background:var(--surface-2);min-height:180px}
|
||||
|
||||
/* Fila de stats por canal */
|
||||
.btn-ico.stats-open{background:var(--amber-dim);color:var(--amber)}
|
||||
/* Sub-fila entrada/salidas: pegada a la fila del canal, a lo ancho */
|
||||
.ch-row td{border-bottom:none}
|
||||
.io-row td{padding:2px 10px 9px;border-bottom:1px solid var(--border)}
|
||||
.io-row:hover td{background:transparent}
|
||||
.io-line{display:flex;align-items:center;gap:12px;flex-wrap:wrap;font-size:14px}
|
||||
.io-label{color:var(--text-dim);font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.06em}
|
||||
.io-block{display:flex;align-items:center;gap:16px;flex-wrap:wrap}
|
||||
.io-block .out-line{display:inline-flex;align-items:center;gap:7px}
|
||||
.io-block .mono,.io-row .out-url{font-size:13px}
|
||||
.io-row .out-copy{font-size:14px}
|
||||
.io-block .out-kind{font-size:12px;font-weight:600}
|
||||
|
||||
.stats-row td{background:var(--bg);padding:14px 16px}
|
||||
.stats-row:hover td{background:var(--bg)}
|
||||
.stats-head{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:8px;flex-wrap:wrap}
|
||||
.stats-values{display:flex;gap:18px;font-size:12px;font-variant-numeric:tabular-nums}
|
||||
.stats-values .sv-in{color:var(--green)}
|
||||
.stats-values .sv-out{color:var(--amber)}
|
||||
.stats-values .sv-drop{color:var(--red)}
|
||||
.stats-values .sv-note{color:var(--text-dim);font-style:italic;cursor:help}
|
||||
.spark-wrap{width:100%;overflow:hidden;flex:1;min-height:120px}
|
||||
.spark-wrap canvas{width:100%;display:block}
|
||||
|
||||
/* Tarjeta SRT (nativas) estilo WMSPanel */
|
||||
.stats-grid{display:grid;grid-template-columns:minmax(0,1fr) minmax(300px,380px);gap:14px;align-items:stretch}
|
||||
.stats-spark{min-width:0;display:flex;flex-direction:column}
|
||||
.srt-card{background:var(--surface);border:1px solid var(--border);border-radius:8px;overflow:hidden}
|
||||
.srt-card-head{padding:7px 12px;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--amber);border-bottom:1px solid var(--border);background:var(--surface-2)}
|
||||
.srt-card-body{padding:8px 12px 10px}
|
||||
.srt-list{display:grid;grid-template-columns:auto 1fr;column-gap:14px;margin:0}
|
||||
.srt-list dt{color:var(--text-dim);font-size:12px;padding:3px 0;border-bottom:1px solid var(--border);white-space:nowrap}
|
||||
.srt-list dd{margin:0;text-align:right;font-size:12px;padding:3px 0;border-bottom:1px solid var(--border);font-variant-numeric:tabular-nums;white-space:nowrap}
|
||||
.srt-list dt:nth-last-of-type(1),.srt-list dd:nth-last-of-type(1){border-bottom:none}
|
||||
.srt-bad{color:#f08a8a}
|
||||
.srt-foot{margin-top:6px;font-size:10px;color:var(--text-dim)}
|
||||
.srt-msg{padding:10px 2px;font-size:12px;color:var(--text-dim)}
|
||||
@media (max-width:1100px){.stats-grid{grid-template-columns:1fr}}
|
||||
|
||||
/* Chip de encoder */
|
||||
.server-head-right{display:flex;align-items:center;gap:10px}
|
||||
.encoder-chip{display:inline-flex;align-items:center;gap:6px;padding:3px 10px;border-radius:20px;font-size:11px;font-weight:600}
|
||||
.encoder-chip::before{content:"";width:7px;height:7px;border-radius:50%;background:currentColor}
|
||||
.encoder-chip.nvenc{color:var(--green);background:rgba(62,207,110,.12)}
|
||||
.encoder-chip.cpu{color:var(--gray);background:rgba(107,114,128,.15)}
|
||||
|
||||
/* Server view */
|
||||
.server-head{display:flex;justify-content:space-between;align-items:center;margin-bottom:14px}
|
||||
.server-name{font-size:17px;font-weight:700}
|
||||
.server-meta{font-size:12px;color:var(--text-dim)}
|
||||
.gauge-row{display:flex;gap:26px;flex-wrap:wrap;margin-bottom:18px}
|
||||
.gauge-box{text-align:center}
|
||||
.gauge-label{font-size:12px;color:var(--text-dim);margin-top:-6px}
|
||||
.gauge-scope{font-size:10px;opacity:.6;font-weight:400}
|
||||
|
||||
/* Modal */
|
||||
.modal-backdrop{position:fixed;inset:0;background:rgba(4,6,10,.72);z-index:100;display:flex;align-items:flex-start;justify-content:center;padding:34px 16px;overflow-y:auto}
|
||||
.modal{background:var(--surface);border:1px solid var(--border);border-radius:12px;width:100%;max-width:760px;box-shadow:0 20px 60px rgba(0,0,0,.5)}
|
||||
.modal-head{display:flex;justify-content:space-between;align-items:center;padding:16px 20px;border-bottom:1px solid var(--border)}
|
||||
.modal-head h2{font-size:16px}
|
||||
.btn-close{background:none;border:none;color:var(--text-dim);font-size:16px;cursor:pointer}
|
||||
.btn-close:hover{color:var(--red)}
|
||||
.modal-body{padding:18px 20px}
|
||||
.modal-foot{display:flex;justify-content:flex-end;gap:10px;margin-top:16px}
|
||||
fieldset{border:1px solid var(--border);border-radius:8px;padding:14px;margin-bottom:16px}
|
||||
legend{padding:0 8px;font-size:12px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:var(--amber)}
|
||||
label{display:flex;flex-direction:column;gap:4px;font-size:12px;color:var(--text-dim);font-weight:600;margin-bottom:8px}
|
||||
input,select,textarea{background:var(--bg);border:1px solid var(--border);border-radius:6px;color:var(--text);padding:7px 10px;font-size:13px;font-family:inherit;width:100%}
|
||||
input:focus,select:focus,textarea:focus{outline:none;border-color:var(--amber)}
|
||||
.chk-wrap{flex-direction:row;align-items:center;gap:8px;margin-top:20px}
|
||||
.chk-wrap input{width:auto}
|
||||
.grid-2{display:grid;grid-template-columns:1fr 1fr;gap:12px}
|
||||
.grid-3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px}
|
||||
.grid-out{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;flex:1}
|
||||
.hint{font-size:11px;color:var(--text-dim);background:var(--amber-dim);border-left:3px solid var(--amber);padding:6px 10px;border-radius:4px;margin-bottom:10px}
|
||||
.hint b{color:var(--amber)}
|
||||
.field-hint{display:block;font-size:11px;line-height:1.35;color:var(--text-dim);margin-top:4px;font-weight:400}
|
||||
.field-hint b{color:var(--text,inherit);font-weight:600}
|
||||
.output-row{display:flex;gap:10px;align-items:flex-start;background:var(--surface-2);border:1px solid var(--border);border-radius:8px;padding:12px;margin-bottom:10px}
|
||||
.btn-remove-output{background:none;border:1px solid var(--border);color:var(--text-dim);border-radius:6px;cursor:pointer;padding:4px 8px;flex-shrink:0}
|
||||
.btn-remove-output:hover{color:var(--red);border-color:var(--red)}
|
||||
.form-error{margin-top:12px;background:rgba(232,85,85,.12);border:1px solid var(--red);color:#ffb4b4;padding:8px 12px;border-radius:6px;font-size:13px}
|
||||
|
||||
/* ================= Historial (uptime) ================= */
|
||||
.swatch.down{background:rgba(232,85,85,.55)}
|
||||
.hist-row{cursor:pointer}
|
||||
.up-bar-wrap{display:flex;align-items:center;gap:8px;min-width:140px}
|
||||
.up-bar{flex:1;height:8px;border-radius:4px;background:var(--surface-2);overflow:hidden;min-width:70px}
|
||||
.up-bar span{display:block;height:100%;border-radius:4px}
|
||||
.up-bar.ok span{background:var(--green)}
|
||||
.up-bar.warn span{background:var(--amber)}
|
||||
.up-bar.bad span{background:var(--red)}
|
||||
.up-bar.na span{background:var(--gray)}
|
||||
.up-val{font-size:11px;font-variant-numeric:tabular-nums;min-width:52px;text-align:right}
|
||||
.up-val.ok{color:var(--green)}
|
||||
.up-val.warn{color:var(--amber)}
|
||||
.up-val.bad{color:var(--red)}
|
||||
.up-val.na{color:var(--gray)}
|
||||
.heatmap{display:flex;gap:2px}
|
||||
.hm-cell{width:10px;height:16px;border-radius:2px;display:inline-block}
|
||||
.hm-cell.ok{background:var(--green);opacity:.85}
|
||||
.hm-cell.warn{background:var(--amber)}
|
||||
.hm-cell.bad{background:var(--red)}
|
||||
.hm-cell.na{background:var(--surface-2);border:1px solid var(--border)}
|
||||
#history-chart{width:100%;display:block}
|
||||
|
||||
/* ================= Respaldos ================= */
|
||||
.backup-actions{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:12px}
|
||||
.backup-msg{margin-bottom:12px;background:rgba(62,207,110,.12);border:1px solid var(--green);color:#b6f0cc;padding:8px 12px;border-radius:6px;font-size:13px}
|
||||
.backup-msg.error{background:rgba(232,85,85,.12);border-color:var(--red);color:#ffb4b4}
|
||||
|
||||
/* ================= Autenticación ================= */
|
||||
.login-overlay{position:fixed;inset:0;z-index:300;background:var(--bg);display:flex;align-items:center;justify-content:center;padding:20px}
|
||||
.login-card{background:var(--surface);border:1px solid var(--border);border-radius:14px;padding:32px 30px;width:100%;max-width:360px;box-shadow:0 24px 70px rgba(0,0,0,.55)}
|
||||
.login-brand{display:flex;align-items:center;gap:12px;justify-content:center;margin-bottom:24px}
|
||||
.login-brand .brand-name{font-size:20px}
|
||||
.login-btn{width:100%;margin-top:10px;padding:9px 14px}
|
||||
.user-box{display:flex;align-items:center;gap:6px;margin-bottom:8px;flex-wrap:wrap}
|
||||
.user-ico{color:var(--amber);font-size:10px}
|
||||
.user-name{font-weight:600;color:var(--text);max-width:90px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.user-role{text-transform:capitalize}
|
||||
.user-logout{margin-left:auto;font-size:11px;padding:2px 6px}
|
||||
.user-logout:hover{color:var(--red)}
|
||||
.modal-sm{max-width:480px}
|
||||
|
||||
/* Gating por rol (la verdad la impone el backend; la UI solo esconde) */
|
||||
body.role-visor .need-op{display:none!important}
|
||||
body.role-visor .need-admin{display:none!important}
|
||||
|
||||
@media (max-width:860px){
|
||||
.layout{flex-direction:column}
|
||||
.sidebar{width:100%;height:auto;position:static;flex-direction:row;align-items:center;flex-wrap:wrap}
|
||||
.nav{flex-direction:row}
|
||||
.sidebar-foot{margin-top:0;border-top:none;margin-left:auto}
|
||||
.grid-2,.grid-3,.grid-out{grid-template-columns:1fr 1fr}
|
||||
.main{padding:14px}
|
||||
}
|
||||
|
||||
/* ================= Asistente de ayuda ================= */
|
||||
.assist-fab{position:fixed;right:22px;bottom:22px;z-index:300;width:48px;height:48px;border-radius:50%;border:none;background:var(--amber);color:#0c0e14;font-size:22px;font-weight:700;cursor:pointer;box-shadow:0 4px 14px rgba(0,0,0,.45);transition:transform .15s}
|
||||
.assist-fab:hover{transform:scale(1.08)}
|
||||
.assist-panel{position:fixed;right:22px;bottom:80px;z-index:300;width:380px;max-width:calc(100vw - 44px);height:520px;max-height:calc(100vh - 120px);display:flex;flex-direction:column;background:var(--surface);border:1px solid var(--border);border-radius:12px;box-shadow:0 10px 34px rgba(0,0,0,.55);overflow:hidden}
|
||||
.assist-head{display:flex;align-items:flex-start;justify-content:space-between;padding:12px 14px;border-bottom:1px solid var(--border);background:var(--surface-2)}
|
||||
.assist-title{font-weight:700;font-size:14px}
|
||||
.assist-title span{color:var(--amber)}
|
||||
.assist-sub{font-size:11px;color:var(--text-dim);margin-top:2px}
|
||||
.assist-head-btns{display:flex;gap:6px;align-items:center}
|
||||
.assist-msgs{flex:1;overflow-y:auto;padding:14px;display:flex;flex-direction:column;gap:10px}
|
||||
.assist-msg{max-width:85%;padding:9px 12px;border-radius:10px;font-size:13px;line-height:1.5;white-space:normal;word-wrap:break-word}
|
||||
.assist-msg.user{align-self:flex-end;background:var(--amber);color:#0c0e14;border-bottom-right-radius:3px;font-weight:500}
|
||||
.assist-msg.assistant{align-self:flex-start;background:var(--surface-2);border:1px solid var(--border);border-bottom-left-radius:3px}
|
||||
.assist-msg code{background:rgba(232,168,56,.12);color:var(--amber);padding:1px 5px;border-radius:4px;font-family:ui-monospace,Consolas,monospace;font-size:12px}
|
||||
.assist-msg.user code{background:rgba(12,14,20,.15);color:inherit}
|
||||
.assist-typing{padding:0 16px 8px;font-size:12px;color:var(--text-dim);font-style:italic}
|
||||
.assist-inputbar{display:flex;gap:8px;padding:10px 12px;border-top:1px solid var(--border);background:var(--surface-2)}
|
||||
.assist-inputbar input{flex:1;background:var(--bg);border:1px solid var(--border);border-radius:8px;color:var(--text);padding:8px 11px;font-size:13px;outline:none}
|
||||
.assist-inputbar input:focus{border-color:var(--amber)}
|
||||
.assist-inputbar .btn{padding:6px 14px}
|
||||
|
||||
/* Disponibilidad (excluye Detenido) bajo la barra de uptime */
|
||||
.hist-avail{font-size:11px;margin-top:3px;font-variant-numeric:tabular-nums}
|
||||
.hist-avail.ok{color:var(--green)}
|
||||
.hist-avail.warn{color:var(--amber,#e8a838)}
|
||||
.hist-avail.bad{color:var(--red)}
|
||||
|
||||
/* Botón ⇄ entrada/salidas activo */
|
||||
.btn-ico.io-open{color:var(--amber);background:var(--amber-dim)}
|
||||
/* Si la sub-fila E/S está colapsada, la fila del canal recupera su borde */
|
||||
.ch-row:has(+ .io-row.hidden) td{border-bottom:1px solid var(--border)}
|
||||
|
||||
/* Conexiones en vivo: fila resumen por canal + detalle expandible */
|
||||
.conn-sum{cursor:pointer;user-select:none}
|
||||
.conn-sum:hover td{background:rgba(232,168,56,.05)}
|
||||
.conn-arrow{display:inline-block;width:14px;color:var(--amber,#e8a838);font-size:11px}
|
||||
.conn-det td{padding-top:4px;padding-bottom:4px;font-size:13px;background:rgba(255,255,255,.015)}
|
||||
/* Canales: acciones pegadas a la derecha (junto a Stats); el ancho sobrante va al nombre */
|
||||
#tbl-channels .c-actions{width:1%}
|
||||
#tbl-channels .c-uptime,#tbl-channels .c-bitrate,#tbl-channels .c-profile{width:1%;padding-right:28px}
|
||||
/* Canales: columnas compactas de corrido; el espacio sobrante queda al final (col Stats) */
|
||||
#tbl-channels .c-name{width:1%;padding-right:40px}
|
||||
#tbl-channels th:last-child,#tbl-channels td:last-child{width:96%;text-align:left}
|
||||
|
||||
/* ---- puntito de calidad de fuente (celda Bitrate In/Out) ---- */
|
||||
.c-bitrate .br-wrap{display:flex;align-items:center;gap:8px}
|
||||
.c-bitrate .br-val{margin-left:auto;font-variant-numeric:tabular-nums}
|
||||
.src-dot{flex:none;width:10px;height:10px;padding:0;border:none;border-radius:50%;
|
||||
cursor:pointer;background:var(--gray);transition:transform .12s;vertical-align:middle}
|
||||
.src-dot:hover{transform:scale(1.25)}
|
||||
.src-dot:focus-visible{outline:2px solid var(--blue);outline-offset:2px}
|
||||
.src-dot.green{background:var(--green);box-shadow:0 0 0 3px rgba(62,207,110,.16)}
|
||||
.src-dot.blue{background:var(--blue);box-shadow:0 0 0 3px rgba(74,163,232,.18)}
|
||||
.src-dot.yellow{background:var(--amber);box-shadow:0 0 0 3px rgba(232,168,56,.18)}
|
||||
.src-dot.red{background:var(--red);box-shadow:0 0 0 3px rgba(232,85,85,.18)}
|
||||
|
||||
/* ---- popup de calidad de fuente ---- */
|
||||
.modal-head h2 .src-dot{display:inline-block}
|
||||
.src-lbl{font-size:13px;color:var(--text-dim);font-weight:500}
|
||||
.src-metrics{display:grid;grid-template-columns:repeat(4,1fr);gap:9px;margin-bottom:12px}
|
||||
.src-metrics .sm{background:var(--bg);border:1px solid var(--border);border-radius:9px;padding:9px 11px}
|
||||
.sm-k{font-size:10px;color:var(--text-dim);text-transform:uppercase;letter-spacing:.5px}
|
||||
.sm-v{font-size:17px;margin-top:2px;font-variant-numeric:tabular-nums}
|
||||
.sm-v.in{color:var(--blue)} .sm-v.out{color:var(--amber)}
|
||||
.sm-u{font-size:10px;color:var(--text-dim)}
|
||||
.src-legend{display:flex;gap:15px;align-items:center;font-size:12px;color:var(--text-dim);margin:2px 0 5px}
|
||||
.src-legend i{display:inline-block;width:14px;height:3px;border-radius:2px;vertical-align:middle;margin-right:5px}
|
||||
.src-legend .ln-in{background:var(--blue)} .src-legend .ln-out{background:var(--amber)}
|
||||
.src-plot{width:100%;height:auto;display:block;overflow:visible}
|
||||
.src-buflab{font-size:10px;color:var(--text-dim);text-transform:uppercase;letter-spacing:.4px;margin:10px 2px 3px}
|
||||
.src-note{margin-top:12px;padding:9px 11px;border-radius:8px;background:rgba(74,163,232,.08);
|
||||
border:1px solid rgba(74,163,232,.22);font-size:12.5px;color:#cdd8e6}
|
||||
.src-note b{color:var(--text)}
|
||||
.src-msg{color:var(--text-dim);font-size:13px;padding:10px 0}
|
||||
|
||||
/* ---- SLA prominente en el popup de fuente ---- */
|
||||
.src-sla{font-size:22px;font-weight:700;margin-bottom:12px;font-variant-numeric:tabular-nums}
|
||||
.src-sla-sub{font-size:12px;font-weight:500;color:var(--text-dim)}
|
||||
.src-sla.green{color:var(--green)} .src-sla.blue{color:var(--blue)}
|
||||
.src-sla.yellow{color:var(--amber)} .src-sla.red{color:var(--red)}
|
||||
|
||||
/* ---- estado naranja: 'A grumos' (completo pero apelotonado, menos grave que rojo) ---- */
|
||||
.src-dot.orange{background:#ef8043;box-shadow:0 0 0 3px rgba(239,128,67,.18)}
|
||||
.src-sla.orange{color:#ef8043}
|
||||
|
||||
/* Pegado rápido de URL de origen (formulario de canal) */
|
||||
.paste-url{display:block;margin-bottom:10px}
|
||||
.paste-row{display:flex;gap:8px;align-items:center}
|
||||
.paste-row input{flex:1;min-width:0;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px}
|
||||
.paste-row .btn-sm{margin-left:0;white-space:nowrap}
|
||||
.paste-msg{font-size:11px;line-height:1.5;padding:6px 10px;border-radius:4px;margin-bottom:10px}
|
||||
.paste-msg.ok{color:var(--text-dim);background:var(--amber-dim);border-left:3px solid var(--amber)}
|
||||
.paste-msg.bad{color:#ffb4b4;background:rgba(232,85,85,.12);border-left:3px solid var(--red)}
|
||||
.paste-msg ul{margin:4px 0 0;padding-left:16px}
|
||||
/* Chip clickeable de dirección de egreso */
|
||||
.chip-click{cursor:pointer}
|
||||
.chip-click:hover{filter:brightness(1.25)}
|
||||
.chip-click:focus-visible{outline:2px solid var(--amber);outline-offset:2px}
|
||||
.bind-src{font-size:11px;color:var(--text-dim);margin-top:6px}
|
||||
.bind-confirm{display:flex;align-items:center;gap:8px;margin-top:12px;font-size:12px;cursor:pointer}
|
||||
.bind-confirm input{width:auto;margin:0}
|
||||
/* Advertencia del modal de egreso. Clase propia: no depende de .paste-msg, que
|
||||
se define en otra feature y podría no estar. */
|
||||
.bind-warn{font-size:11px;line-height:1.5;padding:6px 10px;border-radius:4px;margin-top:12px;
|
||||
color:#ffb4b4;background:rgba(232,85,85,.12);border-left:3px solid var(--red)}
|
||||
|
||||
/* Texto secundario en celdas (procesos srt-mux: "/ N esperadas", "de 8") */
|
||||
.muted{color:var(--text-dim)}
|
||||
|
||||
/* Alta disponibilidad: formulario del par en dos columnas */
|
||||
.ha-form{display:grid;grid-template-columns:repeat(auto-fill,minmax(230px,1fr));gap:8px 14px;margin-top:10px}
|
||||
.ha-form label{display:flex;flex-direction:column;gap:4px;font-size:12px;color:var(--text-dim)}
|
||||
.ha-form-foot{grid-column:1/-1;display:flex;align-items:center;gap:12px}
|
||||
.badge.ha-activo{color:var(--green);background:rgba(62,207,110,.12)}
|
||||
.badge.ha-pasivo{color:var(--blue);background:rgba(74,163,232,.12)}
|
||||
|
||||
/* Marca de agua (vista propia del menú) */
|
||||
.marca-form{display:grid;grid-template-columns:repeat(3,1fr);gap:10px 12px;margin:0 2px 12px}
|
||||
.marca-form-foot{grid-column:1/-1;display:flex;gap:10px;align-items:center;flex-wrap:wrap}
|
||||
#marca-global-msg:empty{display:none} /* vacío se veía como una píldora ámbar suelta */
|
||||
.logo-thumb{height:32px;max-width:140px;padding:4px 6px;border-radius:4px;
|
||||
background:repeating-conic-gradient(#555 0 25%,#999 0 50%) 0 0/12px 12px}
|
||||
@media (max-width:700px){.marca-form{grid-template-columns:1fr 1fr}}
|
||||
|
||||
/* Marca forense (tarea 007) */
|
||||
.forense-box{margin:10px 0 4px;padding:10px 12px;border:1px solid var(--border);border-radius:8px;background:var(--surface-2)}
|
||||
.forense-head{display:flex;gap:10px;align-items:center;margin-bottom:4px}
|
||||
.forense-head .btn{margin-left:auto}
|
||||
.chip.fz-on{background:rgba(232,168,56,.18);border-color:var(--amber,#e8a838);color:var(--amber,#e8a838)}
|
||||
.enc-chip.fz{background:rgba(232,168,56,.18);color:var(--amber,#e8a838)}
|
||||
@@ -0,0 +1,29 @@
|
||||
/* subs.css — lo propio de OrbiSubs encima de styles.css (que es copia de OrbiStream). */
|
||||
.small{font-size:11px}
|
||||
.c-sub{white-space:normal;min-width:220px;max-width:340px}
|
||||
.ch-sub{font-size:12px;line-height:1.35;color:var(--text);overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;margin-bottom:3px}
|
||||
.ch-sub .chip{font-size:10px;padding:0 6px}
|
||||
.btn-ico[disabled]{opacity:.35;cursor:not-allowed}
|
||||
.btn-ico[disabled]:hover{background:none;color:var(--text-dim)}
|
||||
.pair{display:flex;gap:6px}
|
||||
.url-box{margin-top:4px}
|
||||
.url-line{display:flex;align-items:center;gap:8px;font-size:12px;margin:3px 0;flex-wrap:wrap}
|
||||
.url-line .out-url{word-break:break-all}
|
||||
.out-copy{background:none;border:1px solid var(--border);border-radius:5px;cursor:pointer;padding:1px 6px;font-size:12px}
|
||||
.out-copy.copied{border-color:var(--green)}
|
||||
.field-bad{border-color:var(--red)!important}
|
||||
.login-lang{margin-top:16px;text-align:center}
|
||||
.modal-wide{max-width:1180px}
|
||||
.view-grid{display:grid;grid-template-columns:minmax(0,3fr) minmax(0,2fr);gap:18px}
|
||||
@media (max-width:900px){.view-grid{grid-template-columns:1fr}}
|
||||
#view-video{width:100%;background:#000;border-radius:8px;aspect-ratio:16/9}
|
||||
.player-bar{display:flex;align-items:center;justify-content:space-between;gap:10px;margin:8px 0}
|
||||
label.inline{flex-direction:row;align-items:center;gap:8px;margin:0}
|
||||
label.inline select{width:auto}
|
||||
.kpi-sm{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:12px}
|
||||
.kpi-sm .kpi-card{padding:10px 12px}
|
||||
.kpi-sm .kpi-value{font-size:18px}
|
||||
.sub-panel{padding:12px;margin-bottom:12px}
|
||||
.sub-list{list-style:none;font-size:13px;line-height:1.45;max-height:210px;overflow-y:auto}
|
||||
.sub-list li{padding:4px 0;border-bottom:1px solid var(--border)}
|
||||
.sub-list li:first-child{color:var(--amber)}
|
||||
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* url-parse.js — desarma una URL de origen pegada tal cual y la reparte en los
|
||||
* campos del formulario (tipo, URL, passphrase, latencia).
|
||||
*
|
||||
* Por qué existe: los proveedores mandan la URL completa con sus parámetros.
|
||||
* Copiarla entera al campo URL parece que funciona, pero rompe la latencia:
|
||||
* `srtUrl()` en pipeline.js agrega `latency = latency_ms * 1000` (µs para
|
||||
* ffmpeg) SOLO si la query no trae ya un `latency=`. Una URL pegada con
|
||||
* `latency=2000` —que en la convención SRT son 2000 ms— sobrevive intacta y
|
||||
* ffmpeg la lee como **2000 µs = 2 ms**. El canal no aguanta ni la primera
|
||||
* pérdida.
|
||||
*
|
||||
* Por eso se EXTRAEN los parámetros que tienen campo propio (passphrase,
|
||||
* latency, mode) y se DEJAN los que no (pbkeylen, streamid, maxbw…), que
|
||||
* srt-mux sí lee de la URL.
|
||||
*
|
||||
* Función pura y sin dependencias: se usa desde el navegador y desde los tests.
|
||||
*/
|
||||
(function (root) {
|
||||
'use strict';
|
||||
|
||||
// Los que tienen campo propio en el formulario. El resto viaja en la URL.
|
||||
const EXTRAER = new Set(['passphrase', 'latency', 'rcvlatency', 'mode']);
|
||||
|
||||
// Por encima de esto asumimos microsegundos (estilo ffmpeg) y no
|
||||
// milisegundos: 100 s de latencia SRT no existe en la vida real.
|
||||
const UMBRAL_US = 100000;
|
||||
|
||||
// Textos en el idioma del panel (orbi-lang.js). En Node (tests) no hay OrbiLang:
|
||||
// queda el español con los {placeholders} reemplazados.
|
||||
function t(s, v) {
|
||||
if (root.OrbiLang) return root.OrbiLang.t(s, v);
|
||||
return v ? s.replace(/\{(\w+)\}/g, (m, n) => (n in v ? v[n] : m)) : s;
|
||||
}
|
||||
|
||||
function parseMediaUrl(raw) {
|
||||
const aviso = [];
|
||||
let s = String(raw == null ? '' : raw).trim();
|
||||
if (!s) return { error: t('Pega una URL.') };
|
||||
|
||||
// Tolerar comillas y líneas de comando enteras:
|
||||
// srt-live-transmit "srt://1.2.3.4:9000?..." udp://...
|
||||
s = s.replace(/^["'\s]+|["'\s]+$/g, '');
|
||||
const enLinea = s.match(/\b(?:srt|udp|rtmps?|https?):\/\/[^\s"'<>]+/i);
|
||||
if (enLinea && enLinea[0] !== s) {
|
||||
s = enLinea[0].replace(/["']+$/, '');
|
||||
aviso.push(t('Se extrajo la URL del texto pegado.'));
|
||||
}
|
||||
|
||||
const m = s.match(/^([a-z]+):\/\/(.*)$/i);
|
||||
if (!m) return { error: t('No parece una URL: falta el esquema (srt://, udp://, rtmp://, http://).') };
|
||||
const esquema = m[1].toLowerCase();
|
||||
let resto = m[2];
|
||||
|
||||
if (esquema !== 'srt') {
|
||||
const kind = esquema === 'udp' ? 'udp'
|
||||
: (esquema === 'rtmp' || esquema === 'rtmps') ? 'rtmp'
|
||||
: 'hls';
|
||||
if (kind === 'hls' && !/\.m3u8(\?|$)/i.test(s)) {
|
||||
aviso.push(t('La URL no termina en .m3u8; verifica que sea realmente HLS.'));
|
||||
}
|
||||
// Estos tipos no tienen passphrase ni latencia propias: la URL va entera.
|
||||
return { kind, url: s, passphrase: '', latency_ms: null, avisos: aviso };
|
||||
}
|
||||
|
||||
// ---- SRT ----
|
||||
let query = '';
|
||||
const q = resto.indexOf('?');
|
||||
if (q >= 0) { query = resto.slice(q + 1); resto = resto.slice(0, q); }
|
||||
|
||||
// libsrt rechaza host vacío; misma normalización que pipeline.js
|
||||
let host = resto.replace(/^:(\d)/, '0.0.0.0:$1');
|
||||
if (!/:\d+$/.test(host)) {
|
||||
return { error: t('Falta el puerto en "srt://{x}".', { x: resto }) };
|
||||
}
|
||||
|
||||
const campos = {};
|
||||
const sobran = [];
|
||||
for (const par of query.split('&')) {
|
||||
if (!par) continue;
|
||||
const i = par.indexOf('=');
|
||||
const k = (i < 0 ? par : par.slice(0, i)).toLowerCase();
|
||||
const v = i < 0 ? '' : par.slice(i + 1);
|
||||
if (EXTRAER.has(k)) campos[k] = v; else sobran.push(par);
|
||||
}
|
||||
|
||||
// mode explícito manda; si no, se infiere del host.
|
||||
let kind;
|
||||
const modo = (campos.mode || '').toLowerCase();
|
||||
if (modo === 'listener') kind = 'srt_listener';
|
||||
else if (modo === 'caller') kind = 'srt_caller';
|
||||
else if (modo === 'rendezvous') {
|
||||
kind = 'srt_caller';
|
||||
aviso.push(t('mode=rendezvous no está soportado; se dejó como SRT Caller.'));
|
||||
} else {
|
||||
const ip = host.replace(/:\d+$/, '');
|
||||
kind = (ip === '0.0.0.0' || ip === '' || ip === '::') ? 'srt_listener' : 'srt_caller';
|
||||
aviso.push(t('Sin mode= en la URL: se dedujo {k} por el host.', { k: kind === 'srt_listener' ? 'Listener' : 'Caller' }));
|
||||
}
|
||||
|
||||
// Latencia: `latency` gana sobre `rcvlatency`. La convención de las URLs SRT
|
||||
// es milisegundos; un valor enorme delata microsegundos (estilo ffmpeg).
|
||||
let latency_ms = null;
|
||||
const bruta = campos.latency !== undefined ? campos.latency : campos.rcvlatency;
|
||||
if (bruta !== undefined && bruta !== '') {
|
||||
const n = Number(bruta);
|
||||
if (!Number.isFinite(n) || n < 0) {
|
||||
aviso.push(t('Latencia ilegible ("{v}"): se ignoró.', { v: bruta }));
|
||||
} else if (n > UMBRAL_US) {
|
||||
latency_ms = Math.round(n / 1000);
|
||||
aviso.push(t('La latencia venía en microsegundos ({n}); se convirtió a {ms} ms.', { n, ms: latency_ms }));
|
||||
} else {
|
||||
latency_ms = Math.round(n);
|
||||
}
|
||||
}
|
||||
|
||||
let passphrase = '';
|
||||
if (campos.passphrase) {
|
||||
try { passphrase = decodeURIComponent(campos.passphrase); }
|
||||
catch { passphrase = campos.passphrase; aviso.push(t('La passphrase tenía un %-escape inválido; se copió tal cual.')); }
|
||||
if (passphrase.length < 10 || passphrase.length > 79) {
|
||||
aviso.push(t('La passphrase tiene {n} caracteres; SRT exige entre 10 y 79.', { n: passphrase.length }));
|
||||
}
|
||||
}
|
||||
|
||||
if (sobran.length) {
|
||||
aviso.push(t('Se dejaron en la URL: {list}.', { list: sobran.map(p => p.split('=')[0]).join(', ') }));
|
||||
}
|
||||
|
||||
return {
|
||||
kind,
|
||||
url: `srt://${host}` + (sobran.length ? `?${sobran.join('&')}` : ''),
|
||||
passphrase,
|
||||
latency_ms,
|
||||
avisos: aviso
|
||||
};
|
||||
}
|
||||
|
||||
root.parseMediaUrl = parseMediaUrl;
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = { parseMediaUrl };
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
@@ -0,0 +1,140 @@
|
||||
'use strict';
|
||||
// auth.js — login del panel. Misma regla que toda caja Orbi (orbiauth, Jorge
|
||||
// 2026-10-21): cuenta inicial admin/admin, y mientras tenga la clave inicial no da
|
||||
// sesión: solo sirve para elegir la clave nueva. Mismo hash que orbiauth
|
||||
// (PBKDF2-SHA256, 200k vueltas) por si después se pasa al login común.
|
||||
const express = require('express');
|
||||
const crypto = require('crypto');
|
||||
const { db, event } = require('../db');
|
||||
|
||||
const INITIAL_USER = 'admin', INITIAL_PW = 'admin';
|
||||
const MIN_PW = 8;
|
||||
const SESSION_MS = 12 * 3600 * 1000;
|
||||
const CHANGE_MS = 10 * 60 * 1000; // el pase para elegir la clave dura 10 min
|
||||
const COOKIE = 'orbisubs_session';
|
||||
|
||||
function hashPw(pw, salt = crypto.randomBytes(16).toString('hex'), iter = 200000) {
|
||||
return { salt, iter, hash: crypto.pbkdf2Sync(pw, Buffer.from(salt, 'hex'), iter, 32, 'sha256').toString('hex') };
|
||||
}
|
||||
function checkPw(u, pw) {
|
||||
const h = hashPw(pw, u.salt, u.iter).hash;
|
||||
return crypto.timingSafeEqual(Buffer.from(h, 'hex'), Buffer.from(u.hash, 'hex'));
|
||||
}
|
||||
|
||||
// Cuenta inicial solo si no hay ningún usuario (base nueva).
|
||||
if (!db.prepare('SELECT 1 FROM users LIMIT 1').get()) {
|
||||
const h = hashPw(INITIAL_PW);
|
||||
db.prepare('INSERT INTO users (username, salt, iter, hash, role, must_change) VALUES (?, ?, ?, ?, ?, 1)')
|
||||
.run(INITIAL_USER, h.salt, h.iter, h.hash, 'admin');
|
||||
}
|
||||
|
||||
const changeTokens = new Map(); // token → {username, exp}
|
||||
|
||||
function cookieOf(req) {
|
||||
const m = new RegExp(`(?:^|;\\s*)${COOKIE}=([a-f0-9]{64})`).exec(req.headers.cookie || '');
|
||||
return m ? m[1] : null;
|
||||
}
|
||||
function sessionUser(req) {
|
||||
const tok = cookieOf(req);
|
||||
if (!tok) return null;
|
||||
const s = db.prepare(`SELECT s.username, s.sver, s.expires, u.role, u.sver AS usver, u.must_change
|
||||
FROM sessions s JOIN users u ON u.username = s.username WHERE s.token = ?`).get(tok);
|
||||
if (!s || s.expires < Date.now() || s.sver !== s.usver || s.must_change) return null;
|
||||
return { username: s.username, role: s.role };
|
||||
}
|
||||
function newSession(res, username) {
|
||||
const tok = crypto.randomBytes(32).toString('hex');
|
||||
const u = db.prepare('SELECT sver FROM users WHERE username = ?').get(username);
|
||||
db.prepare('DELETE FROM sessions WHERE expires < ?').run(Date.now());
|
||||
db.prepare('INSERT INTO sessions (token, username, sver, expires) VALUES (?, ?, ?, ?)').run(tok, username, u.sver, Date.now() + SESSION_MS);
|
||||
res.setHeader('Set-Cookie', `${COOKIE}=${tok}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${SESSION_MS / 1000}`);
|
||||
}
|
||||
function setPassword(username, pw) {
|
||||
const h = hashPw(pw);
|
||||
db.prepare('UPDATE users SET salt = ?, iter = ?, hash = ?, must_change = 0, sver = sver + 1 WHERE username = ?')
|
||||
.run(h.salt, h.iter, h.hash, username);
|
||||
}
|
||||
function pwRules(username, pw, pw2) {
|
||||
if (pw !== pw2) return 'Las dos claves no coinciden';
|
||||
if (String(pw || '').length < MIN_PW) return `La contraseña tiene que tener al menos ${MIN_PW} caracteres`;
|
||||
if (pw === INITIAL_PW || pw === username) return 'La clave nueva no puede ser la inicial ni el nombre de usuario';
|
||||
return null;
|
||||
}
|
||||
|
||||
// Middleware montado en /api: público solo /health, /auth/login, /auth/first-password y /system/nodo.
|
||||
const PUBLIC = new Set(['/health', '/auth/login', '/auth/first-password', '/system/nodo']);
|
||||
function middleware(req, res, next) {
|
||||
if (PUBLIC.has(req.path)) return next();
|
||||
const u = sessionUser(req);
|
||||
if (!u) return res.status(401).json({ error: 'No autenticado' });
|
||||
req.user = u;
|
||||
next();
|
||||
}
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Frenito contra fuerza bruta: 10 intentos fallidos por IP cada 5 min.
|
||||
const fails = new Map();
|
||||
function tooMany(ip) {
|
||||
const f = fails.get(ip);
|
||||
return f && f.n >= 10 && Date.now() - f.t < 300000;
|
||||
}
|
||||
function fail(ip) {
|
||||
const f = fails.get(ip);
|
||||
if (!f || Date.now() - f.t > 300000) fails.set(ip, { n: 1, t: Date.now() }); else f.n++;
|
||||
}
|
||||
|
||||
router.post('/login', (req, res) => {
|
||||
const { username, password } = req.body || {};
|
||||
if (tooMany(req.ip)) return res.status(429).json({ error: 'Demasiados intentos. Prueba de nuevo en unos minutos.' });
|
||||
const u = db.prepare('SELECT * FROM users WHERE username = ?').get(String(username || ''));
|
||||
if (!u || !checkPw(u, String(password || ''))) {
|
||||
fail(req.ip);
|
||||
event('warn', 'Login fallido', { username: String(username || '').slice(0, 40) });
|
||||
return res.status(401).json({ error: 'Usuario o contraseña incorrectos' });
|
||||
}
|
||||
if (u.must_change) {
|
||||
const token = crypto.randomBytes(24).toString('hex');
|
||||
changeTokens.set(token, { username: u.username, exp: Date.now() + CHANGE_MS });
|
||||
return res.json({ must_change: true, token, username: u.username, min: MIN_PW });
|
||||
}
|
||||
newSession(res, u.username);
|
||||
event('info', 'Ingreso al panel', { username: u.username });
|
||||
res.json({ user: { username: u.username, role: u.role } });
|
||||
});
|
||||
|
||||
router.post('/first-password', (req, res) => {
|
||||
const { token, password, password2 } = req.body || {};
|
||||
const c = changeTokens.get(String(token || ''));
|
||||
if (!c || c.exp < Date.now()) return res.status(401).json({ error: 'El pase venció: vuelve a entrar con la clave inicial' });
|
||||
const err = pwRules(c.username, password, password2);
|
||||
if (err) return res.status(400).json({ error: err });
|
||||
changeTokens.delete(token);
|
||||
setPassword(c.username, password);
|
||||
newSession(res, c.username);
|
||||
event('info', 'Clave inicial cambiada', { username: c.username });
|
||||
res.json({ user: { username: c.username, role: 'admin' } });
|
||||
});
|
||||
|
||||
router.get('/me', (req, res) => res.json({ user: req.user }));
|
||||
|
||||
router.post('/password', (req, res) => {
|
||||
const { current, password, password2 } = req.body || {};
|
||||
const u = db.prepare('SELECT * FROM users WHERE username = ?').get(req.user.username);
|
||||
if (!checkPw(u, String(current || ''))) return res.status(400).json({ error: 'La clave actual no es correcta' });
|
||||
const err = pwRules(u.username, password, password2);
|
||||
if (err) return res.status(400).json({ error: err });
|
||||
setPassword(u.username, password);
|
||||
newSession(res, u.username); // las otras sesiones quedan afuera (sver)
|
||||
event('info', 'Clave cambiada', { username: u.username });
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
router.post('/logout', (req, res) => {
|
||||
const tok = cookieOf(req);
|
||||
if (tok) db.prepare('DELETE FROM sessions WHERE token = ?').run(tok);
|
||||
res.setHeader('Set-Cookie', `${COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`);
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
module.exports = { router, middleware, MIN_PW };
|
||||
@@ -0,0 +1,130 @@
|
||||
'use strict';
|
||||
// channels.js — alta, edición y baja de canales, y su estado real.
|
||||
const express = require('express');
|
||||
const fs = require('fs');
|
||||
const { db, event } = require('../db');
|
||||
const V = require('../engine/validate');
|
||||
const status = require('../engine/status');
|
||||
|
||||
// Iniciar y parar desde el panel: apagado hasta cerrar la 078 (la otra sesión está
|
||||
// trabajando sobre las mismas instancias systemd del CT 176). Ver ~/tareas/079-paralelo.md.
|
||||
const CONTROL = process.env.ORBISUBS_CONTROL === '1';
|
||||
const CONTROL_OFF_MSG = 'Iniciar y parar: disponible al cerrar la 078';
|
||||
|
||||
const router = express.Router();
|
||||
const row2ch = r => ({ id: r.id, slug: r.slug, name: r.name, enabled: !!r.enabled, cfg: JSON.parse(r.cfg), created_at: r.created_at, updated_at: r.updated_at });
|
||||
const allChannels = () => db.prepare('SELECT * FROM channels ORDER BY id').all().map(row2ch);
|
||||
const getChannel = id => { const r = db.prepare('SELECT * FROM channels WHERE id = ?').get(Number(id)); return r ? row2ch(r) : null; };
|
||||
|
||||
function fail(res, e) {
|
||||
if (e instanceof V.ValidationError) return res.status(400).json({ error: e.message, field: e.field });
|
||||
throw e;
|
||||
}
|
||||
|
||||
router.get('/', async (req, res) => {
|
||||
const chs = allChannels();
|
||||
const st = await status.all(chs);
|
||||
res.json({ control: CONTROL, control_msg: CONTROL ? null : CONTROL_OFF_MSG, channels: chs.map(c => ({ ...c, status: st[c.id] })) });
|
||||
});
|
||||
|
||||
router.get('/:id', (req, res) => {
|
||||
const ch = getChannel(req.params.id);
|
||||
if (!ch) return res.status(404).json({ error: 'Canal inexistente' });
|
||||
res.json(ch);
|
||||
});
|
||||
|
||||
// Lo que muestra "Ver canal": últimos subtítulos por idioma y números.
|
||||
router.get('/:id/view', async (req, res) => {
|
||||
const ch = getChannel(req.params.id);
|
||||
if (!ch) return res.status(404).json({ error: 'Canal inexistente' });
|
||||
const st = (await status.all([ch]))[ch.id];
|
||||
st.metrics = status.metrics(ch, { last: 8 });
|
||||
res.json({ channel: ch, status: st, failures: await status.failures(ch) });
|
||||
});
|
||||
|
||||
router.post('/', (req, res) => {
|
||||
let ch;
|
||||
try {
|
||||
ch = V.channel(req.body);
|
||||
V.conflicts(ch, allChannels());
|
||||
} catch (e) { return fail(res, e); }
|
||||
const r = db.prepare('INSERT INTO channels (slug, name, enabled, cfg) VALUES (?, ?, ?, ?)').run(ch.slug, ch.name, ch.enabled ? 1 : 0, JSON.stringify(ch.cfg));
|
||||
event('info', `Canal creado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
|
||||
res.status(201).json(getChannel(r.lastInsertRowid));
|
||||
});
|
||||
|
||||
router.put('/:id', async (req, res) => {
|
||||
const old = getChannel(req.params.id);
|
||||
if (!old) return res.status(404).json({ error: 'Canal inexistente' });
|
||||
let ch;
|
||||
try {
|
||||
ch = V.channel(req.body);
|
||||
V.conflicts(ch, allChannels().filter(o => o.id !== old.id));
|
||||
} catch (e) { return fail(res, e); }
|
||||
// Renombrar el id corto con el canal andando dejaría instancias huérfanas con el nombre viejo.
|
||||
if (ch.slug !== old.slug) {
|
||||
const st = (await status.all([old]))[old.id];
|
||||
if (st.units.some(u => u.active === 'active' || u.active === 'activating')) {
|
||||
return res.status(409).json({ error: 'Detén el canal antes de cambiarle el id corto', field: 'slug' });
|
||||
}
|
||||
}
|
||||
db.prepare("UPDATE channels SET slug = ?, name = ?, enabled = ?, cfg = ?, updated_at = datetime('now') WHERE id = ?")
|
||||
.run(ch.slug, ch.name, ch.enabled ? 1 : 0, JSON.stringify(ch.cfg), old.id);
|
||||
event('info', `Canal editado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
|
||||
res.json(getChannel(old.id));
|
||||
});
|
||||
|
||||
router.delete('/:id', async (req, res) => {
|
||||
const ch = getChannel(req.params.id);
|
||||
if (!ch) return res.status(404).json({ error: 'Canal inexistente' });
|
||||
const st = (await status.all([ch]))[ch.id];
|
||||
if (st.units.some(u => u.active === 'active' || u.active === 'activating')) {
|
||||
return res.status(409).json({ error: 'El canal está andando: detenlo antes de borrarlo' });
|
||||
}
|
||||
db.prepare('DELETE FROM channels WHERE id = ?').run(ch.id);
|
||||
event('warn', `Canal borrado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
for (const act of ['start', 'stop']) {
|
||||
router.post(`/:id/${act}`, (req, res) => {
|
||||
if (!CONTROL) return res.status(409).json({ error: CONTROL_OFF_MSG });
|
||||
res.status(501).json({ error: 'Sin implementar' });
|
||||
});
|
||||
}
|
||||
|
||||
// Base nueva: T13 (el canal de la 076-078, configurado a mano) entra como un canal
|
||||
// más, con lo que dice su /etc/orbisubs/t13.env. Solo se lee.
|
||||
function seedT13() {
|
||||
if (db.prepare('SELECT 1 FROM channels LIMIT 1').get()) return;
|
||||
const file = (process.env.ORBISUBS_ETC || '/etc/orbisubs') + '/t13.env';
|
||||
let env;
|
||||
try {
|
||||
env = {};
|
||||
for (const l of fs.readFileSync(file, 'utf8').split('\n')) {
|
||||
const m = /^([A-Z_][A-Z0-9_]*)=(.*)$/.exec(l.trim());
|
||||
if (m) env[m[1]] = m[2];
|
||||
}
|
||||
} catch { return; }
|
||||
const body = {
|
||||
name: 'T13', slug: 't13', enabled: true,
|
||||
cfg: {
|
||||
input: /^https?:/.test(env.INPUT || '') ? { kind: 'hls', url: env.INPUT } : { kind: 'hls', url: 'http://invalido/' },
|
||||
asr: { lang: 'es', url: env.URL || 'http://192.168.2.10:8004', prompt: '' },
|
||||
tr: { langs: /--en\b/.test(env.ASR_EXTRA || '') ? ['en'] : [], url: env.LLM_URL, model: env.LLM_MODEL },
|
||||
hls: { enabled: true, seg_s: 6, list_size: 10 },
|
||||
srt: env.SRT_PORT ? {
|
||||
enabled: true, mode: 'listener', port: Number(env.SRT_PORT), latency_ms: 200, delay_s: Number(env.SRT_DELAY || 24),
|
||||
cc608: { es: 'CC1', en: 'CC3' }, cc708: { es: 1, en: 2 },
|
||||
} : { enabled: false },
|
||||
},
|
||||
};
|
||||
try {
|
||||
const ch = V.channel(body);
|
||||
db.prepare('INSERT INTO channels (slug, name, enabled, cfg) VALUES (?, ?, ?, ?)').run(ch.slug, ch.name, 1, JSON.stringify(ch.cfg));
|
||||
event('info', 'T13 importado de /etc/orbisubs/t13.env', { channel: 't13' });
|
||||
} catch (e) { console.warn('[orbisubs-panel] no se pudo importar T13:', e.message); }
|
||||
}
|
||||
seedT13();
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,61 @@
|
||||
'use strict';
|
||||
// server.js — panel de OrbiSubs (Express, puerto 4700). Hermano de OrbiStream:
|
||||
// misma base técnica (Express + better-sqlite3, panel en public/ sin framework).
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const express = require('express');
|
||||
|
||||
const PORT = parseInt(process.env.PORT, 10) || 4700;
|
||||
const { db } = require('./db');
|
||||
const auth = require('./routes/auth');
|
||||
const pkg = require('../package.json');
|
||||
|
||||
const app = express();
|
||||
app.set('trust proxy', 'loopback');
|
||||
app.use(express.json({ limit: '64kb' }));
|
||||
|
||||
app.use('/api', auth.middleware);
|
||||
app.use('/api/auth', auth.router);
|
||||
app.get('/api/health', (req, res) => res.json({ status: 'ok' }));
|
||||
|
||||
// Datos del pie común (node-foot.js): producto, hora del nodo, CT e IPs.
|
||||
function nodoConf() {
|
||||
const o = {};
|
||||
try {
|
||||
for (const l of fs.readFileSync('/etc/orbitv/nodo.conf', 'utf8').split('\n')) {
|
||||
const m = /^([A-Z_]+)=["']?(.*?)["']?$/.exec(l.trim());
|
||||
if (m) o[m[1]] = m[2];
|
||||
}
|
||||
} catch { /* sin nodo.conf */ }
|
||||
return o;
|
||||
}
|
||||
app.get('/api/system/nodo', (req, res) => {
|
||||
const n = nodoConf();
|
||||
const ips = [];
|
||||
for (const [ifn, addrs] of Object.entries(os.networkInterfaces())) {
|
||||
for (const a of addrs || []) if (a.family === 'IPv4' && !a.internal) ips.push({ role: n[`RED_${ifn.toUpperCase()}`] || ifn, ip: a.address });
|
||||
}
|
||||
res.json({
|
||||
now: Date.now(),
|
||||
tz: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
product: 'OrbiSubs', version: pkg.version,
|
||||
ct_id: n.CT_ID || process.env.CT_ID || null, pve: n.PVE || process.env.PVE || null,
|
||||
hostname: os.hostname(), ips,
|
||||
});
|
||||
});
|
||||
|
||||
app.use('/api/channels', require('./routes/channels'));
|
||||
app.get('/api/events', (req, res) => {
|
||||
res.json(db.prepare('SELECT * FROM events ORDER BY id DESC LIMIT 200').all());
|
||||
});
|
||||
|
||||
app.use(express.static(path.join(__dirname, 'public')));
|
||||
app.get('*', (req, res, next) => (req.path.startsWith('/api') ? next() : res.sendFile(path.join(__dirname, 'public', 'index.html'))));
|
||||
|
||||
app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars
|
||||
console.error('[orbisubs-panel]', err);
|
||||
res.status(err.status || 500).json({ error: err.status ? err.message : 'Error interno' });
|
||||
});
|
||||
|
||||
app.listen(PORT, () => console.log(`[orbisubs-panel] escuchando en :${PORT}`));
|
||||
@@ -0,0 +1,52 @@
|
||||
'use strict';
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert');
|
||||
const V = require('../src/engine/validate');
|
||||
|
||||
const base = (over = {}) => ({
|
||||
name: 'Canal', slug: 'c1',
|
||||
cfg: {
|
||||
input: { kind: 'srt', mode: 'caller', host: '192.168.10.40', port: 10013, latency_ms: 200 },
|
||||
asr: { lang: 'es' }, tr: { langs: ['en'] }, hls: { enabled: true },
|
||||
srt: { enabled: true, mode: 'listener', port: 9002, delay_s: 24, cc608: { es: 'CC1', en: 'CC3' }, cc708: { es: 1, en: 2 } },
|
||||
...over,
|
||||
},
|
||||
});
|
||||
|
||||
test('canal válido se normaliza', () => {
|
||||
const c = V.channel(base());
|
||||
assert.strictEqual(c.cfg.srt.port, 9002);
|
||||
assert.deepStrictEqual(c.cfg.srt.cc608, { es: 'CC1', en: 'CC3' });
|
||||
assert.strictEqual(c.cfg.asr.url, 'http://192.168.2.10:8004');
|
||||
});
|
||||
|
||||
test('dos canales con el mismo puerto SRT no se pueden guardar', () => {
|
||||
const a = V.channel(base());
|
||||
const b = V.channel({ ...base(), slug: 'c2' });
|
||||
assert.throws(() => V.conflicts(b, [{ name: 'Canal', ...a }]), /9002/);
|
||||
// El siguiente también está tomado (prueba interna de la 078).
|
||||
const c = V.channel({ ...base({ srt: { ...base().cfg.srt, port: 9003 } }), slug: 'c3' });
|
||||
assert.throws(() => V.conflicts(c, [{ name: 'Canal', ...a }]), /9003/);
|
||||
// Entrada SRT listener contra salida de otro canal.
|
||||
const d = V.channel({ ...base({ input: { kind: 'srt', mode: 'listener', port: 9002 }, srt: { enabled: false } }), slug: 'c4' });
|
||||
assert.throws(() => V.conflicts(d, [{ name: 'Canal', ...a }]), /9002/);
|
||||
});
|
||||
|
||||
test('id repetido', () => {
|
||||
const a = V.channel(base());
|
||||
assert.throws(() => V.conflicts(V.channel({ ...base(), cfg: { ...base().cfg, srt: { enabled: false } } }), [{ name: 'Canal', ...a }]), /id corto/);
|
||||
});
|
||||
|
||||
test('URL de entrada mal armada', () => {
|
||||
assert.throws(() => V.channel(base({ input: { kind: 'hls', url: 'htp:/x' } })), /http/);
|
||||
assert.throws(() => V.channel(base({ input: { kind: 'hls', url: 'https://cdn/x.mp4' } })), /m3u8/);
|
||||
assert.throws(() => V.channel(base({ input: { kind: 'udp', url: 'udp://239.1.1.1' } })), /UDP/);
|
||||
assert.throws(() => V.channel(base({ input: { kind: 'srt', mode: 'caller', host: '', port: 1 } })), /host/);
|
||||
assert.throws(() => V.channel(base({ input: { kind: 'srt', mode: 'caller', host: 'a', port: 1, passphrase: 'corta' } })), /passphrase/);
|
||||
});
|
||||
|
||||
test('608 repetido entre idiomas y puertos del sistema', () => {
|
||||
assert.throws(() => V.channel(base({ srt: { ...base().cfg.srt, cc608: { es: 'CC1', en: 'CC1' } } })), /repetido/);
|
||||
assert.throws(() => V.channel(base({ srt: { ...base().cfg.srt, port: 4699 } })), /sistema/);
|
||||
assert.throws(() => V.channel({ ...base(), slug: 't13-cc' }), /-cc/);
|
||||
});
|
||||
Reference in New Issue
Block a user