Files
bpq_gui/journal.mjs
T

109 lines
16 KiB
JavaScript

import {readFile,readdir,stat,writeFile,rename} from 'node:fs/promises';
import path from 'node:path';
const base=call=>String(call||'').toUpperCase().replace(/-\d+$/,'');
const validCall=call=>/^[A-Z0-9]*\d[A-Z0-9]*(?:-\d{1,2})?$/.test(call||'');
export function locatorPosition(locator){
const l=String(locator||'').trim().toUpperCase();if(!/^[A-R]{2}\d{2}(?:[A-X]{2}(?:\d{2})?)?$/.test(l))return null;
let lon=(l.charCodeAt(0)-65)*20-180+Number(l[2])*2,lat=(l.charCodeAt(1)-65)*10-90+Number(l[3]);let dx=2,dy=1;
if(l.length>=6){dx=2/24;dy=1/24;lon+=(l.charCodeAt(4)-65)*dx;lat+=(l.charCodeAt(5)-65)*dy;}
if(l.length===8){dx/=10;dy/=10;lon+=Number(l[6])*dx;lat+=Number(l[7])*dy;}
return {locator:l,lat:lat+dy/2,lon:lon+dx/2};
}
export function distanceKm(a,b){const r=x=>x*Math.PI/180,dlat=r(b.lat-a.lat),dlon=r(b.lon-a.lon);return Math.round(6371*2*Math.asin(Math.min(1,Math.sqrt(Math.sin(dlat/2)**2+Math.cos(r(a.lat))*Math.cos(r(b.lat))*Math.sin(dlon/2)**2))));}
function stamp(date,time){return `${date.length===6?'20'+date.slice(0,2)+'-'+date.slice(2,4)+'-'+date.slice(4):date}T${time}Z`;}
function record(call,at,service,transport,direction,source){return {id:service+'-'+call+'-'+at,call,localCall:null,startedAt:at,connectedAt:null,endedAt:null,service,transport,direction,status:'incomplete',txBytes:null,rxBytes:null,trafficScope:null,snr:null,frequency:null,port:null,receivedMessages:0,sentMessages:0,messages:[],events:[],sources:[source]};}
function event(s,at,text){if(s.events.length<120)s.events.push({at,text});}
export function parseTelnetLog(text,source='Telnet'){
const rows=[],streams=new Map();
for(const line of text.split(/\r?\n/)){
const m=line.match(/^(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2}):(\d{2})\s+(\d+)\s+(\S+)\s+(.*)$/);if(!m)continue;
const at=new Date(Number(m[3]),Number(m[2])-1,Number(m[1]),Number(m[4]),Number(m[5]),Number(m[6])).toISOString(),stream=m[7],ip=m[8],text=m[9];let a;
if(a=text.match(/^Incoming Connect on Port (\d+)$/i))streams.set(stream,{port:Number(a[1]),ip});
if(a=text.match(/^Call Accepted\.?\s+Callsign=([A-Z0-9-]+)\s*$/i)){const connection=streams.get(stream);rows.push({at,call:a[1].toUpperCase(),local:/^(127\.|::1$)/.test(ip),port:connection?.ip===ip?connection.port:null,source});}
}
return rows;
}
export function classifyTransport(s,config,telnet=[]){
if(s.transport==='Unknown'&&s.frequency){s.transport='Radio';s.transportEvidence='Comando RADIO registrato nella sessione';}
const port=config.ports?.find(p=>p.id===s.port);
if(port){s.transport=/TELNET/i.test(port.driver)?'Internet':/AXIP/i.test(port.driver)?'NET/ROM':'Radio';s.transportEvidence='Porta BPQ '+port.id+' · '+(port.name||port.driver);}
if(s.transport==='Unknown'){
const match=telnet.filter(t=>base(t.call)===base(s.call)&&Math.abs(Date.parse(t.at)-Date.parse(s.startedAt))<=20000).sort((a,b)=>Math.abs(Date.parse(a.at)-Date.parse(s.startedAt))-Math.abs(Date.parse(b.at)-Date.parse(s.startedAt)))[0];
if(match){s.transport=match.local?'Local':'Internet';s.transportEvidence='Correlazione con accesso Telnet BPQ in '+match.source;if(!s.sources.includes(match.source))s.sources.push(match.source);}
}
if(s.transport==='Unknown'){
s.transport=s.service==='Winlink'?'CMS':'BPQ';
s.transportEvidence=s.service==='Winlink'?'Accesso al gateway Winlink confermato dal log CMS. Il mezzo di ingresso al nodo non è archiviato.':'Accesso al servizio '+s.service+' del nodo BPQ confermato. La porta di ingresso non è archiviata.';
}
if(!s.transportEvidence)s.transportEvidence=s.transport==='Radio'?'Sessione radio registrata dal modem':s.transport==='NET/ROM'?'Collegamento NET/ROM registrato da BPQ':'Trasporto registrato dal servizio';
return s;
}
export function parseVaraLog(text,source='VARAHF.log',own=''){
const out=[];let current=null,incoming=false,pendingSnr=null;
const start=(call,at,direction)=>{if(current)out.push(current);current=record(call,at,'Radio','Radio',direction,source);current.mode='VARA';};
for(const line of text.split(/\r?\n/)){
const m=line.match(/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})\s+(.*)$/);if(!m)continue;const at=stamp(m[1],m[2]),t=m[3];let a;
if(/Incoming connection/i.test(t)){incoming=true;continue;}
if(a=t.match(/(?:->CONNECT|CONNECT)\s+([A-Z0-9-]+)\s+([A-Z0-9-]+)/)){start(a[2],at,'outgoing');current.localCall=a[1];incoming=false;event(current,at,'Chiamata radio avviata');}
else if(a=t.match(/Connecting to ([A-Z0-9-]+).*?(\d+)\/(\d+)/)){if(!current)start(a[1],at,'outgoing');current.attempts=Number(a[2]);current.maxAttempts=Number(a[3]);}
else if(a=t.match(/<-CONNECTED\s+([A-Z0-9-]+)\s+([A-Z0-9-]+)(?:\s+(\d+))?/)){if(!current||base(current.call)!==base(a[2]))start(a[2],at,incoming?'incoming':'unknown');current.localCall=a[1];current.connectedAt=at;current.bandwidth=a[3]?Number(a[3]):null;event(current,at,'Collegamento radio stabilito');incoming=false;}
else if(a=t.match(/^([A-Z0-9-]+) connected\s+VARA/i)){if(!current||base(current.call)!==base(a[1]))start(a[1],at,incoming?'incoming':'unknown');current.localCall=own;current.connectedAt=at;event(current,at,'Collegamento radio stabilito');incoming=false;}
else if(a=t.match(/^([A-Z0-9-]+) Average S\/N:\s*([\d,.-]+)/)){pendingSnr=Number(a[2].replace(',','.'));if(current)current.snr=pendingSnr;}
else if(a=t.match(/Disconnected\s+TX:\s*(\d+) Bytes \(Max:\s*(\d+) bps\)\s+RX:\s*(\d+) Bytes \(Max:\s*(\d+) bps\)/i)){if(current){current.endedAt=at;current.txBytes=Number(a[1]);current.peakTxBps=Number(a[2]);current.rxBytes=Number(a[3]);current.peakRxBps=Number(a[4]);current.trafficScope='Contatori della sessione VARA';current.status=current.connectedAt?'connected':'failed';event(current,at,'Sessione radio conclusa');out.push(current);current=null;}pendingSnr=null;}
else if(current&&/Connection failed|Connection timeout|No response|Disconnected\s*$/i.test(t)){current.endedAt=at;current.status=current.connectedAt?'connected':'failed';event(current,at,current.connectedAt?'Disconnessione':'Nessuna risposta');out.push(current);current=null;}
}
if(current)out.push(current);return out;
}
export function parseBbsLog(text,source='BBS',service='BBS'){
const out=[],open=new Map();
for(const line of text.split(/\r?\n/)){
const m=line.match(/^(\d{6}) (\d{2}:\d{2}:\d{2}) ([|<>?!])([A-Z0-9-]+)\s+(.*)$/);if(!m)continue;const at=stamp(m[1],m[2]),peer=m[4],t=m[5];let s=open.get(peer),a;
if(/Connecting to (?:BBS|Chat Node)|Incoming Connect from/i.test(t)){if(s)out.push(s);s=record(peer,at,peer==='RMS'?'Winlink':service,peer==='RMS'?'Internet':'Unknown',/Incoming/i.test(t)?'incoming':'outgoing',source);open.set(peer,s);event(s,at,'Avvio '+s.service);}
if(!s)continue;
if(a=t.match(/ATTACH\s+(\d+)/i)){s.port=Number(a[1]);s.transport='Radio';event(s,at,'Porta BPQ '+s.port);}
if(a=t.match(/^(?:C|CONNECT)\s+(\d+)\s+\S+/i)){s.port=Number(a[1]);event(s,at,'Connessione sulla porta BPQ '+s.port);}
if(s.transport==='Unknown'&&/^(?:C|CONNECT)\s+[A-Z0-9]+:[A-Z0-9-]+\s*$/i.test(t))s.transport='NET/ROM';
if(a=t.match(/^RADIO\s+([\d.]+)\s+(\S+)/i)){s.frequency=Number(a[1]);event(s,at,'Frequenza '+a[1]+' MHz '+a[2]);}
if(a=t.match(/(?:\*\*\* Connected to|Connected to\s+(?:[A-Z0-9]+:)?)([A-Z0-9-]+)/i)){if(validCall(a[1]))s.call=a[1];s.connectedAt=at;event(s,at,'Connessione al nodo '+s.call);}
if(service==='Chat'&&/Connected to [A-Z0-9]+:[A-Z0-9-]+/.test(t)){s.transport='NET/ROM';s.connectedAt=at;}
if(a=t.match(/Uncompressing Message Comp Len\s+(\d+) Msg Len\s+(\d+)/i)){s.receivedMessages++;s.messages.push({direction:'RX',compressedBytes:Number(a[1]),bytes:Number(a[2]),at});event(s,at,'Messaggio ricevuto · '+a[2]+' byte');}
if(a=t.match(/^Compressing Message Comp Len\s+(\d+) Msg Len\s+(\d+)/i)){s.sentMessages++;s.messages.push({direction:'TX',compressedBytes:Number(a[1]),bytes:Number(a[2]),at});}
if(a=t.match(/^Msg\s+(\d+) Routing Trace/)){const last=s.messages.at(-1);if(last&&!last.id)last.id=Number(a[1]);}
if(/^[<>]$/.test(m[3])&&/^FQ\s*$/.test(t)){s.exchangeComplete=true;event(s,at,'Scambio forwarding concluso (FQ)');}
if(/Application not available|Already Connected|Failure with|Invalid command|Unexpected Response|does not have .* defined/i.test(t)){s.error=/Already Connected/i.test(t)?'Sessione già presente':/Application not available/i.test(t)?'Applicazione remota non disponibile':/does not have .* defined/i.test(t)?'Nodo chat remoto non configurato per questo collegamento':'Connessione o protocollo non riuscito';event(s,at,s.error);}
if(/Disconnected\s*$/i.test(t)){s.endedAt=at;s.status=s.error?'failed':s.exchangeComplete?'complete':s.connectedAt?'connected':'incomplete';event(s,at,'Disconnessione');out.push(s);open.delete(peer);}
}
out.push(...open.values());return out;
}
export function parseCmsLog(text,date,own,source='CMSAccess'){
const out=[],open=new Map();
for(const line of text.split(/\r?\n/)){const m=line.match(/^(\d{2}:\d{2}:\d{2})\s+(\d+)\s+(.*)$/);if(!m)continue;const at=stamp(date,m[1]),stream=m[2],t=m[3];let a;
if(a=t.match(/^([A-Z0-9-]+) Connected to CMS/)){const self=base(a[1])===base(own);const s=record(self?'CMS':a[1],at,'Winlink',self?'Internet':'Unknown',self?'outgoing':'incoming',source);s.localCall=own;s.connectedAt=at;event(s,at,'Accesso al CMS Winlink');if(open.has(stream))out.push(open.get(stream));open.set(stream,s);}
if(a=t.match(/^Disconnected\. Bytes Sent = (\d+) Bytes Received (\d+) Time (\d+) Seconds/)){const s=open.get(stream);if(s){s.txBytes=Number(a[1]);s.rxBytes=Number(a[2]);s.trafficScope='Contatori della connessione BPQ → CMS';s.endedAt=at;s.status='connected';event(s,at,'Connessione CMS conclusa');out.push(s);open.delete(stream);}}
}out.push(...open.values());return out;
}
export function mergeSessions(bbs,radio,cms){
const out=[...radio.map(s=>({...s,events:[...s.events],sources:[...s.sources]}))],used=new Set();
for(const b of bbs){const candidates=out.filter(r=>r.service==='Radio'&&(r.direction==='unknown'||b.direction==='unknown'||r.direction===b.direction)&&base(r.call)===base(b.call)&&Math.abs(Date.parse(r.startedAt)-Date.parse(b.startedAt))<90000&&!used.has(r.id));const r=candidates.sort((a,c)=>Math.abs(Date.parse(a.startedAt)-Date.parse(b.startedAt))-Math.abs(Date.parse(c.startedAt)-Date.parse(b.startedAt)))[0];
if(r){used.add(r.id);const stats={txBytes:r.txBytes,rxBytes:r.rxBytes,trafficScope:r.trafficScope};Object.assign(r,{...b,call:r.call,localCall:r.localCall||b.localCall,mode:r.mode,snr:r.snr,bandwidth:r.bandwidth,peakTxBps:r.peakTxBps,peakRxBps:r.peakRxBps,attempts:r.attempts,maxAttempts:r.maxAttempts,transport:'Radio',connectedAt:r.connectedAt||b.connectedAt,endedAt:r.endedAt||b.endedAt,...stats,status:b.error?'failed':b.exchangeComplete?'complete':r.status,events:[...b.events,...r.events].sort((a,c)=>a.at.localeCompare(c.at)),sources:[...new Set([...r.sources,...b.sources])]});}else out.push({...b,events:[...b.events]});
}
for(const c of cms){const r=out.find(r=>r.service!=='Winlink'&&(r.direction==='unknown'||r.direction===c.direction)&&base(r.call)===base(c.call)&&r.connectedAt&&Date.parse(c.startedAt)>=Date.parse(r.startedAt)-5000&&Date.parse(c.startedAt)<=Date.parse(r.endedAt||new Date().toISOString())+5000);if(r){r.service='Winlink';r.cmsTraffic={txBytes:c.txBytes,rxBytes:c.rxBytes};r.events.push(...c.events);r.sources.push(...c.sources);}else{const b=c.call==='CMS'?out.find(b=>b.service==='Winlink'&&Math.abs(Date.parse(b.startedAt)-Date.parse(c.startedAt))<10000):null;if(b){b.txBytes=c.txBytes;b.rxBytes=c.rxBytes;b.trafficScope=c.trafficScope;b.connectedAt=c.connectedAt;b.endedAt=c.endedAt||b.endedAt;b.status=b.exchangeComplete?'complete':c.status;b.sources.push(...c.sources);b.events.push(...c.events);}else out.push(c);}}
return out.map(s=>({...s,events:s.events.sort((a,b)=>a.at.localeCompare(b.at)),duration:s.connectedAt&&s.endedAt?Math.max(0,Math.round((Date.parse(s.endedAt)-Date.parse(s.connectedAt))/1000)):null})).sort((a,b)=>b.startedAt.localeCompare(a.startedAt));
}
export class Journal{
constructor(config,dir){this.config=config;this.dir=dir;this.cache=new Map();this.pending=null;this.savedAt=0;this.locationQueue=Promise.resolve();}
async parsed(file,parse){try{const info=await stat(file);const key=info.size+':'+info.mtimeMs;const prior=this.cache.get(file);if(prior?.key===key)return prior.value;let text=await readFile(file,'utf8');const truncated=Buffer.byteLength(text)>16*1024*1024;if(truncated)text=text.slice(-8*1024*1024).split('\n').slice(1).join('\n');const value={rows:parse(text,path.basename(file)),truncated};this.cache.set(file,{key,value});return value;}catch{return {rows:[],unavailable:true};}}
async snapshot(){if(this.pending)return this.pending;if(this.last&&Date.now()-this.savedAt<10000)return this.last;this.pending=this.read();try{this.last=await this.pending;this.savedAt=Date.now();return this.last}finally{this.pending=null}}
async read(){const root=this.config.root,logs=path.join(root,'Logs');let files=[];try{files=await readdir(logs)}catch{}const after=Date.now()-30*86400000;const bbs=[],cms=[],radio=[],telnet=[],warnings=[];let first=null;
for(const name of files.sort()){let m,kind,date;if(m=name.match(/^Telnet_(\d{6})\.log$/)){date='20'+m[1].slice(0,2)+'-'+m[1].slice(2,4)+'-'+m[1].slice(4);if(Date.parse(date+'T23:59:59Z')>=after){const result=await this.parsed(path.join(logs,name),parseTelnetLog);telnet.push(...result.rows);if(result.truncated)warnings.push(name+': letta la parte finale (file grande)');}continue;}if(m=name.match(/^log_(\d{6})_(BBS|CHAT)\.txt$/)){date='20'+m[1].slice(0,2)+'-'+m[1].slice(2,4)+'-'+m[1].slice(4);kind=m[2];}else if(m=name.match(/^CMSAccess_(\d{4})(\d{2})(\d{2})\.log$/)){date=m[1]+'-'+m[2]+'-'+m[3];kind='CMS';}else continue;if(Date.parse(date+'T23:59:59Z')<after)continue;first=!first||date<first?date:first;const result=await this.parsed(path.join(logs,name),(text,source)=>kind==='CMS'?parseCmsLog(text,date,this.config.sysop.call,source):parseBbsLog(text,source,kind==='CHAT'?'Chat':'BBS'));(kind==='CMS'?cms:bbs).push(...result.rows);if(result.truncated)warnings.push(name+': letta la parte finale (file grande)');}
const varaLog=this.config.varaLogPath; if(varaLog){const result=await this.parsed(varaLog,(t,s)=>parseVaraLog(t,s,this.config.sysop.call));radio.push(...result.rows.filter(s=>Date.parse(s.startedAt)>=after));if(result.unavailable)warnings.push('Log VARA non disponibile: traffico radio storico incompleto');}
for(const s of bbs){const port=this.config.ports?.find(p=>p.id===s.port);if(port&&/TELNET/i.test(port.driver))s.transport='Internet';else if(port&&/AXIP/i.test(port.driver))s.transport='NET/ROM';}
const sessions=mergeSessions(bbs,radio,cms).map(s=>classifyTransport(s,this.config,telnet)).slice(0,5000);let locations={};try{locations=JSON.parse(await readFile(path.join(this.dir,'station-locations.json'),'utf8'))}catch{}
const stations=new Map();for(const s of sessions){if(!validCall(s.call)||base(s.call)===base(this.config.sysop.call))continue;const call=base(s.call);let station=stations.get(call);if(!station){const position=locatorPosition(locations[call]?.locator);station={call,position:position?{...position,source:locations[call]?.source||'Locator inserito manualmente'}:null,lastSeen:s.startedAt,sessions:0,services:[],txBytes:0,rxBytes:0};stations.set(call,station);}station.sessions++;if(!station.services.includes(s.service))station.services.push(s.service);station.txBytes+=s.txBytes||0;station.rxBytes+=s.rxBytes||0;}
const own={call:this.config.nodeCall,position:locatorPosition(this.config.locator)};if(own.position)own.position.source='LOCATOR di BPQ';for(const s of stations.values())s.distance=own.position&&s.position?distanceKm(own.position,s.position):null;
return {updatedAt:new Date().toISOString(),since:first,sessions,stations:[...stations.values()],own,warnings,limited:sessions.length>=5000};
}
saveLocation(call,locator){const work=this.locationQueue.then(async()=>{const key=base(call),position=locatorPosition(locator);if(!validCall(key)||!position)throw new Error('Indica un nominativo e un locator Maidenhead valido (4, 6 o 8 caratteri)');const known=(await this.snapshot()).stations.some(s=>s.call===key);if(!known)throw new Error('Stazione non presente nel diario');const file=path.join(this.dir,'station-locations.json');let data={};try{data=JSON.parse(await readFile(file,'utf8'))}catch{}data[key]={locator:position.locator};await writeFile(file+'.tmp',JSON.stringify(data,null,2));await rename(file+'.tmp',file);this.savedAt=0;return this.snapshot();});this.locationQueue=work.catch(()=>{});return work;}
}