Files
bpq_gui/winlink-radio.mjs
T

44 lines
7.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {readFile,writeFile,rename,mkdir,copyFile} from 'node:fs/promises';
import path from 'node:path';
import {forwardingHistory} from './forwarding.mjs';
export function rawProfile(text,peer){const escaped=peer.replace(/[.*+?^${}()|[\]\\]/g,'\\$&'),block=text.match(new RegExp('\\b'+escaped+'\\s*:\\s*\\{([^{}]*)\\}'));if(!block)throw new Error('Profilo RMS non presente in BPQ');const fields={};for(const m of block[1].matchAll(/\b(\w+)\s*=\s*(?:"([^"\r\n]*)"|(\d+))\s*;/g))fields[m[1]]=m[2]??m[3];return fields;}
const textKeys=['TOCalls','ATCalls','FWDTimes','ConnectScript','HRoutes','HRoutesP','BBSHA'];
const keyOrder=['Enabled','FwdInterval','RequestReverse','RevFWDInterval','FWDNewImmediately','AllowBlocked','MaxFBBBlock','FWDPersonalsOnly','AllowCompressed','UseB1Protocol','UseB2Protocol','SendCTRLZ','ConTimeout'];
const booleans=new Set(['Enabled','RequestReverse','FWDNewImmediately','AllowBlocked','FWDPersonalsOnly','AllowCompressed','UseB1Protocol','UseB2Protocol','SendCTRLZ']);
export function profilePayload(fields){return [...textKeys.map(k=>(fields[k]||'').replaceAll('|','\r\n')),...keyOrder.map(k=>booleans.has(k)?fields[k]==='1'?'true':'false':String(Number(fields[k])||0)),''].join('|');}
export function activeMailStreams(html){const options=[...html.matchAll(/<option\b[^>]*value=["']?\d+["']?[^>]*>([\s\S]*?)<\/option>/gi)];if(!options.length)throw new Error('Stato sessioni BBS non verificabile');return options.map(m=>m[1].replace(/&nbsp;/g,' ').replace(/<[^>]*>/g,'').trim()).filter(s=>s&&!/^Idle\b/i.test(s));}
export function radioProfile(original,channel,port){
if(!Number.isInteger(port)||port<1||port>64||! /^(?=.*\d)[A-Z0-9]{3,7}(?:-\d{1,2})?$/.test(channel.call)||!Number.isInteger(channel.dialHz)||channel.dialHz<1e6||channel.dialHz>30e6)throw new Error('Canale radio non valido');
return {...original,ConnectScript:`ATTACH ${port}|RADIO ${(channel.dialHz/1e6).toFixed(6)} USB|PAUSE 2|C ${channel.call}`,Enabled:'0',FWDNewImmediately:'0',UseB1Protocol:'0',UseB2Protocol:'1',AllowBlocked:'1',AllowCompressed:'1',FWDPersonalsOnly:'1'};
}
export class WinlinkRadio{
constructor(config,dir,forwarding,directory){this.config=config;this.fwd=forwarding;this.directory=directory;this.file=path.join(dir,'winlink-radio.session.json');this.job=null;this.busy=false;this.recovered=false;this.init=this.recover();this.timer=setInterval(()=>this.tick().catch(()=>{}),4000);this.timer.unref();}
async persist(){await writeFile(this.file+'.tmp',JSON.stringify(this.job));await rename(this.file+'.tmp',this.file);}
async recover(){try{this.job=JSON.parse(await readFile(this.file,'utf8'));if(this.job?.restoring){this.fwd.lockedPeers.set(this.job.peer,'Sessione Winlink radio da ripristinare');this.recovered=true;}}catch{} }
snapshot(){const j=this.job;return j?{channel:j.channel,startedAt:j.startedAt,endedAt:j.endedAt||null,state:j.state,error:j.error||null,restoring:j.restoring,sent:j.sent??null,received:j.received??null}:null;}
async saveNative(fields){const key=await this.fwd.context();await this.fwd.bpq('/Mail/FwdDetails?'+key,{method:'POST',body:this.job.peer});await this.fwd.bpq('/Mail/FWDSave?'+key,{method:'POST',body:profilePayload(fields)});this.fwd.cached=null;return key;}
async currentProfile(){return rawProfile(await readFile(path.join(this.config.root,'BPQMailChat','BPQMail.cfg'),'utf8'),this.job?.peer||this.config.cmsPeer||'RMS');}
async restore(){await this.init;return this.fwd.exclusive(async()=>{if(!this.job?.restoring)return this.snapshot();if(activeMailStreams(await this.fwd.bpq('/Mail/Status')).length)throw new Error('Attendi la fine della sessione BBS prima di ripristinare Internet');await this.saveNative(this.job.original);this.job.restoring=false;this.job.endedAt=new Date().toISOString();this.job.state='ended';this.job.error=null;this.fwd.lockedPeers.delete(this.job.peer);await this.persist();return this.snapshot();});}
async start(id){await this.init;return this.fwd.exclusive(async()=>{
if(this.job?.restoring)throw new Error('Una sessione Winlink radio è già in corso o in ripristino');
if(!this.config.radio||!this.config.winlinkRadio?.catControl)throw new Error('Controllo frequenza CAT per Winlink radio non configurato');
const channel=await this.directory.selected(id),peer=this.config.cmsPeer||'RMS',now=Date.now(),radio=this.fwd.radio();
if(radio?.active||radio?.connecting)throw new Error('Modem impegnato: attendi la fine della connessione');
if(!radio?.available||now-(radio?.at||0)>20000)throw new Error('Telemetria radio non disponibile: impossibile verificare il modem');
if(now-(this.fwd.requested.get(peer)||0)<30000)throw new Error('Sync Winlink già richiesto: attendi');
const status=await this.fwd.bpq('/Mail/Status');if(activeMailStreams(status).length)throw new Error('Una sessione BBS è attiva: riprova al termine');
const original=rawProfile(await readFile(path.join(this.config.root,'BPQMailChat','BPQMail.cfg'),'utf8'),peer);if(!/^(?:RMS|C(?:ONNECT)?\s+\d+\s+CMS)$/i.test(original.ConnectScript?.trim()||''))throw new Error('Il profilo RMS non è impostato per Internet: verifica la configurazione prima del cambio');
const temporary=radioProfile(original,channel,this.config.radio.id),backup=path.join(this.config.root,'BPQMailChat','Backup-winlink-radio-'+new Date().toISOString().replace(/[:.]/g,'-'));await mkdir(backup);await copyFile(path.join(this.config.root,'BPQMailChat','BPQMail.cfg'),path.join(backup,'BPQMail.cfg'));
this.job={peer,channel:{id:channel.id,call:channel.call,dialHz:channel.dialHz,centerHz:channel.centerHz,mode:channel.mode,grid:channel.grid},original,temporary,startedAt:new Date().toISOString(),state:'requested',restoring:true};this.fwd.lockedPeers.set(peer,'Sessione Winlink radio in corso');await this.persist();
try{const key=await this.saveNative(temporary);await this.fwd.bpq('/Mail/FwdDetails?'+key,{method:'POST',body:peer});await this.fwd.bpq('/Mail/FWDSave?'+key,{method:'POST',body:'StartForward'});this.fwd.requested.set(peer,Date.now());return this.snapshot();}catch{this.job.state='error';this.job.error='Richiesta BPQ non confermata; verifica e ripristino automatico in corso';await this.persist();throw new Error(this.job.error);}
});}
async tick(){await this.init;if(!this.job?.restoring||this.busy)return;this.busy=true;try{await this.fwd.exclusive(async()=>{
const j=this.job,age=Date.now()-Date.parse(j.startedAt),h=forwardingHistory(await this.fwd.logs(),j.peer).find(s=>Date.parse(s.startedAt)>=Date.parse(j.startedAt)-2000),streams=activeMailStreams(await this.fwd.bpq('/Mail/Status'));
if(h){j.sent=h.sent;j.received=h.received;j.state=h.endedAt?h.status:h.connectedAt?'connected':'calling';}
if(streams.length||(!h?.endedAt&&age<45000)){await this.persist();return;}
const current=await this.currentProfile();if(profilePayload(current)!==profilePayload(j.temporary)&&profilePayload(current)!==profilePayload(j.original)){j.state='conflict';j.error='Il profilo RMS è stato modificato durante la sessione: ripristino automatico sospeso';await this.persist();return;}
if(profilePayload(current)!==profilePayload(j.original))await this.saveNative(j.original);
j.restoring=false;j.endedAt=h?.endedAt||new Date().toISOString();j.state=h?.status||'failed';if(!h)j.error='BPQ non ha registrato l’avvio della sessione';this.fwd.lockedPeers.delete(j.peer);await this.persist();
});}catch{this.job.error='Ripristino del profilo RMS in attesa: BPQ non disponibile';}finally{this.busy=false;}}
}