import {readFile,writeFile,rename,mkdir,copyFile} from 'node:fs/promises'; import path from 'node:path'; import {reservePacketSlot,releasePacketSlot} from './radio-slot.mjs'; import {WinlinkRadio,rawProfile,activeMailStreams} from './winlink-radio.mjs'; import {safeScript,parseForwarding} from './forwarding.mjs'; export function manualRoutes(config){ const ids=new Set();return (config.manualForwardingRoutes||[]).map(route=>{ if(!/^[A-Z0-9-]{1,32}$/.test(route.id)||route.id===route.peer||ids.has(route.id)||! /^[A-Z0-9]{1,6}$/.test(route.peer)||! /^[A-Z0-9]{3,7}(?:-\d{1,2})?$/.test(route.connectCall)||!Number.isFinite(route.frequencyMHz)||route.frequencyMHz<1||route.frequencyMHz>500||! /^(USB|LSB|FM|DATA-FM)$/.test(route.mode)||!config.ports.some(p=>p.id===route.port&&!/TELNET|AXIP/i.test(p.driver)))throw Error('Percorso manuale di forwarding non valido'); if(route.controller&&(!path.isAbsolute(route.controller.requestFile||'')||!path.isAbsolute(route.controller.statusFile||'')))throw Error('Percorsi del controllo radio non validi'); ids.add(route.id);return {...route,label:String(route.label||route.id).slice(0,80),script:`ATTACH ${route.port}|RADIO ${route.frequencyMHz.toFixed(6)} ${route.mode}|PAUSE 2|C ${route.connectCall}`}; }); } export class ManualForwarding extends WinlinkRadio{ constructor(config,dir,forwarding){super(config,dir,forwarding,null,{stateFile:'manual-forwarding.session.json'});this.routes=manualRoutes(config);} snapshot(){const state=super.snapshot();if(state?.error)state.error=state.error.replaceAll('profilo RMS','profilo del partner');return state;} async restore(){const state=await super.restore();await this.release();return state;} profiles(native){return this.routes.flatMap(route=>{const p=native.find(p=>p.call===route.peer);if(!p)return [];const j=this.job?.channel?.id===route.id?this.job:null;const history=j?p.history.filter(s=>Date.parse(s.startedAt)>=Date.parse(j.startedAt)-1500&&(!j.endedAt||Date.parse(s.startedAt)<=Date.parse(j.endedAt))):[];return [{...p,call:route.id,label:route.label,peer:route.peer,manualOnly:true,enabled:false,interval:0,immediate:false,reverseInterval:0,times:[],configured:true,port:route.port,driver:this.config.ports.find(p=>p.id===route.port)?.driver||'',transport:'Radio',frequency:[String(route.frequencyMHz),route.mode],script:safeScript(route.script),history,last:history[0]||null,active:Boolean(j?.restoring),preparing:j?.state==='preparing',requestedAt:j?.startedAt||null,nextEstimated:null}];});} async prepare(route,signal){await reservePacketSlot(this,route.controller,route.frequencyMHz,route.port,{signal});} async release(){await releasePacketSlot(this);} displayProfiles(native){const j=this.job;const base=native.map(p=>{if(!j||j.peer!==p.call)return p;const history=p.history.filter(s=>!(Date.parse(s.startedAt)>=Date.parse(j.startedAt)-1500&&(!j.endedAt||Date.parse(s.startedAt)<=Date.parse(j.endedAt))));const original=parseForwarding('BBSForwarding : { '+p.call+' : { '+Object.entries(j.original||{}).map(([k,v])=>k+' = "'+String(v).replaceAll('"','')+'";').join(' ')+' } }',this.config.ports)[0];return {...p,...(j.restoring?original:{}),history,last:history[0]||null,active:j.restoring?false:p.active,reservedBy:j.restoring?j.channel.id:null};});return [...base,...this.profiles(native)];} async startRoute(id,{signal}={}){await this.init;return this.fwd.exclusive(async()=>{ signal?.throwIfAborted();const route=this.routes.find(r=>r.id===id);if(!route)throw Error('Percorso manuale non configurato'); if(this.job?.restoring||this.fwd.lockedPeers.has(route.peer))throw Error('Un inoltro per questo partner è già in corso'); if(!(await this.fwd.profiles()).some(p=>p.call===route.peer&&p.configured))throw Error('Partner BBS non configurato'); const radio=this.fwd.radio();if(!radio?.available||radio.active||radio.connecting||Date.now()-radio.at>20000)throw Error('Radio non disponibile o impegnata'); if(activeMailStreams(await this.fwd.bpq('/Mail/Status')).length)throw Error('Attendi la fine delle sessioni BBS'); const file=path.join(this.config.root,'BPQMailChat','BPQMail.cfg'),original=rawProfile(await readFile(file,'utf8'),route.peer); const backup=path.join(this.config.root,'BPQMailChat','Backup-manual-forwarding-'+new Date().toISOString().replace(/[:.]/g,'-'));await mkdir(backup);await copyFile(file,path.join(backup,'BPQMail.cfg')); const disabled={...original,Enabled:'0',FWDNewImmediately:'0'}; this.job={peer:route.peer,channel:{id:route.id,call:route.connectCall,dialHz:Math.round(route.frequencyMHz*1e6),mode:route.mode},original,temporary:disabled,startedAt:new Date().toISOString(),state:'preparing',restoring:true}; this.busy=true;this.fwd.lockedPeers.set(route.peer,'Inoltro manuale in preparazione o in corso'); try{await this.persist();await this.saveNative(disabled);await this.prepare(route,signal);signal?.throwIfAborted(); if(activeMailStreams(await this.fwd.bpq('/Mail/Status')).length)throw Error('Una sessione BBS è iniziata: riprova al termine'); this.job.temporary={...disabled,ConnectScript:route.script};this.job.startedAt=new Date().toISOString();await this.persist();await this.saveNative(this.job.temporary); const key=await this.fwd.context();await this.fwd.bpq('/Mail/FwdDetails?'+key,{method:'POST',body:route.peer});signal?.throwIfAborted();await this.fwd.bpq('/Mail/FWDSave?'+key,{method:'POST',body:'StartForward'}); this.job.state='requested';this.fwd.requested.set(route.peer,Date.now());await this.persist();return {ok:true,peer:route.peer,route:id,requestedAt:this.job.startedAt}; }catch(error){this.job.state=signal?.aborted?'cancelled':'failed';this.job.error=signal?.aborted?null:error.message;if(!activeMailStreams(await this.fwd.bpq('/Mail/Status')).length){await this.saveNative(original);this.job.restoring=false;this.job.endedAt=new Date().toISOString();this.fwd.lockedPeers.delete(route.peer);await this.release();}await this.persist();throw error;} finally{this.busy=false;} });} async tick(){await super.tick();if(this.job&&!this.job.restoring)await this.release();} }