Add detached service windows and selectable terminal themes

Support standalone APRS, Monitor, Chat and Terminal views with courtesy screens, window focus and return controls, shared sessions and suspended embedded polling.

Add five persistent phosphor palettes, remove Console terminal idle disconnections, and display decoded Mic-E movement and altitude with expandable original packets.

Document the new behavior and add regression coverage. Validation: 182 tests passed; the known hanging PowerShell startup readiness test was excluded.
This commit is contained in:
alberto committed 2026-10-19 22:15:15 +02:00
1 parent 8ee4e9636a
commit c98c67e18b
24 files changed
+415 -22

No files matched your search

+6
View File
@@ -39,6 +39,12 @@ Incoming and queued Winlink messages show an attachment indicator in the list an
In **New email**, use **Attach files** or drop files into the attachment panel. Review filenames, sizes and image thumbnails; remove files before saving. The Console accepts up to 10 files and 64 KiB total per outgoing email, with a combined message text/file limit of 80 KiB and the existing 32 KB body limit. These Console upload limits leave room for multipart headers within the native BPQ HTTP input buffer; BPQ, the receiving gateway and radio conditions may impose further limits. Small files are preferable over radio. Files stay in the browser until the message is saved and then use BPQ’s native WebMail attachment upload and normal Winlink queue, over Internet or radio. The Console verifies that BPQ stored the same filenames and file bytes before confirming success. If it reports a saved message with mismatched attachments, check the queue before retrying.
Use **Detach** in APRS, Monitor, Chat or Terminal to open a standalone window. The embedded section switches to a courtesy screen with **Show window** and **Bring back here**, and pauses its own polling. Returning or closing the detached window restores the embedded view without disconnecting the underlying service. Window ownership is coordinated per browser and origin; stale ownership expires if a window crashes. Popup blocking leaves the embedded view available.
Use **Detach** in the terminal toolbar to open a compact standalone window. Both views share the existing authenticated Telnet session and transcript; closing the window does not disconnect it. **Back to dashboard** returns to the original panel. Allow popups for the Console if the browser blocks the window. Amber, Green, Ice, Violet and White phosphor themes are saved per browser and synchronized between open views.
Terminal connections are not closed by BPQ Console for inactivity, including when another dashboard page is open. Disconnect or sign out to close the terminal. BPQ and remote applications may still enforce their own session limits.
## Telnet login compatibility
Terminal and Chat read `LOGINPROMPT` and `PASSWORDPROMPT` from the Telnet port in `BPQ32.cfg`. Standard `Username:`, `Login:`, `User:` and `Password:` prompts also work. `PASSWORD` is not the prompt setting. Custom CTEXT banners do not need the word Welcome or a node prompt; both `ALIAS:CALL>` and `ALIAS:CALL}` work. After the password, the clients wait for 400 ms of quiet after non-empty banner text; a repeated login/password prompt or explicit denial rejects the login. Password echoes are removed before displaying the terminal banner, and Chat discards the Telnet banner before sending `CHAT`. A server that sends no text at all after the password times out instead of reporting an unconfirmed login as successful. Restart BPQ Console after changing prompt settings.
+1 -1
View File
@@ -8,7 +8,7 @@ export function parseRadioAprs(frame){const lines=frame.text.split('\n'),m=lines
export function parseIsAprs(line,date){const m=line.match(/^(\d{2}:\d{2}:\d{2})([RT])\s+(.*)$/);if(!m)return null;const packet=parseTnc2(m[3]);return packet?{...packet,at:date+'T'+m[1]+'Z',direction:m[2]==='T'?'TX':'RX',transport:'Internet',port:null,evidence:'BPQ APRS-IS log'}:null;}
export function positionOf(body){let text=body;if(/[\/@]/.test(text[0]))text=text.slice(8);else if(/[!=]/.test(text[0]))text=text.slice(1);else return null;
const m=text.match(/^(\d{2})(\d{2}\.\d{2})([NS])(.)(\d{3})(\d{2}\.\d{2})([EW])(.)(.*)$/);if(!m||Number(m[2])>=60||Number(m[6])>=60)return null;const lat=(+m[1]+Number(m[2])/60)*(m[3]==='S'?-1:1),lon=(+m[5]+Number(m[6])/60)*(m[7]==='W'?-1:1);return Math.abs(lat)<=90&&Math.abs(lon)<=180?{lat,lon,symbol:m[8],symset:m[4]}:null;}
export function parseNativeStations(text,now=Date.now()){const out=[];for(const row of text.split(/\r?\n\|/)){const m=row.trim().match(/^A,(-?[\d.]+),(-?[\d.]+),([^,]+),([\s\S]*),([A-Fa-f0-9]{4}.),(\d+)$/);if(!m)continue;const lat=Number(m[1]),lon=Number(m[2]),call=m[3];if(!/^[A-Z0-9-]{2,12}$/i.test(call)||!Number.isFinite(lat)||!Number.isFinite(lon)||Math.abs(lat)>90||Math.abs(lon)>180)continue;const detail=decode(m[4]),port=Number(detail.match(/Last Heard:.*?on Port (\d+)/)?.[1])||0,lines=detail.split(/<br\s*\/?\s*>/i).map(s=>plain(s).trim()).filter(Boolean);out.push({call,position:{lat,lon,...nativeSymbol(m[5])},lastAt:new Date(now-Number(m[6])*1000).toISOString(),transport:port?'Radio':'Internet',port:port||null,path:lines[0]||'',lastBody:lines[1]||'',status:lines.find(s=>!s.startsWith('Last Heard')&&!s.startsWith('Distance')&&s!==lines[0]&&s!==lines[1])||'',heardRadio:port>0,positionSource:'BPQ APRS decoder',native:true});}return out;}
export function parseNativeStations(text,now=Date.now()){const out=[];for(const row of text.split(/\r?\n\|/)){const m=row.trim().match(/^A,(-?[\d.]+),(-?[\d.]+),([^,]+),([\s\S]*),([A-Fa-f0-9]{4}.),(\d+)$/);if(!m)continue;const lat=Number(m[1]),lon=Number(m[2]),call=m[3];if(!/^[A-Z0-9-]{2,12}$/i.test(call)||!Number.isFinite(lat)||!Number.isFinite(lon)||Math.abs(lat)>90||Math.abs(lon)>180)continue;const detail=m[4],port=Number(detail.match(/Last Heard:.*?on Port (\d+)/)?.[1])||0,lines=detail.split(/<br\s*\/?\s*>/i).map(s=>decode(s.replace(/<[^>]+>/g,''))).filter(s=>s.trim());out.push({call,position:{lat,lon,...nativeSymbol(m[5])},lastAt:new Date(now-Number(m[6])*1000).toISOString(),transport:port?'Radio':'Internet',port:port||null,path:lines[0]||'',lastBody:lines[1]||'',status:lines.find(s=>!s.startsWith('Last Heard')&&!s.startsWith('Distance')&&s!==lines[0]&&s!==lines[1])||'',heardRadio:port>0,positionSource:'BPQ APRS decoder',native:true});}return out;}
export class AprsActivity{
constructor(config,dir,bpq,credentials,settings){this.config=config;this.bpq=bpq;this.settings=settings;this.file=path.join(dir,'aprs-activity.cache.json');this.events=[];this.stations=new Map();this.seq=0;this.cursor=0;this.monitor=new Monitor(credentials,{port:config.monitorPort});this.kiss=(config.aprsKissMonitor||[]).map(endpoint=>new AprsKiss(endpoint,(packet,port)=>this.ingest({...parseTnc2(packet),at:new Date().toISOString(),direction:'RX',transport:'Radio',port,evidence:'KISS receive-only monitor'})));this.lastNative=0;this.lastPersist=0;this.logFile=null;this.logOffset=null;this.partial='';this.errors=[];this.started=false;this.busy=false;this.init=this.restore();this.timer=setInterval(()=>{if(this.started)this.sample().catch(()=>{});},2000);this.timer.unref();}
async restore(){try{const data=JSON.parse(await readFile(this.file,'utf8'));this.events=(data.events||[]).slice(-2000);this.seq=this.events.at(-1)?.id||0;this.logFile=data.logFile||null;this.logOffset=data.logOffset??null;this.partial=data.partial||'';this.ownPosition=data.ownPosition;for(const s of data.stations||[])if(s.call)this.stations.set(s.call,s);}catch{} }
+35
View File
@@ -0,0 +1,35 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import vm from 'node:vm';
import {readFileSync} from 'node:fs';
import {parseNativeStations} from './aprs-activity.mjs';
const context=vm.createContext({window:{}});
vm.runInContext(readFileSync(new URL('./public/aprs-symbols.js',import.meta.url),'utf8'),context);
const decode=context.window.BPQAprsPacket.decode;
const mic='`\x7f^U!n^>/';
test('Mic-E station descriptions decode movement and base91 altitude instead of showing binary position bytes',()=>{
const info=decode(mic+'"5J}');
assert.equal(info.format,'Mic-E');assert.equal(info.speedKmh,107);assert.equal(info.course,266);assert.equal(info.altitudeM,142);assert.equal(info.comment,'');
assert.equal(decode(mic+'"5J}Hello from the car').comment,'Hello from the car');
assert.equal(decode('`short').speedKmh,null);assert.equal(decode('`short').comment,'');
});
test('known Mic-E device identifiers are separated from comments; unknown suffixes and real comments are preserved',()=>{
const info=decode(mic+'`"5J}Test_3');assert.equal(info.device,'Yaesu FT5D');assert.equal(info.altitudeM,142);assert.equal(info.comment,'Test');
assert.equal(decode(mic+'>Hello=').device,'Kenwood TH-D72');
assert.equal(decode(mic+'`Hello?Z').comment,'Hello?Z');
assert.equal(decode(mic+'<hello & world>').comment,'<hello & world>');
});
test('plain position descriptions omit position fields without damaging the transmitted text',()=>{
assert.equal(decode('!4534.18N/00907.89E]Local BBS').comment,'Local BBS');
assert.equal(decode('@191200z4534.18N/00907.89E]Local BBS').comment,'Local BBS');
assert.equal(decode('>191200zOn air').comment,'On air');
assert.equal(decode('Comment\x7f with controls').comment,'Comment with controls');
});
test('native HTML decoding preserves Mic-E byte positions, literal angle brackets and repeated spaces',()=>{
const body='`\x7f&lt;U ^&gt;/"5J}';
const row='A,45.5,9.1,N0TEST,TEST,WIDE1-1<br>'+body+'<br>Last Heard: 12:00:00 on Port 3<br>,010D@,1\r\n|';
const station=parseNativeStations(row)[0];
assert.equal(station.lastBody,'`\x7f<U ^>/"5J}');assert.equal(station.lastBody[7],'>');assert.equal(station.lastBody[8],'/');
assert.equal(decode(station.lastBody).altitudeM,142);
});
+52
View File
@@ -0,0 +1,52 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import vm from 'node:vm';
import {readFileSync} from 'node:fs';
const source=readFileSync(new URL('./public/detach.js',import.meta.url),'utf8');
function harness(search='',shared=new Map()){
const docEvents={},events={},sections={},calls=[];let serial=0,tick,popup;
function element(){const children=new Map();return {hidden:false,dataset:{},textContent:'',className:'',innerHTML:'',classes:new Set(),
classList:{toggle(name,on){this.owner.classes[on?'add':'delete'](name);}},append(child){this.child=child;},
querySelector(selector){if(selector==='.detached-placeholder')return this.child||null;if(!children.has(selector))children.set(selector,element());return children.get(selector);},
querySelectorAll(){return [this.querySelector('first'),this.querySelector('second')];}};}
for(const id of ['terminal','aprs','monitor','chat']){sections[id]=element();sections[id].classList.owner=sections[id];}
const main={hidden:false};const document={body:{append(node){calls.push(['notice',node.className]);}},querySelector:()=>main,readyState:'complete',documentElement:{dataset:{}},getElementById:id=>sections[id],createElement:element,addEventListener:(name,fn)=>docEvents[name]=fn};
const window={name:'',addEventListener:(name,fn)=>events[name]=fn,focus:()=>calls.push('focus'),close:()=>calls.push('close'),
open:(...args)=>{calls.push(args);popup={closed:false,focus(){},close(){this.closed=true;}};return popup;}};
const location={pathname:'/',search,hash:'',assign:url=>calls.push(['assign',url])};
const context=vm.createContext({window,document,location,URLSearchParams,crypto:{randomUUID:()=>String(++serial)},
localStorage:{getItem:key=>shared.get(key)||null,setItem:(key,value)=>shared.set(key,value),removeItem:key=>shared.delete(key)},
Date,Set,Map,BPQI18n:{t:s=>s},toast:text=>calls.push(['toast',text]),navigate:id=>calls.push(['navigate',id]),setInterval:fn=>{tick=fn;}});
vm.runInContext(source,context);docEvents.DOMContentLoaded();
return {api:window.BPQDetached,window,document,docEvents,events,sections,calls,shared,main,tick:()=>tick(),popup:()=>popup};
}
test('a page shows courtesy only after its detached view is ready, and another page stays usable',()=>{
const h=harness();h.api.open('aprs');assert.equal(h.api.isAway('aprs'),false);
assert.match(h.calls[0][0],/^\/\?detached=aprs&window=\d+#aprs$/);
h.shared.set('bpq-detached:aprs',JSON.stringify({owner:'2',at:Date.now()}));h.tick();
assert.equal(h.sections.aprs.child.hidden,false);assert.equal(h.api.shouldPoll('aprs'),false);assert.equal(h.api.shouldPoll('chat'),true);
assert.equal(h.sections.aprs.classes.has('section-detached-away'),true);
h.api.dock('aprs');assert.equal(h.sections.aprs.child.hidden,true);assert.equal(h.api.shouldPoll('aprs'),true);assert.equal(h.popup().closed,true);
});
test('closing a child restores its parent and stale records cannot strand a page on the courtesy screen',()=>{
const h=harness();h.api.open('monitor');h.shared.set('bpq-detached:monitor',JSON.stringify({owner:'2',at:Date.now()}));h.tick();
h.popup().closed=true;h.tick();assert.equal(h.api.isAway('monitor'),false);assert.equal(h.sections.monitor.child.hidden,true);
h.shared.set('bpq-detached:chat',JSON.stringify({owner:'old',at:Date.now()-130000}));h.tick();assert.equal(h.api.isAway('chat'),false);
});
test('blocked popups keep the embedded view and never claim a detached session',()=>{
const h=harness();h.window.open=()=>null;h.api.open('chat');assert.equal(h.api.isAway('chat'),false);assert.equal(h.shared.has('bpq-detached:chat'),false);assert.match(h.calls[0][1],/popup/);
});
test('a standalone page claims just its service, releases on close and never reconnects or disconnects BPQ',()=>{
const shared=new Map(),h=harness('?detached=chat&window=child',shared);h.docEvents['station-ready']();
assert.equal(h.api.view,'chat');assert.equal(h.api.shouldPoll('chat'),true);assert.equal(h.api.shouldPoll('aprs'),false);
assert.equal(JSON.parse(shared.get('bpq-detached:chat')).owner,'child');assert.equal(h.document.documentElement.dataset.detachedView,'chat');
h.events.pagehide();assert.equal(shared.has('bpq-detached:chat'),false);h.tick();assert.equal(shared.has('bpq-detached:chat'),false);
assert.ok(h.calls.every(call=>call[0]==='navigate'));
});
test('a dock request stops the detached view even when its browser refuses scripted window closing',()=>{
const h=harness('?detached=monitor&window=child');h.docEvents['station-ready']();
h.events.storage({key:'bpq-detached-command',newValue:JSON.stringify({id:'monitor',action:'dock',at:Date.now()})});
assert.equal(h.shared.has('bpq-detached:monitor'),false);assert.equal(h.api.shouldPoll('monitor'),false);assert.equal(h.main.hidden,true);assert.ok(h.calls.includes('close'));
});
+11
View File
@@ -112,3 +112,14 @@ test('APRS opens at a 30 km radius and refresh does not reset a manually selecte
h.fixture.fitLocal();assert.equal(l.state.fits,3);
data.own.position=null;h.fixture.setData(data);h.fixture.renderMap();assert.equal(h.$('#aprs-map-local').disabled,true);h.fixture.fitLocal();assert.equal(l.state.fits,3);
});
test('APRS popups show decoded Mic-E values and keep encoded bytes only in a collapsed original-packet detail',()=>{
const h=harness('aprs-activity.js','globalThis.fixture={popup,stationDescription};');
const body='`'+String.fromCharCode(127)+'^U!n^>/"5J}';
const s={...station('N0TEST'),status:'',lastBody:body};
const description=h.fixture.stationDescription(s);assert.equal(description,'Mic-E · 107 km/h · 266° · Quota 142 m');
const html=h.fixture.popup(s);assert.match(html,/<details class="aprs-raw-packet"><summary>Pacchetto originale/);
assert.ok(html.includes(String.fromCharCode(92)+'x7f'));assert.ok(!html.includes(String.fromCharCode(127)));
assert.equal(s.lastBody,body);
});
+3 -3
View File
@@ -5,8 +5,8 @@ let csrf='',allMessages=[],dashboardData=null,filter='all',selected=null,page='h
const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
async function api(url,options={}){const {busy=true,...request}=options;const finish=(busy&&window.BPQBusy?.start())||(()=>{});try{const r=await fetch('/api'+url,{...request,headers:{...(options.body instanceof FormData?{}:{'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;}finally{finish();}}
function toast(text){$('#toast').textContent=text;$('#toast').hidden=false;clearTimeout(toast.timer);toast.timer=setTimeout(()=>$('#toast').hidden=true,6500);}
function showLogin(){document.title='BPQ Console';$('#shell').hidden=true;$('#login').hidden=false;csrf='';}
function showShell(user){deletedMessageIds.clear();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 showLogin(){document.dispatchEvent(new Event('bpq-detach-auth-lost'));document.title='BPQ Console';$('#shell').hidden=true;$('#login').hidden=false;csrf='';}
function showShell(user){deletedMessageIds.clear();station=user.config;applyStation(user);csrf=user.csrf;$('#login').hidden=true;$('#shell').hidden=false;if(!window.BPQDetached?.view){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(BPQI18n.locale(),{hour:'2-digit',minute:'2-digit'});}
function categoryLabel(m){return m.type==='P'?BPQI18n.t('PERSONALE'):m.to||BPQI18n.t('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;}
@@ -16,7 +16,7 @@ function navigate(next){page=next;$$('.page').forEach(p=>p.hidden=p.id!==next);$
$$('[data-page]').forEach(b=>b.addEventListener('click',()=>navigate(b.dataset.page)));
$('#login-form').addEventListener('submit',async e=>{e.preventDefault();const b=e.target.querySelector('button');b.disabled=true;$('#login-error').textContent='';try{const user=await api('/login',{method:'POST',body:JSON.stringify(Object.fromEntries(new FormData(e.target)))});e.target.password.value='';showShell(user);}catch(err){$('#login-error').textContent=err.message}finally{b.disabled=false}});
$('#logout').onclick=async()=>{try{await api('/logout',{method:'POST',body:'{}'})}finally{showLogin()}};
async function loadDashboard(background=false){try{const d=await api('/dashboard',{busy:!background});dashboardData=d;$('#connection').textContent=d.errors.length?'● Dati parziali':'● BPQ connesso';$('#notice').hidden=!d.errors.length;$('#notice').textContent=d.errors.join(' · ');$('#k-messages').textContent=d.counts.messages;$('#nav-count').textContent=d.counts.messages;$('#k-message-detail').textContent=`${d.counts.bulletins} bollettini · ${d.counts.personal} personali`;$('#k-nodes').textContent=d.nodes.length;$('#k-routes').textContent=d.routes.filter(r=>r.active).length;$('#k-sync').textContent=logTime(d.sync?.at);$('#k-sync-detail').textContent=d.sync?`${d.sync.received} ${d.sync.received===1?'messaggio ricevuto':'messaggi ricevuti'} · ${mailTimezone()}`:'Nessuno rilevato oggi';const r=d.radio;$('#radio-freq').textContent=r?.frequency||'—';$('#radio-status').textContent=r?.connected?'MODEM ONLINE':'NON DISPONIBILE';$('#radio-modem').textContent=r?.connected?(station.radio?.driver||'Modem')+' '+r.mode:'Non collegato';$('#radio-channel').textContent=r?(r.busy?'Occupato':'Libero'):'—';$('#radio-snr').textContent=r?r.snr+' dB':'—';$('#radio-scan').textContent=r?.scanning?'● Scansione attiva':r?.state&&r.state!=='Free'?'● '+r.state:'Scansione non rilevata';$('#updated').textContent='Aggiornato '+new Date(d.updatedAt).toLocaleTimeString(BPQI18n.locale(),{hour:'2-digit',minute:'2-digit'});$('#routes').innerHTML=d.routes.map(r=>`<tr><td>${esc(r.call)}</td><td><span class="tag">${r.active?'ATTIVO':'INATTIVO'}</span></td><td>${esc(r.port)}</td><td>${r.quality}</td><td>${r.nodes}</td><td>${r.frames}</td><td>${r.retries}</td></tr>`).join('')||'<tr><td colspan="7">Nessuna rotta disponibile</td></tr>';$('#nodes').innerHTML=d.nodes.map(n=>{const [alias,call]=n.split(':');return `<div class="node"><strong>${esc(alias)}</strong><small>${esc(call)}</small></div>`}).join('');$('#node-total').textContent=d.nodes.length+' destinazioni';}catch(err){$('#connection').textContent='● Connessione assente';$('#notice').hidden=false;$('#notice').textContent=err.message;}}
async function loadDashboard(background=false){if(window.BPQDetached?.view)return;try{const d=await api('/dashboard',{busy:!background});dashboardData=d;$('#connection').textContent=d.errors.length?'● Dati parziali':'● BPQ connesso';$('#notice').hidden=!d.errors.length;$('#notice').textContent=d.errors.join(' · ');$('#k-messages').textContent=d.counts.messages;$('#nav-count').textContent=d.counts.messages;$('#k-message-detail').textContent=`${d.counts.bulletins} bollettini · ${d.counts.personal} personali`;$('#k-nodes').textContent=d.nodes.length;$('#k-routes').textContent=d.routes.filter(r=>r.active).length;$('#k-sync').textContent=logTime(d.sync?.at);$('#k-sync-detail').textContent=d.sync?`${d.sync.received} ${d.sync.received===1?'messaggio ricevuto':'messaggi ricevuti'} · ${mailTimezone()}`:'Nessuno rilevato oggi';const r=d.radio;$('#radio-freq').textContent=r?.frequency||'—';$('#radio-status').textContent=r?.connected?'MODEM ONLINE':'NON DISPONIBILE';$('#radio-modem').textContent=r?.connected?(station.radio?.driver||'Modem')+' '+r.mode:'Non collegato';$('#radio-channel').textContent=r?(r.busy?'Occupato':'Libero'):'—';$('#radio-snr').textContent=r?r.snr+' dB':'—';$('#radio-scan').textContent=r?.scanning?'● Scansione attiva':r?.state&&r.state!=='Free'?'● '+r.state:'Scansione non rilevata';$('#updated').textContent='Aggiornato '+new Date(d.updatedAt).toLocaleTimeString(BPQI18n.locale(),{hour:'2-digit',minute:'2-digit'});$('#routes').innerHTML=d.routes.map(r=>`<tr><td>${esc(r.call)}</td><td><span class="tag">${r.active?'ATTIVO':'INATTIVO'}</span></td><td>${esc(r.port)}</td><td>${r.quality}</td><td>${r.nodes}</td><td>${r.frames}</td><td>${r.retries}</td></tr>`).join('')||'<tr><td colspan="7">Nessuna rotta disponibile</td></tr>';$('#nodes').innerHTML=d.nodes.map(n=>{const [alias,call]=n.split(':');return `<div class="node"><strong>${esc(alias)}</strong><small>${esc(call)}</small></div>`}).join('');$('#node-total').textContent=d.nodes.length+' destinazioni';}catch(err){$('#connection').textContent='● Connessione assente';$('#notice').hidden=false;$('#notice').textContent=err.message;}}
async function loadMessages(background=false){if(!station.features.bbs)return;try{allMessages=(await api('/messages',{busy:!background})).filter(m=>!deletedMessageIds.has(m.id));const current=$('#category').value;const categories=[...new Set(allMessages.filter(m=>m.type==='B').map(m=>m.to))].sort();$('#category').innerHTML='<option value="">Tutte le categorie</option>'+categories.map(c=>`<option>${esc(c)}</option>`).join('');$('#category').value=current;renderMessages();}catch(err){toast(err.message)}}
function mailDate(m,kind='received'){const value=kind==='sent'?m.createdAt:(m.receivedAt||m.createdAt);if(!value)return m.date||'—';return new Date(value).toLocaleString(BPQI18n.locale(),{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'});}
function mailTimezone(){const minutes=-new Date().getTimezoneOffset();return 'UTC'+(minutes>=0?'+':'-')+String(Math.floor(Math.abs(minutes)/60)).padStart(2,'0')+':'+String(Math.abs(minutes)%60).padStart(2,'0');}
+2
View File
@@ -45,3 +45,5 @@
.aprs-map-actions{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end}.aprs-map-actions .secondary{white-space:nowrap}@media(max-width:650px){.aprs-map-actions{width:100%;justify-content:flex-start}.aprs-map-actions .secondary{flex:1}}
.aprs-map-actions .secondary[aria-pressed=true]{border-color:#88c7b1;background:#8acbb018;color:#c8ebdf}
.aprs-map-popup p{white-space:pre-line}.aprs-raw-packet summary{font-size:11px;color:#a9c4d8;cursor:pointer}.aprs-raw-packet pre{max-height:120px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere;font:11px/1.5 Consolas,monospace;color:#a7becf;margin:6px 0}.aprs-received-station p{white-space:pre-line}
+15 -4
View File
@@ -17,7 +17,18 @@
}
const symbolKey=(s)=>JSON.stringify([s.position?.symset,s.position?.symbol,s.transport]);
function symbolDetail(position){const info=window.BPQAprsSymbols.decode(position);return info?esc(info.name)+' · <code>'+esc(info.code)+'</code>'+(info.overlay?' · '+BPQI18n.t('Sovrapposizione')+' '+esc(info.overlay):''):BPQI18n.t('Simbolo non disponibile');}
function popup(s){return '<div class="aprs-map-popup"><b>'+esc(s.call)+'</b><span class="aprs-symbol-detail">'+symbolDetail(s.position)+'</span><span>'+esc(s.transport)+(s.port?' · Port '+s.port:'')+'</span><span>'+esc(time(s.lastAt))+'</span><span>'+s.position.lat.toFixed(5)+', '+s.position.lon.toFixed(5)+'</span><p>'+esc(s.status||s.lastBody||'')+'</p><small>'+esc(s.path||'')+'</small></div>';}
function stationDescription(s){
const packet=window.BPQAprsPacket.decode(s.lastBody||''),parts=[];
if(packet.format)parts.push(packet.format==='APRS'?BPQI18n.t('Posizione APRS'):packet.format);
if(packet.speedKmh!==null)parts.push(packet.speedKmh+' km/h');
if(packet.course!==null)parts.push(packet.course+'°');
if(packet.altitudeM!==null)parts.push(BPQI18n.t('Quota')+' '+packet.altitudeM+' m');
if(packet.device)parts.push(packet.device);
const status=window.BPQAprsPacket.decode(s.status||'').comment;
return [parts.join(' · '),status||packet.comment].filter(Boolean).join('\n');
}
function rawPacket(s){return s.lastBody?'<details class="aprs-raw-packet"><summary>'+BPQI18n.t('Pacchetto originale')+'</summary><pre>'+esc(s.lastBody.replace(/[\x00-\x1f\x7f-\x9f]/g,c=>String.fromCharCode(92)+'x'+c.charCodeAt(0).toString(16).padStart(2,'0')))+'</pre></details>':'';}
function popup(s){return '<div class="aprs-map-popup"><b>'+esc(s.call)+'</b><span class="aprs-symbol-detail">'+symbolDetail(s.position)+'</span><span>'+esc(s.transport)+(s.port?' · Port '+s.port:'')+'</span><span>'+esc(time(s.lastAt))+'</span><span>'+s.position.lat.toFixed(5)+', '+s.position.lon.toFixed(5)+'</span><p>'+esc(stationDescription(s))+'</p>'+rawPacket(s)+'<small>'+esc(s.path||'')+'</small></div>';}
function initMap(){if(map||!window.L)return;map=L.map('aprs-station-map',{zoomControl:true,scrollWheelZoom:true}).setView([25,0],2);L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png',{maxZoom:19,referrerPolicy:'origin',attribution:'&copy; <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener">OpenStreetMap</a> contributors · <a href="/vendor/aprs-symbols/README.md" target="_blank" rel="noopener">APRS symbols © OH7LZB</a>'}).addTo(map);layers=L.layerGroup().addTo(map);if(typeof ResizeObserver!=='undefined')new ResizeObserver(()=>{if(page==='aprs'&&view==='activity')map.invalidateSize({pan:false});}).observe($('#aprs-station-map'));}
const validPosition=p=>p&&Number.isFinite(p.lat)&&Number.isFinite(p.lon)&&Math.abs(p.lat)<=90&&Math.abs(p.lon)<=180;
function distanceKm(a,b){
@@ -83,15 +94,15 @@
$('#aprs-map-count').textContent=visible.size+' '+BPQI18n.t('sulla mappa')+' · '+(list.length-visible.size)+' '+BPQI18n.t('senza posizione');
if(!fitted&&(visible.size||own?.position)){if(validPosition(own?.position))fitLocal();else fit();fitted=true;}
}
function renderStations(){const list=stations();markup('#aprs-received-stations',list.map(s=>'<button data-aprs-station="'+esc(s.call)+'" class="aprs-received-station '+(s.call===selected?'selected':'')+'"><span><span class="aprs-list-symbol">'+window.BPQAprsSymbols.html(s.position)+'</span><b>'+esc(s.call)+'</b><i class="aprs-source-dot '+s.transport.toLowerCase()+'"></i></span><small>'+esc(s.transport)+(s.port?' · Port '+s.port:'')+' · '+esc(time(s.lastAt))+'</small><small class="aprs-symbol-detail">'+symbolDetail(s.position)+'</small><p>'+esc(s.status||s.lastBody||'—').slice(0,170)+'</p>'+(!s.position?'<small>Senza posizione</small>':'')+'</button>').join('')||'<p class="empty">Nessuna stazione ricevuta con questi filtri.</p>');}
function renderStations(){const list=stations();markup('#aprs-received-stations',list.map(s=>'<button data-aprs-station="'+esc(s.call)+'" class="aprs-received-station '+(s.call===selected?'selected':'')+'"><span><span class="aprs-list-symbol">'+window.BPQAprsSymbols.html(s.position)+'</span><b>'+esc(s.call)+'</b><i class="aprs-source-dot '+s.transport.toLowerCase()+'"></i></span><small>'+esc(s.transport)+(s.port?' · Port '+s.port:'')+' · '+esc(time(s.lastAt))+'</small><small class="aprs-symbol-detail">'+symbolDetail(s.position)+'</small><p>'+esc((stationDescription(s)||'—').slice(0,170))+'</p>'+(!s.position?'<small>Senza posizione</small>':'')+'</button>').join('')||'<p class="empty">Nessuna stazione ricevuta con questi filtri.</p>');}
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])=>'<article><span>'+esc(k)+'</span><strong>'+v+'</strong></article>').join(''));
$('#aprs-traffic-count').textContent=events.length+' '+BPQI18n.t('pacchetti nel registro');markup('#aprs-traffic-rows',events.slice(0,400).map(e=>'<tr data-aprs-event="'+e.id+'" tabindex="0" aria-expanded="'+(selectedEvent===e.id)+'"><td>'+esc(time(e.at))+'</td><td><span class="aprs-packet-direction '+e.direction.toLowerCase()+'">'+e.direction+'</span></td><td>'+esc(e.transport)+(e.port?'<small>Port '+e.port+'</small>':'')+'</td><td><b>'+esc(e.from)+'</b><small>→ '+esc(e.to)+'</small></td><td><span class="aprs-packet-type">'+esc(type(e.type))+'</span><span class="aprs-packet-preview">'+esc(e.body.slice(0,180))+'</span></td></tr>'+(selectedEvent===e.id?'<tr class="aprs-packet-detail"><td colspan="5"><pre>'+esc(e.packet)+'</pre><small>'+esc(e.evidence)+'</small></td></tr>':'')).join('')||'<tr><td colspan="5" class="empty">In attesa di pacchetti APRS ricevuti o inviati.</td></tr>');
$('#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();
}
async function start(){if(!csrf)return;if(starting||data?.started){if(data)render();return;}starting=true;try{data=await api('/aprs/activity/start',{method:'POST',body:'{}'});render();}catch(e){$('#aprs-activity-status').textContent=e.message;}finally{starting=false;}}
async function poll(background=true){if(!csrf||loading||paused||document.hidden||page!=='aprs'||view!=='activity')return;loading=true;try{const next=await api('/aprs/activity',{busy:!background});data=next;render();if(!data.started)start();}catch(e){$('#aprs-activity-status').textContent=e.message;}finally{loading=false;}}
async function start(){if(!csrf||window.BPQDetached&&!window.BPQDetached.shouldPoll('aprs'))return;if(starting||data?.started){if(data)render();return;}starting=true;try{data=await api('/aprs/activity/start',{method:'POST',body:'{}'});render();}catch(e){$('#aprs-activity-status').textContent=e.message;}finally{starting=false;}}
async function poll(background=true){if(!csrf||loading||paused||document.hidden||window.BPQDetached&&!window.BPQDetached.shouldPoll('aprs')||page!=='aprs'||view!=='activity')return;loading=true;try{const next=await api('/aprs/activity',{busy:!background});data=next;render();if(!data.started)start();}catch(e){$('#aprs-activity-status').textContent=e.message;}finally{loading=false;}}
$('#aprs-map-fit').onclick=fit;$('#aprs-map-local').onclick=fitLocal;$('#aprs-activity-refresh').onclick=()=>{if(paused){render();return;}poll(false);};$('#aprs-activity-pause').onclick=()=>{paused=!paused;$('#aprs-activity-pause').textContent=paused?'Riprendi vista':'Pausa vista';if(!paused)poll();else render();};for(const id of ['aprs-source','aprs-direction','aprs-search'])$('#'+id).addEventListener(id==='aprs-search'?'input':'change',()=>{render();});
$('#aprs-received-stations').onclick=e=>{const call=e.target.closest('[data-aprs-station]')?.dataset.aprsStation;if(!call)return;selected=call;const marker=markers.get(call);if(marker){map.setView(marker.getLatLng(),Math.max(map.getZoom(),13));marker.openPopup();}renderStations();};
$('#aprs-traffic-rows').onclick=e=>{const row=e.target.closest('[data-aprs-event]');if(row){const id=Number(row.dataset.aprsEvent);selectedEvent=selectedEvent===id?null:id;render();}};$('#aprs-traffic-rows').onkeydown=e=>{if(['Enter',' '].includes(e.key)&&e.target.matches('[data-aprs-event]')){e.preventDefault();e.target.click();}};
+36
View File
@@ -13,5 +13,41 @@
const col=info.index%16,row=Math.floor(info.index/16);
return '<span class="aprs-symbol-image aprs-symbol-'+info.table+' aprs-symbol-col-'+col+' aprs-symbol-row-'+row+'" aria-hidden="true">'+(info.overlay?'<span class="aprs-symbol-overlay">'+info.overlay+'</span>':'')+'</span>';
}
// APRS101 chapter 10 and aprs.org/aprs12/mic-e-types.txt.
function packetDetails(body=''){
body=String(body);const result={format:null,comment:body,speedKmh:null,course:null,altitudeM:null,device:null};
if(/^[`']/.test(body)){
result.format='Mic-E';result.comment='';
if(body.length<9||!decode({symset:body[8],symbol:body[7]}))return result;
const [sp,dc,se]=[4,5,6].map(i=>body.charCodeAt(i)-28);
if(sp>=0&&sp<=99&&dc>=0&&dc<=99&&se>=0&&se<=99){
let speed=sp*10+Math.floor(dc/10),course=(dc%10)*100+se;
if(speed>=800)speed-=800;if(course>=400)course-=400;
if(speed>=0&&speed<=799&&course>=0&&course<=360){result.speedKmh=Math.round(speed*1.852);result.course=course||null;}
}
let tail=body.slice(9),prefix=tail[0];
if(prefix==='>'||prefix===']'){
result.device=prefix==='>'?'Kenwood TH-D7':'Kenwood TM-D700';tail=tail.slice(1);
if(tail.endsWith('=')){result.device=prefix==='>'?'Kenwood TH-D72':'Kenwood TM-D710';tail=tail.slice(0,-1);}
else if(prefix==='>'&&tail.endsWith('^')){result.device='Kenwood TH-D74';tail=tail.slice(0,-1);}
}else if(prefix==='`'||prefix==="'"){
tail=tail.slice(1);
const devices={'_ ':'Yaesu VX-8','_"':'Yaesu FTM-350','_#':'Yaesu VX-8G','_$':'Yaesu FT1D','_%':'Yaesu FTM-400DR','_)':'Yaesu FTM-100D','_(':'Yaesu FT2D','_0':'Yaesu FT3D','_3':'Yaesu FT5D','_1':'Yaesu FTM-300D','(5':'AnyTone D578UV','(8':'AnyTone D878UV','|3':'Byonics TinyTrak3','|4':'Byonics TinyTrak4',':4':'SCS DR-7400',':8':'SCS DR-7800'};
const device=devices[tail.slice(-2)];if(device){result.device=device;tail=tail.slice(0,-2);}
}else if(prefix===' ')tail=tail.slice(1);
const altitude=tail.match(/^([!-{]{3})\}/);
if(altitude){result.altitudeM=[...altitude[1]].reduce((n,c)=>n*91+c.charCodeAt(0)-33,0)-10000;tail=tail.slice(4);}
result.comment=tail;
}else if(/^[!=/@]/.test(body)){
result.format='APRS';const payload=body.slice(body[0]==='@'||body[0]==='/'?8:1);
if(/^\d{4}\.\d{2}[NS].\d{5}\.\d{2}[EW]./.test(payload))result.comment=payload.slice(19);
else if(/^[/\A-Z0-9][!-{]{8}[!-~][!-{]{3}/.test(payload))result.comment=payload.slice(13);
else result.comment='';
}else if(body.startsWith('>'))result.comment=body.slice(1).replace(/^\d{6}[zh/]/,'');
// Control bytes belong to the encoded frame, never the operator's description.
result.comment=result.comment.replace(/[\x00-\x1f\x7f-\x9f]/g,' ').trim();return result;
}
window.BPQAprsPacket={decode:packetDetails};
window.BPQAprsSymbols={decode,html};
})();
+6
View File
@@ -0,0 +1,6 @@
.section-detached-away>.detached-placeholder{display:flex;flex:1;min-height:360px;align-items:center;justify-content:center;flex-direction:column;text-align:center;padding:48px 24px;gap:18px;border:1px dashed #3d5368;border-radius:16px;background:radial-gradient(ellipse at top,#233b4c50,transparent 65%)}
.section-detached-away>:not(.detached-placeholder){display:none!important}.section-detached-away>.detached-placeholder[hidden]{display:none!important}.detached-placeholder-icon{display:grid;place-items:center;width:62px;height:62px;background:#8fb5cf10;border:1px solid #8fb5cf35;border-radius:18px;font-size:30px;color:#9fc9e4}.detached-placeholder h2{font-size:24px;letter-spacing:-.4px}.detached-placeholder p{color:#8fa7ba;max-width:420px;line-height:1.7}.detached-placeholder>div{display:flex;gap:10px;flex-wrap:wrap;justify-content:center;margin-top:6px}.detach-button{white-space:nowrap}
html[data-detached-view] #shell>.sidebar,html[data-detached-view] .topbar,html[data-detached-view] #notice{display:none!important}html[data-detached-view] #shell>main{margin:0;padding:0;width:100%;max-width:none}html[data-detached-view] #shell .page{height:100dvh;max-width:none;min-height:0;padding:20px}html[data-detached-view=chat] #chat{height:100dvh}html[data-detached-view=monitor] #monitor{height:100dvh}html[data-detached-view=aprs] #aprs{height:auto;min-height:100dvh;padding:20px}html[data-detached-view=aprs] #aprs-station-map{height:clamp(340px,calc(100dvh - 330px),680px)}html[data-detached-view=aprs] .aprs-stations-card{height:calc(clamp(340px,calc(100dvh - 330px),680px) + 112px)}
@media(max-width:650px){html[data-detached-view] #shell .page{padding:12px}.detached-placeholder>div{width:100%}.detached-placeholder>div button{flex:1}.chat-actions,.monitor-heading>div{flex-wrap:wrap}}
.detached-returned-note{min-height:100dvh;display:flex;align-items:center;justify-content:center;flex-direction:column;gap:20px;text-align:center;padding:30px;color:#cedce8}.detached-returned-note p{color:#8fa7ba}
+87
View File
@@ -0,0 +1,87 @@
/* Window ownership is UI metadata only; authentication stays in the HttpOnly cookie. */
(()=>{
const labels={terminal:'Terminale',aprs:'APRS',monitor:'Monitor',chat:'Chat'},params=new URLSearchParams(location.search);
const requested=location.pathname==='/terminal-window'?'terminal':params.get('detached');
const view=Object.hasOwn(labels,requested)?requested:null;
const owner=params.get('window')||crypto.randomUUID(),refs=new Map(),ready=new Set(),ttl=120000;
const key=id=>'bpq-detached:'+id,commandKey='bpq-detached-command';
const target=id=>'bpq-console-'+id;
const read=id=>{try{const value=JSON.parse(localStorage.getItem(key(id)));return value&&typeof value.owner==='string'&&Number.isFinite(value.at)?value:null;}catch{return null;}};
const write=(id,value)=>{try{value?localStorage.setItem(key(id),JSON.stringify(value)):localStorage.removeItem(key(id));}catch{}};
let initialized=false,authenticated=false,released=false,domReady=document.readyState==='complete';
if(view){document.documentElement.dataset.detachedView=view;window.name=target(view);}
function isAway(id){
if(view===id)return false;
const ref=refs.get(id);
if(ref){if(ref.closed){refs.delete(id);ready.delete(id);write(id,null);return false;}if(ready.has(id))return true;}
const record=read(id);return !!record&&Date.now()-record.at<ttl;
}
function shouldPoll(id){return (!view||!released&&view===id)&&!isAway(id);}
function release(){if(!view)return;released=true;const record=read(view);if(record?.owner===owner)write(view,null);}
function claim(){if(!view||!authenticated||released)return;write(view,{owner,at:Date.now()});}
function tell(id,action){try{localStorage.setItem(commandKey,JSON.stringify({id,action,at:Date.now(),nonce:crypto.randomUUID()}));}catch{}}
function focus(id){const ref=refs.get(id);if(ref&&!ref.closed){ref.focus();return;}tell(id,'focus');const popup=window.open('',target(id),'popup=yes,width=1180,height=820,resizable=yes,scrollbars=yes');if(popup)popup.focus();}
function closeView(){
release();const main=document.querySelector('main');if(main)main.hidden=true;
const note=document.createElement('section');note.className='detached-returned-note';
note.innerHTML='<span class="detached-placeholder-icon" aria-hidden="true">↙</span><h2>Sezione riportata nel pannello</h2><p>Puoi chiudere questa finestra.</p>';
document.body.append(note);window.close();
}
function dock(id){
if(view===id){
try{if(window.opener&&!window.opener.closed){window.opener.location.hash='#'+id;window.opener.focus();}}catch{}
closeView();return;
}
tell(id,'dock');const ref=refs.get(id);if(ref&&!ref.closed)ref.close();refs.delete(id);ready.delete(id);write(id,null);refresh();
if(typeof navigate==='function')navigate(id);
}
function open(id){
if(!Object.hasOwn(labels,id))return;
if(isAway(id)){focus(id);return;}
const nonce=crypto.randomUUID(),url=id==='terminal'?'/terminal-window?window='+nonce:'/?detached='+id+'&window='+nonce+'#'+id;
const popup=window.open(url,target(id),'popup=yes,width=1180,height=820,resizable=yes,scrollbars=yes');
if(!popup){if(typeof toast==='function')toast(BPQI18n.t('Consenti le finestre popup per aprire la sezione separata.'));return;}
refs.set(id,popup);popup.focus();
}
function refresh(){
if(!initialized)return;
for(const id of Object.keys(labels)){
const section=document.getElementById(id);if(!section)continue;
const away=isAway(id);section.classList.toggle('section-detached-away',away);
const placeholder=section.querySelector('.detached-placeholder');if(placeholder)placeholder.hidden=!away;
if(read(id)&&refs.has(id))ready.add(id);
}
}
function setup(){
if(initialized||!domReady)return;initialized=true;
for(const [id,label]of Object.entries(labels)){
const section=document.getElementById(id);if(!section)continue;
const heading=section.querySelector('.terminal-actions,.monitor-heading>div,.chat-actions,.page-heading');
if(id!=='terminal'&&heading){
const button=document.createElement('button');button.type='button';button.className='secondary detach-button';button.dataset.detach=id;
button.textContent=view===id?'↙ Torna al pannello':'↗ Stacca';button.onclick=()=>view===id?dock(id):open(id);heading.append(button);
}
if(!view){
const placeholder=document.createElement('div');placeholder.className='detached-placeholder';placeholder.hidden=true;
placeholder.innerHTML='<span class="detached-placeholder-icon" aria-hidden="true">↗</span><h2></h2><p>Questa sezione è aperta in una finestra separata.</p><div><button type="button" class="primary">Mostra finestra</button><button type="button" class="secondary">Riporta qui</button></div>';
placeholder.querySelector('h2').textContent=label;const buttons=placeholder.querySelectorAll('button');buttons[0].onclick=()=>focus(id);buttons[1].onclick=()=>dock(id);section.append(placeholder);
}
}
if(view&&location.pathname!=='/terminal-window'){
const previous=navigate;navigate=function(){previous(view);};navigate(view);
document.title='BPQ Console · '+labels[view];
}
refresh();
}
window.BPQDetached={view,open,dock,isAway,shouldPoll};
document.addEventListener('DOMContentLoaded',()=>{domReady=true;setup();});
document.addEventListener('station-ready',()=>{authenticated=true;released=false;setup();claim();refresh();if(view){document.title='BPQ Console · '+labels[view];if(location.pathname!=='/terminal-window')navigate(view);}});
document.addEventListener('bpq-detach-auth-lost',()=>{authenticated=false;release();});
window.addEventListener('storage',event=>{
if(event.key===commandKey&&view){try{const cmd=JSON.parse(event.newValue);if(cmd.id===view&&Date.now()-cmd.at<5000){if(cmd.action==='focus')window.focus();else if(cmd.action==='dock')closeView();}}catch{}}
if(event.key?.startsWith('bpq-detached:'))refresh();
});
window.addEventListener('pagehide',release);window.addEventListener('beforeunload',release);
window.addEventListener('pageshow',()=>{if(view&&authenticated){released=false;claim();}});
setInterval(()=>{claim();refresh();},2000);
})();
+2 -2
View File
@@ -12,7 +12,7 @@ function arrival(kind,title,detail,ids=[]){const item=document.createElement('di
let knownStation=null,knownIds;try{const saved=JSON.parse(localStorage.getItem('bpq-message-ids-'+station.call)||'null');knownIds=Array.isArray(saved)?new Set(saved):null}catch{knownIds=null}
const oldLoadMessages=loadMessages;
loadMessages=async function(...args){await oldLoadMessages(...args);if(!csrf||!allMessages.length)return;if(knownStation!==station.call){knownStation=station.call;try{const saved=JSON.parse(localStorage.getItem('bpq-message-ids-'+station.call)||'null');knownIds=Array.isArray(saved)?new Set(saved):null}catch{knownIds=null}}const arrivals=incoming(allMessages,knownIds,station.call);const fresh=[...arrivals.bulletins,...arrivals.mail];knownIds=new Set(allMessages.map(m=>m.id));localStorage.setItem('bpq-message-ids-'+station.call,JSON.stringify([...knownIds]));if(fresh.length){const bulls=fresh.filter(m=>m.type==='B'),mail=fresh.filter(m=>m.type==='P'||m.type==='T');if(bulls.length)arrival('bulletin',bulls.length===1?'Nuovo bollettino scaricato':`${bulls.length} nuovi bollettini scaricati`,bulls.length===1?bulls[0].subject:'Disponibili nella BBS',bulls.map(m=>m.id));if(mail.length)arrival('mail',mail.length===1?'Nuova mail ricevuta':`${mail.length} nuove mail ricevute`,mail.length===1?'Da '+mail[0].from+' · '+mail[0].subject:'Disponibili nella posta personale',mail.map(m=>m.id));chime();}};
setInterval(()=>{if(csrf&&!document.hidden)loadMessages(true)},15000);
setInterval(()=>{if(csrf&&!document.hidden&&!window.BPQDetached?.view)loadMessages(true)},15000);
const chatNav=document.createElement('button');chatNav.dataset.page='chat';chatNav.innerHTML='<span>◇</span> Chat';chatNav.onclick=()=>navigate('chat');$('nav').append(chatNav);
const chatPage=document.createElement('section');chatPage.id='chat';chatPage.className='page';chatPage.hidden=true;chatPage.innerHTML=`<div class="chat-heading"><h1>Chat</h1><div class="chat-actions"><span id="chat-state" class="chat-status">Disconnesso</span><button id="chat-connect" class="primary">Connetti</button><button id="chat-disconnect" class="secondary" hidden>Esci</button></div></div><div class="chat-layout"><aside class="chat-rooms"><div class="chat-label">STANZE<button id="new-topic" aria-label="Crea stanza">+</button></div><div id="chat-topics"><button class="room-button active"># General</button></div><div class="chat-links"><div class="chat-label">COLLEGAMENTI</div><div id="chat-links"></div></div></aside><div class="chat-main"><header class="chat-room-header"><b id="chat-room-name"># General</b><small id="chat-presence-count">— presenti</small></header><div id="chat-messages" class="chat-messages"><div class="chat-empty"><span>◇</span><h2>Chat BPQ</h2><p>Connettiti con il tuo account per partecipare alla chat.</p></div></div><form id="chat-form" class="chat-compose"><div class="chat-recipient"><label for="chat-recipient">Destinatario</label><select id="chat-recipient"><option value="">Tutta la stanza</option></select></div><div class="chat-input-row"><input id="chat-input" aria-label="Messaggio chat" placeholder="Scrivi un messaggio…" maxlength="500" autocomplete="off" disabled><button id="chat-send" class="primary" disabled>Invia ↗</button></div></form></div><aside class="chat-users"><div class="chat-label">PRESENTI <span id="chat-user-count">0</span></div><div id="chat-users"><p class="empty">Non connesso</p></div></aside></div>`;$('main').append(chatPage);
const topicDialog=document.createElement('dialog');topicDialog.innerHTML='<form id="topic-form"><h2>Crea o apri una stanza</h2><input id="topic-name" aria-label="Nome stanza" placeholder="Nome stanza" required pattern="[A-Za-z0-9_-]{1,24}" maxlength="24"><footer><button type="button" id="topic-cancel" class="secondary">Annulla</button><button class="primary">Entra</button></footer></form>';document.body.append(topicDialog);
@@ -45,7 +45,7 @@ function renderChat(data){
}
}
async function pollChat(){if(!csrf||chatPollBusy)return;chatPollBusy=true;try{renderChat(await api('/chat',{busy:false}))}catch(e){if(page==='chat')toast(e.message)}finally{chatPollBusy=false}}
async function pollChat(){if(!csrf||chatPollBusy||window.BPQDetached&&!window.BPQDetached.shouldPoll('chat'))return;chatPollBusy=true;try{renderChat(await api('/chat',{busy:false}))}catch(e){if(page==='chat')toast(e.message)}finally{chatPollBusy=false}}
$('#chat-connect').onclick=async()=>{try{chatLastId=0;chatFollowing=true;chatUnread=0;$('#chat-messages').innerHTML='';renderChat(await api('/chat/connect',{method:'POST',body:'{}'}))}catch(e){toast(e.message)}};$('#chat-disconnect').onclick=async()=>{try{await api('/chat/disconnect',{method:'POST',body:'{}'});pollChat()}catch(e){toast(e.message)}};
$('#chat-form').onsubmit=async e=>{e.preventDefault();const input=$('#chat-input'),button=$('#chat-send'),text=input.value.trim();if(!text)return;button.disabled=true;try{await api('/chat/send',{method:'POST',body:JSON.stringify({text,to:$('#chat-recipient').value})});input.value='';await pollChat()}catch(err){toast(err.message)}finally{button.disabled=chatState!=='online';input.focus()}};
$('#new-topic').onclick=()=>topicDialog.showModal();$('#topic-cancel').onclick=()=>topicDialog.close();$('#topic-form').onsubmit=async e=>{e.preventDefault();try{await api('/chat/topic',{method:'POST',body:JSON.stringify({topic:$('#topic-name').value})});topicDialog.close();pollChat()}catch(err){toast(err.message)}};
+18
View File
@@ -8,6 +8,24 @@ Zona locale · 30 km|Local area · 30 km
Inquadra il gruppo più denso, ignorando le stazioni isolate|Fit the densest group, excluding isolated stations
Inquadra un raggio di 30 km dalla tua stazione|Show a 30 km radius around your station
Posizione della tua stazione non disponibile|Your station position is unavailable
Questa sezione è aperta in una finestra separata.|This section is open in a separate window.
Sezione riportata nel pannello|Section returned to the dashboard
Puoi chiudere questa finestra.|You can close this window.
Mostra finestra|Show window
Riporta qui|Bring back here
Consenti le finestre popup per aprire la sezione separata.|Allow popups to open the detached section.
Fosfori|Phosphor
Stile del terminale|Terminal theme
Stacca|Detach
Torna al pannello|Back to dashboard
Apri il pannello|Open dashboard
Apri il terminale in una finestra separata|Open the terminal in a separate window
Consenti le finestre popup per aprire il terminale separato.|Allow popups to open the detached terminal.
Sessione scaduta. Accedi nuovamente dal pannello.|Session expired. Sign in again from the dashboard.
Terminale non configurato in BPQ.|Terminal is not configured in BPQ.
Quota|Altitude
Posizione APRS|APRS position
Pacchetto originale|Original packet
Simbolo non disponibile|Symbol unavailable
Sovrapposizione|Overlay
Commenta|Comment
+1 -1
View File
@@ -1,5 +1,5 @@
<!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 Console</title><link rel="stylesheet" href="/i18n.css"><script src="/ui-config.js"></script><script src="/i18n.js?v=20261019-label-audit"></script><link rel="stylesheet" href="/style.css"><link rel="stylesheet" href="/dark.css"><link rel="stylesheet" href="/mission.css"><link rel="stylesheet" href="/busy.css"><script defer src="/busy.js"></script><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="/compose-attachments.css"><script defer src="/compose-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><link rel="stylesheet" href="/forwarding.css"><script defer src="/forwarding.js?v=20261017-hourly-2"></script><link rel="stylesheet" href="/winlink-radio.css"><script defer src="/winlink-radio.js"></script><link rel="stylesheet" href="/terminal.css"><script defer src="/terminal.js"></script><link rel="stylesheet" href="/radio-control.css"><link rel="stylesheet" href="/radio-ports.css"><script defer src="/radio-ports.js"></script><link rel="stylesheet" href="/aprs.css"><script defer src="/aprs.js"></script><link rel="stylesheet" href="/vendor/leaflet/leaflet.css"><script defer src="/vendor/leaflet/leaflet.js"></script><link rel="stylesheet" href="/aprs-activity.css?v=20261019-map-fit"><script defer src="/aprs-symbols.js"></script><script defer src="/aprs-activity.js?v=20261019-map-fit"></script><link rel="stylesheet" href="/sync-progress.css"><script type="module" src="/sync-progress.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 Console</title><link rel="stylesheet" href="/i18n.css"><script src="/ui-config.js"></script><script defer src="/detach.js?v=20261019-multi"></script><link rel="stylesheet" href="/detach.css?v=20261019-multi"><script src="/i18n.js?v=20261019-label-audit"></script><link rel="stylesheet" href="/style.css"><link rel="stylesheet" href="/dark.css"><link rel="stylesheet" href="/mission.css"><link rel="stylesheet" href="/busy.css"><script defer src="/busy.js"></script><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="/compose-attachments.css"><script defer src="/compose-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><link rel="stylesheet" href="/forwarding.css"><script defer src="/forwarding.js?v=20261017-hourly-2"></script><link rel="stylesheet" href="/winlink-radio.css"><script defer src="/winlink-radio.js"></script><link rel="stylesheet" href="/terminal.css?v=20261019-themes"><script defer src="/terminal.js?v=20261019-themes"></script><link rel="stylesheet" href="/radio-control.css"><link rel="stylesheet" href="/radio-ports.css"><script defer src="/radio-ports.js"></script><link rel="stylesheet" href="/aprs.css"><script defer src="/aprs.js"></script><link rel="stylesheet" href="/vendor/leaflet/leaflet.css"><script defer src="/vendor/leaflet/leaflet.js"></script><link rel="stylesheet" href="/aprs-activity.css?v=20261019-packet-text"><script defer src="/aprs-symbols.js"></script><script defer src="/aprs-activity.js?v=20261019-packet-text"></script><link rel="stylesheet" href="/sync-progress.css"><script type="module" src="/sync-progress.js"></script></head>
<body>
<section id="login" class="login-screen"><div class="login-art"><h1>BPQ Console</h1><div class="login-byline" data-no-i18n>by IU2EUG</div><p>La tua stazione, in un unico pannello.</p></div><form id="login-form" class="login-card"><div class="login-brand"><span class="brand">BPQ Console</span><div class="login-byline" data-no-i18n>by IU2EUG</div></div><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></form></section>
<div id="shell" hidden><aside class="sidebar"><a class="brand" href="#home">BPQ Console</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>
+1 -1
View File
@@ -5,7 +5,7 @@ $('#home .page-heading').replaceWith(missionHead);
function graph(history,keys,id,minimum=1){const width=350,height=85,pad=5;const values=history.flatMap(s=>keys.map(k=>s[k])).filter(v=>typeof v==='number'&&Number.isFinite(v));if(!values.length)return '<div class="graph-empty">Nessun campione disponibile</div>';const min=Math.min(0,...values),max=Math.max(minimum,...values),range=max-min||1;const x=i=>pad+i*(width-pad*2)/Math.max(1,history.length-1),y=v=>height-pad-(v-min)*(height-pad*2)/range;const lines=keys.map((key,j)=>{let path='',breakLine=true;history.forEach((s,i)=>{const value=s[key];if(typeof value!=='number'||!Number.isFinite(value)){breakLine=true;return;}path+=(breakLine?'M':'L')+x(i).toFixed(2)+' '+y(value).toFixed(2)+' ';breakLine=false;});return `<path class="graph-line line-${j}" d="${path}"/>`}).join('');return `<svg viewBox="0 0 ${width} ${height}" preserveAspectRatio="none" role="img" aria-label="Grafico ${esc(id)}"><path class="graph-grid" d="M0 20 H350 M0 45 H350 M0 70 H350"/>${lines}</svg>`;}
function renderTelemetry(data){modemTelemetry=data;const c=data.current;if(!c)return;const history=data.history.slice(-120);$('#radio-status').textContent=window.bpqRadioControl?.txSuspended?'TX SOSPESO':!c.available?'OFFLINE':c.active?'LINK ATTIVO':'IN ASCOLTO';$('#modem-session').classList.toggle('idle',!c.active);$('#modem-session').classList.toggle('connected',!!c.active);$('#session-label').textContent=window.bpqRadioControl?.txSuspended?'PORTE RADIO IN PAUSA':c.connecting?'CHIAMATA IN CORSO':c.active?'CONNESSIONE RADIO':'STAZIONE IN ASCOLTO';$('#caller-call').textContent=c.active?c.caller||'—':station.nodeCall;$('#called-call').textContent=c.active?c.called||'—':station.alias;$('#call-arrow').textContent=c.active?'→':'◉';$('#caller-label').textContent=c.active?'CHIAMANTE':'NODO LOCALE';$('#called-label').textContent=c.active?'CHIAMATO':'ALIAS';$('#session-detail').textContent=c.active?(c.connecting?'Attendo risposta':(c.caller||'').replace(/-\d+$/,'')===station.call.replace(/-\d+$/,'')?'Chiamata in uscita':'Chiamata in ingresso'):station.radio?.name||'Nessuna porta modem configurata';$('#radio-freq').textContent=c.frequency||'—';$('#radio-scan').textContent=c.scan?'● Scansione attiva':c.active?'● Frequenza bloccata':'—';$('#radio-channel').textContent=c.available?(c.busy?'Canale occupato':'Canale libero'):'—';$('#radio-modem').textContent=c.available?station.radio?.name||'Modem BPQ':'Modem non disponibile';$('#radio-snr').textContent=c.lastSnr!=null?c.lastSnr.toFixed(1)+' dB':'—';$('#bps-value').textContent=c.available?Math.round((c.txBps||0)+(c.rxBps||0)).toLocaleString(BPQI18n.locale()):'—';$('#bps-caption').textContent='TX '+Math.round(c.txBps||0).toLocaleString(BPQI18n.locale())+' / RX '+Math.round(c.rxBps||0).toLocaleString(BPQI18n.locale())+' bit/s · dati BPQ';$('#snr-value').textContent=c.snr!=null?c.snr.toFixed(1)+' dB':'—';$('#vara-cpu-value').textContent=c.varaCpu!=null?c.varaCpu.toFixed(1)+'%':'—';$('#system-cpu-value').textContent=c.cpu!=null?c.cpu.toFixed(1)+'%':'—';$('#snr-caption').textContent=c.active?'SNR esposto da BPQ':'In attesa della prossima connessione';$('#modem-traffic').textContent='TX '+size(c.sent||0)+' / RX '+size(c.received||0);$('#bps-chart').innerHTML=graph(history,['txBps','rxBps'],'traffico BPQ TX RX',100);$('#snr-chart').innerHTML=graph(history,['snr'],'SNR',10);$('#vara-cpu-chart').innerHTML=graph(history,['varaCpu'],'CPU VARA',5);$('#system-cpu-chart').innerHTML=graph(history,['cpu'],'CPU sistema',10);}
async function pollTelemetry(){if(!csrf||modemPolling)return;modemPolling=true;try{renderTelemetry(await api('/telemetry',{busy:false}))}catch{}finally{modemPolling=false}}
const missionDashboard=loadDashboard;loadDashboard=async function(...args){await missionDashboard(...args);if(modemTelemetry)renderTelemetry(modemTelemetry);pollTelemetry();};setInterval(()=>{if(csrf&&!document.hidden)pollTelemetry()},2000);pollTelemetry();
const missionDashboard=loadDashboard;loadDashboard=async function(...args){await missionDashboard(...args);if(modemTelemetry)renderTelemetry(modemTelemetry);pollTelemetry();};setInterval(()=>{if(csrf&&!document.hidden&&!window.BPQDetached?.view)pollTelemetry()},2000);pollTelemetry();
const fullscreenButton=document.createElement('button');fullscreenButton.id='fullscreen-toggle';fullscreenButton.className='icon-button';fullscreenButton.textContent='⛶';fullscreenButton.setAttribute('aria-label','Schermo intero');fullscreenButton.title='Schermo intero';$('#refresh').after(fullscreenButton);
fullscreenButton.onclick=async()=>{try{if(document.fullscreenElement)await document.exitFullscreen();else await document.documentElement.requestFullscreen();}catch{toast('Schermo intero non disponibile in questo browser. Prova F11.');}};
document.addEventListener('fullscreenchange',()=>{const active=!!document.fullscreenElement;fullscreenButton.textContent=active?'⊡':'⛶';fullscreenButton.title=active?'Torna alla finestra':'Schermo intero';fullscreenButton.setAttribute('aria-label',fullscreenButton.title);fullscreenButton.setAttribute('aria-pressed',String(active));});
+1 -1
View File
@@ -6,7 +6,7 @@ const originalNavigate=navigate;navigate=function(next){originalNavigate(next);i
function filtered(){const port=$('#monitor-port').value,dir=$('#monitor-direction').value,q=$('#monitor-search').value.toLowerCase();return events.filter(e=>(!port||String(e.port)===port)&&(!dir||e.direction===dir)&&(!q||e.text.toLowerCase().includes(q)));}
function render(){const list=filtered(),area=$('#monitor-console');area.innerHTML=list.map(e=>`<article class="monitor-frame ${e.direction.toLowerCase()}"><div><span class="monitor-direction">${esc(e.direction)}</span><span class="monitor-port">${e.port?'P'+e.port:'BPQ'}</span></div><pre>${esc(e.text)}</pre></article>`).join('')||'<p class="monitor-empty">'+(state==='online'?'In ascolto. Nessun traffico corrispondente ai filtri.':'Avvia il monitor per seguire il traffico BPQ.')+'</p>';$('#monitor-count').textContent=list.length+' frame · '+events.length+' in memoria'+(paused?' · visualizzazione in pausa':'');if($('#monitor-follow').checked)area.scrollTop=area.scrollHeight;displayedCursor=cursor;}
function status(data){state=data.state;$('#monitor-state').className='chat-status '+state;$('#monitor-state').textContent=data.error||({online:'● In ascolto',connecting:'Connessione…',offline:'Disconnesso',error:'Non disponibile'}[state]);$('#monitor-connect').hidden=state==='online';$('#monitor-connect').disabled=state==='connecting';$('#monitor-stop').hidden=!['online','connecting'].includes(state);const current=$('#monitor-port').value;$('#monitor-port').innerHTML='<option value="">Tutte le porte</option>'+data.ports.map(p=>`<option value="${p.id}">${p.id} · ${esc(p.name)}</option>`).join('');$('#monitor-port').value=current;}
async function poll(){if(!csrf||busy)return;busy=true;try{let data=await api('/monitor?after='+cursor,{busy:false});if(data.latest<cursor){cursor=0;events=[];data=await api('/monitor?after=0');}status(data);events.push(...data.events);events=events.slice(-1000);cursor=data.latest;if(!paused&&(cursor!==displayedCursor||!events.length))render();}catch(e){if(page==='monitor')toast(e.message)}finally{busy=false;}}
async function poll(){if(!csrf||busy||window.BPQDetached&&!window.BPQDetached.shouldPoll('monitor'))return;busy=true;try{let data=await api('/monitor?after='+cursor,{busy:false});if(data.latest<cursor){cursor=0;events=[];data=await api('/monitor?after=0');}status(data);events.push(...data.events);events=events.slice(-1000);cursor=data.latest;if(!paused&&(cursor!==displayedCursor||!events.length))render();}catch(e){if(page==='monitor')toast(e.message)}finally{busy=false;}}
$('#monitor-connect').onclick=async()=>{try{status(await api('/monitor/connect',{method:'POST',body:'{}'}));await poll();}catch(e){toast(e.message)}};
$('#monitor-stop').onclick=async()=>{try{await api('/monitor/disconnect',{method:'POST',body:'{}'});await poll()}catch(e){toast(e.message)}};
$('#monitor-pause').onclick=()=>{paused=!paused;$('#monitor-pause').textContent=paused?'Riprendi':'Pausa';if(!paused)render();else $('#monitor-count').textContent+=' · visualizzazione in pausa';};
+16
View File
@@ -0,0 +1,16 @@
<!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="#11110e"><title>BPQ Console · Terminal</title>
<script src="/ui-config.js"></script><script src="/i18n.js?v=20261019-terminal-window"></script>
<link rel="stylesheet" href="/style.css"><link rel="stylesheet" href="/dark.css"><link rel="stylesheet" href="/terminal.css?v=20261019-themes">
<link rel="stylesheet" href="/detach.css?v=20261019-multi"><script defer src="/detach.js?v=20261019-multi"></script><script defer src="/terminal-window.js"></script><script defer src="/terminal.js?v=20261019-themes"></script>
</head>
<body class="terminal-detached">
<nav hidden></nav><span id="breadcrumb" hidden></span><button id="logout" hidden></button>
<main></main>
<section id="terminal-window-error" hidden role="status"><h1>Terminale</h1><p id="terminal-window-error-text"></p><a class="secondary" href="/#terminal">Apri il pannello</a></section>
<div id="toast" hidden role="status"></div>
</body>
</html>
+22
View File
@@ -0,0 +1,22 @@
// A detached view shares the authenticated browser session and its existing Telnet socket.
const $=selector=>document.querySelector(selector);
let station={features:{}},csrf='',page='terminal';
function navigate(){page='terminal';$('#terminal').hidden=false;}
function toast(text){$('#toast').textContent=text;$('#toast').hidden=false;clearTimeout(toast.timer);toast.timer=setTimeout(()=>$('#toast').hidden=true,6500);}
function terminalWindowError(text){document.dispatchEvent(new Event('bpq-detach-auth-lost'));csrf='';station={features:{}};$('#terminal').hidden=true;$('#terminal-window-error').hidden=false;$('#terminal-window-error-text').textContent=BPQI18n.t(text);}
async function api(url,options={}){
const {busy,...request}=options;
const response=await fetch('/api'+url,{...request,headers:{'Content-Type':'application/json',...(request.method==='POST'?{'X-CSRF-Token':csrf}:{}),...request.headers}});
const data=await response.json();
if(!response.ok){if(response.status===401)terminalWindowError('Sessione scaduta. Accedi nuovamente dal pannello.');throw new Error(data.error||'Richiesta fallita');}
return data;
}
$('#logout').onclick=async()=>{};
document.addEventListener('DOMContentLoaded',async()=>{
try{
const user=await api('/session');station=user.config;csrf=user.csrf;
if(!station.features.terminal){terminalWindowError('Terminale non configurato in BPQ.');return;}
document.title='BPQ Console · '+station.call+' · Terminal';
document.dispatchEvent(new Event('station-ready'));
}catch(error){if(csrf||!$('#terminal-window-error-text').textContent)terminalWindowError(error.message);}
});
+24
View File
@@ -1,3 +1,27 @@
#terminal{height:calc(100dvh - 76px);display:flex;flex-direction:column;min-height:560px;padding:24px 28px}.terminal-heading{display:flex;align-items:center;justify-content:space-between;gap:18px;margin-bottom:20px;flex-shrink:0}.terminal-heading h1{font-size:28px;font-weight:500}.terminal-heading p{font-size:11px;color:var(--muted);margin-top:5px}.terminal-actions{display:flex;gap:9px}.terminal-actions button{font-size:11px}.phosphor-case{flex:1;min-height:0;display:flex;flex-direction:column;border-radius:16px;border:1px solid #51452b;background:#11110e;padding:7px;box-shadow:0 16px 45px #0005,inset 0 1px #8e774822;overflow:hidden}.phosphor-top,.phosphor-bottom{display:flex;justify-content:space-between;align-items:center;gap:18px;color:#9e844d;font:10px Consolas,'Courier New',monospace;letter-spacing:1px;flex-shrink:0;padding:14px 19px}.phosphor-top{border-bottom:1px solid #4a3a1c}.phosphor-top>span:first-child{display:flex;align-items:center;gap:10px}.phosphor-top i{display:inline-block;width:6px;height:6px;background:#5d5033;border-radius:50%}.phosphor-top i.online{background:#ffd477;box-shadow:0 0 9px #ffbd4d}.phosphor-screen{flex:1;min-height:0;overflow:auto;padding:24px 26px;color:#ffd376;background:radial-gradient(ellipse at center,#241d0d 0%,#131106 70%,#0b0b06 100%);box-shadow:inset 0 0 55px #000a;scrollbar-color:#72572a #151207;position:relative;isolation:isolate}.phosphor-screen:before{content:'';position:absolute;inset:0;min-height:100%;pointer-events:none;background:repeating-linear-gradient(0deg,transparent 0 2px,#0002 2px 3px);z-index:1}.phosphor-screen pre{font:14px/1.55 Consolas,'Courier New',monospace;white-space:pre-wrap;overflow-wrap:anywhere;tab-size:8;letter-spacing:.2px;text-shadow:0 0 5px #ffc14b66;margin:0;position:relative;z-index:2;user-select:text}.phosphor-screen pre::selection{background:#94702f;color:#fff2c4}.phosphor-cursor{display:inline-block;color:#ffda84;font:16px Consolas,monospace;animation:phosphor-blink 1.1s steps(1) infinite;text-shadow:0 0 8px #ffc354}#terminal-form{display:flex;align-items:center;gap:12px;margin:0;padding:12px 20px;border-top:1px solid #4a3a1c;background:#1c180e;color:#ffd376;flex-shrink:0}#terminal-form label{font:18px Consolas,monospace}#terminal-input{flex:1;width:0;min-width:0;background:transparent;border:0;border-radius:0;box-shadow:none;color:#ffda8a;font:14px Consolas,'Courier New',monospace;padding:10px 0;caret-color:#ffe2a2}#terminal-input::placeholder{color:#82704b}#terminal-input:focus-visible{outline:0;box-shadow:0 1px #c09c4a}#terminal-send{background:#30250f;border:1px solid #665126;color:#e9c779;font:11px Consolas,monospace;padding:10px 13px;border-radius:5px}.phosphor-bottom{font-size:9px;padding:12px 18px;letter-spacing:.5px;flex-wrap:wrap}.phosphor-bottom button{background:transparent;border:0;color:#ffda84;font:inherit;padding:0}@keyframes phosphor-blink{50%{opacity:0}}@media(prefers-reduced-motion:reduce){.phosphor-cursor{animation:none}}@media(max-width:850px){.terminal-heading{align-items:flex-start;flex-direction:column}.terminal-actions{flex-wrap:wrap}.phosphor-screen{padding:16px}.phosphor-screen pre{font-size:12px}.phosphor-top{font-size:9px;letter-spacing:.3px}}@media(max-width:600px){#terminal{padding:20px 14px;height:calc(100dvh - 175px);min-height:510px}.terminal-heading h1{font-size:25px}.terminal-actions button{padding:8px 10px}.phosphor-top{padding:12px 10px}#terminal-form{padding:10px 12px}.phosphor-bottom>span:nth-child(2){display:none}nav{flex-wrap:wrap}}
@media(min-width:601px){.sidebar:has([data-page=terminal]) nav{min-height:100px;overflow-y:auto;flex-shrink:1;scrollbar-width:thin}.sidebar:has([data-page=terminal])>.brand,.sidebar:has([data-page=terminal])>.side-label,.sidebar:has([data-page=terminal])>.profile{flex-shrink:0}.sidebar:has([data-page=terminal])>.side-station{padding-block:14px;flex-shrink:0}}
/* Coordinated phosphor palettes shared by embedded and detached terminal views. */
#terminal{--phosphor:#ffd376;--phosphor-rgb:255,193,75;--phosphor-muted:#a78c57;--phosphor-bg:#100e08;--phosphor-surface:#1c180e}
#terminal[data-theme=green]{--phosphor:#9cf7ad;--phosphor-rgb:109,244,139;--phosphor-muted:#71a781;--phosphor-bg:#070f0a;--phosphor-surface:#101c14}
#terminal[data-theme=ice]{--phosphor:#b3edff;--phosphor-rgb:113,212,255;--phosphor-muted:#779eaf;--phosphor-bg:#080f15;--phosphor-surface:#101c26}
#terminal[data-theme=violet]{--phosphor:#ddbcff;--phosphor-rgb:186,132,255;--phosphor-muted:#a38bb6;--phosphor-bg:#100a16;--phosphor-surface:#1b1325}
#terminal[data-theme=white]{--phosphor:#e8eee9;--phosphor-rgb:216,230,222;--phosphor-muted:#91a29a;--phosphor-bg:#0c100f;--phosphor-surface:#171e1b}
#terminal .phosphor-case{border-color:rgba(var(--phosphor-rgb),.28);background:var(--phosphor-bg);box-shadow:0 16px 45px #0005,inset 0 1px rgba(var(--phosphor-rgb),.12)}
#terminal .phosphor-top,#terminal .phosphor-bottom{color:var(--phosphor-muted);border-color:rgba(var(--phosphor-rgb),.2)}
#terminal .phosphor-top i.online{background:var(--phosphor);box-shadow:0 0 9px rgba(var(--phosphor-rgb),.8)}
#terminal .phosphor-screen{color:var(--phosphor);background:radial-gradient(ellipse at center,rgba(var(--phosphor-rgb),.075),transparent 80%),var(--phosphor-bg);scrollbar-color:var(--phosphor-muted) var(--phosphor-bg)}
#terminal .phosphor-screen pre{color:var(--phosphor);text-shadow:0 0 5px rgba(var(--phosphor-rgb),.32)}
#terminal .phosphor-screen pre::selection{background:rgba(var(--phosphor-rgb),.35);color:var(--phosphor)}
#terminal .phosphor-cursor{color:var(--phosphor);text-shadow:0 0 8px rgba(var(--phosphor-rgb),.65)}
#terminal-form{background:var(--phosphor-surface);color:var(--phosphor);border-color:rgba(var(--phosphor-rgb),.22)}
#terminal-input{color:var(--phosphor);caret-color:var(--phosphor)}#terminal-input::placeholder{color:var(--phosphor-muted)}#terminal-input:focus-visible{box-shadow:0 1px var(--phosphor-muted)}
#terminal-send{color:var(--phosphor);background:rgba(var(--phosphor-rgb),.08);border-color:rgba(var(--phosphor-rgb),.3)}#terminal .phosphor-bottom button{color:var(--phosphor)}
.terminal-actions{flex-wrap:wrap;justify-content:flex-end}.terminal-theme-bar{display:flex;align-items:center;gap:18px;margin:-5px 0 14px;flex-shrink:0}.terminal-theme-bar>span{color:#8396a6;font-size:10px;letter-spacing:1.5px;text-transform:uppercase}.terminal-theme-bar>div{display:flex;gap:5px;flex-wrap:wrap}
.terminal-theme-bar button{display:inline-flex;align-items:center;gap:7px;padding:6px 10px;border:1px solid transparent;border-radius:6px;background:transparent;color:#899dad;font-size:11px;line-height:1.3}.terminal-theme-bar button::before{content:'';width:7px;height:7px;border-radius:50%;background:var(--theme-dot)}
[data-terminal-theme=amber]{--theme-dot:#ffd376}[data-terminal-theme=green]{--theme-dot:#9cf7ad}[data-terminal-theme=ice]{--theme-dot:#b3edff}[data-terminal-theme=violet]{--theme-dot:#ddbcff}[data-terminal-theme=white]{--theme-dot:#e8eee9}
.terminal-theme-bar button:hover{background:#abc4d40a;color:#cddde8}.terminal-theme-bar button[aria-pressed=true]{color:var(--theme-dot);border-color:#8ba6bc35;background:#abc4d40c}
body.terminal-detached{background:#0d141c;color:#d7e3ec;overflow:hidden}.terminal-detached main{margin:0;padding:0;max-width:none;width:100%;height:100dvh}.terminal-detached #terminal{height:100dvh;min-height:0;padding:20px}.terminal-detached .terminal-heading{margin-bottom:15px}.terminal-detached .terminal-heading h1{font-size:23px}.terminal-detached .phosphor-screen{padding:20px 23px}
#terminal-window-error{margin:10vh auto;max-width:460px;padding:28px;border:1px solid #354656;border-radius:14px;background:#172330}#terminal-window-error p{margin:15px 0 22px;color:#a5bbcc}#terminal-window-error a{text-decoration:none}
@media(max-width:650px){.terminal-detached #terminal{padding:12px}.terminal-theme-bar{gap:10px;align-items:flex-start}.terminal-theme-bar button{padding:6px 7px}.terminal-actions{justify-content:flex-start}.terminal-detached .phosphor-screen{padding:15px}.terminal-theme-bar>span{padding-top:6px}}
+12 -2
View File
@@ -1,13 +1,23 @@
(() => {
const detached=document.body.classList.contains('terminal-detached');
const nav=document.createElement('button');nav.dataset.page='terminal';nav.innerHTML='<span>▸_</span> Terminale';nav.onclick=()=>navigate('terminal');$('nav').append(nav);
const section=document.createElement('section');section.id='terminal';section.className='page';section.hidden=true;section.innerHTML=`<div class="terminal-heading"><div><h1>Terminale</h1><p>BPQ · Telnet</p></div><div class="terminal-actions"><button id="terminal-clear" class="secondary">Pulisci</button><button id="terminal-export" class="secondary">Salva testo</button><button id="terminal-connect" class="primary">Collega</button><button id="terminal-stop" class="secondary" hidden>Disconnetti</button></div></div><div class="phosphor-case"><div class="phosphor-top"><span><i id="terminal-led"></i> BPQ / REMOTE TERMINAL</span><span id="terminal-state" role="status">OFFLINE</span></div><div class="phosphor-screen" id="terminal-screen" tabindex="0" aria-label="Terminale Telnet BPQ"><pre id="terminal-output" aria-live="off"></pre><span class="phosphor-cursor" aria-hidden="true">▌</span></div><form id="terminal-form" autocomplete="off"><label for="terminal-input">&gt;</label><input id="terminal-input" aria-label="Comando Telnet" placeholder="Collega il terminale per iniziare" spellcheck="false" autocapitalize="off" maxlength="1000" disabled><button type="submit" id="terminal-send" disabled aria-label="Invia comando">INVIO ↵</button></form><div class="phosphor-bottom"><span id="terminal-endpoint">TELNET · BPQ LOCALE</span><span>↑ ↓ cronologia · Invio per inviare</span><button type="button" id="terminal-follow" hidden>↓ Torna al fondo</button></div></div>`;$('main').append(section);
const section=document.createElement('section');section.id='terminal';section.className='page';section.hidden=true;section.innerHTML=`<div class="terminal-heading"><div><h1>Terminale</h1><p>BPQ · Telnet</p></div><div class="terminal-actions"><button id="terminal-detach" class="secondary" title="Apri il terminale in una finestra separata">↗ Stacca</button><button id="terminal-dock" class="secondary" hidden>↙ Torna al pannello</button><button id="terminal-clear" class="secondary">Pulisci</button><button id="terminal-export" class="secondary">Salva testo</button><button id="terminal-connect" class="primary">Collega</button><button id="terminal-stop" class="secondary" hidden>Disconnetti</button></div></div><div class="terminal-theme-bar"><span>Fosfori</span><div role="group" aria-label="Stile del terminale"><button type="button" data-terminal-theme="amber" aria-pressed="true">Amber</button><button type="button" data-terminal-theme="green" aria-pressed="false">Green</button><button type="button" data-terminal-theme="ice" aria-pressed="false">Ice</button><button type="button" data-terminal-theme="violet" aria-pressed="false">Violet</button><button type="button" data-terminal-theme="white" aria-pressed="false">White</button></div></div><div class="phosphor-case"><div class="phosphor-top"><span><i id="terminal-led"></i> BPQ / REMOTE TERMINAL</span><span id="terminal-state" role="status">OFFLINE</span></div><div class="phosphor-screen" id="terminal-screen" tabindex="0" aria-label="Terminale Telnet BPQ"><pre id="terminal-output" aria-live="off"></pre><span class="phosphor-cursor" aria-hidden="true">▌</span></div><form id="terminal-form" autocomplete="off"><label for="terminal-input">&gt;</label><input id="terminal-input" aria-label="Comando Telnet" placeholder="Collega il terminale per iniziare" spellcheck="false" autocapitalize="off" maxlength="1000" disabled><button type="submit" id="terminal-send" disabled aria-label="Invia comando">INVIO ↵</button></form><div class="phosphor-bottom"><span id="terminal-endpoint">TELNET · BPQ LOCALE</span><span>↑ ↓ cronologia · Invio per inviare</span><button type="button" id="terminal-follow" hidden>↓ Torna al fondo</button></div></div>`;$('main').append(section);if(detached)section.hidden=false;
const themes=['amber','green','ice','violet','white'];
function applyTheme(value){const theme=themes.includes(value)?value:'amber';section.dataset.theme=theme;section.querySelectorAll('[data-terminal-theme]').forEach(button=>button.setAttribute('aria-pressed',String(button.dataset.terminalTheme===theme)));}
function savedTheme(){try{return localStorage.getItem('bpq-terminal-theme');}catch{return 'amber';}}
applyTheme(savedTheme());
section.querySelector('.terminal-theme-bar').onclick=event=>{const theme=event.target.closest('[data-terminal-theme]')?.dataset.terminalTheme;if(!themes.includes(theme))return;applyTheme(theme);try{localStorage.setItem('bpq-terminal-theme',theme);}catch{}};
window.addEventListener('storage',event=>{if(event.key==='bpq-terminal-theme')applyTheme(event.newValue);});
$('#terminal-detach').hidden=detached;$('#terminal-dock').hidden=!detached;
$('#terminal-detach').onclick=()=>{if(window.BPQDetached){window.BPQDetached.open('terminal');return;}const popup=window.open('/terminal-window','bpq-console-terminal','popup=yes,width=1120,height=780,resizable=yes,scrollbars=yes');if(popup)popup.focus();else toast(BPQI18n.t('Consenti le finestre popup per aprire il terminale separato.'));};
$('#terminal-dock').onclick=()=>{if(window.BPQDetached){window.BPQDetached.dock('terminal');return;}try{if(window.opener&&!window.opener.closed){window.opener.location.hash='#terminal';window.opener.focus();window.close();return;}}catch{}window.location.assign('/#terminal');};
let cursor=0,busy=false,state='offline',buffer='',following=true,history=[],historyIndex=0,draft='',sending=false,generation=0;
const area=$('#terminal-screen'),output=$('#terminal-output'),input=$('#terminal-input');
const previousNavigate=navigate;navigate=function(next){previousNavigate(next);if(next==='terminal'){$('#breadcrumb').textContent='Stazione / Terminale';poll();}};
function bottom(){area.scrollTop=area.scrollHeight;following=true;$('#terminal-follow').hidden=true;}
function append(text){buffer=(buffer+text).slice(-200000);output.textContent=buffer;if(following)bottom();}
function status(data){const wasOnline=state==='online';state=data.state;const online=state==='online',connecting=state==='connecting';$('#terminal-state').textContent=data.error||({online:'ONLINE',connecting:'COLLEGAMENTO…',offline:'OFFLINE',error:'ERRORE'}[state]||state);$('#terminal-led').classList.toggle('online',online);$('#terminal-connect').hidden=online||connecting;$('#terminal-stop').hidden=!online&&!connecting;input.disabled=!online;$('#terminal-send').disabled=!online||sending;input.placeholder=online?'Scrivi un comando…':'Collega il terminale per iniziare';$('#terminal-endpoint').textContent='TELNET · 127.0.0.1:'+data.port;if(online&&!wasOnline&&page==='terminal')input.focus();}
async function poll(){if(!csrf||busy||!station.features.terminal)return;busy=true;const current=generation;try{const d=await api('/terminal?after='+cursor,{busy:false});if(current!==generation)return;if(d.latest<cursor){cursor=0;buffer='';}status(d);for(const e of d.events)append(e.text);cursor=d.latest;}catch(e){if(page==='terminal')$('#terminal-state').textContent=e.message;}finally{busy=false;}}
async function poll(){if(!csrf||busy||!station.features.terminal||window.BPQDetached&&!window.BPQDetached.shouldPoll('terminal'))return;busy=true;const current=generation;try{const d=await api('/terminal?after='+cursor,{busy:false});if(current!==generation)return;if(d.latest<cursor){cursor=0;buffer='';}status(d);for(const e of d.events)append(e.text);cursor=d.latest;}catch(e){if(page==='terminal')$('#terminal-state').textContent=e.message;}finally{busy=false;}}
$('#terminal-connect').onclick=async()=>{const button=$('#terminal-connect');button.disabled=true;try{const d=await api('/terminal/connect',{method:'POST',body:'{}'});buffer='';output.textContent='';following=true;cursor=0;status(d);await poll();}catch(e){toast(e.message);}finally{button.disabled=false;}};
$('#terminal-stop').onclick=async()=>{try{status(await api('/terminal/disconnect',{method:'POST',body:'{}'}));await poll();}catch(e){toast(e.message);}};
$('#terminal-form').onsubmit=async e=>{e.preventDefault();if(sending||state!=='online')return;const text=input.value;sending=true;$('#terminal-send').disabled=true;try{await api('/terminal/send',{method:'POST',body:JSON.stringify({text})});if(text&&history.at(-1)!==text)history.push(text);history=history.slice(-100);historyIndex=history.length;draft='';input.value='';await poll();}catch(e){toast(e.message);}finally{sending=false;$('#terminal-send').disabled=state!=='online';if(state==='online')input.focus();}};
+1 -1
View File
@@ -210,7 +210,7 @@ const server=http.createServer(async(req,res)=>{
}
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 files={'/aprs-symbols.js':'aprs-symbols.js','/vendor/aprs-symbols/primary.png':'vendor/aprs-symbols/primary.png','/vendor/aprs-symbols/alternate.png':'vendor/aprs-symbols/alternate.png','/vendor/aprs-symbols/README.md':'vendor/aprs-symbols/README.md','/vendor/aprs-symbols/COPYRIGHT.md':'vendor/aprs-symbols/COPYRIGHT.md','/busy.js':'busy.js','/busy.css':'busy.css','/vendor/leaflet/leaflet.js':'vendor/leaflet/leaflet.js','/vendor/leaflet/leaflet.css':'vendor/leaflet/leaflet.css','/aprs-activity.js':'aprs-activity.js','/aprs-activity.css':'aprs-activity.css','/aprs.js':'aprs.js','/aprs.css':'aprs.css','/radio-ports.js':'radio-ports.js','/radio-ports.css':'radio-ports.css','/compose-attachments.js':'compose-attachments.js','/compose-attachments.css':'compose-attachments.css','/i18n.js':'i18n.js','/i18n.css':'i18n.css','/sync-state.js':'sync-state.js','/sync-progress.js':'sync-progress.js','/sync-progress.css':'sync-progress.css','/radio-control.js':'radio-control.js','/radio-control.css':'radio-control.css','/terminal.js':'terminal.js','/terminal.css':'terminal.css','/winlink-radio.js':'winlink-radio.js','/winlink-radio.css':'winlink-radio.css','/forwarding.js':'forwarding.js','/forwarding.css':'forwarding.css','/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('.png')?'image/png':file.endsWith('.md')?'text/plain; charset=utf-8':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);
const files={'/detach.js':'detach.js','/detach.css':'detach.css','/terminal-window':'terminal-window.html','/terminal-window.js':'terminal-window.js','/aprs-symbols.js':'aprs-symbols.js','/vendor/aprs-symbols/primary.png':'vendor/aprs-symbols/primary.png','/vendor/aprs-symbols/alternate.png':'vendor/aprs-symbols/alternate.png','/vendor/aprs-symbols/README.md':'vendor/aprs-symbols/README.md','/vendor/aprs-symbols/COPYRIGHT.md':'vendor/aprs-symbols/COPYRIGHT.md','/busy.js':'busy.js','/busy.css':'busy.css','/vendor/leaflet/leaflet.js':'vendor/leaflet/leaflet.js','/vendor/leaflet/leaflet.css':'vendor/leaflet/leaflet.css','/aprs-activity.js':'aprs-activity.js','/aprs-activity.css':'aprs-activity.css','/aprs.js':'aprs.js','/aprs.css':'aprs.css','/radio-ports.js':'radio-ports.js','/radio-ports.css':'radio-ports.css','/compose-attachments.js':'compose-attachments.js','/compose-attachments.css':'compose-attachments.css','/i18n.js':'i18n.js','/i18n.css':'i18n.css','/sync-state.js':'sync-state.js','/sync-progress.js':'sync-progress.js','/sync-progress.css':'sync-progress.css','/radio-control.js':'radio-control.js','/radio-control.css':'radio-control.css','/terminal.js':'terminal.js','/terminal.css':'terminal.css','/winlink-radio.js':'winlink-radio.js','/winlink-radio.css':'winlink-radio.css','/forwarding.js':'forwarding.js','/forwarding.css':'forwarding.css','/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('.png')?'image/png':file.endsWith('.md')?'text/plain; charset=utf-8':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'});}
});
server.listen(port,'0.0.0.0',()=>console.log(`BPQ Console: http://127.0.0.1:${port}`));
+46
View File
@@ -0,0 +1,46 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import vm from 'node:vm';
import {readFileSync} from 'node:fs';
function harness(detached=false,saved='amber'){
const nodes=new Map(),listeners={},calls=[],storage=new Map([['bpq-terminal-theme',saved]]);
const element=()=>({dataset:{},hidden:false,value:'',textContent:'',innerHTML:'',attributes:{},classList:{toggle(){}},addEventListener(){},append(){},focus(){},setAttribute(k,v){this.attributes[k]=v;},querySelector:s=>$(s),querySelectorAll:()=>buttons});
const $=s=>{if(!nodes.has(s))nodes.set(s,element());return nodes.get(s);};
const buttons=['amber','green','ice','violet','white'].map(theme=>Object.assign(element(),{dataset:{terminalTheme:theme}}));
let focused=0;
const window={addEventListener:(name,fn)=>listeners[name]=fn,open:(...args)=>{calls.push(args);return {focus(){focused++;}};},location:{assign:url=>calls.push(['navigate',url])}};
const context=vm.createContext({$,window,document:{body:{classList:{contains:()=>detached}},createElement:element,addEventListener:(name,fn)=>listeners[name]=fn},
localStorage:{getItem:key=>storage.get(key),setItem:(key,value)=>storage.set(key,value)},location:{hash:''},BPQI18n:{t:s=>s},
csrf:'test',page:'terminal',station:{features:{terminal:true}},navigate(){},api:async(...args)=>{calls.push(args);return {state:'online',latest:0,events:[],port:8100};},toast:text=>calls.push(['toast',text]),setInterval(){},setTimeout(){},clearTimeout(){}});
vm.runInContext(readFileSync(new URL('./public/terminal.js',import.meta.url),'utf8').replace(/\}\)\(\);\s*$/, 'window.testSection=section;})();'),context);
return {$,window,listeners,storage,buttons,calls,focused:()=>focused};
}
test('terminal themes persist, synchronize between windows and reject invalid stored values',()=>{
const h=harness(false,'green');assert.equal(h.window.testSection.dataset.theme,'green');
const violet=h.buttons.find(b=>b.dataset.terminalTheme==='violet');
h.$('.terminal-theme-bar').onclick({target:{closest:()=>violet}});
assert.equal(h.window.testSection.dataset.theme,'violet');assert.equal(h.storage.get('bpq-terminal-theme'),'violet');
assert.equal(violet.attributes['aria-pressed'],'true');
h.listeners.storage({key:'bpq-terminal-theme',newValue:'ice'});assert.equal(h.window.testSection.dataset.theme,'ice');
assert.equal(harness(false,'<bad>').window.testSection.dataset.theme,'amber');
});
test('detach opens a reusable standalone window without connecting, disconnecting or exposing credentials',()=>{
const h=harness();h.$('#terminal-detach').onclick();
assert.deepEqual(h.calls,[['/terminal-window','bpq-console-terminal','popup=yes,width=1120,height=780,resizable=yes,scrollbars=yes']]);assert.equal(h.focused(),1);
h.window.open=()=>null;h.$('#terminal-detach').onclick();assert.match(h.calls.at(-1)[1],/popup/);
});
test('returning from a detached terminal focuses the original panel without closing the Telnet session',()=>{
const h=harness(true);let focused=0,closed=0;h.window.opener={closed:false,location:{},focus(){focused++;}};h.window.close=()=>closed++;
assert.equal(h.$('#terminal-detach').hidden,true);assert.equal(h.$('#terminal-dock').hidden,false);
h.$('#terminal-dock').onclick();assert.equal(h.window.opener.location.hash,'#terminal');assert.equal(focused,1);assert.equal(closed,1);assert.equal(h.calls.length,0);
h.window.opener=null;h.$('#terminal-dock').onclick();assert.deepEqual(h.calls,[['navigate','/#terminal']]);
});
test('detached terminal restores the existing session before polling and never reconnects automatically',async()=>{
const nodes=new Map(),listeners={},calls=[],$=s=>{if(!nodes.has(s))nodes.set(s,{hidden:false,textContent:'',onclick:null});return nodes.get(s);};
const context=vm.createContext({document:{querySelector:$,addEventListener:(name,fn)=>listeners[name]=fn,dispatchEvent:event=>calls.push(['event',event.type])},
window:{},Event,BPQI18n:{t:s=>s},setTimeout(){},clearTimeout(){},fetch:async(url,options)=>{calls.push([url,options]);return {ok:true,json:async()=>({csrf:'private-csrf',config:{call:'N0TEST',features:{terminal:true}}})};}});
vm.runInContext(readFileSync(new URL('./public/terminal-window.js',import.meta.url),'utf8'),context);
await listeners.DOMContentLoaded();assert.equal(calls[0][0],'/api/session');assert.deepEqual(calls[1],['event','station-ready']);
assert.equal(calls.filter(([url])=>url.includes('connect')).length,0);assert.equal(context.document.title,'BPQ Console · N0TEST · Terminal');
});
+6 -6
View File
@@ -4,10 +4,10 @@ import {StringDecoder} from 'node:string_decoder';
import {TelnetText,TelnetLogin} from './telnet-login.mjs';
export {TelnetText} from './telnet-login.mjs';
export class Terminal {
constructor(credentials,options={}){this.credentials=credentials;this.options=options;this.state='offline';this.events=[];this.seq=0;this.lastAccess=Date.now();this.lastInput=Date.now();this.timer=setInterval(()=>{if(this.socket&&!this.socket.destroyed&&(Date.now()-this.lastAccess>90000||Date.now()-this.lastInput>15*60000))this.disconnect('Sessione chiusa per inattività');},10000);this.timer.unref();}
constructor(credentials,options={}){this.credentials=credentials;this.options=options;this.state='offline';this.events=[];this.seq=0;}
event(text){if(!text)return;this.events.push({id:++this.seq,text});let size=this.events.reduce((n,e)=>n+e.text.length,0);while(this.events.length>500||size>200000)size-=this.events.shift().text.length;}
snapshot(after=0){this.lastAccess=Date.now();return {state:this.state,events:this.events.filter(e=>e.id>after),latest:this.seq,port:this.options.port,error:this.error||null};}
async connect(){if(this.state==='connecting'||this.socket&&!this.socket.destroyed)return this.snapshot();this.state='connecting';let credentials;try{credentials=await this.credentials();}catch{this.state='error';throw new Error('Credenziali Telnet BPQ non disponibili');}if(this.state!=='connecting')return this.snapshot();this.error=null;this.events=[];this.stage=0;this.escape='';this.pendingCR=false;this.decoder=new StringDecoder('utf8');this.lastAccess=this.lastInput=Date.now();const socket=net.createConnection({host:'127.0.0.1',port:this.options.port});this.socket=socket;const telnet=new TelnetText(b=>socket.write(b));socket.setTimeout(15000);
snapshot(after=0){return {state:this.state,events:this.events.filter(e=>e.id>after),latest:this.seq,port:this.options.port,error:this.error||null};}
async connect(){if(this.state==='connecting'||this.socket&&!this.socket.destroyed)return this.snapshot();this.state='connecting';let credentials;try{credentials=await this.credentials();}catch{this.state='error';throw new Error('Credenziali Telnet BPQ non disponibili');}if(this.state!=='connecting')return this.snapshot();this.error=null;this.events=[];this.stage=0;this.escape='';this.pendingCR=false;this.decoder=new StringDecoder('utf8');const socket=net.createConnection({host:'127.0.0.1',port:this.options.port});this.socket=socket;const telnet=new TelnetText(b=>socket.write(b));socket.setTimeout(15000);
socket.on('timeout',()=>{if(this.state==='connecting')socket.destroy(new Error('Accesso Telnet non confermato'));});
socket.on('error',e=>{if(this.socket!==socket)return;this.state='error';this.error=['Accesso rifiutato','Accesso Telnet non confermato'].includes(e.message)?e.message:'Connessione Telnet BPQ non disponibile';this.event('\n[Connessione Telnet non disponibile]\n');});
socket.on('close',()=>{if(this.socket!==socket)return;this.login?.close();if(this.pendingCR){this.event('\n');this.pendingCR=false;}if(this.state!=='error')this.state='offline';this.event('\n[Sessione terminata]\n');});
@@ -18,7 +18,7 @@ export class Terminal {
if(this.escape){this.escape+=c;if(this.escape.length>128||/^\x1b\[[0-?]*[ -/]*[@-~]$/.test(this.escape)||this.escape.length===2&&c!=='[')this.escape='';continue;}
if(c==='\x1b'){this.escape=c;continue;}if(c==='\r'){this.pendingCR=true;continue;}if(c==='\b'){out=out.slice(0,-1);continue;}if(c==='\n'||c==='\t'||c.charCodeAt(0)>=32)out+=c;
}this.event(out);}
send(text){if(this.state!=='online'||!this.socket||this.socket.destroyed)throw new Error('Collega prima il terminale');if(typeof text!=='string'||text.length>1000||/[\x00-\x1f\x7f]/.test(text))throw new Error('Invia un solo comando, massimo 1000 caratteri');this.lastInput=this.lastAccess=Date.now();this.event(text+'\n');this.socket.write(text+'\r');}
disconnect(reason='Disconnessione richiesta'){this.login?.close();this.lastInput=Date.now();if(this.socket&&!this.socket.destroyed)this.socket.destroy();this.state='offline';this.event('\n['+reason+']\n');}
close(){this.disconnect();clearInterval(this.timer);}
send(text){if(this.state!=='online'||!this.socket||this.socket.destroyed)throw new Error('Collega prima il terminale');if(typeof text!=='string'||text.length>1000||/[\x00-\x1f\x7f]/.test(text))throw new Error('Invia un solo comando, massimo 1000 caratteri');this.event(text+'\n');this.socket.write(text+'\r');}
disconnect(reason='Disconnessione richiesta'){this.login?.close();if(this.socket&&!this.socket.destroyed)this.socket.destroy();this.state='offline';this.event('\n['+reason+']\n');}
close(){this.disconnect();}
}
+11
View File
@@ -6,3 +6,14 @@ test('terminal authenticates privately, preserves fragmented output, sends lines
try{await Promise.all([t.connect(),t.connect()]);await until(()=>t.state==='online');await until(()=>t.events.some(e=>e.text.includes('TEST:N0TEST>')));const text=t.snapshot().events.map(e=>e.text).join('');assert.equal(text,'Welcome to TEST\nTEST:N0TEST>');assert.ok(!text.includes('secret-example'));assert.ok(!text.includes('fixture'));assert.equal(received.filter(x=>x==='fixture').length,1);t.send('INFO');await until(()=>received.includes('INFO'));assert.throws(()=>t.send('INFO\rC EVIL'),/un solo comando/);assert.throws(()=>t.send('x'.repeat(1001)),/1000/);await until(()=>t.events.some(e=>e.text.includes('Response: INFO')));const last=t.seq;assert.equal(t.snapshot(last).events.length,0);t.output('\x1b[31mred\x1b[0m\r\0next');assert.equal(t.events.at(-1).text,'red\nnext');t.disconnect();assert.throws(()=>t.send('INFO'),/Collega/);assert.equal(t.state,'offline');}finally{t.close();for(const socket of sockets)socket.destroy();server.close();await once(server,'close');}
});
test('terminal transcript stays bounded and reconnect history does not grow indefinitely',()=>{const t=new Terminal(async()=>({}),{port:1});try{for(let i=0;i<800;i++)t.event('x'.repeat(500));assert.ok(t.events.length<=500);assert.ok(t.events.reduce((n,e)=>n+e.text.length,0)<=200000);}finally{t.close();}});
test('terminal stays connected without browser polling or user input and still closes explicitly',context=>{
context.mock.timers.enable({apis:['Date','setInterval']});
const t=new Terminal(async()=>({}),{port:1});let destroyed=false;
t.socket={destroyed:false,destroy(){destroyed=true;this.destroyed=true;}};t.state='online';
try{
context.mock.timers.tick(20*60*1000);
assert.equal(t.state,'online');assert.equal(destroyed,false);assert.equal(t.events.length,0);
t.disconnect();assert.equal(t.state,'offline');assert.equal(destroyed,true);
}finally{t.close();context.mock.timers.reset();}
});