20:self.pending.popleft();self.dropped+=1
+ if not self.pending:return None
+ self.current=self.pending.popleft();self.index=0;self.retries=0
+ if now-self.current[0]>20:self.current=None;self.dropped+=1;return None
+ self.waiting=True;self.sentAt=now;return self.current[1][self.index]
+ def ack(self,status,now):
+ if not self.waiting:return 'unsolicited'
+ self.waiting=False
+ if status==0:
+ self.index+=1
+ if self.index==len(self.current[1]):self.current=None;self.readyAt=now+1.0
+ return 'accepted'
+ if status==6 and self.retries<3 and now-self.current[0]<20:
+ self.retries+=1;self.retried+=1;self.index=0;self.readyAt=now+1.5
+ return 'retry'
+ self.current=None;self.dropped+=1;self.readyAt=now+1.5;return 'dropped'
+
+class RadioGate:
+ """Require fresh status and a quiet channel before starting a packet."""
+ def __init__(self):self.updated=None;self.quietSince=None;self.blocked=True
+ def update(self,now,blocked):
+ self.updated=now;self.blocked=blocked
+ if blocked:self.quietSince=None
+ elif self.quietSince is None:self.quietSince=now
+ def allows(self,now,starting=True):
+ return self.updated is not None and 0<=now-self.updated<=0.35 and not self.blocked and (not starting or self.quietSince is not None and now-self.quietSince>=0.3)
diff --git a/integrations/vr-n7500/test_packet_tx.py b/integrations/vr-n7500/test_packet_tx.py
new file mode 100644
index 0000000..f396b23
--- /dev/null
+++ b/integrations/vr-n7500/test_packet_tx.py
@@ -0,0 +1,25 @@
+import sys,pathlib,unittest
+sys.path.insert(0,str(pathlib.Path(__file__).parent))
+from packet_tx import PacketTx,RadioGate
+class Tests(unittest.TestCase):
+ def test_retry_restarts_packet_and_preserves_next(self):
+ q=PacketTx();q.add(b'A'*80,0);q.add(b'B'*10,0)
+ first=q.next(0);q.ack(0,.1);second=q.next(.2);self.assertNotEqual(first,second)
+ self.assertEqual(q.ack(6,.3),'retry');self.assertIsNone(q.next(1));self.assertEqual(q.next(2),first)
+ q.ack(0,2.1);q.next(2.2);q.ack(0,2.3);self.assertIsNone(q.next(2.4));self.assertIn(b'B'*10,q.next(4))
+ def test_retry_limit_drops_only_current(self):
+ q=PacketTx();q.add(b'A',0);q.add(b'B',0)
+ for i in range(4):q.next(i*2);action=q.ack(6,i*2+.1)
+ self.assertEqual(action,'dropped');self.assertEqual(q.dropped,1);self.assertIn(b'B',q.next(9))
+ def test_expiry_and_no_unacknowledged_advance(self):
+ q=PacketTx();q.add(b'A'*80,0);q.next(0);self.assertIsNone(q.next(1));q.ack(0,1);self.assertIsNone(q.next(21));self.assertEqual(q.dropped,1)
+ def test_permanent_error_preserves_pending(self):
+ q=PacketTx();q.add(b'A',0);q.add(b'B',0);q.next(0);self.assertEqual(q.ack(5,.1),'dropped');self.assertIn(b'B',q.next(2))
+class GateTests(unittest.TestCase):
+ def test_unknown_stale_and_recent_busy_never_start(self):
+ g=RadioGate();self.assertFalse(g.allows(1));g.update(1,False);self.assertFalse(g.allows(1.1));g.update(1.2,False);self.assertTrue(g.allows(1.31));self.assertFalse(g.allows(2));g.update(2,True);g.update(2.1,False);self.assertFalse(g.allows(2.2))
+ def test_fragments_continue_without_repeated_quiet_delay(self):
+ g=RadioGate();g.update(1,False);self.assertTrue(g.allows(1.1,starting=False));g.update(1.2,True);self.assertFalse(g.allows(1.21,starting=False));g.update(1.3,False);self.assertTrue(g.allows(1.31,starting=False));self.assertFalse(g.allows(1.31))
+ def test_new_reception_resets_quiet_period(self):
+ g=RadioGate();g.update(0,False);g.update(.2,False);self.assertTrue(g.allows(.31));g.update(.32,True);g.update(.4,False);g.update(.6,False);self.assertFalse(g.allows(.65));self.assertTrue(g.allows(.71))
+unittest.main()
diff --git a/map-refresh-ui.test.mjs b/map-refresh-ui.test.mjs
index ec992e3..7ae7538 100644
--- a/map-refresh-ui.test.mjs
+++ b/map-refresh-ui.test.mjs
@@ -60,22 +60,11 @@ test('APRS removes only stations outside the filter and retains the local marker
});
const journalData=()=>({since:'2026-01-01',warnings:['fixture.log: partial tail'],limited:false,own:{call:'N0LOCAL',position:{lat:44,lon:9}},stations:[station('N0AAA')],sessions:[{id:'one',call:'N0AAA',startedAt:new Date().toISOString(),connectedAt:new Date().toISOString(),service:'BBS',direction:'incoming',transport:'Radio',status:'complete',duration:12}]});
-function journalHarness(){
- let next=journalData();const h=harness('journal.js','globalThis.fixture={load,zoom,renderMap,mapInfo,getView:()=>[...view]};',async()=>structuredClone(next));
- h.context.page='map';h.$('#map-period').value='7';h.$('#journal-period').value='7';h.$('#map-tracks').checked=true;
- return {...h,setNext:value=>next=value};
-}
-test('journal refresh keeps the zoom and unchanged SVG instead of fitting or rebuilding the map',async()=>{
- const h=journalHarness();await h.fixture.load();h.fixture.zoom(.65);const view=h.fixture.getView(),svg=h.$('#station-map'),writes=svg.writes;
- await h.fixture.load(true,true);await h.fixture.load(true,true);
- assert.deepEqual(h.fixture.getView(),view);assert.equal(svg.writes,writes);
+test('journal loads without the removed station map and preserves coverage warnings',async()=>{
+ const h=harness('journal.js','globalThis.fixture={load};',async()=>journalData());
+ h.context.page='journal';h.$('#journal-period').value='7';await h.fixture.load();
assert.equal(h.$('#journal-warning').hidden,false);assert.match(h.$('#journal-warning-detail').textContent,/partial tail/);
});
-test('map refresh preserves an unsaved locator even after the field loses focus',async()=>{
- const h=journalHarness();await h.fixture.load();const s=station('N0AAA');h.fixture.mapInfo(s);
- const input=h.$('#station-locator');input.defaultValue='JN45MM';input.value='JN45NN';const writes=h.$('#map-info').writes;
- h.fixture.mapInfo({...s,lastAt:new Date().toISOString()});assert.equal(input.value,'JN45NN');assert.equal(h.$('#map-info').writes,writes);
-});
test('background API polls stay quiet, while interactive requests finish the busy indicator even on error',async()=>{
let starts=0,finishes=0,request,fail=false;
diff --git a/public/aprs-activity.js b/public/aprs-activity.js
index b0bbb42..596fc50 100644
--- a/public/aprs-activity.js
+++ b/public/aprs-activity.js
@@ -97,7 +97,7 @@
function renderStations(){const list=stations();markup('#aprs-received-stations',list.map(s=>''+window.BPQAprsSymbols.html(s.position)+' '+esc(s.call)+' '+esc(s.transport)+(s.port?' · Port '+s.port:'')+' · '+esc(time(s.lastAt))+' '+symbolDetail(s.position)+' '+esc((stationDescription(s)||'—').slice(0,170))+'
'+(!s.position?'Senza posizione ':'')+' ').join('')||'Nessuna stazione ricevuta con questi filtri.
');}
function render(){if(!data)return;const events=data.events.filter(e=>(!source()||e.transport===source())&&(!$('#aprs-direction').value||e.direction===$('#aprs-direction').value)&&(!query()||(e.packet+' '+e.from).toUpperCase().includes(query()))).slice().reverse();
$('#aprs-live-state').textContent=paused?'Vista in pausa':data.monitor==='online'?'● APRS in tempo reale':'Monitor '+data.monitor;
- markup('#aprs-activity-kpis',[['Radio RX',events.filter(e=>e.transport==='Radio'&&e.direction==='RX').length],['Radio TX · BPQ',events.filter(e=>e.transport==='Radio'&&e.direction==='TX').length],['Internet RX',events.filter(e=>e.transport==='Internet'&&e.direction==='RX').length],['Internet TX',events.filter(e=>e.transport==='Internet'&&e.direction==='TX').length],['Stazioni ricevute',stations().length]].map(([k,v])=>''+esc(k)+' '+v+' ').join(''));
+ markup('#aprs-activity-kpis',[['Radio RX',data.counts?.radioRx??events.filter(e=>e.transport==='Radio'&&e.direction==='RX').length],['Radio TX · BPQ',data.counts?.radioTx??events.filter(e=>e.transport==='Radio'&&e.direction==='TX').length],['Internet RX',data.counts?.internetRx??events.filter(e=>e.transport==='Internet'&&e.direction==='RX').length],['Internet TX',data.counts?.internetTx??events.filter(e=>e.transport==='Internet'&&e.direction==='TX').length],['Stazioni ricevute',stations().length]].map(([k,v])=>''+esc(k)+' '+v+' ').join(''));
$('#aprs-traffic-count').textContent=events.length+' '+BPQI18n.t('pacchetti nel registro');markup('#aprs-traffic-rows',events.slice(0,400).map(e=>''+esc(time(e.at))+' '+e.direction+' '+esc(e.transport)+(e.port?'Port '+e.port+' ':'')+' '+esc(e.from)+' → '+esc(e.to)+' '+esc(type(e.type))+' '+esc(e.body.slice(0,180))+' '+(selectedEvent===e.id?''+esc(e.packet)+' '+esc(e.evidence)+' ':'')).join('')||'In attesa di pacchetti APRS ricevuti o inviati. ');
$('#aprs-traffic-scope').textContent=BPQI18n.t('Ultimi 2000 pacchetti · TX radio = richieste registrate da BPQ.');$('#aprs-activity-status').textContent=[...data.errors,...(!data.loggingInternet?[BPQI18n.t('Log Internet non disponibile')]:[]),BPQI18n.t('Aggiornato')+' '+time(data.updatedAt)].join(' · ');renderStations();renderMap();
}
diff --git a/public/journal.js b/public/journal.js
index 52a3c40..8f4c9b8 100644
--- a/public/journal.js
+++ b/public/journal.js
@@ -1,48 +1,25 @@
(() => {
-let data=null,loading=false,selected=null,mapCall=null,land=null,view=[0,0,1000,500],drag=null,moved=false,fitted=false,mapInfoCall=null;
+let data=null,loading=false,selected=null;
const snapshots=new WeakMap();
function markup(el,html){if(snapshots.get(el)===html)return false;const open=[...el.querySelectorAll('details[open][id]')].map(d=>d.id);snapshots.set(el,html);el.innerHTML=html;for(const id of open){const item=document.getElementById(id);if(item)item.open=true;}return true;}
-const base=c=>String(c||'').replace(/-\d+$/,'');
const time=t=>t?new Date(t).toLocaleString(BPQI18n.locale(),{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',Local:'Locale / Telnet',CMS:'Gateway Winlink',BPQ:'Nodo BPQ',Unknown:'Porta non archiviata'}[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=''+icon+' '+title;b.onclick=()=>navigate(id);$('nav').append(b);}
+for(const [id,title,icon]of [['journal','Diario','◷']]){const b=document.createElement('button');b.dataset.page=id;b.innerHTML=''+icon+' '+title;b.onclick=()=>navigate(id);$('nav').append(b);}
const journal=document.createElement('section');journal.id='journal';journal.className='page';journal.hidden=true;journal.innerHTML=`Diario dei collegamenti Lettura dei log BPQ…
↓ CSV ↻ Aggiorna
Ultime 24 ore Ultimi 7 giorni Ultimi 30 giorni Tutti i servizi BBS Winlink Chat Radio Tutte le direzioni In ingresso In uscita Non rilevata Tutti gli esiti Scambio concluso Collegato Non riuscito Esito non registrato
Copertura parziale dei dati
`;$('main').append(journal);
-const map=document.createElement('section');map.id='map';map.className='page';map.hidden=true;map.innerHTML=`Mappa delle stazioni Posizioni dai locator · ${esc(mailTimezone())}
↻ Aggiorna Mostra collegamentiTutti i servizi BBS Winlink Chat Radio 24 ore 7 giorni 30 giorni
+ − Inquadra rete
● Radio ● Internet / rete ● Mezzo non archiviato ◇ Stazione locale
Natural Earth · pubblico dominio
Informazioni sulla mappa 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 con lo stesso centro del locator condividono il punto: selezionale dal riquadro dettagli o dall’elenco. I nominativi senza locator restano nel diario e nell’elenco.
`;$('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,background=false){if(!csrf||loading)return;if(data&&!force){render();return;}loading=true;try{data=await api('/journal',{busy:!background});if(!land){try{const r=await fetch('/world-land.json');if(r.ok)land=await r.json();}catch{}}render();}catch(e){toast(e.message);$('#journal-coverage').textContent='Diario non disponibile: '+e.message;}finally{loading=false;}}
+const previousNavigate=navigate;navigate=function(next){if(next==='map')next='journal';previousNavigate(next);if(next==='journal'){$('#breadcrumb').textContent='Stazione / Diario';load();}};
+async function load(force=false,background=false){if(!csrf||loading)return;if(data&&!force){render();return;}loading=true;try{data=await api('/journal',{busy:!background});render();}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=BPQI18n.t('Dal')+' '+(data.since||'—')+' · '+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);markup($('#journal-kpis'),[['Sessioni',list.length],['Collegamenti stabiliti',connected.length],['Destinazioni',peers.size],['Traffico registrato',bytes(tx)+' / '+bytes(rx)]].map(([title,value])=>`${esc(title)} ${esc(value)} `).join(''));$('#journal-warning').hidden=!data.warnings.length&&!data.limited;$('#journal-warning-detail').textContent=[...data.warnings,data.limited?'Sono mostrate le 5000 sessioni più recenti.':''].filter(Boolean).join(' · ');markup($('#journal-rows'),list.map(s=>`${esc(time(s.startedAt))} ${esc(direction(s.direction))} ${esc(s.call)} ${esc(s.service)} ${esc(transport(s.transport))} ${s.frequency?esc(s.frequency)+' MHz':s.port?'Porta '+s.port:'—'} ${esc(duration(s.duration))} ↑ ${esc(bytes(s.txBytes))} ↓ ${esc(bytes(s.rxBytes))} ${s.sentMessages||0} ↑ / ${s.receivedMessages||0} ↓ ${esc(state(s.status))} `).join('')||'Nessuna sessione corrisponde ai filtri. ');$$('#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));markup($('#journal-detail'),`${esc(s.service)} · ${esc(direction(s.direction))} ${esc(s.call)} ${esc(state(s.status))} ${[['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])=>`
${esc(k)} ${esc(v)}
`).join('')}
Dettagli dei dati ${esc(s.transportEvidence||'')} ${esc(s.trafficScope||'Contatori di traffico non presenti nel log.')} Le statistiche disponibili dipendono dal servizio e dal modem; i trattini indicano dati non registrati.
${s.cmsTraffic?`Connessione CMS: TX ${esc(bytes(s.cmsTraffic.txBytes))} / RX ${esc(bytes(s.cmsTraffic.rxBytes))}
`:''} ${station?'◎ Mostra stazione sulla mappa ':''}Sequenza degli eventi ${s.events.map(e=>`${esc(time(e.at))} ${esc(e.text)} `).join('')} ${s.messages.length?`Messaggi trasferiti ${s.messages.map(m=>`
${esc(m.direction)} ${m.id?'#'+m.id:''} ${esc(bytes(m.bytes))} · compressi ${esc(bytes(m.compressedBytes))}
`).join('')}
`:''}Fonti ${esc([...new Set(s.sources)].join(', '))}
`);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(keepInfo=false){if(!data||page!=='map'||drag)return;if(!fitted&&(data.own.position||mapStations().some(s=>s.position))){fit();return;}const stations=mapStations(),known=stations.filter(s=>s.position),own=data.own.position,svg=$('#station-map'),scale=Math.max(view[2]/(svg.clientWidth||1000),view[3]/(svg.clientHeight||500));$('#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=` `;
- for(let x=0;x<=1000;x+=1000/12)content+=` `;for(let y=0;y<=500;y+=500/6)content+=` `;
- const local=own?xy(own):null;for(const s of known){const [x,y]=xy(s.position);const sessions=mapSessions().filter(r=>base(r.call)===s.call),radio=sessions.some(r=>r.transport==='Radio'),color=radio?'#96d6c0':sessions.every(r=>['CMS','BPQ','Unknown'].includes(r.transport))?'#d3c394':'#91bdea';if(local&&Math.hypot(x-local[0],y-local[1])>1e-8&&$('#map-tracks').checked){const mx=(x+local[0])/2,my=(y+local[1])/2-Math.min(55,Math.hypot(x-local[0],y-local[1])*.18);content+=`${esc(data.own.call+' ↔ '+s.call+' · '+sessions.length+' sessioni')} `;}
- content+=`${esc(s.call)} ${esc(s.call+' · '+s.position.locator+' · ultimo collegamento '+time(sessions[0]?.startedAt))} `;}
- if(local)content+=`${esc(data.own.call)} `;
- markup(svg,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();}};});
- markup($('#map-station-list'),stations.map(s=>`${esc(s.call)} ${s.position?esc(s.position.locator):'+ Aggiungi locator'} ${esc(s.services.join(' · '))} `).join('')||'Nessun collegamento stabilito nel periodo selezionato.
');$$('[data-peer]').forEach(b=>b.onclick=()=>{mapCall=b.dataset.peer;renderMap();});if(!keepInfo)mapInfo(stations.find(s=>s.call===mapCall));}
-function mapInfo(s){const info=$('#map-info'),input=$('#station-locator');if(s?.call===mapInfoCall&&input&&(info.contains(document.activeElement)||input.value!==input.defaultValue))return;mapInfoCall=s?.call||null;if(!s){markup($('#map-info'),`◎ Seleziona una stazione Clicca un punto, una traccia o un nominativo nell’elenco.
${!data.own.position?'
Il LOCATOR della stazione locale non è presente in BPQ: le tracce non possono essere disegnate.
':''}
`);return;}
- const sessions=mapSessions().filter(r=>base(r.call)===s.call),latest=sessions[0];const samePosition=p=>s.position&&p&&Math.abs(p.lat-s.position.lat)<1e-8&&Math.abs(p.lon-s.position.lon)<1e-8;const colocated=mapStations().filter(other=>samePosition(other.position));const sharedLocal=samePosition(data.own.position);const shared=sharedLocal||colocated.length>1?'Stazioni nello stesso punto '+(sharedLocal?'
'+esc(data.own.call)+' · stazione locale
':'')+colocated.map(other=>'
'+esc(other.call)+' ').join('')+'
Il locator individua un’area: le posizioni effettive possono essere diverse. ':'';markup($('#map-info'),`${shared}Ultimo collegamento nel periodo ${esc(time(latest?.startedAt))} ${esc(latest?.service||'')} · ${esc(transport(latest?.transport))} · ${esc(direction(latest?.direction))}
${sessions.length} collegamenti nel periodo ${sessions.slice(0,8).map(r=>`${esc(r.service)} ${esc(duration(r.duration))} ${esc(time(r.startedAt))} TX ${esc(bytes(r.txBytes))} / RX ${esc(bytes(r.rxBytes))} `).join('')}
`);$$('[data-colocated]').forEach(b=>b.onclick=()=>{mapCall=b.dataset.colocated;renderMap();});$('#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})});mapInfoCall=null;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(){fitted=true;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,anchor){const w=Math.max(5,Math.min(1000,view[2]*factor));if(w===view[2])return;const point=anchor||{x:view[0]+view[2]/2,y:view[1]+view[3]/2},u=(point.x-view[0])/view[2],v=(point.y-view[1])/view[3];view=[Math.max(0,Math.min(1000-w,point.x-u*w)),Math.max(0,Math.min(500-w/2,point.y-v*w/2)),w,w/2];renderMap(true);}
-$('#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;renderMap(true);setTimeout(()=>moved=false,0)});svg.addEventListener('pointercancel',()=>{drag=null;renderMap(true)});
-let wheelDelta=0,wheelPoint=null,wheelFrame=0;
-svg.addEventListener('wheel',e=>{if(!data||!e.deltaY||drag)return;e.preventDefault();const unit=e.deltaMode===1?16:e.deltaMode===2?svg.clientHeight:1;wheelDelta+=e.deltaY*unit;wheelPoint={x:e.clientX,y:e.clientY};if(wheelFrame)return;wheelFrame=requestAnimationFrame(()=>{wheelFrame=0;const matrix=svg.getScreenCTM();if(matrix&&wheelPoint){const p=svg.createSVGPoint();p.x=wheelPoint.x;p.y=wheelPoint.y;zoom(Math.exp(Math.max(-240,Math.min(240,wheelDelta))*.002),p.matrixTransform(matrix.inverse()));}wheelDelta=0;wheelPoint=null;});},{passive:false});
+function render(){if(!data)return;const list=filtered();$('#journal-coverage').textContent=BPQI18n.t('Dal')+' '+(data.since||'—')+' · '+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);markup($('#journal-kpis'),[['Sessioni',list.length],['Collegamenti stabiliti',connected.length],['Destinazioni',peers.size],['Traffico registrato',bytes(tx)+' / '+bytes(rx)]].map(([title,value])=>`${esc(title)} ${esc(value)} `).join(''));$('#journal-warning').hidden=!data.warnings.length&&!data.limited;$('#journal-warning-detail').textContent=[...data.warnings,data.limited?'Sono mostrate le 5000 sessioni più recenti.':''].filter(Boolean).join(' · ');markup($('#journal-rows'),list.map(s=>`${esc(time(s.startedAt))} ${esc(direction(s.direction))} ${esc(s.call)} ${esc(s.service)} ${esc(transport(s.transport))} ${s.frequency?esc(s.frequency)+' MHz':s.port?'Porta '+s.port:'—'} ${esc(duration(s.duration))} ↑ ${esc(bytes(s.txBytes))} ↓ ${esc(bytes(s.rxBytes))} ${s.sentMessages||0} ↑ / ${s.receivedMessages||0} ↓ ${esc(state(s.status))} `).join('')||'Nessuna sessione corrisponde ai filtri. ');$$('#journal-rows tr').forEach(row=>{const b=row.querySelector('[data-session]');if(b)row.onclick=()=>detail(b.dataset.session);});if(selected)detail(selected,false);}
+function detail(id,refresh=true){const s=data.sessions.find(s=>s.id===id);if(!s)return;selected=id;markup($('#journal-detail'),`${esc(s.service)} · ${esc(direction(s.direction))} ${esc(s.call)} ${esc(state(s.status))} ${[['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])=>`
${esc(k)} ${esc(v)}
`).join('')}
Dettagli dei dati ${esc(s.transportEvidence||'')} ${esc(s.trafficScope||'Contatori di traffico non presenti nel log.')} Le statistiche disponibili dipendono dal servizio e dal modem; i trattini indicano dati non registrati.
${s.cmsTraffic?`Connessione CMS: TX ${esc(bytes(s.cmsTraffic.txBytes))} / RX ${esc(bytes(s.cmsTraffic.rxBytes))}
`:''}Sequenza degli eventi ${s.events.map(e=>`${esc(time(e.at))} ${esc(e.text)} `).join('')} ${s.messages.length?`Messaggi trasferiti ${s.messages.map(m=>`
${esc(m.direction)} ${m.id?'#'+m.id:''} ${esc(bytes(m.bytes))} · compressi ${esc(bytes(m.compressedBytes))}
`).join('')}
`:''}Fonti ${esc([...new Set(s.sources)].join(', '))}
`);if(refresh)$$('#journal-rows tr').forEach(row=>row.classList.toggle('selected',row.querySelector('[data-session]')?.dataset.session===id));}
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-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,true)},30000);
-if(typeof ResizeObserver!=='undefined')new ResizeObserver(()=>{if(page==='map'&&data&&!drag)renderMap(true);}).observe(svg);
+setInterval(()=>{if(csrf&&!document.hidden&&page==='journal')load(true,true)},30000);
document.addEventListener('bpq-languagechange',()=>{if(data)render();});
-document.addEventListener('station-ready',()=>{if(['journal','map'].includes(page))load();});
+document.addEventListener('station-ready',()=>{if(page==='journal')load();});
document.addEventListener('DOMContentLoaded',()=>{const hash=location.hash.slice(1);if(['journal','map'].includes(hash))navigate(hash)});
})();
diff --git a/server.mjs b/server.mjs
index 7dc2ca0..64fe9ea 100644
--- a/server.mjs
+++ b/server.mjs
@@ -203,7 +203,7 @@ const server=http.createServer(async(req,res)=>{
if(url.pathname==='/api/winlink/sync'&&req.method==='POST'){if(Date.now()-lastCmsRequest<10000)throw new Error('Sincronizzazione già richiesta. Attendi qualche secondo.');await syncNow(config.cmsPeer||'RMS');lastCmsRequest=Date.now();json(res,200,{ok:true});return;}
const readRoute=url.pathname.match(/^\/api\/messages\/(\d+)\/read$/);if(readRoute&&req.method==='POST'){const item=(await messages()).find(m=>m.id===Number(readRoute[1]));if(!item)throw new Error('Messaggio non disponibile');json(res,200,await messageReadState.mark(item));return;}
if(/^\/api\/messages\/\d+\/delete$/.test(url.pathname)&&req.method==='POST'){json(res,200,await deleteMessage(Number(url.pathname.split('/')[3])));return;}
- if(/^\/api\/messages\/\d+$/.test(url.pathname)&&req.method==='GET'){const id=url.pathname.split('/').pop();const {key}=await mailContext();const msg=parseMessage(await bpq('/WebMail/WM?'+key+'&'+id));if(!msg)throw new Error('Messaggio non disponibile');try{const raw=await attachedMessage(Number(id));const text=b2Body(raw.bytes);if(text!==null)msg.text=text.replace(/\r\n|\r/g,'\n');}catch{}const fields=await messageFields(Number(id));json(res,200,{id:Number(id),...msg,to:fields.To||msg.to,via:fields.VIA||msg.via||'',...await messageTimes(Number(id))});return;}
+ if(/^\/api\/messages\/\d+$/.test(url.pathname)&&req.method==='GET'){const id=url.pathname.split('/').pop();let {key}=await mailContext();let msg=parseMessage(await bpq('/WebMail/WM?'+key+'&'+id));if(!msg){mailKey=null;({key}=await mailContext());msg=parseMessage(await bpq('/WebMail/WM?'+key+'&'+id));}if(!msg)throw new Error('Messaggio non disponibile');try{const raw=await attachedMessage(Number(id));const text=b2Body(raw.bytes);if(text!==null)msg.text=text.replace(/\r\n|\r/g,'\n');}catch{}const fields=await messageFields(Number(id));json(res,200,{id:Number(id),...msg,to:fields.To||msg.to,via:fields.VIA||msg.via||'',...await messageTimes(Number(id))});return;}
if(url.pathname==='/api/messages'&&req.method==='POST'){json(res,201,await sendMessage(await readSubmission(req)));return;}
if(url.pathname==='/api/sync'&&req.method==='POST'){await syncNow();json(res,200,{ok:true});return;}
json(res,404,{error:'Operazione non disponibile'});return;