Files
bpq_gui/sync-operations.mjs
T

46 lines
5.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {randomUUID} from 'node:crypto';
import {plain} from './bpq.mjs';
import {forwardingHistory} from './forwarding.mjs';
export function mailStreams(html){if(!/<option\b[^>]*value=["']?\d+/i.test(html))throw Error('Stato sessioni BPQ non verificabile');return [...html.matchAll(/<option\b[^>]*value=["']?(\d+)["']?[^>]*>([\s\S]*?)<\/option>/gi)].map(m=>({id:Number(m[1]),text:plain(m[2])})).filter(s=>s.text&&!/^Idle\b/i.test(s.text));}
export class SyncOperations{
constructor(fwd){this.fwd=fwd;this.jobs=new Map();}
snapshot(j){return {id:j.id,label:j.label,kind:j.kind,peer:j.peer,frequency:j.frequency||null,mode:j.mode||null,state:j.state,detail:j.detail,startedAt:j.startedAt,endedAt:j.endedAt||null,sent:j.sent,received:j.received,events:j.events,active:!j.endedAt};}
state(j,state,detail){j.detail=detail;if(j.state!==state){j.state=state;j.events.push({at:new Date().toISOString(),state,detail});}}
start({peer,label,kind,run,client,frequency,mode}){
if([...this.jobs.values()].some(j=>!j.endedAt))throw Error('Una sincronizzazione è già in corso');
const j={id:randomUUID(),peer,label,kind,client,frequency,mode,controller:new AbortController(),startedAt:new Date().toISOString(),state:null,detail:'',sent:0,received:0,events:[],dispatched:false};
this.jobs.set(j.id,j);this.state(j,'preparing',kind==='winlink-internet'?'Verifica della sessione CMS e della coda':'Verifica radio e preparazione del percorso');
j.task=Promise.resolve().then(()=>run(j.controller.signal)).then(()=>{j.dispatched=true;if(!j.controller.signal.aborted)this.state(j,'calling','Richiesta accettata da BPQ · attendo il collegamento');}).catch(e=>{if(!j.controller.signal.aborted){if(j.client?.job?.restoring&&Date.parse(j.client.job.startedAt)>=Date.parse(j.startedAt)-1500){j.failure=e.message;this.state(j,'restoring','Ripristino del percorso dopo errore: '+e.message);}else{this.state(j,'failed',e.message);j.endedAt=new Date().toISOString();clearInterval(j.timer);}}});
j.timer=setInterval(()=>this.update(j).catch(e=>{j.detail='Aggiornamento BPQ in attesa: '+e.message;}),1500);j.timer.unref();
for(const [id,old]of this.jobs)if(old.endedAt&&Date.now()-Date.parse(old.endedAt)>86400000)this.jobs.delete(id);
return this.snapshot(j);
}
get(id){const j=this.jobs.get(id);if(!j)throw Error('Sincronizzazione non trovata');return this.snapshot(j);}
async update(j){
if(j.updating||j.endedAt||j.controller.signal.aborted)return;j.updating=true;
try{if(j.failure){if(!j.client?.job?.restoring){this.state(j,'failed',j.failure);j.endedAt=new Date().toISOString();clearInterval(j.timer);}return;}const log=await this.fwd.logs();if(j.controller.signal.aborted)return;const h=forwardingHistory(log,j.peer).find(s=>Date.parse(s.startedAt)>=Date.parse(j.startedAt)-1500);
if(h){j.sent=h.sent;j.received=h.received;if(h.endedAt){if(j.client?.job?.restoring){this.state(j,'restoring','Ripristino del percorso e della scansione');return;}this.state(j,h.complete||h.status==='complete'?'complete':'failed',h.complete||h.status==='complete'?'Sincronizzazione completata':h.error||'Collegamento terminato senza completare lo scambio');j.endedAt=h.endedAt;clearInterval(j.timer);}else if(h.connectedAt)this.state(j,'connected','Collegamento stabilito · scambio messaggi');else this.state(j,'calling','Chiamata in corso · attendo la risposta del nodo');}
else if(j.dispatched&&Date.now()-Date.parse(j.startedAt)>90000){this.state(j,'failed','BPQ non ha registrato l’avvio della sessione');j.endedAt=new Date().toISOString();clearInterval(j.timer);}
}finally{j.updating=false;}
}
async abort(id){
const j=this.jobs.get(id);if(!j)throw Error('Sincronizzazione non trovata');if(j.endedAt)return this.snapshot(j);if(j.aborting)return j.aborting;
j.controller.abort();this.state(j,'cancelling','Interruzione richiesta · attendo la conferma di BPQ');
j.aborting=this.cancel(j).finally(()=>{j.aborting=null;});return j.aborting;
}
async cancel(j){
await j.task;
// StartForward can create its stream a few seconds after the HTTP response.
const until=Date.now()+(j.dispatched?12000:2000);let empty=0;
while(Date.now()<until){const html=await this.fwd.bpq('/Mail/Status'),streams=mailStreams(html);const mine=streams.filter(s=>s.text.split(/\s+/).some(token=>token===j.peer));
if(mine.length){const action=html.match(/action=["']?(\/Mail\/DisSession\?[^\s>"']+)/i)?.[1];if(!action)throw Error('Comando di disconnessione BPQ non disponibile');for(const stream of mine)await this.fwd.bpq(action,{method:'POST',body:'call='+stream.id+'&Disconnect=Disconnect'});empty=0;}
else empty++;
if(empty>=2){if(!j.dispatched)break;const ended=forwardingHistory(await this.fwd.logs(),j.peer).some(h=>Date.parse(h.startedAt)>=Date.parse(j.startedAt)-1500&&h.endedAt);if(ended)break;}
await new Promise(r=>setTimeout(r,400));
}
const active=mailStreams(await this.fwd.bpq('/Mail/Status')).some(s=>s.text.split(/\s+/).includes(j.peer));if(active)throw Error('BPQ non ha ancora confermato la disconnessione: riprova');
if(j.client?.job?.restoring&&Date.parse(j.client.job.startedAt)>=Date.parse(j.startedAt)-1500)await j.client.restore();
this.state(j,'cancelled','Sincronizzazione interrotta · percorso ripristinato');j.endedAt=new Date().toISOString();clearInterval(j.timer);return this.snapshot(j);
}
}