64 lines
7.5 KiB
JavaScript
64 lines
7.5 KiB
JavaScript
import {readFile,readdir} from 'node:fs/promises';
|
|
import path from 'node:path';
|
|
import {parseBbsLog} from './journal.mjs';
|
|
|
|
const lines=value=>String(value||'').split(/[|\r\n]+/).map(s=>s.trim()).filter(Boolean);
|
|
export function safeScript(value){return lines(value).map(l=>/^(?:RMS|CMS|ATTACH\s+\d+|RADIO\s+[\d.]+\s+[A-Z0-9 ]+|PAUSE\s+\d+|OVERRIDEBUSY|INTERLOCK\s+\d+|TIMES\s+[\d-]+|ELSE|C(?:ONNECT)?\s+(?:\d+\s+)?[A-Z0-9:-]+|MSGTYPES\s+[A-Z0-9]+)$/i.test(l)?l:'[Comando riservato o non visualizzabile]');}
|
|
export function parseForwarding(text,ports=[]){
|
|
const section=text.split(/BBSForwarding\s*:\s*\{/)[1]?.split(/\nBBSUsers\s*:/)[0]||'';const profiles=[];
|
|
for(const m of section.matchAll(/\b([A-Z0-9-]+)\s*:\s*\{([^{}]*)\}/g)){
|
|
const fields={};for(const f of m[2].matchAll(/\b(\w+)\s*=\s*(?:"([^"\r\n]*)"|(\d+))\s*;/g))fields[f[1]]=f[2]??f[3];
|
|
const script=fields.ConnectScript||'',port=Number(script.match(/\bATTACH\s+(\d+)/i)?.[1]||script.match(/\bC\s+(\d+)\s/i)?.[1])||null,driver=ports.find(p=>p.id===port)?.driver||'';
|
|
profiles.push({timesLocal:/^\s*Localtime\s*=\s*1\s*;/m.test(text),call:m[1],enabled:fields.Enabled==='1',interval:Number(fields.FwdInterval)||0,reverse:fields.RequestReverse==='1',reverseInterval:Number(fields.RevFWDInterval)||0,immediate:fields.FWDNewImmediately==='1',times:lines(fields.FWDTimes),ha:fields.BBSHA||'',to:lines(fields.TOCalls),at:lines(fields.ATCalls),bulletins:lines(fields.HRoutes),personal:lines(fields.HRoutesP),personalOnly:fields.FWDPersonalsOnly==='1',script:safeScript(script),port,driver,transport:/\b(?:CMS|RMS)\b/i.test(script)||/TELNET/i.test(driver)?'Internet':port&&!/AXIP/i.test(driver)?'Radio':/AXIP/i.test(driver)?'Rete AXIP':'Percorso BPQ',frequency:script.match(/\bRADIO\s+([\d.]+)\s+(\w+)/i)?.slice(1)||null,configured:Boolean(script.trim())});
|
|
}
|
|
return profiles;
|
|
}
|
|
export function nextForwarding(profile,last,now=Date.now(),queued=null){
|
|
if(!profile.enabled||!profile.configured||!profile.interval||(!profile.reverse&&queued===0))return null;
|
|
if(!last?.startedAt)return null;
|
|
const bands=profile.times.length?profile.times:['0000-2359'];const valid=bands.map(b=>b.match(/^(\d{2})(\d{2})-(\d{2})(\d{2})$/)).filter(Boolean).map(m=>[Number(m[1])*60+Number(m[2]),Number(m[3])*60+Number(m[4])]).filter(([a,b])=>a<=b&&b<1440);
|
|
if(!valid.length)return null;
|
|
let target=Date.parse(last.startedAt)+profile.interval*1000;if(!Number.isFinite(target))return null;
|
|
// BPQ owns the real timer; a missed estimate must not appear as a firm countdown.
|
|
if(target<now)target=now;
|
|
const day=new Date(target);if(profile.timesLocal)day.setHours(0,0,0,0);else day.setUTCHours(0,0,0,0);
|
|
for(let d=0;d<3;d++)for(const [start,end]of valid){let a,b;if(profile.timesLocal){const t=new Date(day);t.setDate(t.getDate()+d);t.setHours(Math.floor(start/60),start%60,0,0);a=+t;t.setHours(Math.floor(end/60),end%60,59,999);b=+t;}else{a=+day+d*86400000+start*60000;b=+day+d*86400000+(end+1)*60000-1;}if(target<=b)return new Date(Math.max(target,a)).toISOString();}
|
|
return null;
|
|
}
|
|
export function forwardingHistory(text,peer,now=Date.now()){
|
|
const filtered=text.split(/\r?\n/).filter(l=>l.match(/^\d{6} \d{2}:\d{2}:\d{2} [|<>?!]([A-Z0-9-]+)\s/)?.[1]===peer).join('\n');
|
|
// Some BPQ builds omit outgoing compression records. A remote turn after FS
|
|
// acknowledges the accepted outgoing batch; FS alone is not delivery evidence.
|
|
const confirmed=new Map();let session=null,proposals=0,accepted=0;
|
|
for(const line of filtered.split('\n')){const m=line.match(/^(\d{2})(\d{2})(\d{2}) (\d{2}:\d{2}:\d{2}) ([|<>?!])[A-Z0-9-]+\s+(.*)$/);if(!m)continue;const t=m[6];if(/Connecting to BBS|Incoming Connect from/i.test(t)){session=`20${m[1]}-${m[2]}-${m[3]}T${m[4]}Z`;proposals=0;accepted=0;}
|
|
if(m[5]==='>'&&/^F[ABC]\s/.test(t))proposals++;
|
|
if(m[5]==='<'&&/^FS\s/.test(t)){accepted=Math.min(proposals,(t.slice(3).match(/[+Y!]/g)||[]).length);proposals=0;}
|
|
else if(m[5]==='<'&&/^(?:FF|FQ|F[ABC]\s)/.test(t)&&accepted){confirmed.set(session,(confirmed.get(session)||0)+accepted);accepted=0;}
|
|
}
|
|
return parseBbsLog(filtered).map(s=>({startedAt:s.startedAt,endedAt:s.endedAt,connectedAt:s.connectedAt,sent:Math.max(s.sentMessages,confirmed.get(s.startedAt)||0),received:s.receivedMessages,status:s.endedAt?s.status:now-Date.parse(s.startedAt)>30*60000?'unknown':s.connectedAt?'connected':'calling',direction:s.direction,error:s.error||null,complete:s.exchangeComplete||false})).sort((a,b)=>Date.parse(b.startedAt)-Date.parse(a.startedAt)).slice(0,8);
|
|
}
|
|
export class Forwarding{
|
|
constructor(config,bpq,radio){this.config=config;this.bpq=bpq;this.radio=radio;this.chain=Promise.resolve();this.requested=new Map();this.lockedPeers=new Map();this.cached=null;this.cachedAt=0;}
|
|
exclusive(fn){const result=this.chain.then(fn);this.chain=result.catch(()=>{});return result;}
|
|
async profiles(){return parseForwarding(await readFile(path.join(this.config.root,'BPQMailChat','BPQMail.cfg'),'utf8'),this.config.ports);}
|
|
async context(){const status=await this.bpq('/Mail/Status');const link=status.match(/href=(\/Mail\/FWD\?[^\s>]+)/)?.[1];if(!link)throw new Error('Forwarding BPQ non disponibile');const page=await this.bpq(link);const key=page.match(/var Key\s*=\s*"([^"]+)"/)?.[1];if(!key)throw new Error('Sessione forwarding non disponibile');return key;}
|
|
async logs(){const dir=path.join(this.config.root,'Logs');const names=(await readdir(dir)).filter(n=>/^log_\d{6}_BBS\.txt$/i.test(n)).sort().slice(-7);return (await Promise.all(names.map(n=>readFile(path.join(dir,n),'utf8').catch(()=>'')))).join('\n');}
|
|
snapshot(){return this.exclusive(async()=>{
|
|
if(this.cached&&Date.now()-this.cachedAt<4000)return this.cached;
|
|
const profiles=await this.profiles(),log=await this.logs().catch(()=>''),errors=[];let key;try{key=await this.context();}catch{errors.push('BPQ non disponibile: le code non sono aggiornate.');}
|
|
const out=[];for(const p of profiles){let queued=null;if(key)try{const html=await this.bpq('/Mail/FwdDetails?'+key,{method:'POST',body:p.call});const n=html.match(/-\s*(\d+) Messages Queued/i);if(n)queued=Number(n[1]);}catch{errors.push('Coda '+p.call+' non disponibile');}
|
|
const history=forwardingHistory(log,p.call),last=history[0]||null;out.push({...p,queued,history,last,active:Boolean(last&&!last.endedAt&&['calling','connected'].includes(last.status)),requestedAt:this.requested.get(p.call)||null,nextEstimated:nextForwarding(p,last,Date.now(),queued)});
|
|
}
|
|
this.cached={profiles:out,updatedAt:new Date().toISOString(),scheduleTimezone:profiles.some(p=>p.timesLocal)?'Locale server BPQ':'UTC',radio:this.radio(),errors};this.cachedAt=Date.now();return this.cached;
|
|
});}
|
|
start(peer){return this.exclusive(async()=>{
|
|
if(this.lockedPeers.has(peer))throw new Error(this.lockedPeers.get(peer));
|
|
const p=(await this.profiles()).find(p=>p.call===peer);if(!p?.configured)throw new Error('Profilo di forwarding non configurato');
|
|
if(Date.now()-(this.requested.get(peer)||0)<30000)throw new Error('Sincronizzazione già richiesta: attendi 30 secondi');
|
|
const last=forwardingHistory(await this.logs().catch(()=>''),peer)[0];if(last&&!last.endedAt&&['calling','connected'].includes(last.status))throw new Error('Forwarding già in corso per questo partner');
|
|
const radio=this.radio();if(p.transport==='Radio'&&(radio?.active||radio?.connecting))throw new Error('Modem occupato da una connessione: riprova al termine');
|
|
const key=await this.context();await this.bpq('/Mail/FwdDetails?'+key,{method:'POST',body:peer});await this.bpq('/Mail/FWDSave?'+key,{method:'POST',body:'StartForward'});
|
|
this.requested.set(peer,Date.now());this.cached=null;return {ok:true,peer,requestedAt:new Date().toISOString()};
|
|
});}
|
|
}
|