AvanzaCast/packages/broadcast-panel/scripts/connect-via-backend.js

83 lines
3.0 KiB
JavaScript

#!/usr/bin/env node
/* connect-via-backend.js
Simple script de prueba que solicita al backend /api/connection-details y luego intenta una conexión WebSocket al servidor LiveKit
USO: node scripts/connect-via-backend.js --backend http://localhost:4000 --room test_room --name tester
*/
import fetch from 'node-fetch';
import WebSocket from 'ws';
import { argv } from 'process';
function parseArgs() {
const out = { backend: 'http://localhost:4000', room: 'test_room', name: 'tester' };
for (let i = 2; i < argv.length; i++) {
const a = argv[i];
if (a === '--backend' && argv[i+1]) { out.backend = argv[i+1]; i++; continue }
if (a === '--room' && argv[i+1]) { out.room = argv[i+1]; i++; continue }
if (a === '--name' && argv[i+1]) { out.name = argv[i+1]; i++; continue }
}
return out;
}
(async () => {
const { backend, room, name } = parseArgs();
console.log('Requesting token from backend:', backend, 'room=', room, 'name=', name);
try {
const resp = await fetch(`${backend}/api/connection-details?room=${encodeURIComponent(room)}&participantName=${encodeURIComponent(name)}`);
if (!resp.ok) {
console.error('Backend responded', resp.status, await resp.text());
process.exit(2);
}
const json = await resp.json();
console.log('Backend returned:', json);
const { serverUrl, participantToken } = json;
if (!serverUrl || !participantToken) {
console.error('Missing serverUrl or participantToken in backend response');
process.exit(3);
}
// Build wss url param if serverUrl is http(s)
let wsUrl = serverUrl;
if (wsUrl.startsWith('http://')) wsUrl = wsUrl.replace(/^http:\/\//, 'ws://');
if (wsUrl.startsWith('https://')) wsUrl = wsUrl.replace(/^https:\/\//, 'wss://');
// append path if not present
if (!wsUrl.endsWith('/')) wsUrl = wsUrl.replace(/\/$/, '');
const connectUrl = `${wsUrl}/rtc?access_token=${encodeURIComponent(participantToken)}`;
console.log('Attempting WebSocket connect to', connectUrl.slice(0,200));
const ws = new WebSocket(connectUrl, { rejectUnauthorized: false });
let connected = false;
ws.on('open', () => {
connected = true;
console.log('WebSocket opened OK');
// close after a short timeout
setTimeout(() => { ws.close(); }, 1500);
});
ws.on('message', (msg) => {
try { console.log('Message:', msg.toString().slice(0,200)); } catch (e) { }
});
ws.on('close', (code, reason) => {
console.log('WebSocket closed', code, reason && reason.toString ? reason.toString() : reason);
process.exit(0);
});
ws.on('error', (err) => {
console.error('WebSocket error', err && err.message ? err.message : err);
if (!connected) process.exit(4);
});
// Timeout if no connect
setTimeout(() => {
if (!connected) {
console.error('Connection timeout');
process.exit(5);
}
}, 8000);
} catch (e) {
console.error('Script failed', String(e));
process.exit(1);
}
})();