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.
67 lines
15 KiB
JavaScript
67 lines
15 KiB
JavaScript
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
|
||
let station={call:'',alias:'',features:{},apps:[]};
|
||
const deletedMessageIds=new Set();
|
||
let csrf='',allMessages=[],dashboardData=null,filter='all',selected=null,page='home',loadGeneration=0;
|
||
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.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;}
|
||
function readableBody(text){const m=text.match(/^((?:R:[^\n]*\n)+)/);if(!m)return esc(text);return `<details class="routing-trace"><summary>Percorso del messaggio nella rete</summary><pre>${esc(m[1])}</pre></details>${esc(text.slice(m[1].length).replace(/^\n+/,''))}`;}
|
||
function size(n){return n>1024?(n/1024).toFixed(1)+' KB':n+' B'}
|
||
function navigate(next){page=next;$$('.page').forEach(p=>p.hidden=p.id!==next);$$('nav button').forEach(b=>b.classList.toggle('active',b.dataset.page===next));$('#breadcrumb').textContent='Stazione / '+({home:'Panoramica',bbs:'BBS & messaggi',network:'Rete & nodi'}[next]);location.hash=next;if(next==='bbs')loadMessages();}
|
||
$$('[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){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');}
|
||
function mailTimeMeta(m){const zone=mailTimezone();const stamp=kind=>{const value=kind==='sent'?m.createdAt:m.receivedAt;return value?new Date(value).toLocaleString(BPQI18n.locale(),{day:'2-digit',month:'2-digit',year:'numeric',hour:'2-digit',minute:'2-digit'}):null;};return [stamp('sent')?'Inviato <b>'+esc(stamp('sent'))+'</b>':'',stamp('received')?'Ricevuto <b>'+esc(stamp('received'))+'</b>':'','Timezone: '+esc(zone)].filter(Boolean).map(x=>'<span>'+x+'</span>').join('');}
|
||
function mailRow(m,selection,attribute,options={}){const unread=!m.read&&m.status==='N',current=selection===m.id;return `<button class="message-item mail-row ${current?'selected':''} ${unread?'unread':''}" ${attribute}="${m.id}" aria-pressed="${current}" title="${esc(m.subject)}"><span class="mail-indicator" aria-label="${unread?'Non letto':'Letto'}">${unread?'●':'○'}</span><span class="mail-from" title="${esc(options.from||m.from)}">${esc(options.from||m.from)}</span><span class="mail-subject">${esc(m.subject||'(Senza oggetto)')}${m.attachmentCount?'<span class="mail-paperclip" aria-label="Allegati" title="'+m.attachmentCount+' '+BPQI18n.t('Allegati')+'">📎 '+m.attachmentCount+'</span>':''}</span><span class="mail-category">${esc(options.category||m.to)}</span><time class="mail-date" datetime="${esc(m.receivedAt||m.createdAt||'')}" title="${esc(mailDate(m,'sent'))}">${esc(mailDate(m,options.dateKind))}</time><span class="mail-size">${size(m.size)}</span><span class="mail-status">${esc(options.status||m.status)}</span></button>`;}
|
||
function renderMessages(){const q=$('#search').value.toLowerCase(),cat=$('#category').value;const list=allMessages.filter(m=>(filter==='all'||m.type===filter||filter==='sent'&&m.from.replace(/-\d+$/,'')===station.call.replace(/-\d+$/,''))&&(!cat||m.to===cat)&&(!q||`${m.subject} ${m.from} ${m.to} ${m.id}`.toLowerCase().includes(q)));$('#list-count').textContent=list.length+' messaggi';$('#message-list').innerHTML=list.map(m=>mailRow(m,selected,'data-id',{category:categoryLabel(m),status:m.status==='F'?'Inoltrato':m.status==='N'?(m.read?'Letto':'Nuovo'):m.status==='Y'?'Letto':m.status==='H'?'Trattenuto':m.status})).join('')||'<p class="empty">Nessun messaggio corrisponde ai filtri.</p>';$$('#message-list [data-id]').forEach(b=>b.onclick=()=>readMessage(Number(b.dataset.id)));}
|
||
function replyDraft(message,comment=false){const bulletin=comment&&message.type==='B',destination=String((bulletin?message.to:message.from)||'').trim().replace(/\s*@\s*/g,'@'),via=String(message.via||'').trim();return {to:bulletin&&via&&!destination.includes('@')?destination+'@'+via:destination,type:bulletin?'B':'P',subject:(/^Re:/i.test(message.subject)?message.subject:'Re: '+message.subject).slice(0,80),text:'\n\n--- '+message.from+' ---\n'+message.text.split('\n').map(line=>'> '+line).join('\n')};}
|
||
async function readMessage(id){const generation=++loadGeneration;selected=id;renderMessages();$('#reader').innerHTML='<div class="reader-empty"><h2>Caricamento messaggio…</h2></div>';try{const m=await api('/messages/'+id);if(generation!==loadGeneration)return;$('#reader').innerHTML=`<div class="reader-header"><span class="tag">${m.type==='B'?'BOLLETTINO':'MESSAGGIO PERSONALE'} · #${id}</span><h2>${esc(m.subject)}</h2><div class="reader-meta"><span>Da <b>${esc(m.from)}</b></span><span>A <b>${esc(m.to)}</b></span>${mailTimeMeta(m)}</div></div><div class="reader-body">${readableBody(m.text)}</div><footer class="reader-footer"><span>BID ${esc(m.bid||'—')}</span><div class="reader-reply-actions">${m.type==='B'?'<button class="secondary" id="comment" title="Pubblica un commento come bollettino">▤ Commenta</button>':''}<button class="secondary" id="reply" title="Rispondi all’autore con un messaggio personale">↩ Rispondi</button></div></footer>`;markMessageRead(id).catch(error=>toast(error.message));$('#reply').onclick=()=>openCompose(replyDraft(m));if(m.type==='B')$('#comment').onclick=()=>openCompose(replyDraft(m,true));}catch(err){$('#reader').innerHTML=`<div class="reader-empty"><h2>Messaggio non disponibile</h2><p>${esc(err.message)}</p></div>`}}
|
||
$$('[data-filter]').forEach(b=>b.onclick=()=>{filter=b.dataset.filter;$$('[data-filter]').forEach(x=>x.classList.toggle('active',x===b));renderMessages()});$('#search').oninput=renderMessages;$('#category').onchange=renderMessages;
|
||
function openCompose(data={}){const f=$('#compose-form');f.reset();for(const [key,value]of Object.entries(data))f.elements[key].value=value;$('#compose-error').textContent='';$('#compose').showModal();f.elements.to.focus()}
|
||
$$('.compose-button').forEach(b=>b.onclick=()=>openCompose());$$('.close-compose').forEach(b=>b.onclick=()=>{const f=$('#compose-form');if((f.elements.text.value||f.elements.subject.value||window.bpqComposeAttachments?.count())&&!bpqConfirm('Chiudere e scartare questa bozza?'))return;$('#compose').close()});
|
||
$('#compose-form').addEventListener('submit',async e=>{e.preventDefault();const winlinkMode=typeof wlCompose!=='undefined'&&wlCompose;const b=$('#send-button');b.disabled=true;b.textContent='Salvataggio in BPQ…';window.bpqComposeAttachments?.busy(true);$('#compose-error').textContent='';try{const data=Object.fromEntries(new FormData(e.target));const payload=winlinkMode&&window.bpqComposeAttachments?.count()?window.bpqComposeAttachments.form(data):JSON.stringify(data);const created=await api('/messages',{method:'POST',body:payload});$('#compose').close();toast('Messaggio #'+created.id+' salvato nella BBS. L’inoltro sarà gestito da BPQ.');if(winlinkMode){wlFolder='queue';navigate('winlink');await wlLoad(true);wlRender();wlRead(created.id);}else{navigate('bbs');await loadMessages();readMessage(created.id);}loadDashboard();}catch(err){$('#compose-error').textContent=err.message}finally{window.bpqComposeAttachments?.busy(false);b.disabled=false;b.textContent='Salva e metti in coda →'}});
|
||
$('#refresh').onclick=async()=>{const b=$('#refresh');b.disabled=true;await Promise.all([loadDashboard(),loadMessages()]);b.disabled=false};
|
||
setInterval(()=>{if(csrf&&!document.hidden)loadDashboard(true)},20000);setInterval(()=>{$('#clock').textContent=new Date().toLocaleTimeString(BPQI18n.locale(),{hour:'2-digit',minute:'2-digit'})+' · '+mailTimezone()},1000);
|
||
function restoreSession(){api('/session').then(showShell).catch(()=>showLogin());}
|
||
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',restoreSession,{once:true});else restoreSession();
|
||
|
||
function applyStation(user){
|
||
document.title='BPQ Console · '+station.nodeCall;
|
||
$('.side-station').textContent=[station.nodeCall,station.alias,station.locator].filter(Boolean).join(' · ');
|
||
$('.profile .avatar').textContent=station.call.slice(0,2);
|
||
$('.profile > div:nth-child(2)').textContent=user.name+' · '+user.call;
|
||
$('.mission-heading h1').textContent=station.nodeCall+' / '+station.alias;
|
||
$('.mission-location').textContent=station.locator||'BPQ';
|
||
$('.modem-brand').textContent=station.radio?.name||BPQI18n.t('Nessuna porta modem');
|
||
$('#home .page-footer').firstChild.textContent='BPQ Console · '+station.nodeCall+' ';
|
||
$('#compose .eyebrow').textContent=station.call;
|
||
$('.compose-help').textContent='Il messaggio sarà salvato nella BBS. L’inoltro segue i profili BPQ.';
|
||
|
||
$('.wl-account').textContent=station.call.replace(/-\d+$/,'')+'@winlink.org';
|
||
$('.chat-empty h2').textContent=station.apps.find(a=>a.command==='CHAT')?.alias||'Chat BPQ';
|
||
$('.chat-empty p').textContent='Connettiti come '+station.call+' per partecipare alla chat.';
|
||
for(const feature of ['bbs','chat','winlink','monitor']){const button=$('nav [data-page="'+feature+'"]');if(button)button.hidden=!station.features[feature];}
|
||
$$('.services-card .service-call').forEach((el,i)=>el.textContent=(station.apps.find(a=>a.command===['BBS','CHAT','RMS'][i])?.call||(i===3?station.nodeCall:'Non configurato')));
|
||
$('.services-card .muted').textContent=station.call;
|
||
$$('.services-card .service').forEach((el,i)=>{if(i<3)el.hidden=!station.features[['bbs','chat','winlink'][i]];});
|
||
$$('#home [data-page="bbs"]').forEach(b=>b.disabled=!station.features.bbs);
|
||
$('#wl-sync').disabled=!station.features.winlink;
|
||
$('#bps-chart').closest('article').hidden=!station.features.radio;
|
||
$('#vara-cpu-chart').closest('article').hidden=!station.features.vara;
|
||
if(!station.features.bbs){$('#nav-count').hidden=true;$$('.compose-button').forEach(b=>b.disabled=true);}
|
||
if(!station.features[page]&&['bbs','chat','winlink','monitor'].includes(page))navigate('home');
|
||
}
|
||
|
||
document.addEventListener('bpq-languagechange',()=>{if(csrf){if(!station.radio)$('.modem-brand').textContent=BPQI18n.t('Nessuna porta modem');renderMessages();if(typeof wlRender==='function')wlRender();}});
|
||
|
||
async function markMessageRead(id){const state=await api('/messages/'+id+'/read',{method:'POST',body:'{}'});for(const item of allMessages)if(item.id===id)Object.assign(item,state);if(typeof wlData!=='undefined'&&wlData)for(const item of wlData.messages)if(item.id===id)Object.assign(item,state);renderMessages();if(typeof wlRender==='function')wlRender();}
|