Add connection journal with service traffic details and interactive offline station map
This commit is contained in:
1 parent
78839f5bb4
commit
106b04d631
14 files changed
+168
-7
No files matched your search
@@ -17,3 +17,6 @@ work/
|
|||||||
Thumbs.db
|
Thumbs.db
|
||||||
|
|
||||||
console.config.json
|
console.config.json
|
||||||
|
|
||||||
|
station-locations.json
|
||||||
|
station-locations.json.tmp
|
||||||
@@ -12,6 +12,8 @@ if(!$BpqRoot){
|
|||||||
}
|
}
|
||||||
$arguments=@((Join-Path $PSScriptRoot 'install.mjs'),'--bpq-root',$BpqRoot,'--port',"$Port")
|
$arguments=@((Join-Path $PSScriptRoot 'install.mjs'),'--bpq-root',$BpqRoot,'--port',"$Port")
|
||||||
foreach($option in @(@('http-port',$HttpPort),@('radio-port',$RadioPort),@('sysop-user',$SysopUser),@('forward-peer',$ForwardPeer))){if($option[1]){$arguments+=@('--'+$option[0],"$($option[1])")}}
|
foreach($option in @(@('http-port',$HttpPort),@('radio-port',$RadioPort),@('sysop-user',$SysopUser),@('forward-peer',$ForwardPeer))){if($option[1]){$arguments+=@('--'+$option[0],"$($option[1])")}}
|
||||||
|
$vara=Get-Process -Name VARA -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||||
|
if($vara.Path){$varaLog=Join-Path (Split-Path $vara.Path) 'VARAHF.log';if(Test-Path -LiteralPath $varaLog){$arguments+=@('--vara-log',$varaLog)}}
|
||||||
if($CheckOnly){$arguments+='--check-only'}
|
if($CheckOnly){$arguments+='--check-only'}
|
||||||
& $nodeExe @arguments
|
& $nodeExe @arguments
|
||||||
if($LASTEXITCODE -ne 0){throw 'Installazione interrotta: verifica BPQ fallita.'}
|
if($LASTEXITCODE -ne 0){throw 'Installazione interrotta: verifica BPQ fallita.'}
|
||||||
|
|||||||
@@ -75,3 +75,16 @@ node --test test.mjs
|
|||||||
```
|
```
|
||||||
|
|
||||||
Per riavviare, arrestare soltanto il processo Node di questo pannello ed eseguire Start-Console.ps1. Per rimuovere l'avvio automatico, eliminare la task BPQ-WebConsole. BPQ e il modem continuano a funzionare indipendentemente dal pannello.
|
Per riavviare, arrestare soltanto il processo Node di questo pannello ed eseguire Start-Console.ps1. Per rimuovere l'avvio automatico, eliminare la task BPQ-WebConsole. BPQ e il modem continuano a funzionare indipendentemente dal pannello.
|
||||||
|
|
||||||
|
|
||||||
|
## Diario e mappa delle stazioni
|
||||||
|
|
||||||
|
Le sezioni Diario e Mappa ricostruiscono fino a 30 giorni dai log BPQ BBS, Chat e CMSAccess, con un massimo di 5000 sessioni. Il diario distingue servizio, direzione, trasporto, esito, frequenza quando registrata, durata del collegamento, SNR, tentativi, contatori TX/RX ed eventi. Filtri per periodo, nominativo, servizio, direzione ed esito; esportazione CSV delle righe filtrate. Si aggiorna ogni 30 secondi quando la sezione è aperta.
|
||||||
|
|
||||||
|
I log VARA possono arricchire le sessioni con byte effettivi e picchi TX/RX. Install.ps1 rileva VARAHF.log dal processo VARA locale quando disponibile; in alternativa impostare varaLogPath nel file locale console.config.json. Non è necessario usare VARA: i servizi presenti nei log BPQ rimangono disponibili. I contatori della connessione CMS e quelli radio sono distinti. Messaggi e conteggi sono quelli esplicitamente registrati: dati mancanti rimangono non disponibili. File ruotati, mancanti o incompleti possono impedire di ricostruire l'intera sessione; un esito non registrato non viene considerato riuscito. Per file oltre 16 MB viene letta la parte finale e mostrato un avviso.
|
||||||
|
|
||||||
|
La mappa è locale, senza servizi di tile, API key o invio dei log a terzi. Usa i poligoni pubblici [Natural Earth](https://www.naturalearthdata.com/about/terms-of-use/), inclusi nel progetto. Posizione locale da LOCATOR BPQ; per le stazioni remote selezionare un nominativo e salvare il locator Maidenhead comunicato dalla stazione (4, 6 o 8 caratteri). I locator vengono salvati nel file locale station-locations.json, escluso da Git. I punti rappresentano il centro del locator. Stazioni nello stesso locator sono distanziate graficamente per poterle selezionare.
|
||||||
|
|
||||||
|
Punti e tracce sono cliccabili, con nominativo, ultimo collegamento nel periodo, servizio, orario e accesso al dettaglio di ogni sessione. Pulsanti zoom e Inquadra rete; trascinamento della mappa e filtro per servizio/periodo. Mostra collegamenti permette di attivare o nascondere le tracce. Le tracce uniscono stazioni e non descrivono il percorso fisico radio o gli hop NET/ROM. Le stazioni senza locator rimangono nell'elenco, senza coordinate inventate.
|
||||||
|
|
||||||
|
Il diario espone eventi strutturati, non i log grezzi: password, challenge CMS, contenuto delle email e conversazioni chat non sono restituiti dall'API.
|
||||||
+1
-1
@@ -14,7 +14,7 @@ if(radioPort&&!detected.radioPorts.some(p=>p.id===radioPort))throw new Error('Po
|
|||||||
const sysopUser=arg('sysop-user')||previous.sysopUser||detected.users[0].user;
|
const sysopUser=arg('sysop-user')||previous.sysopUser||detected.users[0].user;
|
||||||
if(!detected.users.some(u=>u.user===sysopUser))throw new Error('Utente sysop non rilevato');
|
if(!detected.users.some(u=>u.user===sysopUser))throw new Error('Utente sysop non rilevato');
|
||||||
let peers=[];try{const mail=await readFile(path.join(root,'BPQMailChat','BPQMail.cfg'),'utf8');const forward=mail.split(/BBSForwarding\s*:/i)[1]?.split(/BBSUsers\s*:/i)[0]||'';peers=[...forward.matchAll(/^\s{2}([A-Z0-9-]+)\s*:/gm)].map(m=>m[1]);}catch{}
|
let peers=[];try{const mail=await readFile(path.join(root,'BPQMailChat','BPQMail.cfg'),'utf8');const forward=mail.split(/BBSForwarding\s*:/i)[1]?.split(/BBSUsers\s*:/i)[0]||'';peers=[...forward.matchAll(/^\s{2}([A-Z0-9-]+)\s*:/gm)].map(m=>m[1]);}catch{}
|
||||||
const config={nodeExe:process.execPath,bpqRoot:root,httpPort,port,radioPort,sysopUser,forwardPeer:arg('forward-peer')||previous.forwardPeer||'',cmsPeer:'RMS',varaSyslogPort:18514};
|
const config={nodeExe:process.execPath,bpqRoot:root,httpPort,port,radioPort,sysopUser,forwardPeer:arg('forward-peer')||previous.forwardPeer||'',cmsPeer:'RMS',varaSyslogPort:18514,varaLogPath:arg('vara-log')||previous.varaLogPath||null};
|
||||||
if(config.forwardPeer&&!peers.includes(config.forwardPeer))throw new Error('Profilo forwarding selezionato non rilevato');
|
if(config.forwardPeer&&!peers.includes(config.forwardPeer))throw new Error('Profilo forwarding selezionato non rilevato');
|
||||||
console.log(JSON.stringify({bpq:'in esecuzione, HTTP verificato',nodeCall:detected.nodeCall,ports:detected.ports,services:detected.apps.map(a=>a.command),forwardProfiles:peers,selectedRadio:radioPort,sysopUser},null,2));
|
console.log(JSON.stringify({bpq:'in esecuzione, HTTP verificato',nodeCall:detected.nodeCall,ports:detected.ports,services:detected.apps.map(a=>a.command),forwardProfiles:peers,selectedRadio:radioPort,sysopUser},null,2));
|
||||||
if(!args.includes('--check-only')){await writeFile(path.join(dir,'console.config.json'),JSON.stringify(config,null,2)+'\n');console.log('Configurazione salvata senza password.');}
|
if(!args.includes('--check-only')){await writeFile(path.join(dir,'console.config.json'),JSON.stringify(config,null,2)+'\n');console.log('Configurazione salvata senza password.');}
|
||||||
+81
@@ -0,0 +1,81 @@
|
|||||||
|
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 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(/^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=[],warnings=[];let first=null;
|
||||||
|
for(const name of files.sort()){let m,kind,date;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).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;}
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
Natural Earth, 1:110m land polygons. Public domain.
|
||||||
|
Source: https://github.com/nvkelso/natural-earth-vector/blob/master/geojson/ne_110m_land.geojson
|
||||||
|
Terms: https://www.naturalearthdata.com/about/terms-of-use/
|
||||||
+3
-2
@@ -5,7 +5,7 @@ const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'&
|
|||||||
async function api(url,options={}){const r=await fetch('/api'+url,{...options,headers:{'Content-Type':'application/json',...(options.method==='POST'?{'X-CSRF-Token':csrf}:{}),...options.headers}});const data=await r.json();if(!r.ok){if(r.status===401&&url!=='/login')showLogin();throw new Error(data.error||'Richiesta fallita')}return data;}
|
async function api(url,options={}){const r=await fetch('/api'+url,{...options,headers:{'Content-Type':'application/json',...(options.method==='POST'?{'X-CSRF-Token':csrf}:{}),...options.headers}});const data=await r.json();if(!r.ok){if(r.status===401&&url!=='/login')showLogin();throw new Error(data.error||'Richiesta fallita')}return data;}
|
||||||
function toast(text){$('#toast').textContent=text;$('#toast').hidden=false;clearTimeout(toast.timer);toast.timer=setTimeout(()=>$('#toast').hidden=true,6500);}
|
function toast(text){$('#toast').textContent=text;$('#toast').hidden=false;clearTimeout(toast.timer);toast.timer=setTimeout(()=>$('#toast').hidden=true,6500);}
|
||||||
function showLogin(){$('#shell').hidden=true;$('#login').hidden=false;csrf='';}
|
function showLogin(){$('#shell').hidden=true;$('#login').hidden=false;csrf='';}
|
||||||
function showShell(user){station=user.config;applyStation(user);csrf=user.csrf;$('#login').hidden=true;$('#shell').hidden=false;loadDashboard();if(station.features.bbs)loadMessages();}
|
function showShell(user){station=user.config;applyStation(user);csrf=user.csrf;$('#login').hidden=true;$('#shell').hidden=false;loadDashboard();if(station.features.bbs)loadMessages();document.dispatchEvent(new Event('station-ready'));}
|
||||||
function logTime(value){if(!value)return '—';const m=value.match(/^(\d{2})(\d{2})(\d{2}) (\d{2}:\d{2}:\d{2})$/);if(!m)return value;return new Date(`20${m[1]}-${m[2]}-${m[3]}T${m[4]}Z`).toLocaleTimeString('it-IT',{hour:'2-digit',minute:'2-digit'});}
|
function logTime(value){if(!value)return '—';const m=value.match(/^(\d{2})(\d{2})(\d{2}) (\d{2}:\d{2}:\d{2})$/);if(!m)return value;return new Date(`20${m[1]}-${m[2]}-${m[3]}T${m[4]}Z`).toLocaleTimeString('it-IT',{hour:'2-digit',minute:'2-digit'});}
|
||||||
function categoryLabel(m){return m.type==='P'?'PERSONALE':m.to||'BOLLETTINO'}
|
function categoryLabel(m){return m.type==='P'?'PERSONALE':m.to||'BOLLETTINO'}
|
||||||
function friendlyActivity(text){if(/Failure with/.test(text))return 'il nodo remoto non ha risposto alla chiamata';if(/Connecting to BBS/.test(text))return 'Chiamata radio verso il nodo remoto avviata';if(/Incoming Connect/.test(text))return 'il nodo remoto si è collegato alla nostra BBS';if(/Uncompressing Message/.test(text))return 'Ricevuto e salvato un nuovo bollettino';if(/Disconnected/.test(text))return 'Sessione con il nodo remoto terminata';return text;}
|
function friendlyActivity(text){if(/Failure with/.test(text))return 'il nodo remoto non ha risposto alla chiamata';if(/Connecting to BBS/.test(text))return 'Chiamata radio verso il nodo remoto avviata';if(/Incoming Connect/.test(text))return 'il nodo remoto si è collegato alla nostra BBS';if(/Uncompressing Message/.test(text))return 'Ricevuto e salvato un nuovo bollettino';if(/Disconnected/.test(text))return 'Sessione con il nodo remoto terminata';return text;}
|
||||||
@@ -29,7 +29,8 @@ $$('.compose-button').forEach(b=>b.onclick=()=>openCompose());$$('.close-compose
|
|||||||
$('#compose-form').addEventListener('submit',async e=>{e.preventDefault();const winlinkMode=typeof wlCompose!=='undefined'&&wlCompose;const b=$('#send-button');b.disabled=true;b.textContent='Salvataggio in BPQ…';$('#compose-error').textContent='';try{const data=Object.fromEntries(new FormData(e.target));const created=await api('/messages',{method:'POST',body:JSON.stringify(data)});$('#compose').close();toast('Messaggio #'+created.id+' salvato nella BBS. L’inoltro sarà gestito da BPQ.');if(winlinkMode){navigate('winlink');wlFolder='queue';await wlLoad();wlRender();wlRead(created.id);}else{navigate('bbs');await loadMessages();readMessage(created.id);}loadDashboard();}catch(err){$('#compose-error').textContent=err.message}finally{b.disabled=false;b.textContent='Salva e metti in coda →'}});
|
$('#compose-form').addEventListener('submit',async e=>{e.preventDefault();const winlinkMode=typeof wlCompose!=='undefined'&&wlCompose;const b=$('#send-button');b.disabled=true;b.textContent='Salvataggio in BPQ…';$('#compose-error').textContent='';try{const data=Object.fromEntries(new FormData(e.target));const created=await api('/messages',{method:'POST',body:JSON.stringify(data)});$('#compose').close();toast('Messaggio #'+created.id+' salvato nella BBS. L’inoltro sarà gestito da BPQ.');if(winlinkMode){navigate('winlink');wlFolder='queue';await wlLoad();wlRender();wlRead(created.id);}else{navigate('bbs');await loadMessages();readMessage(created.id);}loadDashboard();}catch(err){$('#compose-error').textContent=err.message}finally{b.disabled=false;b.textContent='Salva e metti in coda →'}});
|
||||||
$('#refresh').onclick=async()=>{const b=$('#refresh');b.disabled=true;await Promise.all([loadDashboard(),loadMessages()]);b.disabled=false};$('#sync-open').onclick=()=>$('#sync-dialog').showModal();$('#sync-cancel').onclick=()=>$('#sync-dialog').close();$('#sync-confirm').onclick=async()=>{const b=$('#sync-confirm');b.disabled=true;try{await api('/sync',{method:'POST',body:'{}'});$('#sync-dialog').close();toast('Richiesta di forwarding inviata a BPQ. Segui l’esito nell’attività.');setTimeout(loadDashboard,2500)}catch(err){toast(err.message)}finally{b.disabled=false}};
|
$('#refresh').onclick=async()=>{const b=$('#refresh');b.disabled=true;await Promise.all([loadDashboard(),loadMessages()]);b.disabled=false};$('#sync-open').onclick=()=>$('#sync-dialog').showModal();$('#sync-cancel').onclick=()=>$('#sync-dialog').close();$('#sync-confirm').onclick=async()=>{const b=$('#sync-confirm');b.disabled=true;try{await api('/sync',{method:'POST',body:'{}'});$('#sync-dialog').close();toast('Richiesta di forwarding inviata a BPQ. Segui l’esito nell’attività.');setTimeout(loadDashboard,2500)}catch(err){toast(err.message)}finally{b.disabled=false}};
|
||||||
setInterval(()=>{if(csrf&&!document.hidden)loadDashboard()},20000);setInterval(()=>{$('#clock').textContent=new Date().toLocaleTimeString('it-IT',{hour:'2-digit',minute:'2-digit'})+' · '+mailTimezone()},1000);
|
setInterval(()=>{if(csrf&&!document.hidden)loadDashboard()},20000);setInterval(()=>{$('#clock').textContent=new Date().toLocaleTimeString('it-IT',{hour:'2-digit',minute:'2-digit'})+' · '+mailTimezone()},1000);
|
||||||
api('/session').then(showShell).catch(()=>showLogin());
|
function restoreSession(){api('/session').then(showShell).catch(()=>showLogin());}
|
||||||
|
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',restoreSession,{once:true});else restoreSession();
|
||||||
|
|
||||||
function applyStation(user){
|
function applyStation(user){
|
||||||
document.title='BPQ Console · '+station.nodeCall;
|
document.title='BPQ Console · '+station.nodeCall;
|
||||||
|
|||||||
@@ -58,5 +58,5 @@ if(location.hash==='#chat')navigate('chat');
|
|||||||
|
|
||||||
window.addEventListener('DOMContentLoaded',()=>{for(const target of ['#bbs .mail-list-heading','#winlink .mail-list-heading']){const heading=$(target);if(heading){const tag=document.createElement('small');tag.className='mail-timezone';tag.textContent='Timezone: '+mailTimezone();heading.append(tag);}}});
|
window.addEventListener('DOMContentLoaded',()=>{for(const target of ['#bbs .mail-list-heading','#winlink .mail-list-heading']){const heading=$(target);if(heading){const tag=document.createElement('small');tag.className='mail-timezone';tag.textContent='Timezone: '+mailTimezone();heading.append(tag);}}});
|
||||||
|
|
||||||
function restoreMailPage(){const target=location.hash.slice(1);if(['home','bbs','winlink','chat','network','monitor'].includes(target)&&page!==target&&document.getElementById(target))navigate(target);}
|
function restoreMailPage(){const target=location.hash.slice(1);if(['home','bbs','winlink','chat','network','monitor','journal','map'].includes(target)&&page!==target&&document.getElementById(target))navigate(target);}
|
||||||
window.addEventListener('DOMContentLoaded',restoreMailPage);window.addEventListener('hashchange',restoreMailPage);
|
window.addEventListener('DOMContentLoaded',restoreMailPage);window.addEventListener('hashchange',restoreMailPage);
|
||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="it"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#101916"><title>BPQ — Radio & BBS</title><link rel="stylesheet" href="/style.css"><link rel="stylesheet" href="/dark.css"><link rel="stylesheet" href="/mission.css"><script defer src="/app.js"></script><script type="module" src="/enhancements.js"></script><script defer src="/winlink.js"></script><script defer src="/mission.js"></script><script defer src="/attachments.js"></script><link rel="stylesheet" href="/monitor.css"><script defer src="/monitor.js"></script></head>
|
<html lang="it"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#101916"><title>BPQ — Radio & BBS</title><link rel="stylesheet" href="/style.css"><link rel="stylesheet" href="/dark.css"><link rel="stylesheet" href="/mission.css"><script defer src="/app.js"></script><script type="module" src="/enhancements.js"></script><script defer src="/winlink.js"></script><script defer src="/mission.js"></script><script defer src="/attachments.js"></script><link rel="stylesheet" href="/monitor.css"><script defer src="/monitor.js"></script><link rel="stylesheet" href="/journal.css"><script defer src="/journal.js"></script></head>
|
||||||
<body>
|
<body>
|
||||||
<section id="login" class="login-screen"><div class="login-art"><span class="eyebrow">BPQ NETWORK</span><h1>BPQ<br><em>Radio Console</em></h1><div class="signal-art"><i></i><i></i><i></i><i></i><b>STAZIONE</b></div><p>La tua stazione, in un unico pannello.</p></div><form id="login-form" class="login-card"><span class="brand">◉ BPQ<span>CONSOLE</span></span><h2>Benvenuto in stazione.</h2><p>Accedi con l’utente e la password Telnet del tuo BPQ.</p><label>Utente<input name="user" autocomplete="username" required placeholder="Il tuo utente BPQ"></label><label>Password<input name="password" type="password" autocomplete="current-password" required></label><button class="primary" type="submit">Entra nel pannello <span>→</span></button><div id="login-error" class="error" role="alert"></div><small>Created by IU2EUG · PC e rete locale</small></form></section>
|
<section id="login" class="login-screen"><div class="login-art"><span class="eyebrow">BPQ NETWORK</span><h1>BPQ<br><em>Radio Console</em></h1><div class="signal-art"><i></i><i></i><i></i><i></i><b>STAZIONE</b></div><p>La tua stazione, in un unico pannello.</p></div><form id="login-form" class="login-card"><span class="brand">◉ BPQ<span>CONSOLE</span></span><h2>Benvenuto in stazione.</h2><p>Accedi con l’utente e la password Telnet del tuo BPQ.</p><label>Utente<input name="user" autocomplete="username" required placeholder="Il tuo utente BPQ"></label><label>Password<input name="password" type="password" autocomplete="current-password" required></label><button class="primary" type="submit">Entra nel pannello <span>→</span></button><div id="login-error" class="error" role="alert"></div><small>Created by IU2EUG · PC e rete locale</small></form></section>
|
||||||
<div id="shell" hidden><aside class="sidebar"><a class="brand" href="#home">◉ BPQ<span>RADIO CONSOLE</span></a><div class="side-label">LA TUA STAZIONE</div><nav><button data-page="home" class="active"><span>▦</span> Panoramica</button><button data-page="bbs"><span>▤</span> BBS <b id="nav-count">—</b></button><button data-page="network"><span>⌘</span> Rete & nodi</button></nav><div class="side-station">Stazione BPQ</div><div class="profile"><div class="avatar">BP</div><div>Sysop<small>BPQ</small></div><button id="logout" title="Esci" aria-label="Esci dal pannello">↗</button></div></aside>
|
<div id="shell" hidden><aside class="sidebar"><a class="brand" href="#home">◉ BPQ<span>RADIO CONSOLE</span></a><div class="side-label">LA TUA STAZIONE</div><nav><button data-page="home" class="active"><span>▦</span> Panoramica</button><button data-page="bbs"><span>▤</span> BBS <b id="nav-count">—</b></button><button data-page="network"><span>⌘</span> Rete & nodi</button></nav><div class="side-station">Stazione BPQ</div><div class="profile"><div class="avatar">BP</div><div>Sysop<small>BPQ</small></div><button id="logout" title="Esci" aria-label="Esci dal pannello">↗</button></div></aside>
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
#journal,#map{max-width:none;padding:28px} .journal-heading{display:flex;justify-content:space-between;align-items:center;gap:20px;margin-bottom:22px}.journal-heading h1{font-size:29px;font-weight:500;margin:8px 0}.journal-heading p{color:#8b9eb6;font-size:12px}.journal-heading>div:last-child{display:flex;gap:10px}.journal-heading>div:first-child{display:block}.journal-kpis{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:14px;margin-bottom:18px}.journal-kpis article{padding:18px 20px;border:1px solid #2c4056;border-radius:13px;background:linear-gradient(130deg,#18283a,#111b29)}.journal-kpis span{font-size:11px;color:#91a5bc}.journal-kpis strong{display:block;font:24px Consolas,monospace;margin-top:10px;color:#d5e7f7}.journal-filters,.map-toolbar{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:18px}.journal-filters input{flex:1;min-width:200px}.journal-filters input,.journal-filters select,.map-toolbar select{height:42px;border-radius:9px;padding:0 13px;font-size:12px}.journal-layout{display:grid;grid-template-columns:minmax(0,1fr) 340px;gap:18px;align-items:start}.journal-table-card{min-width:0}.journal-table-card .card-header{padding:18px 20px}.journal-table-card h2{font-size:15px}.journal-table-card .card-header>span{font-size:11px;color:#8fa5bd}.journal-table-scroll{max-height:calc(100dvh - 360px);min-height:300px;overflow:auto}.journal-table{width:100%;font-size:11px;border-collapse:collapse;white-space:nowrap}.journal-table th{position:sticky;top:0;background:#172334;color:#a9bfd6;z-index:1;font-size:10px;padding:14px 12px;text-align:left}.journal-table td{padding:14px 12px;border-bottom:1px solid #26384b;vertical-align:middle}.journal-table tbody tr{cursor:pointer}.journal-table tbody tr:hover{background:#1b2c40}.journal-table tr.selected{background:#243c55}.journal-table td b{font:14px Consolas,monospace;color:#d7e9f7}.journal-table td small{display:block;color:#839bb4;margin-top:6px;font-size:10px}.journal-open{background:none;border:0;color:#bfd7ed;padding:0;font:inherit;text-align:left}.journal-badge{padding:4px 7px;background:#253851;border-radius:5px;color:#adc6e5;font-size:10px}.journal-badge.radio{background:#243f3a;color:#a8dac6}.journal-result{font-size:10px;color:#92a7bc;line-height:1.5}.journal-result.complete,.journal-result.connected{color:#a6d8bc}.journal-result.failed{color:#dba6a6}.journal-detail{max-height:calc(100dvh - 350px);min-height:400px;overflow:auto;padding:22px}.journal-detail header h2{font:28px Consolas,monospace;margin:10px 0}.journal-detail h3,.map-info h3{font-size:12px;margin:22px 0 14px;color:#b1c4d9}.journal-facts{display:grid;grid-template-columns:1fr 1fr;gap:16px 12px;margin-top:22px}.journal-facts span{font-size:10px;color:#7e98b3;display:block;margin-bottom:5px}.journal-facts b{font-size:11px;font-weight:500;overflow-wrap:anywhere}.journal-source,.journal-footnote{font-size:10px;color:#8196ac;line-height:1.7;margin:18px 0}.journal-timeline{padding:0;list-style:none;border-left:1px solid #3b546b;margin-left:4px}.journal-timeline li{position:relative;padding:0 0 18px 16px}.journal-timeline li:before{content:'';position:absolute;left:-4px;top:4px;width:7px;height:7px;background:#7ca7c7;border-radius:50%}.journal-timeline time{display:block;color:#7b96b0;font-size:9px;margin-bottom:5px}.journal-timeline span{font-size:11px;line-height:1.6}.journal-transfers>div{display:flex;justify-content:space-between;gap:10px;padding:8px 0;border-bottom:1px solid #28394b;font-size:10px}.journal-warning{padding:12px 16px;margin-bottom:15px;border:1px solid #665940;border-radius:9px;color:#d4c59f;font-size:11px}.map-toolbar{font-size:12px;color:#a2b9d0}.map-toolbar label{display:flex;align-items:center;gap:8px}.map-toolbar input[type=checkbox]{width:16px;height:16px}.map-toolbar #map-summary{margin-left:auto;font-size:11px}.map-layout{display:grid;grid-template-columns:minmax(0,1fr) 320px;gap:18px;align-items:stretch}.map-card{position:relative;min-height:520px;background:#0d1b2b;overflow:hidden}.map-card svg{display:block;width:100%;height:100%;min-height:520px;touch-action:none;cursor:grab}.map-card svg:active{cursor:grabbing}.map-land{fill:#203b4d;stroke:#456171;stroke-width:.7;vector-effect:non-scaling-stroke;fill-rule:evenodd}.map-gridline{stroke:#7496b0;stroke-width:.4;opacity:.15;vector-effect:non-scaling-stroke;fill:none}.map-track{fill:none;stroke-width:2;opacity:.7;vector-effect:non-scaling-stroke;cursor:pointer;stroke-dasharray:5 5}.map-track:hover,.map-track.selected{opacity:1;stroke-width:3;stroke-dasharray:none}.map-point{cursor:pointer;outline:none}.map-point text,.map-local text{font-family:Consolas,monospace;paint-order:stroke;stroke:#0b1824;stroke-width:.6px;stroke-linejoin:round}.map-point:hover circle:first-child,.map-point.selected circle:first-child,.map-point:focus circle:first-child{opacity:.6}.map-controls{position:absolute;top:16px;left:16px;display:flex;gap:5px;z-index:2}.map-controls button{height:35px;min-width:35px;Line truncated
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
(() => {
|
||||||
|
let data=null,loading=false,selected=null,mapCall=null,land=null,view=[0,0,1000,500],drag=null,moved=false;
|
||||||
|
const base=c=>String(c||'').replace(/-\d+$/,'');
|
||||||
|
const time=t=>t?new Date(t).toLocaleString('it-IT',{day:'2-digit',month:'2-digit',year:'numeric',hour:'2-digit',minute:'2-digit',second:'2-digit'}):'—';
|
||||||
|
const bytes=n=>n==null?'—':size(n);
|
||||||
|
const state=s=>({complete:'Scambio concluso',connected:'Collegato',failed:'Non riuscito',incomplete:'Esito non registrato'}[s]||s);
|
||||||
|
const direction=d=>({incoming:'In ingresso',outgoing:'In uscita',unknown:'Non rilevata'}[d]);
|
||||||
|
const transport=t=>({Radio:'Radio',Internet:'Internet','NET/ROM':'NET/ROM',Unknown:'Non rilevato'}[t]||t);
|
||||||
|
const duration=s=>s==null?'—':s>=3600?Math.floor(s/3600)+' h '+Math.floor(s%3600/60)+' min':s>=60?Math.floor(s/60)+' min '+s%60+' s':s+' s';
|
||||||
|
for(const [id,title,icon]of [['journal','Diario','◷'],['map','Mappa','◎']]){const b=document.createElement('button');b.dataset.page=id;b.innerHTML='<span>'+icon+'</span> '+title;b.onclick=()=>navigate(id);$('nav').append(b);}
|
||||||
|
const journal=document.createElement('section');journal.id='journal';journal.className='page';journal.hidden=true;journal.innerHTML=`<div class="journal-heading"><div><span class="eyebrow">STATION LOGBOOK</span><h1>Diario dei collegamenti</h1><p id="journal-coverage">Lettura dei log BPQ…</p></div><div><button class="secondary" id="journal-export">↓ CSV</button><button class="primary" id="journal-refresh">↻ Aggiorna</button></div></div><div class="journal-kpis" id="journal-kpis"></div><div class="journal-filters"><input id="journal-search" type="search" placeholder="Cerca nominativo, servizio o frequenza…" aria-label="Cerca nel diario"><select id="journal-period" aria-label="Periodo diario"><option value="1">Ultime 24 ore</option><option value="7" selected>Ultimi 7 giorni</option><option value="30">Ultimi 30 giorni</option></select><select id="journal-service" aria-label="Servizio diario"><option value="">Tutti i servizi</option><option>BBS</option><option>Winlink</option><option>Chat</option><option>Radio</option></select><select id="journal-direction" aria-label="Direzione diario"><option value="">Tutte le direzioni</option><option value="incoming">In ingresso</option><option value="outgoing">In uscita</option><option value="unknown">Non rilevata</option></select><select id="journal-result" aria-label="Esito diario"><option value="">Tutti gli esiti</option><option value="complete">Scambio concluso</option><option value="connected">Collegato</option><option value="failed">Non riuscito</option><option value="incomplete">Esito non registrato</option></select></div><div id="journal-warning" class="journal-warning" hidden></div><div class="journal-layout"><div class="card journal-table-card"><div class="card-header"><h2>Sessioni</h2><span id="journal-count"></span></div><div class="journal-table-scroll"><table class="journal-table"><thead><tr><th>Data e ora</th><th>Stazione / servizio</th><th>Collegamento</th><th>Durata</th><th>TX / RX</th><th>Messaggi</th><th>Esito</th></tr></thead><tbody id="journal-rows"></tbody></table></div></div><aside class="card journal-detail" id="journal-detail"><div class="reader-empty"><span>◷</span><h2>Ogni collegamento ha una storia.</h2><p>Seleziona una sessione per vedere traffico, servizio e sequenza degli eventi.</p></div></aside></div>`;$('main').append(journal);
|
||||||
|
const map=document.createElement('section');map.id='map';map.className='page';map.hidden=true;map.innerHTML=`<div class="journal-heading"><div><span class="eyebrow">CONNECTED STATIONS</span><h1>La rete, sulla mappa.</h1><p>Posizioni dai locator · orari ${esc(mailTimezone())}</p></div><button class="secondary" id="map-refresh">↻ Aggiorna</button></div><div class="map-toolbar"><label><input id="map-tracks" type="checkbox" checked> Mostra collegamenti</label><select id="map-service" aria-label="Servizio mappa"><option value="">Tutti i servizi</option><option>BBS</option><option>Winlink</option><option>Chat</option><option>Radio</option></select><select id="map-period" aria-label="Periodo mappa"><option value="1">24 ore</option><option value="7" selected>7 giorni</option><option value="30">30 giorni</option></select><span id="map-summary"></span></div><div class="map-layout"><div class="card map-card"><div class="map-controls"><button id="map-plus" aria-label="Ingrandisci mappa">+</button><button id="map-minus" aria-label="Riduci mappa">−</button><button id="map-fit">Inquadra rete</button></div><svg id="station-map" viewBox="0 0 1000 500" role="img" aria-label="Mappa interattiva delle stazioni collegate"></svg><div class="map-legend"><span class="legend-radio">● Radio</span><span class="legend-network">● Internet / rete</span><span>◇ Stazione locale</span></div><div class="map-attribution">Natural Earth · pubblico dominio</div></div><aside class="card map-info" id="map-info"></aside></div><div class="card map-stations"><div class="card-header"><h2>Stazioni nel periodo</h2><span id="map-station-count"></span></div><div id="map-station-list"></div></div><p class="journal-footnote">Le tracce uniscono le posizioni delle stazioni: non rappresentano il percorso fisico del segnale. Il punto è il centro del locator, non una posizione GPS esatta. Stazioni nello stesso locator sono separate graficamente. I nominativi senza locator restano nel diario e nell’elenco.</p>`;$('main').append(map);
|
||||||
|
const previousNavigate=navigate;navigate=function(next){previousNavigate(next);if(next==='journal'||next==='map'){$('#breadcrumb').textContent='Stazione / '+(next==='journal'?'Diario':'Mappa');load();}};
|
||||||
|
async function load(force=false){if(!csrf||loading)return;if(data&&!force){render();return;}loading=true;try{data=await api('/journal');if(!land){try{const r=await fetch('/world-land.json');if(r.ok)land=await r.json();}catch{}}render();if(page==='map')fit();}catch(e){toast(e.message);$('#journal-coverage').textContent='Diario non disponibile: '+e.message;}finally{loading=false;}}
|
||||||
|
function filtered(){const q=$('#journal-search').value.toUpperCase(),days=Number($('#journal-period').value),svc=$('#journal-service').value,dir=$('#journal-direction').value,result=$('#journal-result').value;return (data?.sessions||[]).filter(s=>Date.parse(s.startedAt)>=Date.now()-days*86400000&&(!svc||s.service===svc)&&(!dir||s.direction===dir)&&(!result||s.status===result)&&(!q||[s.call,s.localCall,s.service,s.frequency,s.transport].join(' ').toUpperCase().includes(q)));}
|
||||||
|
function render(){if(!data)return;const list=filtered();$('#journal-coverage').textContent='Log disponibili dal '+(data.since||'—')+' · massimo 30 giorni · '+mailTimezone();$('#journal-count').textContent=list.length+' sessioni';const connected=list.filter(s=>s.connectedAt||s.status==='complete');const peers=new Set(list.map(s=>s.call));const tx=list.reduce((a,s)=>a+(s.txBytes||0),0),rx=list.reduce((a,s)=>a+(s.rxBytes||0),0);$('#journal-kpis').innerHTML=[['Sessioni',list.length],['Collegamenti stabiliti',connected.length],['Destinazioni',peers.size],['Traffico registrato',bytes(tx)+' / '+bytes(rx)]].map(([title,value])=>`<article><span>${esc(title)}</span><strong>${esc(value)}</strong></article>`).join('');$('#journal-warning').hidden=!data.warnings.length&&!data.limited;$('#journal-warning').textContent=[...data.warnings,data.limited?'Sono mostrate le 5000 sessioni più recenti.':''].filter(Boolean).join(' · ');$('#journal-rows').innerHTML=list.map(s=>`<tr class="${selected===s.id?'selected':''}"><td><button class="journal-open" data-session="${esc(s.id)}">${esc(time(s.startedAt))}</button><small>${esc(direction(s.direction))}</small></td><td><b>${esc(s.call)}</b><small>${esc(s.service)}</small></td><td><span class="journal-badge ${s.transport==='Radio'?'radio':''}">${esc(transport(s.transport))}</span><small>${s.frequency?esc(s.frequency)+' MHz':s.port?'Porta '+s.port:'—'}</small></td><td>${esc(duration(s.duration))}</td><td><span class="tx-key">↑ ${esc(bytes(s.txBytes))}</span><small class="rx-key">↓ ${esc(bytes(s.rxBytes))}</small></td><td>${s.sentMessages||0} ↑ / ${s.receivedMessages||0} ↓</td><td><span class="journal-result ${esc(s.status)}">${esc(state(s.status))}</span></td></tr>`).join('')||'<tr><td colspan="7" class="empty">Nessuna sessione corrisponde ai filtri.</td></tr>';$$('#journal-rows tr').forEach(row=>{const b=row.querySelector('[data-session]');if(b)row.onclick=()=>detail(b.dataset.session);});if(selected)detail(selected,false);renderMap();}
|
||||||
|
function detail(id,refresh=true){const s=data.sessions.find(s=>s.id===id);if(!s)return;selected=id;const station=data.stations.find(p=>p.call===base(s.call));$('#journal-detail').innerHTML=`<header><span class="eyebrow">${esc(s.service)} · ${esc(direction(s.direction))}</span><h2>${esc(s.call)}</h2><span class="journal-result ${esc(s.status)}">${esc(state(s.status))}</span></header><div class="journal-facts">${[['Inizio',time(s.startedAt)],['Connessione',time(s.connectedAt)],['Fine',time(s.endedAt)],['Durata collegamento',duration(s.duration)],['Trasporto',transport(s.transport)],['Modem',s.mode||'Non registrato'],['Porta BPQ',s.port||'—'],['Frequenza',s.frequency?s.frequency+' MHz':'Non registrata'],['SNR medio',s.snr==null?'—':s.snr+' dB'],['Tentativi',s.attempts?s.attempts+' / '+s.maxAttempts:'—'],['TX',bytes(s.txBytes)],['RX',bytes(s.rxBytes)],['Picco TX / RX',s.peakTxBps==null?'—':s.peakTxBps+' / '+s.peakRxBps+' bit/s'],['Messaggi inviati / ricevuti',s.sentMessages+' / '+s.receivedMessages]].map(([k,v])=>`<div><span>${esc(k)}</span><b>${esc(v)}</b></div>`).join('')}</div><p class="journal-source">${esc(s.trafficScope||'Contatori di traffico non presenti nel log.')}<br>Le statistiche disponibili dipendono dal servizio e dal modem; i trattini indicano dati non registrati.</p>${s.cmsTraffic?`<p class="journal-source">Connessione CMS: TX ${esc(bytes(s.cmsTraffic.txBytes))} / RX ${esc(bytes(s.cmsTraffic.rxBytes))}</p>`:''}${station?'<button id="journal-map-open" class="secondary full">◎ Mostra stazione sulla mappa</button>':''}<h3>Sequenza degli eventi</h3><ol class="journal-timeline">${s.events.map(e=>`<li><time>${esc(time(e.at))}</time><span>${esc(e.text)}</span></li>`).join('')}</ol>${s.messages.length?`<h3>Messaggi trasferiti</h3><div class="journal-transfers">${s.messages.map(m=>`<div><b>${esc(m.direction)} ${m.id?'#'+m.id:''}</b><span>${esc(bytes(m.bytes))} · compressi ${esc(bytes(m.compressedBytes))}</span></div>`).join('')}</div>`:''}<p class="journal-source">Fonti: ${esc([...new Set(s.sources)].join(', '))}</p>`;if($('#journal-map-open'))$('#journal-map-open').onclick=()=>{mapCall=station.call;navigate('map');renderMap();fit();};if(refresh)$$('#journal-rows tr').forEach(row=>row.classList.toggle('selected',row.querySelector('[data-session]')?.dataset.session===id));}
|
||||||
|
function mapSessions(){const days=Number($('#map-period').value),svc=$('#map-service').value;return (data?.sessions||[]).filter(s=>Date.parse(s.startedAt)>=Date.now()-days*86400000&&(!svc||s.service===svc)&&(s.connectedAt||s.status==='complete'));}
|
||||||
|
function mapStations(){const calls=new Set(mapSessions().map(s=>base(s.call)));return (data?.stations||[]).filter(s=>calls.has(s.call));}
|
||||||
|
const xy=p=>[(p.lon+180)*1000/360,(90-p.lat)*500/180];
|
||||||
|
function landPath(){if(!land)return '';const polygon=rings=>rings.map(r=>r.map((p,i)=>(i?'L':'M')+xy({lon:p[0],lat:p[1]}).map(n=>n.toFixed(3)).join(' ')).join(' ')+'Z').join(' ');return land.features.map(f=>f.geometry.type==='Polygon'?polygon(f.geometry.coordinates):f.geometry.type==='MultiPolygon'?f.geometry.coordinates.map(polygon).join(' '):'').join(' ');}
|
||||||
|
let cachedLand='';
|
||||||
|
function renderMap(){if(!data)return;const stations=mapStations(),known=stations.filter(s=>s.position),own=data.own.position,svg=$('#station-map'),scale=view[2]/1000;$('#map-summary').textContent=known.length+' sulla mappa · '+(stations.length-known.length)+' senza locator';$('#map-station-count').textContent=stations.length+' stazioni';if(!cachedLand&&land)cachedLand=landPath();let content=`<defs><radialGradient id="map-sea"><stop stop-color="#17354d"/><stop offset="1" stop-color="#0b1624"/></radialGradient></defs><rect x="0" y="0" width="1000" height="500" fill="url(#map-sea)"/><path class="map-land" d="${cachedLand}"/>`;
|
||||||
|
for(let x=0;x<=1000;x+=1000/12)content+=`<path class="map-gridline" d="M${x} 0V500"/>`;for(let y=0;y<=500;y+=500/6)content+=`<path class="map-gridline" d="M0 ${y}H1000"/>`;
|
||||||
|
const local=own?xy(own):null;for(const s of known){let [x,y]=xy(s.position);const same=local&&Math.hypot(x-local[0],y-local[1])<scale*20;if(same){x+=scale*34;y-=scale*22;}const sessions=mapSessions().filter(r=>base(r.call)===s.call),radio=sessions.some(r=>r.transport==='Radio'),color=radio?'#96d6c0':'#91bdea';if(local&&$('#map-tracks').checked){const mx=(x+local[0])/2,my=(y+local[1])/2-Math.min(55,Math.abs(x-local[0])*.18+scale*10);content+=`<path class="map-track ${mapCall===s.call?'selected':''}" data-map-call="${esc(s.call)}" d="M${local[0]} ${local[1]} Q${mx} ${my} ${x} ${y}" stroke="${color}"><title>${esc(data.own.call+' ↔ '+s.call+' · '+sessions.length+' sessioni')}</title></path>`;}
|
||||||
|
content+=`<g class="map-point ${mapCall===s.call?'selected':''}" data-map-call="${esc(s.call)}" role="button" tabindex="0" aria-label="Dettagli stazione ${esc(s.call)}"><rect x="${x-scale*12}" y="${y-scale*24}" width="${scale*115}" height="${scale*40}" fill="transparent" pointer-events="all"/><circle cx="${x}" cy="${y}" r="${scale*11}" fill="${color}" opacity=".14"/><circle cx="${x}" cy="${y}" r="${scale*4.8}" fill="${color}"/><text x="${x+scale*9}" y="${y-scale*8}" font-size="${scale*12}" fill="${color}">${esc(s.call)}</text><title>${esc(s.call+' · '+s.position.locator+' · ultimo collegamento '+time(sessions[0]?.startedAt))}</title></g>`;}
|
||||||
|
if(local)content+=`<g class="map-local"><path d="M${local[0]} ${local[1]-scale*7}l${scale*7} ${scale*7}l${-scale*7} ${scale*7}l${-scale*7} ${-scale*7}Z" fill="#f0d498"/><text x="${local[0]-scale*10}" y="${local[1]+scale*19}" font-size="${scale*12}" text-anchor="end" fill="#f0d498">${esc(data.own.call)}</text></g>`;
|
||||||
|
svg.innerHTML=content;svg.setAttribute('viewBox',view.join(' '));$$('#station-map [data-map-call]').forEach(el=>{el.onclick=e=>{if(moved)return;e.stopPropagation();mapCall=el.dataset.mapCall;renderMap();};el.onkeydown=e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();mapCall=el.dataset.mapCall;renderMap();}};});
|
||||||
|
$('#map-station-list').innerHTML=stations.map(s=>`<button class="map-station ${mapCall===s.call?'selected':''}" data-peer="${esc(s.call)}"><b>${esc(s.call)}</b><span>${s.position?esc(s.position.locator):'+ Aggiungi locator'}</span><small>${esc(s.services.join(' · '))}</small></button>`).join('')||'<p class="empty">Nessun collegamento stabilito nel periodo selezionato.</p>';$$('[data-peer]').forEach(b=>b.onclick=()=>{mapCall=b.dataset.peer;renderMap();});mapInfo(stations.find(s=>s.call===mapCall));}
|
||||||
|
function mapInfo(s){if(!s){$('#map-info').innerHTML=`<div class="map-info-empty"><span>◎</span><h2>Scegli una stazione.</h2><p>Clicca un punto, una traccia o un nominativo nell’elenco.</p>${!data.own.position?'<p>Il LOCATOR della stazione locale non è presente in BPQ: le tracce non possono essere disegnate.</p>':''}</div>`;return;}
|
||||||
|
const sessions=mapSessions().filter(r=>base(r.call)===s.call),latest=sessions[0];$('#map-info').innerHTML=`<header><span class="eyebrow">STAZIONE COLLEGATA</span><h2>${esc(s.call)}</h2><p>${s.position?esc(s.position.locator)+' · '+(s.distance==null?'Distanza non disponibile':s.distance===0?'Stesso locator del nodo':s.distance+' km dal nodo'):'Posizione non disponibile'}</p></header><div class="map-last"><span>Ultimo collegamento nel periodo</span><b>${esc(time(latest?.startedAt))}</b><small>${esc(latest?.service||'')} · ${esc(transport(latest?.transport))} · ${esc(direction(latest?.direction))}</small></div><form id="locator-form"><label>Locator Maidenhead<input id="station-locator" name="locator" required maxlength="8" placeholder="Es. JN45NN" value="${esc(s.position?.locator||'')}"></label><button class="secondary" type="submit">Salva posizione</button><small>${esc(s.position?.source||'Inserisci il locator comunicato dalla stazione.')}</small></form><h3>${sessions.length} collegamenti nel periodo</h3><div class="map-recent">${sessions.slice(0,8).map(r=>`<button data-map-session="${esc(r.id)}"><b>${esc(r.service)} <span>${esc(duration(r.duration))}</span></b><small>${esc(time(r.startedAt))}</small><small>TX ${esc(bytes(r.txBytes))} / RX ${esc(bytes(r.rxBytes))}</small></button>`).join('')}</div>`;$('#locator-form').onsubmit=async e=>{e.preventDefault();try{data=await api('/stations/location',{method:'POST',body:JSON.stringify({call:s.call,locator:$('#station-locator').value})});render();fit();toast('Locator salvato per '+s.call);}catch(err){toast(err.message)}};$$('[data-map-session]').forEach(b=>b.onclick=()=>{navigate('journal');detail(b.dataset.mapSession);});}
|
||||||
|
function fit(){const points=mapStations().filter(s=>s.position).map(s=>xy(s.position));if(data?.own.position)points.push(xy(data.own.position));if(!points.length){view=[0,0,1000,500];renderMap();return;}const xs=points.map(p=>p[0]),ys=points.map(p=>p[1]);const w=Math.min(1000,Math.max(100,(Math.max(...xs)-Math.min(...xs))*1.7,(Math.max(...ys)-Math.min(...ys))*3.4)),cx=(Math.min(...xs)+Math.max(...xs))/2,cy=(Math.min(...ys)+Math.max(...ys))/2;view=[Math.max(0,Math.min(1000-w,cx-w/2)),Math.max(0,Math.min(500-w/2,cy-w/4)),w,w/2];renderMap();}
|
||||||
|
function zoom(factor){const w=Math.max(5,Math.min(1000,view[2]*factor)),cx=view[0]+view[2]/2,cy=view[1]+view[3]/2;view=[Math.max(0,Math.min(1000-w,cx-w/2)),Math.max(0,Math.min(500-w/2,cy-w/4)),w,w/2];renderMap();}
|
||||||
|
$('#map-plus').onclick=()=>zoom(.65);$('#map-minus').onclick=()=>zoom(1.5);$('#map-fit').onclick=fit;$('#map-tracks').onchange=renderMap;for(const id of ['map-period','map-service'])$('#'+id).onchange=()=>{mapCall=null;renderMap();fit();};
|
||||||
|
const svg=$('#station-map');svg.addEventListener('pointerdown',e=>{drag={x:e.clientX,y:e.clientY,view:[...view]};moved=false});svg.addEventListener('pointermove',e=>{if(!drag)return;const box=svg.getBoundingClientRect(),dx=(e.clientX-drag.x)*drag.view[2]/box.width,dy=(e.clientY-drag.y)*drag.view[3]/box.height;if(Math.abs(e.clientX-drag.x)+Math.abs(e.clientY-drag.y)>4){moved=true;if(!svg.hasPointerCapture(e.pointerId))svg.setPointerCapture(e.pointerId);}view=[drag.view[0]-dx,drag.view[1]-dy,...drag.view.slice(2)];svg.setAttribute('viewBox',view.join(' '));});svg.addEventListener('pointerup',()=>{drag=null;setTimeout(()=>moved=false,0)});svg.addEventListener('pointercancel',()=>{drag=null});
|
||||||
|
for(const id of ['journal-search','journal-period','journal-service','journal-direction','journal-result'])$('#'+id).oninput=render;
|
||||||
|
$('#journal-refresh').onclick=()=>load(true);$('#map-refresh').onclick=()=>load(true);
|
||||||
|
$('#journal-export').onclick=()=>{const quote=v=>'"'+String(v??'').replaceAll('"','""')+'"';const rows=[['Stazione','Servizio','Trasporto','Direzione','Inizio UTC','Connessione UTC','Fine UTC','Durata s','Frequenza MHz','TX byte','RX byte','Messaggi TX','Messaggi RX','Esito'],...filtered().map(s=>[s.call,s.service,s.transport,s.direction,s.startedAt,s.connectedAt,s.endedAt,s.duration,s.frequency,s.txBytes,s.rxBytes,s.sentMessages,s.receivedMessages,s.status])];const url=URL.createObjectURL(new Blob(['\ufeff'+rows.map(row=>row.map(quote).join(';')).join('\r\n')],{type:'text/csv;charset=utf-8'})),a=document.createElement('a');a.href=url;a.download='BPQ-diario-'+new Date().toISOString().slice(0,10)+'.csv';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
|
||||||
|
setInterval(()=>{if(csrf&&!document.hidden&&['journal','map'].includes(page))load(true)},30000);
|
||||||
|
document.addEventListener('station-ready',()=>{if(['journal','map'].includes(page))load();});
|
||||||
|
document.addEventListener('DOMContentLoaded',()=>{const hash=location.hash.slice(1);if(['journal','map'].includes(hash))navigate(hash)});
|
||||||
|
})();
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"type":"FeatureCollection","name":"ne_110m_land","crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:OGC:1.3:CRS84"}},"features":[{"type":"Feature","properties":{"featurecla":"Land","scalerank":1,"min_zoom":1},"bbox":[-66.290031,-81.000327,-59.572095,-79.628679],"geometry":{"type":"Polygon","coordinates":[[[-59.572095,-80.040179],[-59.865849,-80.549657],[-60.159656,-81.000327],[-62.255393,-80.863178],[-64.488125,-80.921934],[-65.741666,-80.588827],[-65.741666,-80.549657],[-66.290031,-80.255773],[-64.037688,-80.294944],[-61.883246,-80.39287],[-61.138976,-79.981371],[-60.610119,-79.628679],[-59.572095,-80.040179]]]}},{"type":"Feature","properties":{"featurecla":"Land","scalerank":1,"min_zoom":1},"bbox":[-163.712896,-79.634209,-159.208184,-78.223338],"geometry":{"type":"Polygon","coordinates":[[[-159.208184,-79.497059],[-161.127601,-79.634209],[-162.439847,-79.281465],[-163.027408,-78.928774],[-163.066604,-78.869966],[-163.712896,-78.595667],[-163.712896,-78.595667],[-163.105801,-78.223338],[-161.245113,-78.380176],[-160.246208,-78.693645],[-159.482405,-79.046338],[-159.208184,-79.497059]]]}},{"type":"Feature","properties":{"featurecla":"Land","scalerank":1,"min_zoom":0},"bbox":[-54.164259,-81.025442,-43.333267,-77.831476],"geometry":{"type":"Polygon","coordinates":[[[-45.154758,-78.04707],[-43.920828,-78.478103],[-43.48995,-79.08556],[-43.372438,-79.516645],[-43.333267,-80.026123],[-44.880537,-80.339644],[-46.506174,-80.594357],[-48.386421,-80.829485],[-50.482107,-81.025442],[-52.851988,-80.966685],[-54.164259,-80.633528],[-53.987991,-80.222028],[-51.853134,-79.94773],[-50.991326,-79.614623],[-50.364595,-79.183487],[-49.914131,-78.811209],[-49.306959,-78.458569],[-48.660616,-78.047018],[-48.660616,-78.047019],[-48.151396,-78.04707],[-46.662857,-77.831476],[-45.154758,-78.04707]]]}},{"type":"Feature","properties":{"featurecla":"Land","scalerank":1,"min_zoom":1},"bbox":[-122.621735,-74.08881,-118.724143,-73.324619],"geometry":{"type":"Polygon","coordinates":[[[-121.211511,-73.50099],[-119.918851,-73.657725],[-118.724143,-73.481353],[-119.292119,-73.834097],[-120.232217,-74.08881],[-121.62283,-74.010468],[-122.621735,-73.657778],[-122.621735,-73.657777],[-122.406245,-73.324619],[-121.211511,-73.50099]]]}},{"type":"Feature","properties":{"featurecla":"Land","scalerank":1,"min_zoom":1},"bbox":[-127.28313,-73.873268,-124.031882,-73.246226],"geometry":{"type":"Polygon","coordinates":[[[-125.559566,-73.481353],[-124.031882,-73.873268],[-124.619469,-73.834097],[-125.912181,-73.736118],[-127.28313,-73.461769],[-127.28313,-73.461768],[-126.558472,-73.246226],[-125.559566,-73.481353]]]}},{"type":"Feature","properties":{"featurecla":"Land","scalerank":1,"min_zoom":1},"bbox":[-102.330725,-72.521205,-96.20035,-71.717792],"geometry":{"type":"Polygon","coordinates":[[[-98.98155,-71.933334],[-97.884743,-72.070535],[-96.787937,-71.952971],[-96.20035,-72.521205],[-96.983765,-72.442864],[-98.198083,-72.482035],[-99.432013,-72.442864],[-100.783455,-72.50162],[-101.801868,-72.305663],[-102.330725,-71.894164],[-102.330725,-71.894164],[-101.703967,-71.717792],[-100.430919,-71.854993],[-98.98155,-71.933334]]]}},{"type":"Feature","properties":{"featurecla":"Land","scalerank":1,"min_zoom":1},"bbox":[-75.012625,-72.503842,-68.333834,-68.87874],"geometry":{"type":"Polygon","coordinates":[[[-68.451346,-70.955823],[-68.333834,-71.406493],[-68.510128,-71.798407],[-68.784297,-72.170736],[-69.959471,-72.307885],[-71.075889,-72.503842],[-72.388134,-72.484257],[-71.8985,-72.092343],[-73.073622,-72.229492],[-74.19004,-72.366693],[-74.953895,-72.072757],[-75.012625,-71.661258],[-73.915819,-71.269345],[-73.915819,-71.269344],[-73.230331,-71.15178],[-72.074717,-71.190951],[-71.780962,-70.681473],[-71.72218,-70.309196],[-71.741791,-69.505782],[-71.173815,-69.035475],[-70.253252,-68.87874],[-69.724447,-69.251017],[-69.489422,-69.623346],[-69.058518,-70.074016],[-68.725541,-70.505153],[-68.451346,-70.955823]]]}},{"type":"Feature","properties":{"featurecla":"Land","scalerank":0,"min_zoom":0},"bbox":[-180,-90,180,-63.27066],"geometry":{"type":"Polygon","coordinates":[[[-58.614143,-64.152467],[-59.045073,-64.36801],[-59.789342,-64.211223],[-60.611928,-64.309202],[-61.297416,-64.54433],[-62.0221,-64.799094],[-62.51176,-65.09303],[-62.648858,-65.484942],[-62.590128,-65.857219],[-62.120079,-66.190326],[-62.805567,-66.425505],[-63.74569,-66.503847],[-64.294106,-66.837004],[-64.881693,-67.150474],[-65.508425,-67.58161],[-65.665082,-67.953887],[-65.312545,-68.365335],[-64.783715,-68.678908],[-63.961103,-68.913984],[-63.1973,-69.227556],[-62.785955,-69.619419],[-62.570516,-69.991747],[-62.276736,-70.383661],[-61.806661,-70.716768],[-61.512906,-71.089045],[-61.375809,-72.010074],[-61.081977,-72.382351],[-61.003661,-72.774265],[-60.690269,-73.166179],[-60.827367,-73.695242],[-61.375809,-74.106742],[-61.96337,-74.439848],[-63.295201,-74.576997],[-63.74569,-74.92974],[-64.352836,-75.262847],[-65.860987,-75.635124],[-67.192818,-75.79191],[-68.446282,-76.0074Line truncated
|
||||||
+5
-1
@@ -1,4 +1,5 @@
|
|||||||
import http from 'node:http';
|
import http from 'node:http';
|
||||||
|
import {Journal} from './journal.mjs';
|
||||||
import {loadConfig,parseConfig,publicConfig,ownCall} from './config.mjs';
|
import {loadConfig,parseConfig,publicConfig,ownCall} from './config.mjs';
|
||||||
import {readFile, stat} from 'node:fs/promises';
|
import {readFile, stat} from 'node:fs/promises';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
@@ -16,6 +17,7 @@ import {parseAttachments,safeName,b2Body} from './attachments.mjs';
|
|||||||
const dir=path.dirname(fileURLToPath(import.meta.url));
|
const dir=path.dirname(fileURLToPath(import.meta.url));
|
||||||
const config=await loadConfig();
|
const config=await loadConfig();
|
||||||
const root=config.root;
|
const root=config.root;
|
||||||
|
const journal=new Journal(config,dir);
|
||||||
const upstream='http://127.0.0.1:'+config.httpPort;
|
const upstream='http://127.0.0.1:'+config.httpPort;
|
||||||
const sessions=new Map(), attempts=new Map();
|
const sessions=new Map(), attempts=new Map();
|
||||||
const port=config.port;
|
const port=config.port;
|
||||||
@@ -107,6 +109,8 @@ const server=http.createServer(async(req,res)=>{
|
|||||||
if(url.pathname==='/api/chat/send'&&req.method==='POST'){const data=await body(req);chat.send(data.text,data.to);json(res,200,{ok:true});return;}
|
if(url.pathname==='/api/chat/send'&&req.method==='POST'){const data=await body(req);chat.send(data.text,data.to);json(res,200,{ok:true});return;}
|
||||||
if(url.pathname==='/api/chat/topic'&&req.method==='POST'){chat.changeTopic((await body(req)).topic);json(res,200,{ok:true});return;}
|
if(url.pathname==='/api/chat/topic'&&req.method==='POST'){chat.changeTopic((await body(req)).topic);json(res,200,{ok:true});return;}
|
||||||
if(url.pathname==='/api/logout'&&req.method==='POST'){const token=req.headers.cookie.match(/alnode=([a-f0-9]+)/)?.[1];sessions.delete(token);res.setHeader('Set-Cookie','alnode=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0');json(res,200,{ok:true});return;}
|
if(url.pathname==='/api/logout'&&req.method==='POST'){const token=req.headers.cookie.match(/alnode=([a-f0-9]+)/)?.[1];sessions.delete(token);res.setHeader('Set-Cookie','alnode=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0');json(res,200,{ok:true});return;}
|
||||||
|
if(url.pathname==='/api/journal'&&req.method==='GET'){json(res,200,await journal.snapshot());return;}
|
||||||
|
if(url.pathname==='/api/stations/location'&&req.method==='POST'){const data=await body(req);json(res,200,await journal.saveLocation(String(data.call||''),String(data.locator||'')));return;}
|
||||||
if(url.pathname==='/api/dashboard'){json(res,200,await dashboard());return;}
|
if(url.pathname==='/api/dashboard'){json(res,200,await dashboard());return;}
|
||||||
if(url.pathname==='/api/telemetry'&&req.method==='GET'){json(res,200,telemetry);return;}
|
if(url.pathname==='/api/telemetry'&&req.method==='GET'){json(res,200,telemetry);return;}
|
||||||
if(url.pathname==='/api/messages'&&req.method==='GET'){json(res,200,await messages());return;}
|
if(url.pathname==='/api/messages'&&req.method==='GET'){json(res,200,await messages());return;}
|
||||||
@@ -123,7 +127,7 @@ const server=http.createServer(async(req,res)=>{
|
|||||||
}
|
}
|
||||||
if(req.method!=='GET'){json(res,405,{error:'Metodo non disponibile'});return;}
|
if(req.method!=='GET'){json(res,405,{error:'Metodo non disponibile'});return;}
|
||||||
const vendor=url.pathname.match(/^\/vendor\/pdfjs\/(pdf\.min\.mjs|pdf\.worker\.min\.mjs|(?:standard_fonts|cmaps)\/[A-Za-z0-9_.-]+)$/);if(vendor&&!vendor[1].includes('..')){const bytes=await readFile(path.join(dir,'public','vendor','pdfjs',vendor[1]));res.writeHead(200,{'Content-Type':vendor[1].endsWith('.mjs')?'text/javascript':'application/octet-stream','Cache-Control':'public, max-age=86400'});res.end(bytes);return;}
|
const vendor=url.pathname.match(/^\/vendor\/pdfjs\/(pdf\.min\.mjs|pdf\.worker\.min\.mjs|(?:standard_fonts|cmaps)\/[A-Za-z0-9_.-]+)$/);if(vendor&&!vendor[1].includes('..')){const bytes=await readFile(path.join(dir,'public','vendor','pdfjs',vendor[1]));res.writeHead(200,{'Content-Type':vendor[1].endsWith('.mjs')?'text/javascript':'application/octet-stream','Cache-Control':'public, max-age=86400'});res.end(bytes);return;}
|
||||||
const files={'/monitor.js':'monitor.js','/monitor.css':'monitor.css','/':'index.html','/app.js':'app.js','/enhancements.js':'enhancements.js','/notifications.js':'notifications.js','/winlink.js':'winlink.js','/mission.js':'mission.js','/attachments.js':'attachments.js','/mission.css':'mission.css','/style.css':'style.css','/dark.css':'dark.css'};const file=files[url.pathname];if(!file){json(res,404,{error:'Pagina non trovata'});return;}const bytes=await readFile(path.join(dir,'public',file));res.writeHead(200,{'Content-Type':file.endsWith('.css')?'text/css; charset=utf-8':file.endsWith('.js')?'text/javascript; charset=utf-8':'text/html; charset=utf-8','Cache-Control':'no-cache'});res.end(bytes);
|
const files={'/journal.js':'journal.js','/journal.css':'journal.css','/world-land.json':'world-land.json','/monitor.js':'monitor.js','/monitor.css':'monitor.css','/':'index.html','/app.js':'app.js','/enhancements.js':'enhancements.js','/notifications.js':'notifications.js','/winlink.js':'winlink.js','/mission.js':'mission.js','/attachments.js':'attachments.js','/mission.css':'mission.css','/style.css':'style.css','/dark.css':'dark.css'};const file=files[url.pathname];if(!file){json(res,404,{error:'Pagina non trovata'});return;}const bytes=await readFile(path.join(dir,'public',file));res.writeHead(200,{'Content-Type':file.endsWith('.json')?'application/json':file.endsWith('.css')?'text/css; charset=utf-8':file.endsWith('.js')?'text/javascript; charset=utf-8':'text/html; charset=utf-8','Cache-Control':'no-cache'});res.end(bytes);
|
||||||
}catch(e){json(res,502,{error:e.message||'BPQ temporaneamente non disponibile'});}
|
}catch(e){json(res,502,{error:e.message||'BPQ temporaneamente non disponibile'});}
|
||||||
});
|
});
|
||||||
server.listen(port,'0.0.0.0',()=>console.log(`BPQ Console: http://127.0.0.1:${port}`));
|
server.listen(port,'0.0.0.0',()=>console.log(`BPQ Console: http://127.0.0.1:${port}`));
|
||||||
@@ -55,7 +55,7 @@ test('generic PACTOR station runs without VARA, chat, monitor or BBS',async()=>{
|
|||||||
try{
|
try{
|
||||||
await new Promise((resolve,reject)=>{const timeout=setTimeout(()=>reject(new Error('Server fixture timeout')),8000);child.stdout.once('data',()=>{clearTimeout(timeout);resolve()});child.once('exit',code=>{clearTimeout(timeout);reject(new Error('Server fixture exited '+code))})});
|
await new Promise((resolve,reject)=>{const timeout=setTimeout(()=>reject(new Error('Server fixture timeout')),8000);child.stdout.once('data',()=>{clearTimeout(timeout);resolve()});child.once('exit',code=>{clearTimeout(timeout);reject(new Error('Server fixture exited '+code))})});
|
||||||
const base='http://127.0.0.1:18991';const login=await fetch(base+'/api/login',{method:'POST',headers:{Origin:base,'Content-Type':'application/json'},body:JSON.stringify({user:'admin',password:'fixture'})});assert.equal(login.status,200);const user=await login.json();assert.equal(user.call,'N9DEMO');assert.equal(user.config.features.vara,false);assert.equal(user.config.features.bbs,false);assert.equal(user.config.radio.id,3);assert.equal(JSON.stringify(user.config).includes('fixture'),false);
|
const base='http://127.0.0.1:18991';const login=await fetch(base+'/api/login',{method:'POST',headers:{Origin:base,'Content-Type':'application/json'},body:JSON.stringify({user:'admin',password:'fixture'})});assert.equal(login.status,200);const user=await login.json();assert.equal(user.call,'N9DEMO');assert.equal(user.config.features.vara,false);assert.equal(user.config.features.bbs,false);assert.equal(user.config.radio.id,3);assert.equal(JSON.stringify(user.config).includes('fixture'),false);
|
||||||
const headers={Cookie:login.headers.get('set-cookie').split(';')[0]};assert.equal((await fetch(base+'/api/chat',{headers})).status,409);assert.equal((await fetch(base+'/api/monitor',{headers})).status,409);assert.equal((await fetch(base+'/api/winlink',{headers})).status,409);
|
const headers={Cookie:login.headers.get('set-cookie').split(';')[0]};const logbook=await fetch(base+'/api/journal',{headers});assert.equal(logbook.status,200);assert.deepEqual((await logbook.json()).sessions,[]);const denied=await fetch(base+'/api/stations/location',{method:'POST',headers:{...headers,Origin:base,'Content-Type':'application/json'},body:JSON.stringify({call:'N3TEST',locator:'JN45NN'})});assert.equal(denied.status,403);assert.equal((await fetch(base+'/api/chat',{headers})).status,409);assert.equal((await fetch(base+'/api/monitor',{headers})).status,409);assert.equal((await fetch(base+'/api/winlink',{headers})).status,409);
|
||||||
await new Promise(r=>setTimeout(r,1200));const telemetry=await (await fetch(base+'/api/telemetry',{headers})).json();assert.equal(telemetry.current.available,true);assert.equal(telemetry.current.nativeRate.listening,false);assert.equal(telemetry.current.varaCpu,null);assert.equal(telemetry.current.sent,12);
|
await new Promise(r=>setTimeout(r,1200));const telemetry=await (await fetch(base+'/api/telemetry',{headers})).json();assert.equal(telemetry.current.available,true);assert.equal(telemetry.current.nativeRate.listening,false);assert.equal(telemetry.current.varaCpu,null);assert.equal(telemetry.current.sent,12);
|
||||||
const dash=await (await fetch(base+'/api/dashboard',{headers})).json();assert.equal(dash.counts.messages,0);
|
const dash=await (await fetch(base+'/api/dashboard',{headers})).json();assert.equal(dash.counts.messages,0);
|
||||||
}finally{child.kill();await new Promise(r=>child.once('exit',r));await new Promise(r=>upstream.close(r));await fs.rm(tmp,{recursive:true,force:true});}
|
}finally{child.kill();await new Promise(r=>child.once('exit',r));await new Promise(r=>upstream.close(r));await fs.rm(tmp,{recursive:true,force:true});}
|
||||||
@@ -65,3 +65,13 @@ test('generic own-call handling accepts SSIDs without station constants',()=>{as
|
|||||||
test('configuration detects a Telnet-only node without inventing a modem',async()=>{const {parseConfig}=await import('./config.mjs');const c=parseConfig('NODECALL=N8TEST-7\nPORT\nDRIVER=Telnet.dll\nPORTNUM=2\nHTTPPORT=8088\nTCPPORT=9000\nENDPORT');assert.equal(c.httpPort,8088);assert.equal(c.telnetPort,9000);assert.deepEqual(c.radioPorts,[]);assert.equal(c.call,'N8TEST');});
|
test('configuration detects a Telnet-only node without inventing a modem',async()=>{const {parseConfig}=await import('./config.mjs');const c=parseConfig('NODECALL=N8TEST-7\nPORT\nDRIVER=Telnet.dll\nPORTNUM=2\nHTTPPORT=8088\nTCPPORT=9000\nENDPORT');assert.equal(c.httpPort,8088);assert.equal(c.telnetPort,9000);assert.deepEqual(c.radioPorts,[]);assert.equal(c.call,'N8TEST');});
|
||||||
|
|
||||||
test('empty modem state after restart remains idle',()=>{assert.equal(parseRadio('Comms State Connected to VARA TNC TNC State Mode Channel State Clear').state,'Free');});
|
test('empty modem state after restart remains idle',()=>{assert.equal(parseRadio('Comms State Connected to VARA TNC TNC State Mode Channel State Clear').state,'Free');});
|
||||||
|
|
||||||
|
|
||||||
|
test('journal locator conversion validates grid precision and distance',async()=>{const {locatorPosition,distanceKm}=await import('./journal.mjs');const a=locatorPosition('JN45NN');assert.ok(Math.abs(a.lat-45.56)<.03);assert.ok(Math.abs(a.lon-9.12)<.05);assert.equal(locatorPosition('ZZ99ZZ'),null);assert.equal(locatorPosition('JN45NN00').locator,'JN45NN00');assert.equal(distanceKm(a,a),0);assert.ok(distanceKm(a,locatorPosition('IM75IV'))>1500);});
|
||||||
|
test('journal merges VARA traffic and BBS messages without duplicating session',async()=>{const {parseVaraLog,parseBbsLog,mergeSessions}=await import('./journal.mjs');const radio=parseVaraLog('2026-10-15 12:00:00 ->CONNECT N0TEST-11 N1TEST-8\n2026-10-15 12:00:10 <-CONNECTED N0TEST-11 N1TEST-8 2300\n2026-10-15 12:01:00 N1TEST-8 Average S/N: 12,3 dB\n2026-10-15 12:01:00 Disconnected TX: 127 Bytes (Max: 270 bps) RX: 3180 Bytes (Max: 500 bps)');const bbs=parseBbsLog('261015 12:00:00 |N1TEST Connecting to BBS N1TEST\n261015 12:00:00 >N1TEST ATTACH 3\n261015 12:00:00 >N1TEST RADIO 14.100 USB\n261015 12:00:30 |N1TEST Uncompressing Message Comp Len 300 Msg Len 800 CRC abcd\n261015 12:00:31 ?N1TEST Msg 20 Routing Trace To WX Via WW\n261015 12:00:59 <N1TEST FQ\n261015 12:01:00 |N1TEST N1TEST Disconnected');const out=mergeSessions(bbs,radio,[]);assert.equal(out.length,1);assert.equal(out[0].service,'BBS');assert.equal(out[0].status,'complete');assert.equal(out[0].txBytes,127);assert.equal(out[0].rxBytes,3180);assert.equal(out[0].receivedMessages,1);assert.equal(out[0].messages[0].id,20);assert.equal(out[0].duration,50);assert.equal(out[0].frequency,14.1);assert.equal(out[0].port,3);assert.equal(out[0].snr,12.3);});
|
||||||
|
test('journal recognizes incoming Winlink and keeps CMS counters separate',async()=>{const {parseVaraLog,parseCmsLog,mergeSessions}=await import('./journal.mjs');const radio=parseVaraLog('2026-10-15 12:00:00 Incoming connection...\n2026-10-15 12:00:05 N2TEST connected VARA HF v4.9.0\n2026-10-15 12:01:00 Disconnected TX: 100 Bytes (Max: 270 bps) RX: 200 Bytes (Max: 270 bps)','VARA','N0TEST');const cms=parseCmsLog('12:00:10 15 N2TEST Connected to CMS\n12:00:59 15 Disconnected. Bytes Sent = 80 Bytes Received 50 Time 49 Seconds','2026-10-15','N0TEST');const list=mergeSessions([],radio,cms);assert.equal(list.length,1);assert.equal(list[0].service,'Winlink');assert.equal(list[0].direction,'incoming');assert.equal(list[0].txBytes,100);assert.equal(list[0].cmsTraffic.txBytes,80);});
|
||||||
|
test('journal never exposes credentials or mail/chat text from raw logs',async()=>{const {parseBbsLog,parseCmsLog}=await import('./journal.mjs');const log='261015 12:00:00 |RMS Connecting to BBS RMS\n261015 12:00:01 >RMS ;PR: secret-fixture\n261015 12:00:02 <RMS private-message-fixture\n261015 12:00:04 |RMS RMS Disconnected';const out=JSON.stringify(parseBbsLog(log));assert.equal(out.includes('secret-fixture'),false);assert.equal(out.includes('private-message-fixture'),false);const cms=parseCmsLog('23:59:00 15 N0TEST-11 Connected to CMS\n23:59:20 15 Disconnected. Bytes Sent = 12 Bytes Received 13 Time 20 Seconds','2026-10-15','N0TEST');assert.equal(cms[0].call,'CMS');assert.equal(cms[0].transport,'Internet');assert.equal(cms[0].endedAt,'2026-10-15T23:59:20Z');});
|
||||||
|
|
||||||
|
test('journal keeps simultaneous rejected inbound and successful outbound calls separate',async()=>{const {parseVaraLog,parseBbsLog,mergeSessions}=await import('./journal.mjs');const radio=parseVaraLog('2026-10-15 12:00:02 ->CONNECT N0TEST-11 N1TEST-8\n2026-10-15 12:00:20 <-CONNECTED N0TEST-11 N1TEST-8 2300\n2026-10-15 12:01:00 Disconnected TX: 10 Bytes (Max: 270 bps) RX: 20 Bytes (Max: 270 bps)');const bbs=parseBbsLog('261015 12:00:00 |N1TEST Connecting to BBS N1TEST\n261015 12:00:02 |N1TEST-8 Incoming Connect from N1TEST\n261015 12:00:03 >N1TEST-8 Already Connected\n261015 12:00:04 |N1TEST-8 N1TEST-8 Disconnected\n261015 12:00:20 <N1TEST *** Connected to N1TEST-8\n261015 12:00:59 <N1TEST FQ\n261015 12:01:00 |N1TEST N1TEST Disconnected');const list=mergeSessions(bbs,radio,[]);assert.equal(list.length,2);assert.equal(list.find(s=>s.direction==='incoming').status,'failed');assert.equal(list.find(s=>s.direction==='outgoing').txBytes,10);assert.equal(list.find(s=>s.direction==='outgoing').status,'complete');});
|
||||||
|
|
||||||
|
test('journal saves locators only for observed stations and validates input',async()=>{const {Journal}=await import('./journal.mjs');const fs=await import('node:fs/promises'),path=await import('node:path'),os=await import('node:os');const tmp=await fs.mkdtemp(path.join(os.tmpdir(),'bpq-journal-test-'));try{await fs.mkdir(path.join(tmp,'Logs'));const now=new Date(),date=now.toISOString().slice(0,10).replaceAll('-','');await fs.writeFile(path.join(tmp,'Logs','CMSAccess_'+date+'.log'),'12:00:00 15 N3TEST Connected to CMS\n12:01:00 15 Disconnected. Bytes Sent = 1 Bytes Received 2 Time 60 Seconds');const j=new Journal({root:tmp,sysop:{call:'N0TEST'},nodeCall:'N0TEST-7',locator:'JN45NN'},tmp);await assert.rejects(j.saveLocation('N3TEST','ZZ99ZZ'));await assert.rejects(j.saveLocation('N4OTHER','JN45NN'));const d=await j.saveLocation('N3TEST','JN46LB');assert.equal(d.stations[0].position.locator,'JN46LB');assert.ok(d.stations[0].distance>0);assert.equal(JSON.parse(await fs.readFile(path.join(tmp,'station-locations.json'),'utf8')).N3TEST.locator,'JN46LB');}finally{await fs.rm(tmp,{recursive:true,force:true})}});
|
||||||
Reference in new issue
Block a user