diff --git a/.gitignore b/.gitignore index 14fb0c8..d876b05 100644 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,6 @@ manual-forwarding.session.json* propagation.config.json* aprs-activity.cache.json* voacap-cache/ +forwarding-schedule.state.json* + +message-read-state.json* diff --git a/README.md b/README.md index 252fda6..e5af2f7 100644 --- a/README.md +++ b/README.md @@ -259,3 +259,17 @@ APRS frequency controls are exposed for packet controllers explicitly advertisin Enabling APRS listening selects that port's APRS frequency as its fixed listening channel. Manual Winlink/BBS reservations temporarily override it, then restore the port's listening selection. Disabling APRS routing does not power down the radio; listening channels remain manageable from Overview. Native APRS digipeating handles paths, hop limits and duplicates. Broad geographic APRS-IS → RF forwarding is not enabled by this page. APRS RX monitoring can optionally use a receive-only TCP KISS endpoint that explicitly supports multiple clients: set aprsKissMonitor to an array of objects with port (BPQ port number), host and tcpPort in console.config.json. This connection never sends data or commands. Do not enable it on a single-client TNC. Radio TX still comes from the BPQ monitor; historical native station entries are not counted as received packets. + +### Scheduled packet forwarding + +Optional `forwardingSchedules` in the private `console.config.json` schedules an existing `manualForwardingRoutes` entry, for example: + +```json +"forwardingSchedules": [ + { "route": "N0TEST-VHF", "enabled": true, "intervalSeconds": 3600 } +] +``` + +The Console server must remain running. Hourly calls start on hour boundaries, independently of the browser. The scheduler uses the same radio reservation, BBS queue, routing rules and recovery as a manual call. It does not edit listening channels: after completion, failure or cancellation, the packet adapter releases the temporary frequency and resumes the current listening/APRS selection. TX suspension, active radio links and BBS sessions still block calls; a blocked attempt is skipped until the next boundary. Persisted schedule state prevents replay after a server restart. Disable the native HF forwarding timer for that partner when replacing it with a packet schedule, to avoid competing calls. The Forwarding table shows the interval and next attempt. + +An optional schedule hours object, for example { "timeZone": "Europe/Rome", "start": 7, "end": 24 }, limits attempts to local operating hours. The next attempt skips closed hours and follows daylight-saving changes. Hardware power scheduling is provided by the local station adapter; the generic installer does not create power-off tasks. diff --git a/chat-roster.test.mjs b/chat-roster.test.mjs new file mode 100644 index 0000000..436008a --- /dev/null +++ b/chat-roster.test.mjs @@ -0,0 +1,21 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {Chat} from './chat.mjs'; + +test('wrapped node lists stay out of chat, including seven character aliases and single trailing nodes',()=>{ + const chat=new Chat(async()=>({})); + try{ + for(let i=0;i<3;i++){ + chat.line('90 Node(s)');chat.line('Here ALBCHT <- DM4CHT CHTMI'); + chat.line('TSVCHAT KTCHAT NPRCHT CAMCHT TVLCHT UTHCHT KYCHAT JTQSO OCGCHT GYBCHT'); + chat.line('Nodes via DM4CHT(5) - DM4CHT CHTMI'); + chat.line('TSVCHAT'); + chat.line('IW2OHX : T'); + chat.line('Links Defined:');chat.line('DM4RW-4 Open RTT 1');chat.line('IW2OHX-5 Idle'); + } + assert.deepEqual(chat.events.map(e=>[e.type,e.sender,e.text]),Array.from({length:3},()=>['message','IW2OHX','T'])); + assert.equal(chat.links.length,2); + chat.line('IW2OHX : TSVCHAT KTCHAT NPRCHT'); + assert.equal(chat.events.at(-1).text,'TSVCHAT KTCHAT NPRCHT'); + }finally{clearInterval(chat.timer);} +}); diff --git a/chat.mjs b/chat.mjs index 9d38fab..93d3881 100644 --- a/chat.mjs +++ b/chat.mjs @@ -27,10 +27,11 @@ export class Chat { const count=line.match(/^(\d+) Station\(s\) connected:/);if(count){this.users=[];this.remaining=Number(count[1]);this.section='users';return;} const user=parseUser(line);if(user){this.users=this.users.filter(u=>u.call!==user.call);this.users.push(user);if(user.call===this.call)this.topic=user.topic;this.remaining--;if(this.remaining<=0)this.section='';return;} if(line==='Active Topics are:'){this.topics=[];this.section='topics';return;} - if(/^\d+ Node\(s\)|^Here |^User [A-Z0-9-]+|^Links Defined:/.test(line)){if(line==='Links Defined:'){this.section='links';this.links=[]}else this.section='';return;} + if(/^\d+ Node\(s\)|^Here |^User [A-Z0-9-]+|^Links Defined:/.test(line)){if(line==='Links Defined:'){this.section='links';this.links=[]}else this.section=/^(?:\d+ Node\(s\)|Here )/.test(line)?'nodes':'';return;} if(this.section==='topics'){if(/^[A-Za-z0-9_-]+$/.test(line)&&line!==this.call){this.topics.push(line);}return;} if(this.section==='links'){const m=line.match(/^([A-Z0-9]+(?:-\d+)?)\s+(Open|Connect failed|Connecting|Closed|Idle)(.*)$/i);if(m){this.links.push({call:m[1],state:m[2],detail:m[3].trim()});return;}this.section='';} - if(/^(Nodes via|\s*[A-Z0-9#]{3,6}(?:\s+[A-Z0-9#]{3,6}){2,})/.test(line))return; + if(/^Nodes via /.test(line)){this.section='nodes';return;} + if(this.section==='nodes'&&/^[A-Z0-9#][A-Z0-9#_-]{0,31}(?:\s+[A-Z0-9#][A-Z0-9#_-]{0,31})*$/.test(line))return; if(/^[A-Z0-9-]+ Chat Server|^Type \/h|^Bringing up links|^This may take|^The \/p|^[A-Z0-9]{1,6}:/.test(line))return; const message=line.match(/^(?:\d{2}:\d{2}(?::\d{2})?\s+)?(?:<|\[)?([A-Z0-9]*\d[A-Z0-9]*(?:-\d+)?)(?:>|\])?\s*(?:\([^)]*\))?[: ]+(.+)$/); this.event(message?'message':'system',message?message[2]:line,message?message[1]:null);} diff --git a/forwarding-scheduler.mjs b/forwarding-scheduler.mjs new file mode 100644 index 0000000..3227675 --- /dev/null +++ b/forwarding-scheduler.mjs @@ -0,0 +1,31 @@ +import {readFile,writeFile,rename} from 'node:fs/promises'; +import path from 'node:path'; + +export class ForwardingScheduler { + constructor(config,dir,client,{clock=Date.now}={}){ + this.client=client;this.clock=clock;this.file=path.join(dir,'forwarding-schedule.state.json');this.jobs={};this.busy=false; + this.schedules=(config.forwardingSchedules||[]).map(s=>{ + if(!client.routes.some(r=>r.id===s.route)||!Number.isInteger(s.intervalSeconds)||s.intervalSeconds<300||s.intervalSeconds>86400||typeof s.enabled!=='boolean')throw Error('Programmazione forwarding non valida'); + if(s.hours){const h=s.hours;if(!Number.isInteger(h.start)||!Number.isInteger(h.end)||h.start<0||h.end>24||h.start>=h.end)throw Error('Orari forwarding non validi');new Intl.DateTimeFormat('en',{timeZone:h.timeZone}).format();} + return {...s,intervalMs:s.intervalSeconds*1000}; + }); + if(new Set(this.schedules.map(s=>s.route)).size!==this.schedules.length)throw Error('Programmazione forwarding duplicata'); + this.init=this.restore();this.timer=setInterval(()=>this.tick().catch(()=>{}),5000);this.timer.unref(); + } + allowed(schedule,now){if(!schedule.hours)return true;const h=schedule.hours,hour=Number(new Intl.DateTimeFormat('en-GB',{timeZone:h.timeZone,hour:'2-digit',hourCycle:'h23'}).format(new Date(now)));return hour>=h.start&&hour({...s,...this.jobs[s.route],nextAt:s.enabled?new Date(this.jobs[s.route]?.nextAt||this.boundary(s,this.clock())).toISOString():null,enabled:s.enabled}));} + async tick(){await this.init;if(this.busy)return;this.busy=true; + try{for(const s of this.schedules){const j=this.jobs[s.route],now=this.clock();if(!s.enabled||now{ + const dir=await mkdtemp(path.join(os.tmpdir(),'fwd-schedule-'));let now=Date.parse('2026-10-17T19:37:00Z'),calls=[],blocked=false; + const client={routes:[{id:'N0TEST-VHF'}],startRoute:async id=>{calls.push(id);if(blocked)throw Error('Radio occupata');}}; + const config={forwardingSchedules:[{route:'N0TEST-VHF',intervalSeconds:3600,enabled:true}]};let first,second; + try{first=new ForwardingScheduler(config,dir,client,{clock:()=>now});await first.init;assert.equal(first.snapshot()[0].nextAt,'2026-10-17T20:00:00.000Z');await first.tick();assert.equal(calls.length,0); + now=Date.parse('2026-10-17T20:00:00Z');await Promise.all([first.tick(),first.tick()]);assert.deepEqual(calls,['N0TEST-VHF']); + second=new ForwardingScheduler(config,dir,client,{clock:()=>now});await second.init;await second.tick();assert.equal(calls.length,1); + blocked=true;now+=3600000;await second.tick();assert.equal(calls.length,2);assert.equal(second.snapshot()[0].error,'Radio occupata');await second.tick();assert.equal(calls.length,2); + assert.equal(second.snapshot()[0].nextAt,new Date(now+3600000).toISOString()); + }finally{if(first)clearInterval(first.timer);if(second)clearInterval(second.timer);await rm(dir,{recursive:true,force:true});} +}); +test('Rome operating hours skip midnight and follow summer/winter UTC offsets',async()=>{ + const dir=await mkdtemp(path.join(os.tmpdir(),'fwd-hours-'));const config={forwardingSchedules:[{route:'N0TEST-VHF',intervalSeconds:3600,enabled:true,hours:{timeZone:'Europe/Rome',start:7,end:24}}]};const scheduler=new ForwardingScheduler(config,dir,{routes:[{id:'N0TEST-VHF'}]}); + try{await scheduler.init;const s=scheduler.schedules[0];assert.equal(new Date(scheduler.boundary(s,Date.parse('2026-10-17T21:00:00Z'))).toISOString(),'2026-10-18T05:00:00.000Z');assert.equal(new Date(scheduler.boundary(s,Date.parse('2026-11-17T22:00:00Z'))).toISOString(),'2026-11-18T06:00:00.000Z');assert.equal(scheduler.allowed(s,Date.parse('2026-10-17T22:00:00Z')),false);assert.equal(scheduler.allowed(s,Date.parse('2026-10-18T05:00:00Z')),true); + }finally{clearInterval(scheduler.timer);await rm(dir,{recursive:true,force:true});} +}); diff --git a/message-read-state.mjs b/message-read-state.mjs new file mode 100644 index 0000000..af27e21 --- /dev/null +++ b/message-read-state.mjs @@ -0,0 +1,10 @@ +import {readFile,writeFile,rename} from 'node:fs/promises'; +import {createHash} from 'node:crypto'; + +// Keep reading separate from BPQ delivery/forwarding flags. +export class MessageReadState { + constructor(file){this.file=file;this.entries={};this.chain=Promise.resolve();this.ready=readFile(file,'utf8').then(text=>{this.entries=JSON.parse(text);}).catch(error=>{if(error.code!=='ENOENT')throw error;});} + key(message){return createHash('sha256').update(JSON.stringify([message.id,message.from,message.to,message.subject])).digest('hex');} + decorate(messages){return messages.map(message=>({...message,read:message.status==='Y'||Boolean(this.entries[this.key(message)]),readAt:this.entries[this.key(message)]||null}));} + mark(message){const run=this.chain.then(async()=>{await this.ready;const key=this.key(message),at=this.entries[key]||new Date().toISOString();const entries={...this.entries,[key]:at};await writeFile(this.file+'.tmp',JSON.stringify(entries),'utf8');await rename(this.file+'.tmp',this.file);this.entries=entries;return {id:message.id,read:true,readAt:at};});this.chain=run.catch(()=>{});return run;} +} diff --git a/message-read-state.test.mjs b/message-read-state.test.mjs new file mode 100644 index 0000000..725d3f8 --- /dev/null +++ b/message-read-state.test.mjs @@ -0,0 +1,23 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {mkdtemp,rm} from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import {MessageReadState} from './message-read-state.mjs'; + +test('reading persists independently of delivery status, including concurrent opens',async()=>{ + const dir=await mkdtemp(path.join(os.tmpdir(),'bpq-read-')); + try{ + const file=path.join(dir,'read.json'),store=new MessageReadState(file);await store.ready; + const first={id:1,from:'N0ABC',to:'N0TEST',subject:'Hello',status:'N'}; + const queued={...first,id:2}; + assert.equal(store.decorate([first])[0].read,false); + await Promise.all([store.mark(first),store.mark(queued)]); + const reloaded=new MessageReadState(file);await reloaded.ready; + const results=reloaded.decorate([first,{...queued,status:'F'}]); + assert.deepEqual(results.map(m=>[m.read,m.status]),[[true,'N'],[true,'F']]); + assert.equal(first.read,undefined); + assert.equal(reloaded.decorate([{...first,subject:'Different message'}])[0].read,false); + assert.equal(reloaded.decorate([{...first,id:3,status:'Y'}])[0].read,true); + }finally{await rm(dir,{recursive:true,force:true});} +}); diff --git a/public/app.js b/public/app.js index 78182e1..1fb5604 100644 --- a/public/app.js +++ b/public/app.js @@ -3,7 +3,7 @@ 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 r=await fetch('/api'+url,{...options,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;} +async function api(url,options={}){const finish=window.BPQBusy?.start()||(()=>{});try{const r=await fetch('/api'+url,{...options,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'));} @@ -21,9 +21,9 @@ async function loadMessages(){if(!station.features.bbs)return;try{allMessages=(a 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 '+esc(stamp('sent'))+'':'',stamp('received')?'Ricevuto '+esc(stamp('received'))+'':'','Timezone: '+esc(zone)].filter(Boolean).map(x=>''+x+'').join('');} -function mailRow(m,selection,attribute,options={}){const unread=m.status==='N',current=selection===m.id;return ``;} -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'?'Nuovo':m.status==='Y'?'Letto':m.status==='H'?'Trattenuto':m.status})).join('')||'

Nessun messaggio corrisponde ai filtri.

';$$('#message-list [data-id]').forEach(b=>b.onclick=()=>readMessage(Number(b.dataset.id)));} -async function readMessage(id){const generation=++loadGeneration;selected=id;renderMessages();$('#reader').innerHTML='

Caricamento messaggio…

';try{const m=await api('/messages/'+id);if(generation!==loadGeneration)return;$('#reader').innerHTML=`
${m.type==='B'?'BOLLETTINO':'MESSAGGIO PERSONALE'} · #${id}

${esc(m.subject)}

Da ${esc(m.from)}A ${esc(m.to)}${mailTimeMeta(m)}
${readableBody(m.text)}
BID ${esc(m.bid||'—')}
`;$('#reply').onclick=()=>openCompose({to:m.from,subject:(/^Re:/i.test(m.subject)?m.subject:'Re: '+m.subject).slice(0,80),text:'\n\n--- '+m.from+' ---\n'+m.text.split('\n').map(l=>'> '+l).join('\n')});}catch(err){$('#reader').innerHTML=`

Messaggio non disponibile

${esc(err.message)}

`}} +function mailRow(m,selection,attribute,options={}){const unread=!m.read&&m.status==='N',current=selection===m.id;return ``;} +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('')||'

Nessun messaggio corrisponde ai filtri.

';$$('#message-list [data-id]').forEach(b=>b.onclick=()=>readMessage(Number(b.dataset.id)));} +async function readMessage(id){const generation=++loadGeneration;selected=id;renderMessages();$('#reader').innerHTML='

Caricamento messaggio…

';try{const m=await api('/messages/'+id);if(generation!==loadGeneration)return;$('#reader').innerHTML=`
${m.type==='B'?'BOLLETTINO':'MESSAGGIO PERSONALE'} · #${id}

${esc(m.subject)}

Da ${esc(m.from)}A ${esc(m.to)}${mailTimeMeta(m)}
${readableBody(m.text)}
BID ${esc(m.bid||'—')}
`;markMessageRead(id).catch(error=>toast(error.message));$('#reply').onclick=()=>openCompose({to:m.from,subject:(/^Re:/i.test(m.subject)?m.subject:'Re: '+m.subject).slice(0,80),text:'\n\n--- '+m.from+' ---\n'+m.text.split('\n').map(l=>'> '+l).join('\n')});}catch(err){$('#reader').innerHTML=`

Messaggio non disponibile

${esc(err.message)}

`}} $$('[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()}); @@ -62,3 +62,5 @@ function applyStation(user){ } document.addEventListener('bpq-languagechange',()=>{if(csrf){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();} diff --git a/public/busy.css b/public/busy.css new file mode 100644 index 0000000..1ad52ab --- /dev/null +++ b/public/busy.css @@ -0,0 +1,10 @@ +.bpq-busy{position:fixed;left:254px;bottom:24px;z-index:900;display:flex;align-items:center;gap:12px;padding:13px 18px;border:1px solid #91bce537;border-radius:16px;background:linear-gradient(135deg,#1a2838ed,#101923f5);box-shadow:0 12px 38px #0005,0 0 24px #8bb8e00a;backdrop-filter:blur(18px);color:#d8e7f6;font-size:12px;font-weight:500;letter-spacing:.025em;pointer-events:none;animation:busy-enter .2s ease-out} +.bpq-busy[hidden]{display:none} +.busy-orbit{display:inline-block;flex:none;width:20px;height:20px;border:2px solid #93bce32b;border-top-color:#b2d8ff;border-right-color:#7ea8cf;border-radius:50%;animation:busy-spin .95s linear infinite} +.busy-dots{display:flex;gap:4px;margin-left:4px}.busy-dots i{width:3px;height:3px;border-radius:50%;background:#9ebfdf;animation:busy-dot 1.4s ease-in-out infinite}.busy-dots i:nth-child(2){animation-delay:.18s}.busy-dots i:nth-child(3){animation-delay:.36s} +.bpq-working:before{content:'';position:fixed;top:0;left:0;width:35%;height:2px;z-index:2000;background:linear-gradient(90deg,transparent,#b4d8fb,transparent);animation:busy-track 1.8s ease-in-out infinite;pointer-events:none} +.forward-loading{padding:24px;border:1px solid #8baac41c;border-radius:14px;background:#121c27;overflow:hidden}.forward-loading-head{display:flex;align-items:center;gap:12px;margin-bottom:24px;color:#a9bfd3;font-size:12px}.forward-skeleton{display:grid;grid-template-columns:1.2fr 1fr .5fr 1.3fr .6fr 1fr;gap:24px;padding:21px 0;border-top:1px solid #91a8be13}.forward-skeleton span{height:10px;border-radius:6px;background:linear-gradient(100deg,#233140 25%,#354b60 45%,#233140 65%);background-size:260% 100%;animation:busy-shimmer 2s ease-in-out infinite}.forward-skeleton span:nth-child(2n){width:70%} +#forwarding[aria-busy=true] #forward-refresh{opacity:.65}#forwarding[aria-busy=true] #forward-refresh:before{content:'';display:inline-block;width:11px;height:11px;border:1.5px solid #9ebfdf40;border-top-color:#c3e0fb;border-radius:50%;margin-right:8px;animation:busy-spin .95s linear infinite} +@keyframes busy-spin{to{transform:rotate(360deg)}}@keyframes busy-dot{0%,80%,100%{opacity:.25}40%{opacity:1}}@keyframes busy-track{from{transform:translateX(-110%)}to{transform:translateX(390%)}}@keyframes busy-shimmer{to{background-position:-160% 0}}@keyframes busy-enter{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:translateY(0)}} +@media(prefers-reduced-motion:reduce){.bpq-busy,.busy-orbit,.busy-dots i,.bpq-working:before,.forward-skeleton span,#forwarding[aria-busy=true] #forward-refresh:before{animation:none}} +@media(max-width:650px){.bpq-busy{left:16px;bottom:16px}.forward-skeleton{gap:12px;grid-template-columns:1fr 1fr 1fr}.forward-skeleton span:nth-child(n+4){display:none}} diff --git a/public/busy.js b/public/busy.js new file mode 100644 index 0000000..9dc4aee --- /dev/null +++ b/public/busy.js @@ -0,0 +1,23 @@ +(() => { + let pending=0,showTimer,hideTimer,shownAt=0,indicator; + function mount(){ + if(indicator)return; + indicator=document.createElement('div');indicator.className='bpq-busy';indicator.hidden=true; + indicator.setAttribute('role','status');indicator.setAttribute('aria-live','polite'); + indicator.innerHTML='Elaborazione BPQ'; + document.body.append(indicator); + } + window.BPQBusy={ + start(){ + pending++;clearTimeout(hideTimer); + if(pending===1){showTimer=setTimeout(()=>{if(!pending)return;mount();shownAt=Date.now();indicator.hidden=false;document.documentElement.classList.add('bpq-working');},300);} + let finished=false; + return ()=>{ + if(finished)return;finished=true;pending=Math.max(0,pending-1); + if(pending)return; + clearTimeout(showTimer); + hideTimer=setTimeout(()=>{if(pending)return;if(indicator)indicator.hidden=true;document.documentElement.classList.remove('bpq-working');},Math.max(0,650-(Date.now()-shownAt))); + }; + } + }; +})(); diff --git a/public/forwarding.js b/public/forwarding.js index 69d00bc..8439063 100644 --- a/public/forwarding.js +++ b/public/forwarding.js @@ -1,25 +1,25 @@ (() => { let data=null,loading=false,pending=new Map(),expanded=null; const nav=document.createElement('button');nav.dataset.page='forwarding';nav.innerHTML='⇄ Forwarding';nav.onclick=()=>navigate('forwarding');$('nav [data-page="network"]').before(nav); -const panel=document.createElement('section');panel.id='forwarding';panel.className='page';panel.hidden=true;panel.innerHTML='

Forwarding

Partner e scambi della BBS

Caricamento profili BPQ…

Le fasce mostrano il fuso configurato in BPQ. Il prossimo tentativo è una stima: timer, disponibilità del modem e condizioni di connessione sono gestiti da BPQ. Le regole si modificano nella configurazione BPQ.

';$('main').append(panel); +const panel=document.createElement('section');panel.id='forwarding';panel.className='page';panel.hidden=true;panel.innerHTML='

Forwarding

Partner e scambi della BBS

Connessione a BPQ

Le fasce mostrano il fuso configurato in BPQ. Il prossimo tentativo è una stima: timer, disponibilità del modem e condizioni di connessione sono gestiti da BPQ. Le regole si modificano nella configurazione BPQ.

';$('main').append(panel); const prevNavigate=navigate;navigate=function(next){prevNavigate(next);if(next==='forwarding'){$('#breadcrumb').textContent='Stazione / Forwarding';load();}}; const time=t=>t?new Date(t).toLocaleString(BPQI18n.locale(),{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit',second:'2-digit'}):'Non rilevato'; const interval=n=>!n?'Non impostato':n%3600===0?n/3600+' h':n%60===0?n/60+' min':n+' s'; const state=s=>({complete:'Completato',calling:'Chiamata in corso',connected:'Collegato',failed:'Non riuscito',incomplete:'Sessione interrotta',unknown:'Esito non registrato'}[s]||'In attesa'); const rules=(values,kind)=>!values.length?'Nessuna regola esplicita':values.includes('WW')?(kind==='bulletins'?'Tutte le aree geografiche':'Destinazioni geografiche tramite questo partner'):values.join(', '); const bands=p=>p.times.length?p.times.map(t=>t.replace(/^(\d{2})(\d{2})-(\d{2})(\d{2})$/,'$1:$2–$3:$4')).join(' · '):'00:00–23:59'; -function render(){if(!data)return;$('#forward-restore').hidden=!(data.manualSession?.restoring&&data.manualSession?.error);const focused=document.activeElement,focusPeer=focused.closest?.('[data-forward-row]')?.dataset.forwardRow,focusKind=focused.matches?.('[data-forward-start]')?'[data-forward-start]':focused.matches?.('.forward-toggle')?'.forward-toggle':null;const profiles=[...data.profiles].sort((a,b)=>Number(b.enabled&&b.configured)-Number(a.enabled&&a.configured)||Number(b.transport==='Radio')-Number(a.transport==='Radio')||a.call.localeCompare(b.call)),total=profiles.reduce((a,p)=>a+(p.manualOnly?0:p.queued||0),0);$('#forward-summary').innerHTML=[['Percorsi',profiles.length],['Automatici',profiles.filter(p=>p.enabled&&p.configured).length],['Messaggi in coda',total+(profiles.some(p=>p.queued===null)?' + ?':'')],['Sessioni attive',profiles.filter(p=>p.active).length]].map(([label,n])=>'
'+label+''+n+'
').join('');const errors=[...data.errors,...(data.manualSession?.error?[data.manualSession.error]:[])];$('#forward-error').hidden=!errors.length;$('#forward-error').textContent=errors.join(' · ');$('#forward-updated').textContent='Aggiornato '+time(data.updatedAt)+' · '+mailTimezone(); +function render(){if(!data)return;$('#forward-restore').hidden=!(data.manualSession?.restoring&&data.manualSession?.error);const focused=document.activeElement,focusPeer=focused.closest?.('[data-forward-row]')?.dataset.forwardRow,focusKind=focused.matches?.('[data-forward-start]')?'[data-forward-start]':focused.matches?.('.forward-toggle')?'.forward-toggle':null;const profiles=[...data.profiles].sort((a,b)=>Number(b.enabled&&b.configured)-Number(a.enabled&&a.configured)||Number(b.transport==='Radio')-Number(a.transport==='Radio')||a.call.localeCompare(b.call)),total=profiles.reduce((a,p)=>a+((p.manualOnly||p.scheduled)?0:p.queued||0),0);$('#forward-summary').innerHTML=[['Percorsi',profiles.length],['Automatici',profiles.filter(p=>p.enabled&&p.configured).length],['Messaggi in coda',total+(profiles.some(p=>p.queued===null)?' + ?':'')],['Sessioni attive',profiles.filter(p=>p.active).length]].map(([label,n])=>'
'+label+''+n+'
').join('');const errors=[...data.errors,...(data.manualSession?.error?[data.manualSession.error]:[])];$('#forward-error').hidden=!errors.length;$('#forward-error').textContent=errors.join(' · ');$('#forward-updated').textContent='Aggiornato '+time(data.updatedAt)+' · '+mailTimezone(); $('#forward-partners').innerHTML='
'+profiles.map(p=>{ const requested=pending.get(p.call),requestWaiting=requested&&Date.now()-requested<30000,radioReason=p.transport!=='Radio'?'':(data.radio?.txSuspended||data.radio?.portsPaused?.[p.port]||!p.independentRadio&&data.radio?.portSuspended)?'Trasmissioni sospese':!p.independentRadio&&(data.radio?.active||data.radio?.connecting)?'Modem impegnato':'',blocked=p.reservedBy||p.active||requestWaiting||radioReason,last=p.last; - const status=p.reservedBy?'Riservato al percorso VHF':p.active?(p.preparing?'Preparazione radio':state(last?.status)):requestWaiting?'Richiesta inviata':!p.configured?'Non configurato':p.manualOnly?'Solo manuale':p.enabled?'Automatico':'Disattivato'; - const next=p.reservedBy?'Attende fine percorso VHF':p.active?'Sessione in corso':p.manualOnly?'Solo su richiesta':!p.enabled?'Automatico disattivo':!p.configured?'Script assente':p.nextEstimated?time(p.nextEstimated):!p.reverse&&p.queued===0?'In attesa di messaggi':'Timer non disponibile'; + const status=p.reservedBy?'Riservato al percorso VHF':p.active?(p.preparing?'Preparazione radio':state(last?.status)):requestWaiting?'Richiesta inviata':!p.configured?'Non configurato':p.scheduled?'Automatico':p.manualOnly?'Solo manuale':p.enabled?'Automatico':'Disattivato'; + const next=p.reservedBy?'Attende fine percorso VHF':p.active?'Sessione in corso':p.scheduled?time(p.nextEstimated):p.manualOnly?'Solo su richiesta':!p.enabled?'Automatico disattivo':!p.configured?'Script assente':p.nextEstimated?time(p.nextEstimated):!p.reverse&&p.queued===0?'In attesa di messaggi':'Timer non disponibile'; const isOpen=expanded===p.call; - return ``; + return ``; }).join('')+'
Partner / percorsoStatoCodaUltimo scambioTX / RXProgrammazioneProssimo · stimaAzioni
${esc(status)}${p.queued??'—'}${esc(time(last?.startedAt).replace(/:\d{2}$/,''))}${esc(last?state(last.status):'Nessuna sessione recente')}${last?last.sent+' / '+last.received:'—'}${p.manualOnly?'Solo manuale':esc(interval(p.interval))}${p.manualOnly?esc(p.frequency.join(' MHz ')):esc(bands(p))+' · '+(p.timesLocal?'locale BPQ':'UTC')}${esc(next)}${p.nextEstimated?esc(mailTimezone()):''}${radioReason&&!p.active?''+esc(radioReason)+'':''}
${isOpen?details(p):''}
${esc(status)}${p.queued??'—'}${esc(time(last?.startedAt).replace(/:\d{2}$/,''))}${esc(last?state(last.status):'Nessuna sessione recente')}${last?last.sent+' / '+last.received:'—'}${p.manualOnly&&!p.scheduled?'Solo manuale':esc(interval(p.interval))}${(p.manualOnly||p.scheduled)?esc(p.frequency.join(' MHz ')):esc(bands(p))+' · '+(p.timesLocal?'locale BPQ':'UTC')}${esc(next)}${p.nextEstimated?esc(mailTimezone()):''}${radioReason&&!p.active?''+esc(radioReason)+'':''}
${isOpen?details(p):''}
'+(!profiles.length?'

Nessun partner di forwarding configurato in BPQ.

':'')+'
'; if(focusPeer){const row=$$('#forward-partners [data-forward-row]').find(r=>r.dataset.forwardRow===focusPeer);(focusKind?row?.querySelector(focusKind):row)?.focus({preventScroll:true});} } -function details(p){return `

Regole di inoltro

Bollettini
${p.personalOnly?'Esclusi: solo posta personale':esc(rules(p.bulletins,'bulletins'))} ${esc(p.bulletins.join(', '))}
Posta personale e bollettini diretti
${esc(rules(p.personal,'personal'))} ${esc(p.personal.join(', '))}
Destinatari espliciti · TO
${esc(p.to.join(', ')||'Nessuno')}
Distribuzioni esplicite · AT
${esc(p.at.join(', ')||'Nessuna')}
Richiesta messaggi al partner
${p.reverse?'Attiva · intervallo '+esc(interval(p.reverseInterval)):'Disattiva'}
Invio immediato nuovi messaggi
${p.immediate?'Attivo':'Disattivo'}

${p.manualOnly?'Stessa coda e stesse regole del partner '+esc(p.peer)+'. Nessun timer automatico per questo percorso. ':''}Le regole geografiche dipendono dagli indirizzi gerarchici e dalle altre rotte BPQ. I messaggi locali e quelli già ricevuti dal partner seguono le regole di esclusione di BPQ.

Percorso di connessione${p.port?' · porta '+p.port:''}

${esc(p.script.join('\n')||'Nessuno script configurato')}

Indirizzo gerarchico

${esc(p.ha||'Non impostato')}

${p.frequency?'

Dial: '+esc(p.frequency.join(' MHz '))+'

':''}

Ultimi scambi · ${esc(mailTimezone())}

${p.history.map(s=>'').join('')||''}
Data e oraDirezioneTX / RXEsito
'+esc(time(s.startedAt))+''+(s.direction==='incoming'?'Ingresso':'Uscita')+''+s.sent+' / '+s.received+''+esc(state(s.status))+'
Nessuno scambio nei sette file di log più recenti.
TX / RX: messaggi registrati nei log della sessione, non byte.
`;} -async function load(){if(!csrf||!station.features.bbs||loading)return;loading=true;try{data=await api('/forwarding');render();}catch(e){$('#forward-error').hidden=false;$('#forward-error').textContent=e.message;}finally{loading=false;}} +function details(p){return `

Regole di inoltro

Bollettini
${p.personalOnly?'Esclusi: solo posta personale':esc(rules(p.bulletins,'bulletins'))} ${esc(p.bulletins.join(', '))}
Posta personale e bollettini diretti
${esc(rules(p.personal,'personal'))} ${esc(p.personal.join(', '))}
Destinatari espliciti · TO
${esc(p.to.join(', ')||'Nessuno')}
Distribuzioni esplicite · AT
${esc(p.at.join(', ')||'Nessuna')}
Richiesta messaggi al partner
${p.reverse?'Attiva · intervallo '+esc(interval(p.reverseInterval)):'Disattiva'}
Invio immediato nuovi messaggi
${p.immediate?'Attivo':'Disattivo'}

${(p.manualOnly||p.scheduled)?'Stessa coda e stesse regole del partner '+esc(p.peer)+(p.scheduled?'. Sync automatico gestito dalla console. ':'. Nessun timer automatico per questo percorso. '):''}Le regole geografiche dipendono dagli indirizzi gerarchici e dalle altre rotte BPQ. I messaggi locali e quelli già ricevuti dal partner seguono le regole di esclusione di BPQ.

Percorso di connessione${p.port?' · porta '+p.port:''}

${esc(p.script.join('\n')||'Nessuno script configurato')}

Indirizzo gerarchico

${esc(p.ha||'Non impostato')}

${p.frequency?'

Dial: '+esc(p.frequency.join(' MHz '))+'

':''}

Ultimi scambi · ${esc(mailTimezone())}

${p.history.map(s=>'').join('')||''}
Data e oraDirezioneTX / RXEsito
'+esc(time(s.startedAt))+''+(s.direction==='incoming'?'Ingresso':'Uscita')+''+s.sent+' / '+s.received+''+esc(state(s.status))+'
Nessuno scambio nei sette file di log più recenti.
TX / RX: messaggi registrati nei log della sessione, non byte.
`;} +async function load(){if(!csrf||!station.features.bbs||loading)return;loading=true;panel.setAttribute('aria-busy','true');$('#forward-refresh').disabled=true;try{data=await api('/forwarding');render();}catch(e){$('#forward-error').hidden=false;$('#forward-error').textContent=e.message;if(!data)$('#forward-partners').innerHTML='';}finally{loading=false;panel.setAttribute('aria-busy','false');$('#forward-refresh').disabled=false;}} $('#forward-refresh').onclick=load; $('#forward-restore').onclick=async()=>{try{await api('/forwarding/manual/restore',{method:'POST',body:'{}'});toast('Percorso originale ripristinato');await load();}catch(e){toast(e.message);}}; panel.addEventListener('keydown',e=>{if(e.target.matches('[data-forward-row]')&&['Enter',' '].includes(e.key)){e.preventDefault();e.target.click();}}); diff --git a/public/i18n.js b/public/i18n.js index 072dd06..721823b 100644 --- a/public/i18n.js +++ b/public/i18n.js @@ -107,6 +107,8 @@ Connessione assente|No connection Inviato|Sent Ricevuto|Received Non letto|Unread +Elaborazione BPQ|BPQ processing +Connessione a BPQ|Connecting to BPQ Letto|Read (Senza oggetto)|(No subject) Inoltrato|Forwarded diff --git a/public/index.html b/public/index.html index f473df2..348ef09 100644 --- a/public/index.html +++ b/public/index.html @@ -1,5 +1,5 @@ -BPQ Console +BPQ Console