From 106b04d63107ee24249fbaa406b8dc6609759c8f Mon Sep 17 00:00:00 2001 From: alberto Date: Thu, 15 Oct 2026 23:17:44 +0200 Subject: [PATCH] Add connection journal with service traffic details and interactive offline station map --- .gitignore | 3 ++ Install.ps1 | 2 + README.md | 13 ++++++ install.mjs | 2 +- journal.mjs | 81 ++++++++++++++++++++++++++++++++++++ public/WORLD-MAP-LICENSE.txt | 3 ++ public/app.js | 5 ++- public/enhancements.js | 2 +- public/index.html | 2 +- public/journal.css | 1 + public/journal.js | 42 +++++++++++++++++++ public/world-land.json | 1 + server.mjs | 6 ++- test.mjs | 12 +++++- 14 files changed, 168 insertions(+), 7 deletions(-) create mode 100644 journal.mjs create mode 100644 public/WORLD-MAP-LICENSE.txt create mode 100644 public/journal.css create mode 100644 public/journal.js create mode 100644 public/world-land.json diff --git a/.gitignore b/.gitignore index 4adcdfd..20a7151 100644 --- a/.gitignore +++ b/.gitignore @@ -17,3 +17,6 @@ work/ Thumbs.db console.config.json + +station-locations.json +station-locations.json.tmp diff --git a/Install.ps1 b/Install.ps1 index 95f531a..7154819 100644 --- a/Install.ps1 +++ b/Install.ps1 @@ -12,6 +12,8 @@ if(!$BpqRoot){ } $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])")}} +$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'} & $nodeExe @arguments if($LASTEXITCODE -ne 0){throw 'Installazione interrotta: verifica BPQ fallita.'} diff --git a/README.md b/README.md index 4c1f145..c4fafd9 100644 --- a/README.md +++ b/README.md @@ -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. + + +## 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. diff --git a/install.mjs b/install.mjs index d0b6c1f..f845a29 100644 --- a/install.mjs +++ b/install.mjs @@ -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; 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{} -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'); 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.');} diff --git a/journal.mjs b/journal.mjs new file mode 100644 index 0000000..d94b878 --- /dev/null +++ b/journal.mjs @@ -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')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;} +} diff --git a/public/WORLD-MAP-LICENSE.txt b/public/WORLD-MAP-LICENSE.txt new file mode 100644 index 0000000..2092aa3 --- /dev/null +++ b/public/WORLD-MAP-LICENSE.txt @@ -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/ diff --git a/public/app.js b/public/app.js index edff467..a828aab 100644 --- a/public/app.js +++ b/public/app.js @@ -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;} 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 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 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;} @@ -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 →'}}); $('#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); -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){ document.title='BPQ Console · '+station.nodeCall; diff --git a/public/enhancements.js b/public/enhancements.js index 3995b9c..ed1e22d 100644 --- a/public/enhancements.js +++ b/public/enhancements.js @@ -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);}}}); -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); diff --git a/public/index.html b/public/index.html index 1386898..525d6e8 100644 --- a/public/index.html +++ b/public/index.html @@ -1,5 +1,5 @@ -BPQ — Radio & BBS +BPQ — Radio & BBS