import {readFile,writeFile,rename} from 'node:fs/promises'; import path from 'node:path'; import {createHash} from 'node:crypto'; import {locatorPosition} from './journal.mjs'; export const directoryURL='https://cms.winlink.org:444/GatewayChannels.aspx'; const decode=s=>String(s).replace(/"/g,'"').replace(/'/g,"'").replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); const attr=(s,n)=>decode(s.match(new RegExp('\\b'+n+'="([^"]*)"','i'))?.[1]||''); export function csvRows(text){const rows=[];let row=[],cell='',quoted=false;for(let i=0;is.trim().match(/^(\d{2})-(\d{2})$/)).filter(Boolean);if(!ranges.length)return null;const h=now.getUTCHours();return ranges.some(m=>+m[1]<=23&&+m[2]<=23&&(+m[1]<=+m[2]?h>=+m[1]&&h<=+m[2]:h>=+m[1]||h<=+m[2])); } export function distanceKm(a,b){const rad=x=>x*Math.PI/180,lat=rad(b.lat-a.lat),lon=rad(b.lon-a.lon);return Math.round(6371*2*Math.asin(Math.min(1,Math.sqrt(Math.sin(lat/2)**2+Math.cos(rad(a.lat))*Math.cos(rad(b.lat))*Math.sin(lon/2)**2))));} export function parseChannels(csv,mode){ const rows=csvRows(csv.replace(/^\uFEFF/,'')),head=rows.shift();if(!['Timestamp','Callsign','GridSquare','Frequency','Mode','Hours'].every(k=>head?.includes(k)))throw new Error('Formato elenco Winlink non riconosciuto'); const out=new Map();for(const row of rows){const o=Object.fromEntries(head.map((k,i)=>[k,row[i]||''])),match=o.Frequency.match(/^([\d,.]+)\s*(KHz|MHz)$/i),call=o.Callsign.trim().toUpperCase(),position=locatorPosition(o.GridSquare.trim());if(!match||!position||! /^(?=.*\d)[A-Z0-9]{3,7}(?:-\d{1,2})?$/.test(call))continue;const centerHz=Math.round(Number(match[1].replaceAll(',',''))*(match[2].toUpperCase()==='MHZ'?1e6:1e3));if(!Number.isFinite(centerHz)||centerHz<1e6||centerHz>30e6)continue;const id=createHash('sha256').update([call,centerHz,o.Mode,o.GridSquare].join('|')).digest('hex').slice(0,24);out.set(id,{id,call,grid:o.GridSquare.trim().toUpperCase(),centerHz,dialHz:centerHz-1500,mode:o.Mode.trim(),family:mode,hours:o.Hours.trim(),postedAt:parsePosted(o.Timestamp),qth:o.QTH.trim().slice(0,160),position:{lat:position.lat,lon:position.lon}});} return [...out.values()]; } export function modemFamily(driver){return /VARA/i.test(driver)?'VARA':/PACTOR|SCS/i.test(driver)?'Pactor':/ARDOP/i.test(driver)?'ARDOP':null;} export class GatewayDirectory{ constructor(config,dir,fetcher=fetch){this.config=config;this.file=path.join(dir,'winlink-gateways.cache.json');this.fetcher=fetcher;this.cache=null;this.pending=null;this.lastAttempt=0;this.error=null;} async refresh(){if(this.pending)return this.pending;this.pending=(async()=>{ const mode=modemFamily(this.config.radio?.driver);if(!mode)throw new Error('Nessun modem HF compatibile con la directory Winlink'); this.lastAttempt=Date.now();const page=await this.fetcher(directoryURL,{signal:AbortSignal.timeout(15000)});if(!page.ok)throw new Error('Directory pubblica Winlink non disponibile');const html=await page.text();if(html.length>4e6)throw new Error('Pagina Winlink troppo grande');const form=new URLSearchParams();for(const m of html.matchAll(/]*>/gi))if(/type="hidden"/i.test(m[0]))form.set(attr(m[0],'name'),attr(m[0],'value'));if(!form.has('__VIEWSTATE'))throw new Error('Modulo pubblico Winlink non riconosciuto');form.set('rblModes',mode);form.set('txtServiceCodes','PUBLIC');form.set('btnCsvFile','CSV File'); const response=await this.fetcher(directoryURL,{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:form,signal:AbortSignal.timeout(20000)});if(!response.ok)throw new Error('Download canali Winlink non disponibile');const csv=await response.text();if(csv.length>8e6)throw new Error('Elenco canali troppo grande');const channels=parseChannels(csv,mode);if(!channels.length)throw new Error('Nessun canale HF valido nel download Winlink');this.cache={fetchedAt:new Date().toISOString(),mode,channels};this.error=null;await writeFile(this.file+'.tmp',JSON.stringify(this.cache));await rename(this.file+'.tmp',this.file);return this.cache; })().catch(e=>{this.error=e.message;throw e}).finally(()=>this.pending=null);return this.pending;} async load(force=false){if(!this.cache)try{const c=JSON.parse(await readFile(this.file,'utf8'));if(c.mode===modemFamily(this.config.radio?.driver)&&Array.isArray(c.channels))this.cache=c;}catch{}if((force||!this.cache||Date.now()-Date.parse(this.cache.fetchedAt)>15*60000)&&Date.now()-this.lastAttempt>60000)try{await this.refresh();}catch(e){if(!this.cache)throw e;}if(!this.cache)throw new Error(this.error||'Elenco gateway non disponibile');return this.cache;} async snapshot(force=false){const c=await this.load(force),own=String(this.config.sysop.call).replace(/-\d+$/,''),origin=locatorPosition(this.config.locator),now=Date.now();return {source:directoryURL,fetchedAt:c.fetchedAt,mode:c.mode,error:this.error,stale:now-Date.parse(c.fetchedAt)>30*60000,channels:c.channels.filter(ch=>ch.call.replace(/-\d+$/,'')!==own).map(ch=>({...ch,distanceKm:origin?distanceKm(origin,ch.position):null,open:channelOpen(ch.hours),fresh:ch.postedAt&&now-Date.parse(ch.postedAt)<6*3600000&&Date.parse(ch.postedAt)<=now+300000})),station:{grid:this.config.locator,radio:this.config.radio,offsetHz:1500}};} async selected(id){const d=await this.snapshot();const ch=d.channels.find(c=>c.id===id);if(!ch||d.stale||!ch.fresh||ch.open!==true)throw new Error('Canale non disponibile: aggiorna elenco e verifica orari del gateway');return ch;} }