From c98c67e18bd74699e8a192f90851deee728747f0 Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 19 Oct 2026 22:15:15 +0200 Subject: [PATCH] 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. --- README.md | 6 +++ aprs-activity.mjs | 2 +- aprs-packet-text.test.mjs | 35 +++++++++++++++ detach.test.mjs | 52 ++++++++++++++++++++++ map-refresh-ui.test.mjs | 11 +++++ public/app.js | 6 +-- public/aprs-activity.css | 2 + public/aprs-activity.js | 19 ++++++-- public/aprs-symbols.js | 36 +++++++++++++++ public/detach.css | 6 +++ public/detach.js | 87 +++++++++++++++++++++++++++++++++++++ public/enhancements.js | 4 +- public/i18n.js | 18 ++++++++ public/index.html | 2 +- public/mission.js | 2 +- public/monitor.js | 2 +- public/terminal-window.html | 16 +++++++ public/terminal-window.js | 22 ++++++++++ public/terminal.css | 24 ++++++++++ public/terminal.js | 14 +++++- server.mjs | 2 +- terminal-window.test.mjs | 46 ++++++++++++++++++++ terminal.mjs | 12 ++--- terminal.test.mjs | 11 +++++ 24 files changed, 415 insertions(+), 22 deletions(-) create mode 100644 aprs-packet-text.test.mjs create mode 100644 detach.test.mjs create mode 100644 public/detach.css create mode 100644 public/detach.js create mode 100644 public/terminal-window.html create mode 100644 public/terminal-window.js create mode 100644 terminal-window.test.mjs diff --git a/README.md b/README.md index 985f36a..5d2807a 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/aprs-activity.mjs b/aprs-activity.mjs index 705fd6a..399826b 100644 --- a/aprs-activity.mjs +++ b/aprs-activity.mjs @@ -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(//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(//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{} } diff --git a/aprs-packet-text.test.mjs b/aprs-packet-text.test.mjs new file mode 100644 index 0000000..94a6fa1 --- /dev/null +++ b/aprs-packet-text.test.mjs @@ -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+'').comment,''); +}); +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<U ^>/"5J}'; + const row='A,45.5,9.1,N0TEST,TEST,WIDE1-1
'+body+'
Last Heard: 12:00:00 on Port 3
,010D@,1\r\n|'; + const station=parseNativeStations(row)[0]; + assert.equal(station.lastBody,'`\x7f/"5J}');assert.equal(station.lastBody[7],'>');assert.equal(station.lastBody[8],'/'); + assert.equal(decode(station.lastBody).altitudeM,142); +}); diff --git a/detach.test.mjs b/detach.test.mjs new file mode 100644 index 0000000..75a4a59 --- /dev/null +++ b/detach.test.mjs @@ -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')); +}); diff --git a/map-refresh-ui.test.mjs b/map-refresh-ui.test.mjs index c1a88da..ec992e3 100644 --- a/map-refresh-ui.test.mjs +++ b/map-refresh-ui.test.mjs @@ -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,/
Pacchetto originale/); + assert.ok(html.includes(String.fromCharCode(92)+'x7f'));assert.ok(!html.includes(String.fromCharCode(127))); + assert.equal(s.lastBody,body); +}); diff --git a/public/app.js b/public/app.js index 686070d..754e1db 100644 --- a/public/app.js +++ b/public/app.js @@ -5,8 +5,8 @@ let csrf='',allMessages=[],dashboardData=null,filter='all',selected=null,page='h const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[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=>`${esc(r.call)}${r.active?'ATTIVO':'INATTIVO'}${esc(r.port)}${r.quality}${r.nodes}${r.frames}${r.retries}`).join('')||'Nessuna rotta disponibile';$('#nodes').innerHTML=d.nodes.map(n=>{const [alias,call]=n.split(':');return `
${esc(alias)}${esc(call)}
`}).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=>`${esc(r.call)}${r.active?'ATTIVO':'INATTIVO'}${esc(r.port)}${r.quality}${r.nodes}${r.frames}${r.retries}`).join('')||'Nessuna rotta disponibile';$('#nodes').innerHTML=d.nodes.map(n=>{const [alias,call]=n.split(':');return `
${esc(alias)}${esc(call)}
`}).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=''+categories.map(c=>``).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');} diff --git a/public/aprs-activity.css b/public/aprs-activity.css index 3e038f8..758b902 100644 --- a/public/aprs-activity.css +++ b/public/aprs-activity.css @@ -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} diff --git a/public/aprs-activity.js b/public/aprs-activity.js index 34ba6a3..b0bbb42 100644 --- a/public/aprs-activity.js +++ b/public/aprs-activity.js @@ -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)+' · '+esc(info.code)+''+(info.overlay?' · '+BPQI18n.t('Sovrapposizione')+' '+esc(info.overlay):''):BPQI18n.t('Simbolo non disponibile');} - function popup(s){return '
'+esc(s.call)+''+symbolDetail(s.position)+''+esc(s.transport)+(s.port?' · Port '+s.port:'')+''+esc(time(s.lastAt))+''+s.position.lat.toFixed(5)+', '+s.position.lon.toFixed(5)+'

'+esc(s.status||s.lastBody||'')+'

'+esc(s.path||'')+'
';} + 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?'
'+BPQI18n.t('Pacchetto originale')+'
'+esc(s.lastBody.replace(/[\x00-\x1f\x7f-\x9f]/g,c=>String.fromCharCode(92)+'x'+c.charCodeAt(0).toString(16).padStart(2,'0')))+'
':'';} + function popup(s){return '
'+esc(s.call)+''+symbolDetail(s.position)+''+esc(s.transport)+(s.port?' · Port '+s.port:'')+''+esc(time(s.lastAt))+''+s.position.lat.toFixed(5)+', '+s.position.lon.toFixed(5)+'

'+esc(stationDescription(s))+'

'+rawPacket(s)+''+esc(s.path||'')+'
';} 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:'© OpenStreetMap contributors · APRS symbols © OH7LZB'}).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=>'').join('')||'

Nessuna stazione ricevuta con questi filtri.

');} + function renderStations(){const list=stations();markup('#aprs-received-stations',list.map(s=>'').join('')||'

Nessuna stazione ricevuta con questi filtri.

');} function render(){if(!data)return;const events=data.events.filter(e=>(!source()||e.transport===source())&&(!$('#aprs-direction').value||e.direction===$('#aprs-direction').value)&&(!query()||(e.packet+' '+e.from).toUpperCase().includes(query()))).slice().reverse(); $('#aprs-live-state').textContent=paused?'Vista in pausa':data.monitor==='online'?'● APRS in tempo reale':'Monitor '+data.monitor; markup('#aprs-activity-kpis',[['Radio RX',events.filter(e=>e.transport==='Radio'&&e.direction==='RX').length],['Radio TX · BPQ',events.filter(e=>e.transport==='Radio'&&e.direction==='TX').length],['Internet RX',events.filter(e=>e.transport==='Internet'&&e.direction==='RX').length],['Internet TX',events.filter(e=>e.transport==='Internet'&&e.direction==='TX').length],['Stazioni ricevute',stations().length]].map(([k,v])=>'
'+esc(k)+''+v+'
').join('')); $('#aprs-traffic-count').textContent=events.length+' '+BPQI18n.t('pacchetti nel registro');markup('#aprs-traffic-rows',events.slice(0,400).map(e=>''+esc(time(e.at))+''+e.direction+''+esc(e.transport)+(e.port?'Port '+e.port+'':'')+''+esc(e.from)+'→ '+esc(e.to)+''+esc(type(e.type))+''+esc(e.body.slice(0,180))+''+(selectedEvent===e.id?'
'+esc(e.packet)+'
'+esc(e.evidence)+'':'')).join('')||'In attesa di pacchetti APRS ricevuti o inviati.'); $('#aprs-traffic-scope').textContent=BPQI18n.t('Ultimi 2000 pacchetti · TX radio = richieste registrate da BPQ.');$('#aprs-activity-status').textContent=[...data.errors,...(!data.loggingInternet?[BPQI18n.t('Log Internet non disponibile')]:[]),BPQI18n.t('Aggiornato')+' '+time(data.updatedAt)].join(' · ');renderStations();renderMap(); } - 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();}}; diff --git a/public/aprs-symbols.js b/public/aprs-symbols.js index 06ae428..a746196 100644 --- a/public/aprs-symbols.js +++ b/public/aprs-symbols.js @@ -13,5 +13,41 @@ const col=info.index%16,row=Math.floor(info.index/16); return ''; } + + // 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}; })(); diff --git a/public/detach.css b/public/detach.css new file mode 100644 index 0000000..8f310d3 --- /dev/null +++ b/public/detach.css @@ -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} diff --git a/public/detach.js b/public/detach.js new file mode 100644 index 0000000..0971d4c --- /dev/null +++ b/public/detach.js @@ -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.atdiv,.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='

Questa sezione è aperta in una finestra separata.

'; + 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); +})(); diff --git a/public/enhancements.js b/public/enhancements.js index 23accd3..8d0dbbd 100644 --- a/public/enhancements.js +++ b/public/enhancements.js @@ -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='◇ Chat';chatNav.onclick=()=>navigate('chat');$('nav').append(chatNav); const chatPage=document.createElement('section');chatPage.id='chat';chatPage.className='page';chatPage.hidden=true;chatPage.innerHTML=`

Chat

Disconnesso
# General— presenti
◇

Chat BPQ

Connettiti con il tuo account per partecipare alla chat.

`;$('main').append(chatPage); const topicDialog=document.createElement('dialog');topicDialog.innerHTML='

Crea o apri una stanza

';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)}}; diff --git a/public/i18n.js b/public/i18n.js index 5ee2da8..04a6539 100644 --- a/public/i18n.js +++ b/public/i18n.js @@ -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 diff --git a/public/index.html b/public/index.html index 1be51eb..0923629 100644 --- a/public/index.html +++ b/public/index.html @@ -1,5 +1,5 @@ -BPQ Console +BPQ Console