import {readFile,writeFile,rename,mkdir,copyFile} from 'node:fs/promises'; import path from 'node:path'; import {channelSupport} from './winlink-gateways.mjs'; import {reservePacketSlot,releasePacketSlot,renewPacketSlot} from './radio-slot.mjs'; 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(/]*value=["']?\d+["']?[^>]*>([\s\S]*?)<\/option>/gi)];if(!options.length)throw new Error('Stato sessioni BBS non verificabile');return options.map(m=>m[1].replace(/ /g,' ').replace(/<[^>]*>/g,'').trim()).filter(s=>s&&!/^Idle\b/i.test(s));} export function radioProfile(original,channel,port,{nativeKiss=false}={}){ const packet=channel.family==='Packet'; 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>(packet?500e6:30e6))throw new Error('Canale radio non valido'); return {...original,ConnectScript:packet&&nativeKiss?`C ${port} !${channel.call}`:`ATTACH ${port}|RADIO ${(channel.dialHz/1e6).toFixed(6)} ${packet?'DATA-FM':'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,options={}){this.config=config;this.fwd=forwarding;this.directory=directory;this.file=path.join(dir,options.stateFile||'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();await releasePacketSlot(this);return this.snapshot();});} async start(id,{signal}={}){await this.init;return this.fwd.exclusive(async()=>{ signal?.throwIfAborted();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(); const independent=channel.family==='Packet'&&this.config.winlinkRadio?.packetController?.independent===true; if(radio?.txSuspended||independent&&radio?.portsPaused?.[this.config.winlinkRadio.packetPort]||!independent&&radio?.portSuspended)throw new Error('Trasmissioni radio sospese'); if(!independent&&(radio?.active||radio?.connecting))throw new Error('Modem impegnato: attendi la fine della connessione'); if(!independent&&(!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 support=channelSupport(this.config,channel.family?channel:{...channel,family:channel.mode});if(!support.supported)throw Error(support.reason); const nativeKiss=independent&&/KISS/i.test(this.config.ports.find(p=>p.id===support.port)?.driver||''); const temporary=radioProfile(original,channel,support.port,{nativeKiss}),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(); this.busy=true;try{if(channel.family==='Packet'&&this.config.winlinkRadio?.packetController){this.job.temporary={...original,Enabled:'0',FWDNewImmediately:'0'};this.job.state='preparing';await this.persist();await this.saveNative(this.job.temporary);await reservePacketSlot(this,this.config.winlinkRadio.packetController,channel.dialHz/1e6,support.port,{signal});signal?.throwIfAborted();if(activeMailStreams(await this.fwd.bpq('/Mail/Status')).length)throw Error('Una sessione BBS è iniziata: riprova al termine');this.job.temporary=temporary;this.job.startedAt=new Date().toISOString();this.job.state='requested';await this.persist();}const key=await this.saveNative(temporary);await this.fwd.bpq('/Mail/FwdDetails?'+key,{method:'POST',body:peer});signal?.throwIfAborted();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);}finally{this.busy=false;} });} async tick(){await this.init;if(!this.job?.restoring||this.busy)return;this.busy=true;try{await this.fwd.exclusive(async()=>{ await renewPacketSlot(this); 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); await releasePacketSlot(this);j.restoring=false;j.endedAt=h?.endedAt||new Date().toISOString();j.state=h?.status||'failed';if(!h&&!j.error)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;}} }