'use strict'; // Staging only. Never writes OBS settings, never changes the live :4178 service. const http=require('node:http'),fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto'); const port=Number(process.env.PORT||4180),clients=new Set();let last={status:'waiting',source:'obs-meter'},ws,closing=false,reconnect; const config=process.env.OBS_WEBSOCKET_CONFIG||path.join(process.env.HOME,'Library/Application Support/obs-studio/plugin_config/obs-websocket/config.json'); function emit(data){last={...data,at:Date.now(),source:'obs-meter'};for(const c of clients)c.write('data: '+JSON.stringify(last)+'\n\n')} function connect(){if(closing)return;let cfg;try{cfg=JSON.parse(fs.readFileSync(config,'utf8'))}catch{emit({error:'OBS control configuration unavailable'});reconnect=setTimeout(connect,3000);return} ws=new WebSocket('ws://127.0.0.1:'+(cfg.server_port||4455));ws.onmessage=e=>{try{const m=JSON.parse(e.data);if(m.op===0){const d={rpcVersion:1,eventSubscriptions:65536};if(m.d.authentication){const h=s=>crypto.createHash('sha256').update(s).digest('base64');d.authentication=h(h(cfg.server_password+m.d.authentication.salt)+m.d.authentication.challenge)}ws.send(JSON.stringify({op:1,d}))} if(m.op===2)emit({status:'connected'}); if(m.op===5&&m.d.eventType==='InputVolumeMeters'){const source=m.d.eventData.inputs.find(i=>i.inputName==='macOS Audio Capture');if(!source)return;const channels=source.inputLevelsMul||[];let rms=0,peak=0;for(const c of channels){rms=Math.max(rms,Number(c[0])||0);peak=Math.max(peak,Number(c[1])||0)}emit({status:'audio',rms,peak,input:source.inputName})}}catch(err){console.error('Meter message:',err.message)}}; ws.onerror=()=>{};ws.onclose=()=>{emit({status:'disconnected'});if(!closing)reconnect=setTimeout(connect,3000)}; } const server=http.createServer((req,res)=>{if(req.url==='/audio'){res.writeHead(200,{'Content-Type':'text/event-stream','Cache-Control':'no-store','Connection':'keep-alive'});res.write('data: '+JSON.stringify(last)+'\n\n');clients.add(res);req.on('close',()=>clients.delete(res));return}if(req.url==='/health'){res.setHeader('Content-Type','application/json');res.end(JSON.stringify(last));return}if(req.url!=='/'){res.writeHead(404);res.end();return}res.setHeader('Content-Type','text/html; charset=utf-8');res.setHeader('Cache-Control','no-store');fs.createReadStream(path.join(__dirname,'index.html')).pipe(res)}); server.listen(port,'127.0.0.1',()=>{console.log('Isolated staging listening on loopback port '+port);connect()}); const heartbeat=setInterval(()=>{for(const c of clients)c.write(': heartbeat\n\n')},10000); function stop(){closing=true;clearTimeout(reconnect);clearInterval(heartbeat);ws?.close();for(const c of clients)c.end();server.close(()=>process.exit())}process.on('SIGTERM',stop);process.on('SIGINT',stop);