diff --git a/.gitignore b/.gitignore index a192659..4adcdfd 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,5 @@ outputs/ work/ .DS_Store Thumbs.db + +console.config.json diff --git a/Enable-LAN.ps1 b/Enable-LAN.ps1 index 27167aa..0246043 100644 --- a/Enable-LAN.ps1 +++ b/Enable-LAN.ps1 @@ -1,6 +1,5 @@ -# Eseguire come amministratore solo se il pannello non si apre da altri PC della LAN. -$ErrorActionPreference = 'Stop' -$nodeExe = 'C:\Users\User1\.cache\codex-runtimes\codex-primary-runtime\dependencies\node\bin\node.exe' -if (!(Get-NetFirewallRule -DisplayName 'ALNODE Web Console LAN' -ErrorAction SilentlyContinue)) { - New-NetFirewallRule -DisplayName 'ALNODE Web Console LAN' -Direction Inbound -Action Allow -Protocol TCP -LocalPort 8090 -RemoteAddress '192.168.1.0/24' -Program $nodeExe -Profile Any -} +$ErrorActionPreference='Stop' +$config=Get-Content -LiteralPath (Join-Path $PSScriptRoot 'console.config.json') -Raw | ConvertFrom-Json +$nodeExe=if($config.nodeExe -and (Test-Path -LiteralPath $config.nodeExe)){$config.nodeExe}else{(Get-Command node.exe -ErrorAction Stop).Source} +Get-NetFirewallRule -DisplayName 'BPQ Web Console LAN' -ErrorAction SilentlyContinue | Remove-NetFirewallRule +New-NetFirewallRule -DisplayName 'BPQ Web Console LAN' -Direction Inbound -Action Allow -Protocol TCP -LocalPort $config.port -RemoteAddress LocalSubnet -Program $nodeExe -Profile Private | Out-Null diff --git a/Install.ps1 b/Install.ps1 new file mode 100644 index 0000000..95f531a --- /dev/null +++ b/Install.ps1 @@ -0,0 +1,26 @@ +param([string]$BpqRoot,[int]$Port=8090,[int]$HttpPort,[int]$RadioPort,[string]$SysopUser,[string]$ForwardPeer,[switch]$CheckOnly,[switch]$AutoStart,[switch]$EnableLAN) +$ErrorActionPreference='Stop' +$nodeExe=(Get-Command node.exe -ErrorAction Stop).Source +$major=[int]((& $nodeExe --version).TrimStart('v').Split('.')[0]) +if($major -lt 20){throw 'Serve Node.js 20 o successivo nel PATH.'} +if(!$BpqRoot){ + $candidates=@((Join-Path $env:APPDATA 'BPQ32')) + $running=Get-CimInstance Win32_Process | Where-Object {$_.Name -match '^(BPQTerminal|BPQMail|BPQChat|bpq32)\.exe$'} + foreach($proc in $running){if($proc.ExecutablePath){$candidates+=Split-Path $proc.ExecutablePath}} + $BpqRoot=$candidates | Where-Object {Test-Path -LiteralPath (Join-Path $_ 'BPQ32.cfg')} | Select-Object -First 1 + if(!$BpqRoot){throw 'BPQ32.cfg non trovato. Usare -BpqRoot con la cartella dati BPQ.'} +} +$arguments=@((Join-Path $PSScriptRoot 'install.mjs'),'--bpq-root',$BpqRoot,'--port',"$Port") +foreach($option in @(@('http-port',$HttpPort),@('radio-port',$RadioPort),@('sysop-user',$SysopUser),@('forward-peer',$ForwardPeer))){if($option[1]){$arguments+=@('--'+$option[0],"$($option[1])")}} +if($CheckOnly){$arguments+='--check-only'} +& $nodeExe @arguments +if($LASTEXITCODE -ne 0){throw 'Installazione interrotta: verifica BPQ fallita.'} +if($CheckOnly){return} +if($AutoStart){ + $action=New-ScheduledTaskAction -Execute 'powershell.exe' -Argument ('-NoProfile -WindowStyle Hidden -File "'+(Join-Path $PSScriptRoot 'Start-Console.ps1')+'"') -WorkingDirectory $PSScriptRoot + $trigger=New-ScheduledTaskTrigger -AtLogOn -User ([Security.Principal.WindowsIdentity]::GetCurrent().Name) + Register-ScheduledTask -TaskName 'BPQ-WebConsole' -Action $action -Trigger $trigger -Description 'BPQ web console locale' -Force | Out-Null +} +if($EnableLAN){& (Join-Path $PSScriptRoot 'Enable-LAN.ps1')} +& (Join-Path $PSScriptRoot 'Start-Console.ps1') +Write-Host "Pannello: http://127.0.0.1:$Port" diff --git a/README.md b/README.md index 20af15b..e445459 100644 --- a/README.md +++ b/README.md @@ -1,60 +1,77 @@ -# ALNODE Console +# BPQ Console -Console web locale per BPQ32, con backend Node.js e interfaccia HTML/CSS/JavaScript. Le pagine BPQ non vengono incorporate nell'interfaccia. +Pannello web per una stazione BPQ32, con dashboard, BBS, Winlink, chat, monitor e telemetria modem. Backend Node.js senza dipendenze esterne; interfaccia HTML/CSS/JavaScript. Il nominativo, gli alias, il locator e le porte sono letti dalla configurazione della stazione. -## Avvio +## Requisiti -Richiede Windows, Node.js 20 o successivo e BPQ32 attivo sullo stesso computer. +- Windows con PowerShell e Node.js 20 o successivo disponibile nel PATH. +- BPQ32 installato e già in esecuzione, con HTTPPORT configurata nel driver Telnet. +- Almeno un USER Telnet con ruolo sysop. Le credenziali rimangono in BPQ32.cfg. +- BPQMail per la BBS e Winlink; BPQChat e TCPPORT per la chat; FBBPORT per il monitor. Questi servizi sono opzionali. + +## Installazione + +Scaricare o clonare il repository, aprire PowerShell nella cartella del progetto e avviare BPQ. Verificare prima il rilevamento senza modificare nulla: ```powershell -node server.mjs +.\Install.ps1 -CheckOnly ``` -Aprire http://127.0.0.1:8090 oppure http://IP-DEL-PC:8090 sulla rete locale. La porta del pannello può essere impostata con la variabile BPQ_CONSOLE_PORT. +L'installer cerca BPQ32.cfg in %APPDATA%\BPQ32 e nelle cartelle dei processi BPQ attivi. Verifica che l'interfaccia HTTP BPQ risponda e mostra porte, applicazioni e profili forwarding rilevati. Se BPQ non risponde, interrompe l'installazione senza creare la configurazione. -Il progetto è configurato per la stazione IU2EUG: legge BPQ32.cfg e i dati BPQ da %APPDATA%/BPQ32. L'accesso usa le credenziali Telnet dell'account sysop IU2EUG, lette sul server. Password e configurazioni della stazione non sono incluse nel repository. +Installazione e avvio del pannello: -Connessioni locali richieste: +```powershell +.\Install.ps1 +``` -| Servizio | Porta | -| --- | --- | -| Interfaccia HTTP BPQ | 8080 | -| Telnet BPQ / chat | 8100 | -| BPQTermTCP / monitor FBB | 8101 | -| Pannello web | 8090 | -| Syslog VARA, UDP loopback | 18514 | +Aprire http://127.0.0.1:8090 e accedere con l'utente Telnet sysop selezionato. Il primo sysop è scelto automaticamente; usare -SysopUser quando ce ne sono diversi. Non servono npm install o una compilazione. -Start-Console.ps1 avvia il pannello in background evitando una seconda istanza sulla porta 8090. Gli script Start-Console.ps1 e Enable-LAN.ps1 contengono il percorso Node di questo PC: adattarlo per altre installazioni. Enable-LAN.ps1 richiede privilegi amministrativi e apre la porta 8090 per la rete 192.168.1.0/24. La task Windows ALNODE-WebConsole presente su questo PC non viene creata automaticamente dal repository. +Per percorsi o porte diversi e per selezionare il modem e il profilo BBS: -## Funzioni +```powershell +.\Install.ps1 -BpqRoot 'D:\BPQ' -Port 8090 -HttpPort 8080 -RadioPort 3 -SysopUser 'sysop' -ForwardPeer 'N1TEST' +``` -- Dashboard scura con stato radio, CAT e VARA, chiamante/chiamato, CPU del PC e di VARA, SNR, grafici e modalità schermo intero. -- BBS e Winlink con elenco sopra e lettura sotto, scorrimento indipendente, ricerca, filtri, composizione, risposta e cancellazione. -- Date e ore convertite nella timezone del browser, indicata come offset UTC. Quando BPQ omette l'anno, viene ricostruito usando i riferimenti temporali del messaggio. -- Aggiornamento manuale Winlink tramite il profilo RMS via Internet e avvio del forwarding configurato verso IW2OHX. -- Chat Telnet nativa con utenti, stanze, collegamenti, messaggi pubblici e privati, scorrimento automatico e indicatore di nuovi messaggi. -- Monitor BPQTermTCP con traffico RX/TX, porte, frame di controllo e NODES, ricerca, pausa e download TXT. -- Notifiche per nuovi bollettini e posta, con suono disattivabile. Operano mentre il pannello è aperto; il suono richiede un gesto nel browser. -- Allegati B2: download e anteprime immagini, PDF tramite PDF.js locale e testo. HTML e SVG sono mostrati come testo. Messaggi 7plus scaricabili, senza ricostruzione automatica delle parti. +-RadioPort seleziona una porta modem rilevata; in assenza dell'opzione viene scelta la prima. -ForwardPeer deve corrispondere a un profilo esistente nella BBS. Senza un profilo selezionato il pulsante di forwarding manuale è disabilitato. L'installer non crea profili radio o modifica la configurazione BPQ. -Il KPI bitrate legge i comandi BITRATE del syslog nativo VARA, con direzione TX/RX, senza una seconda connessione TCP al modem. Configurare VARA con Syslog abilitato, host 127.0.0.1, porta UDP 18514 e CommandsLog attivo. Il ricevitore locale è verificato; il valore BITRATE effettivo deve ancora essere verificato durante una sessione radio. A riposo mostra zero; durante una sessione senza dato mostra velocità non disponibile. SNR viene da BPQ e non è una misura continua. +Opzioni aggiuntive: -## Dati e sicurezza +```powershell +# Avvio automatico al login Windows +.\Install.ps1 -AutoStart -Il pannello è amministrativo e destinato al PC e alla LAN fidata. Non esporre direttamente la porta HTTP su Internet. Include sessioni HttpOnly/SameSite, controlli Origin/CSRF e host limitati a loopback e indirizzi LAN privati. Dopo il riavvio del server occorre accedere di nuovo. +# Accesso dalla sottorete locale, su profilo rete Privato +# Eseguire PowerShell come amministratore per la regola firewall +.\Install.ps1 -EnableLAN +``` -Lettura e scrittura dei messaggi passano dall'interfaccia BPQ. I file .mes vengono letti per gli allegati; DIRMES.SYS e i file dei messaggi non sono modificati direttamente. Elimina marca il messaggio K nella BBS locale: non richiama email già consegnate al CMS. Inviate indica inoltro al CMS, non lettura del destinatario. +-AutoStart registra la task BPQ-WebConsole. -EnableLAN apre soltanto la porta del pannello alla sottorete locale. Per usare entrambe le opzioni: .\Install.ps1 -AutoStart -EnableLAN. Se PowerShell blocca gli script scaricati, sbloccare i file dopo averne verificato il contenuto, secondo le policy del proprio PC. -La chat usa una sessione condivisa IU2EUG; conserva fino a 300 eventi in memoria. Il monitor conserva fino a 1000 frame in memoria e viene avviato dal suo pulsante. Entrambi si disconnettono dopo due minuti senza polling. Telemetria e payload syslog non sono archiviati dal pannello. +La configurazione generata console.config.json contiene percorsi, porte e selezioni, senza password, ed è esclusa da Git. Il percorso Node rilevato viene salvato per l'avvio automatico. È possibile modificare il file e riavviare il solo pannello. BPQ_ROOT e BPQ_CONSOLE_PORT permettono di sovrascrivere cartella dati e porta HTTP del pannello. -I log di runtime, le credenziali, le configurazioni BPQ/VARA e i messaggi della BBS sono esclusi da Git. Il progetto non contiene BPQ32 o VARA e richiede la configurazione della stazione già operativa. +## Modem e servizi opzionali -## Verifica +Il progetto non richiede VARA. Con PACTOR o altri driver BPQ mostra la porta selezionata e i dati disponibili nell'interfaccia BPQ. Le informazioni non esposte dal driver restano non disponibili: non vengono simulate. Non vengono inviati comandi CAT specifici per una radio. + +I grafici bitrate nativo e CPU VARA sono abilitati soltanto quando la porta selezionata usa il driver VARA. Per il bitrate, configurare il syslog VARA verso 127.0.0.1 UDP 18514, con CommandsLog attivo; varaSyslogPort nel file locale permette di cambiarne la porta. Non viene aperta una seconda connessione TCP al modem. Per un VARA remoto la CPU locale non è disponibile. Il bitrate deve essere emesso dalla versione VARA utilizzata. + +BBS, chat, monitor e Winlink vengono abilitati in base alle applicazioni e alle porte BPQ rilevate. Le API dei servizi assenti sono disabilitate. Winlink richiede CMS=1 e una BBS configurata; Aggiorna mail avvia il profilo RMS via Internet. cmsPeer consente di specificare un nome diverso nel file locale. Non viene installato o configurato automaticamente un gateway Winlink. + +## Funzioni e dati + +Dashboard scura, schermo intero, stato modem, chiamante/chiamato quando esposti, CPU di sistema, rotte NET/ROM e attività forwarding. BBS e Winlink hanno elenco sopra e lettura sotto, ricerca, composizione, risposta, cancellazione e allegati B2. Anteprime immagini, PDF e testo; HTML/SVG mostrati come testo. Messaggi 7plus scaricabili senza ricostruzione automatica. + +Chat nativa con sessione condivisa dell'account sysop selezionato, utenti, stanze, collegamenti e messaggi privati; fino a 300 eventi in memoria. Monitor BPQTermTCP con filtri e download TXT; fino a 1000 frame in memoria. Disconnessione dopo due minuti senza polling. + +Date e ore nella timezone del browser. Notifiche per nuovi bollettini e posta mentre il sito è aperto; il suono richiede un gesto nel browser. Lettura e scrittura tramite BPQ, senza modifiche dirette a DIRMES.SYS o ai file .mes. Elimina marca il messaggio K localmente e non richiama email già consegnate al CMS. + +## Sicurezza e verifica + +Pannello amministrativo per PC e LAN fidata, in HTTP. Non esporre direttamente su Internet. Sessioni HttpOnly/SameSite, controlli Origin/CSRF e host limitati a loopback e indirizzi LAN privati. I log, la configurazione locale e i dati BBS sono esclusi dal repository. PDF.js e font/CMap mantengono le licenze in public/vendor/pdfjs. ```powershell node --test test.mjs ``` -I test coprono parsing BPQ, allegati binari, classificazione della posta Winlink, stato CMS, notifiche, chat, monitor, bitrate VARA e timestamp. - -PDF.js e le risorse font/CMap incluse mantengono le proprie licenze in public/vendor/pdfjs. +Per riavviare, arrestare soltanto il processo Node di questo pannello ed eseguire Start-Console.ps1. Per rimuovere l'avvio automatico, eliminare la task BPQ-WebConsole. BPQ e il modem continuano a funzionare indipendentemente dal pannello. diff --git a/Start-Console.ps1 b/Start-Console.ps1 index 2db7983..025d8fd 100644 --- a/Start-Console.ps1 +++ b/Start-Console.ps1 @@ -1,5 +1,9 @@ -$ErrorActionPreference = 'Stop' -$listener = Get-NetTCPConnection -LocalPort 8090 -State Listen -ErrorAction SilentlyContinue -if ($listener) { exit 0 } -$nodeExe = 'C:\Users\User1\.cache\codex-runtimes\codex-primary-runtime\dependencies\node\bin\node.exe' -Start-Process -FilePath $nodeExe -ArgumentList 'server.mjs' -WorkingDirectory $PSScriptRoot -WindowStyle Hidden -RedirectStandardOutput (Join-Path $PSScriptRoot 'server.log') -RedirectStandardError (Join-Path $PSScriptRoot 'server-error.log') +$ErrorActionPreference='Stop' +$configPath=Join-Path $PSScriptRoot 'console.config.json' +$port=8090 +if(Test-Path -LiteralPath $configPath){$settings=Get-Content -LiteralPath $configPath -Raw | ConvertFrom-Json;if($settings.port){$port=$settings.port}} +if($env:BPQ_CONSOLE_PORT){$port=[int]$env:BPQ_CONSOLE_PORT} +$listener=Get-NetTCPConnection -LocalPort $port -State Listen -ErrorAction SilentlyContinue +if($listener){$proc=Get-CimInstance Win32_Process -Filter "ProcessId=$($listener[0].OwningProcess)";if($proc.Name -eq 'node.exe' -and $proc.CommandLine.Contains((Join-Path $PSScriptRoot 'server.mjs'))){exit 0};throw "Porta $port occupata da un altro processo"} +$nodeExe=if($settings.nodeExe -and (Test-Path -LiteralPath $settings.nodeExe)){$settings.nodeExe}else{(Get-Command node.exe -ErrorAction Stop).Source} +Start-Process -FilePath $nodeExe -ArgumentList ('"'+(Join-Path $PSScriptRoot 'server.mjs')+'"') -WorkingDirectory $PSScriptRoot -WindowStyle Hidden -RedirectStandardOutput (Join-Path $PSScriptRoot 'server.log') -RedirectStandardError (Join-Path $PSScriptRoot 'server-error.log') diff --git a/bpq.mjs b/bpq.mjs index e5e58ac..005c7d8 100644 --- a/bpq.mjs +++ b/bpq.mjs @@ -4,4 +4,4 @@ export function parseMessages(html){const result=[];const regex=/([\s\S]*?)<\/tr>/gi)].flatMap(m=>{const cells=[...m[1].matchAll(/]*>([\s\S]*?)<\/td>/gi)].map(c=>plain(c[1]));if(cells.length<12)return [];return [{port:cells[0].replace('>',''),active:cells[0].startsWith('>'),call:cells[1],quality:Number(cells[2]),nodes:Number(cells[3]),frames:Number(cells[4]),retries:Number(cells[5]),heard:cells[9],queued:Number(cells[10])}];});} export function parseMessage(html){const m=html.match(/]*>([\s\S]*?)<\/textarea>/i);if(!m)return null;const text=decode(m[1]).replace(/\r\n|\r/g,'\n');const header={},first=text.indexOf('\n\n');for(const l of text.slice(0,first).split('\n')){const sep=l.indexOf(':');if(sep>0)header[l.slice(0,sep)]=l.slice(sep+1).trim();}return {from:header.From||'',to:header.To||'',subject:header.Title||'',date:header['Date/Time']||'',bid:header.Bid||'',type:header['Type/Status']?.[0]||'',text:first>=0?text.slice(first+2):text};} export function bpqTimestamp(value,reference=new Date()) {const m=String(value||'').match(/^(\d{1,2})-([A-Za-z]{3})\s+(\d{2}):(\d{2})Z$/);if(!m)return null;const month=['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'].indexOf(m[2].toLowerCase());if(month<0||Number(m[1])>31||Number(m[3])>23||Number(m[4])>59)return null;let year=reference.getUTCFullYear();let date=new Date(Date.UTC(year,month,Number(m[1]),Number(m[3]),Number(m[4])));if(date.getTime()>reference.getTime()+86400000)date=new Date(Date.UTC(--year,month,Number(m[1]),Number(m[3]),Number(m[4])));if(date.getUTCMonth()!==month||date.getUTCDate()!==Number(m[1]))return null;return date.toISOString();} -export function parseRadio(html){const t=plain(html);return {connected:t.includes('Connected to VARA TNC'),state:t.match(/TNC State (.*?) Mode/)?.[1]||'Free',busy:t.includes('Channel State Busy'),mode:t.match(/Mode (\d+)/)?.[1]||'2300',snr:t.match(/S\/N ([\d,.-]+)/)?.[1]||'—',sent:Number(t.match(/Traffic Sent (\d+)/)?.[1]||0),received:Number(t.match(/RXed (\d+)/)?.[1]||0),frequency:t.match(/FT991A ([\d.]+) USB/)?.[1]||'—',scanning:/FT991A [\d.]+ USB S/.test(t)};} +export function parseRadio(html){const t=plain(html);return {connected:/Connected to .*?(?:TNC|Modem)|Comms State Connected/i.test(t),state:t.match(/TNC State (.*?)(?: Mode| Channel| Traffic|$)/)?.[1]||'Free',busy:t.includes('Channel State Busy'),mode:t.match(/Mode (\S+)/)?.[1]||'',snr:t.match(/S\/N ([\d,.-]+)/)?.[1]||'—',sent:Number(t.match(/Traffic Sent (\d+)/)?.[1]||0),received:Number(t.match(/RXed (\d+)/)?.[1]||0),frequency:t.match(/\b(\d+\.\d+)\s+(?:USB|LSB|FM|DIG|DATA)\b/)?.[1]||'—',scanning:/\b\d+\.\d+\s+(?:USB|LSB|FM|DIG|DATA)\s+S\b/.test(t)};} diff --git a/chat.mjs b/chat.mjs index 6606cc9..8904c1b 100644 --- a/chat.mjs +++ b/chat.mjs @@ -3,32 +3,32 @@ import {StringDecoder} from 'node:string_decoder'; export function parseUser(line){const m=line.match(/^([A-Z0-9]+(?:-\d+)?)\s+at\s+(\S+)\s+(.+?),\s*(.*?)\s+\[([^\]]+)\] Idle for (\d+) seconds/i);return m?{call:m[1],node:m[2],name:m[3],qth:m[4],topic:m[5],idle:Number(m[6])}:null;} export class Chat { - constructor(credentials){this.credentials=credentials;this.state='offline';this.events=[];this.seq=0;this.users=[];this.topics=['General'];this.links=[];this.topic='General';this.lastAccess=Date.now();this.timer=setInterval(()=>{if(this.state==='online'&&Date.now()-this.lastAccess>120000)this.disconnect();else if(this.state==='online'&&Date.now()-this.lastRoster>30000)this.roster()},10000);this.timer.unref();} + constructor(credentials,options={}){this.options=options;this.call=options.call||'';this.credentials=credentials;this.state='offline';this.events=[];this.seq=0;this.users=[];this.topics=['General'];this.links=[];this.topic='General';this.lastAccess=Date.now();this.timer=setInterval(()=>{if(this.state==='online'&&Date.now()-this.lastAccess>120000)this.disconnect();else if(this.state==='online'&&Date.now()-this.lastRoster>30000)this.roster()},10000);this.timer.unref();} event(type,text,sender=null,to=null){this.events.push({id:++this.seq,type,text,sender,to,at:new Date().toISOString()});if(this.events.length>300)this.events.shift();} - snapshot(){this.lastAccess=Date.now();return {state:this.state,events:this.events,users:this.users,topics:this.topics,links:this.links,topic:this.topic,call:'IU2EUG'};} - async connect(){if(this.socket&&!this.socket.destroyed)return this.snapshot();const {user,password}=await this.credentials();this.users=[];this.links=[];this.events=[];this.state='connecting';this.section='';this.stage=0;this.buffer='';this.authBuffer='';this.decoder=new StringDecoder('utf8');this.iac=0;this.socket=net.createConnection({host:'127.0.0.1',port:8100});this.socket.setTimeout(15000);this.socket.on('timeout',()=>{if(this.state!=='online')this.socket.destroy(new Error('Timeout di accesso chat'));});this.socket.on('error',e=>{this.state='error';this.event('system','Chat non disponibile: '+e.message)});this.socket.on('close',()=>{if(this.state!=='error')this.state='offline';this.event('system','Disconnesso dalla chat')}); + snapshot(){this.lastAccess=Date.now();return {state:this.state,events:this.events,users:this.users,topics:this.topics,links:this.links,topic:this.topic,call:this.call};} + async connect(){if(this.socket&&!this.socket.destroyed)return this.snapshot();const {user,password}=await this.credentials();this.users=[];this.links=[];this.events=[];this.state='connecting';this.section='';this.stage=0;this.buffer='';this.authBuffer='';this.decoder=new StringDecoder('utf8');this.iac=0;this.socket=net.createConnection({host:'127.0.0.1',port:this.options.port||8100});this.socket.setTimeout(15000);this.socket.on('timeout',()=>{if(this.state!=='online')this.socket.destroy(new Error('Timeout di accesso chat'));});this.socket.on('error',e=>{this.state='error';this.event('system','Chat non disponibile: '+e.message)});this.socket.on('close',()=>{if(this.state!=='error')this.state='offline';this.event('system','Disconnesso dalla chat')}); this.socket.on('data',chunk=>{const bytes=[];for(const b of chunk){if(this.iac===1){if(b===255){bytes.push(b);this.iac=0}else if([251,252,253,254].includes(b))this.iac=2;else this.iac=0;continue}if(this.iac===2){this.iac=0;continue}if(b===255){this.iac=1;continue}bytes.push(b)}const text=this.decoder.write(Buffer.from(bytes)).replace(/\x1b\[[0-9;]*m/g,'');this.authBuffer=(this.authBuffer+text).slice(-5000); if(this.stage===0&&/Username:/i.test(this.authBuffer)){this.write(user);this.stage=1;this.authBuffer='';return;} if(this.stage===1&&/Password:/i.test(this.authBuffer)){this.write(password);this.stage=2;this.authBuffer='';return;} - if(this.stage===2&&/Welcome|ALNODE:IU2EUG-7/i.test(this.authBuffer)){this.write('CHAT');this.stage=3;this.authBuffer='';return;} + if(this.stage===2&&/Welcome|[A-Z0-9]{1,6}:[A-Z0-9-]+>/i.test(this.authBuffer)){this.write('CHAT');this.stage=3;this.authBuffer='';return;} if(this.stage<3)return;this.buffer+=text.replace(/\r\n/g,'\n').replace(/\r/g,'\n');const lines=this.buffer.split('\n');this.buffer=lines.pop();for(const line of lines)this.line(line.trim());}); this.lastAccess=Date.now();return this.snapshot();} - line(line){if(!line)return;if(line.includes('[BPQChatServer-')){this.state='online';this.socket.setTimeout(0);this.event('system','Connesso a ALBCHT come IU2EUG');setTimeout(()=>{if(this.state==='online')this.roster()},1000);return;} - if(/Already connected/i.test(line)){this.event('system','BPQ ha rilevato una precedente sessione IU2EUG. Se la connessione si chiude, premi Connetti.');return;} + line(line){if(!line)return;if(line.includes('[BPQChatServer-')){this.state='online';this.socket.setTimeout(0);this.event('system','Connesso alla chat come '+this.call);setTimeout(()=>{if(this.state==='online')this.roster()},1000);return;} + if(/Already connected/i.test(line)){this.event('system','BPQ ha rilevato una precedente sessione. Se la connessione si chiude, premi Connetti.');return;} if(/Disconnected from Stream/i.test(line)){this.socket?.end();return;} 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==='IU2EUG')this.topic=user.topic;this.remaining--;if(this.remaining<=0)this.section='';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 IU2EUG|^Links Defined:/.test(line)){if(line==='Links Defined:'){this.section='links';this.links=[]}else this.section='';return;} - if(this.section==='topics'){if(/^[A-Za-z0-9_-]+$/.test(line)&&!/^IU2EUG$/.test(line)){this.topics.push(line);}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(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)(.*)$/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(/^IU2EUG Chat Server|^Type \/h|^Bringing up links|^This may take|^The \/p|^ALNODE:/.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);} write(text){this.socket?.write(text+'\r');} roster(){this.lastRoster=Date.now();this.write('/U');setTimeout(()=>{if(this.state==='online')this.write('/T')},500);setTimeout(()=>{if(this.state==='online')this.write('/P')},1000);} - send(text,to=''){if(this.state!=='online')throw new Error('Connettiti alla chat prima di scrivere');if(typeof text!=='string'||!text.trim()||text.length>500||/[\r\n\x00-\x1f]/.test(text)||text.trim().startsWith('/'))throw new Error('Scrivi un messaggio su una sola riga, massimo 500 caratteri');if(to&&!/^[A-Z0-9]*\d[A-Z0-9]*(?:-\d+)?$/i.test(to))throw new Error('Nominativo non valido');this.write(to?'/S '+to.toUpperCase()+' '+text:text);this.event('message',text,'IU2EUG',to?to.toUpperCase():null);this.lastAccess=Date.now();} + send(text,to=''){if(this.state!=='online')throw new Error('Connettiti alla chat prima di scrivere');if(typeof text!=='string'||!text.trim()||text.length>500||/[\r\n\x00-\x1f]/.test(text)||text.trim().startsWith('/'))throw new Error('Scrivi un messaggio su una sola riga, massimo 500 caratteri');if(to&&!/^[A-Z0-9]*\d[A-Z0-9]*(?:-\d+)?$/i.test(to))throw new Error('Nominativo non valido');this.write(to?'/S '+to.toUpperCase()+' '+text:text);this.event('message',text,this.call,to?to.toUpperCase():null);this.lastAccess=Date.now();} changeTopic(name){if(this.state!=='online')throw new Error('Chat non connessa');if(!/^[A-Za-z0-9_-]{1,24}$/.test(name))throw new Error('Nome stanza non valido');this.write('/T '+name);this.topic=name;this.event('system','Stanza selezionata: '+name);setTimeout(()=>this.state==='online'&&this.roster(),800);} disconnect(){if(this.socket&&!this.socket.destroyed){this.write('/QUIT');this.socket.end();}this.state='offline';} } diff --git a/config.mjs b/config.mjs new file mode 100644 index 0000000..4dbfef2 --- /dev/null +++ b/config.mjs @@ -0,0 +1,29 @@ +import {readFile} from 'node:fs/promises'; +import path from 'node:path'; +import os from 'node:os'; +import {fileURLToPath} from 'node:url'; + +export function parseConfig(text){ + const lines=text.split(/\r?\n/).map(l=>l.split(';')[0].trim()).filter(Boolean); + const value=(name)=>lines.find(l=>new RegExp('^'+name+'\\s*=','i').test(l))?.split('=').slice(1).join('=').trim()||''; + const users=lines.flatMap(l=>{const m=l.match(/^USER=([^,]+),([^,]+),([^,]+),(.*)$/i);return m&&/\bsysop\b/i.test(m[4])?[{user:m[1].trim(),password:m[2],call:m[3].trim().toUpperCase()}]:[]}); + const apps=lines.flatMap(l=>{const m=l.match(/^APPLICATION\s+\d+,([^,]+),([^,]*),([^,]*),([^,]*)/i);return m?[{command:m[1],call:m[3],alias:m[4]}]:[]}); + let ports=[],current=null; + for(const l of lines){if(/^PORT$/i.test(l)){current={id:ports.length+1,name:'',driver:''};continue;}if(/^ENDPORT$/i.test(l)){if(current){if(!current.driver)current.driver=current.protocol||current.type||'';ports.push(current)};current=null;continue;}if(current){const m=l.match(/^(PORTNUM|ID|DRIVER|TYPE|PROTOCOL)=(.*)$/i);if(m)current[({PORTNUM:'id',ID:'name',DRIVER:'driver',TYPE:'type',PROTOCOL:'protocol'})[m[1].toUpperCase()]]=m[1].toUpperCase()==='PORTNUM'?Number(m[2]):m[2];}} + const radioPorts=ports.filter(p=>!/TELNET|AXIP|LOOPBACK/i.test(p.driver)&&p.driver); + const nodeCall=value('NODECALL'),sysop=users[0]; + return {nodeCall,call:sysop?.call||nodeCall.replace(/-\d+$/,''),alias:value('NODEALIAS'),locator:value('LOCATOR'),apps,ports,radioPorts,users,httpPort:Number(value('HTTPPORT'))||null,telnetPort:Number(value('TCPPORT'))||null,monitorPort:Number(value('FBBPORT'))||null,winlink:value('CMS')==='1'}; +} +export async function loadConfig(){ + const dir=path.dirname(fileURLToPath(import.meta.url));let saved={}; + try{saved=JSON.parse(await readFile(process.env.BPQ_CONSOLE_CONFIG||path.join(dir,'console.config.json'),'utf8'));}catch(e){if(e.code!=='ENOENT')throw e;} + const root=process.env.BPQ_ROOT||saved.bpqRoot||path.join(process.env.APPDATA||path.join(os.homedir(),'AppData','Roaming'),'BPQ32'); + const detected=parseConfig(await readFile(path.join(root,'BPQ32.cfg'),'utf8')); + if(!detected.users.length)throw new Error('Nessun utente Telnet sysop in BPQ32.cfg'); + const radio=detected.radioPorts.find(p=>p.id===saved.radioPort)||detected.radioPorts[0]||null; + const httpPort=saved.httpPort||detected.httpPort;if(!httpPort)throw new Error('HTTPPORT BPQ non rilevata: eseguire Install.ps1'); + const features={bbs:detected.apps.some(a=>a.command==='BBS'),chat:detected.apps.some(a=>a.command==='CHAT')&&!!detected.telnetPort,monitor:!!detected.monitorPort,winlink:detected.winlink&&detected.apps.some(a=>a.command==='BBS'),vara:!!radio&&/^VARA/i.test(radio.driver),radio:!!radio}; + return {...detected,...saved,root,httpPort,radio,features,port:Number(process.env.BPQ_CONSOLE_PORT||saved.port||8090),sysop:detected.users.find(u=>u.user===saved.sysopUser)||detected.users[0]}; +} +export function publicConfig(c){return {call:c.sysop.call,nodeCall:c.nodeCall,alias:c.alias,locator:c.locator,apps:c.apps,radio:c.radio,ports:c.ports,features:c.features,forwardPeer:c.forwardPeer||'',cmsPeer:c.cmsPeer||'RMS'};} +export function ownCall(sender,call){return !!call&&String(sender||'').replace(/^RMS[/:]/i,'').toUpperCase().split('@')[0].replace(/-\d+$/,'')===String(call).toUpperCase().split('@')[0].replace(/-\d+$/,'');} diff --git a/install.mjs b/install.mjs new file mode 100644 index 0000000..d0b6c1f --- /dev/null +++ b/install.mjs @@ -0,0 +1,20 @@ +process.on('uncaughtException',e=>{console.error('Installazione interrotta: '+e.message);process.exit(1)}); +import {readFile,writeFile} from 'node:fs/promises'; +import http from 'node:http';import path from 'node:path';import {fileURLToPath} from 'node:url';import {parseConfig} from './config.mjs'; +const dir=path.dirname(fileURLToPath(import.meta.url)),args=process.argv.slice(2),arg=n=>{const i=args.indexOf('--'+n);return i>=0?args[i+1]:undefined}; +const root=arg('bpq-root')||path.join(process.env.APPDATA||'','BPQ32'); +const detected=parseConfig(await readFile(path.join(root,'BPQ32.cfg'),'utf8')); +if(!detected.users.length)throw new Error('Configurare un USER Telnet sysop in BPQ32.cfg'); +const port=Number(arg('port')||8090),httpPort=Number(arg('http-port')||detected.httpPort); +if(!Number.isInteger(port)||port<1024||port>65535||!httpPort)throw new Error('Porte non valide o HTTPPORT BPQ assente'); +await new Promise((resolve,reject)=>{const req=http.get({host:'127.0.0.1',port:httpPort,path:'/Node/Ports.html',headers:{Connection:'close'}},res=>{let text='';res.on('data',b=>text+=b);res.on('end',()=>res.statusCode===200&&/BPQ|Ports/i.test(text)?resolve():reject(new Error('Il server HTTP non conferma BPQ')))});req.setTimeout(8000,()=>req.destroy(new Error('BPQ non risponde: avviare BPQ e verificare HTTPPORT')));req.on('error',()=>reject(new Error('BPQ non raggiungibile: avviare BPQ e verificare HTTPPORT')))}); +let previous={};try{previous=JSON.parse(await readFile(path.join(dir,'console.config.json'),'utf8'))}catch{} +const radioPort=Number(arg('radio-port')||previous.radioPort)||detected.radioPorts[0]?.id||null; +if(radioPort&&!detected.radioPorts.some(p=>p.id===radioPort))throw new Error('Porta radio selezionata non rilevata'); +const sysopUser=arg('sysop-user')||previous.sysopUser||detected.users[0].user; +if(!detected.users.some(u=>u.user===sysopUser))throw new Error('Utente sysop non rilevato'); +let peers=[];try{const mail=await readFile(path.join(root,'BPQMailChat','BPQMail.cfg'),'utf8');const forward=mail.split(/BBSForwarding\s*:/i)[1]?.split(/BBSUsers\s*:/i)[0]||'';peers=[...forward.matchAll(/^\s{2}([A-Z0-9-]+)\s*:/gm)].map(m=>m[1]);}catch{} +const config={nodeExe:process.execPath,bpqRoot:root,httpPort,port,radioPort,sysopUser,forwardPeer:arg('forward-peer')||previous.forwardPeer||'',cmsPeer:'RMS',varaSyslogPort:18514}; +if(config.forwardPeer&&!peers.includes(config.forwardPeer))throw new Error('Profilo forwarding selezionato non rilevato'); +console.log(JSON.stringify({bpq:'in esecuzione, HTTP verificato',nodeCall:detected.nodeCall,ports:detected.ports,services:detected.apps.map(a=>a.command),forwardProfiles:peers,selectedRadio:radioPort,sysopUser},null,2)); +if(!args.includes('--check-only')){await writeFile(path.join(dir,'console.config.json'),JSON.stringify(config,null,2)+'\n');console.log('Configurazione salvata senza password.');} diff --git a/model.mjs b/model.mjs index ad27600..1616bec 100644 --- a/model.mjs +++ b/model.mjs @@ -1,3 +1,4 @@ -export function mailDirection(m){const sender=String(m.fromAddress||m.from||'').replace(/^RMS[/:]/i,'').trim().toUpperCase();const own=/^IU2EUG(?:-\d+)?(?:@WINLINK\.ORG)?$/.test(sender)||/^IU2EUG(?:-\d+)?$/i.test(m.from||'');return own?'outgoing':'incoming';} -export function mailFolder(m){if(mailDirection(m)==='incoming')return 'inbox';return ['F','D'].includes(m.status)?'sent':'queue';} +import {ownCall} from './config.mjs'; +export function mailDirection(m,call){const sender=String(m.fromAddress||m.from||'').replace(/^RMS[/:]/i,'').trim().toUpperCase();const own=ownCall(sender,call)||ownCall(m.from,call);return own?'outgoing':'incoming';} +export function mailFolder(m,call){if(mailDirection(m,call)==='incoming')return 'inbox';return ['F','D'].includes(m.status)?'sent':'queue';} export function cmsStatus(log){const lines=log.split(/\r?\n/).filter(l=>/[|<>]RMS\s+/.test(l)&&!/;PR:|;PQ:|;FW:/.test(l));const start=lines.findLastIndex(l=>/Connecting to BBS RMS/.test(l));if(start<0)return {state:'idle',at:null,text:'Nessuna sessione rilevata oggi'};const part=lines.slice(start),last=part.at(-1);const done=part.some(l=>/[<>]RMS\s+FQ\s*$/.test(l));const failed=part.some(l=>/Protocol Error|Failure with|Authentication failed|Connection failed|Invalid password/i.test(l));const ended=part.some(l=>/RMS Disconnected/.test(l));return {state:done?'complete':failed?'error':ended?'ended':'running',at:last.slice(0,15),text:done?'Sincronizzazione completata':failed?'Errore nella sessione CMS':ended?'Sessione CMS conclusa':'Sincronizzazione in corso'};} diff --git a/monitor.mjs b/monitor.mjs index ec7a0e7..7947f93 100644 --- a/monitor.mjs +++ b/monitor.mjs @@ -9,9 +9,9 @@ export class MonitorDecoder { }} } export class Monitor { - constructor(credentials){this.credentials=credentials;this.state='offline';this.events=[];this.seq=0;this.ports=[];this.lastAccess=0;this.timer=setInterval(()=>{if(this.socket&&Date.now()-this.lastAccess>120000)this.disconnect()},15000);this.timer.unref();} + constructor(credentials,options={}){this.options=options;this.credentials=credentials;this.state='offline';this.events=[];this.seq=0;this.ports=[];this.lastAccess=0;this.timer=setInterval(()=>{if(this.socket&&Date.now()-this.lastAccess>120000)this.disconnect()},15000);this.timer.unref();} snapshot(after=0){this.lastAccess=Date.now();return {state:this.state,error:this.error,ports:this.ports,latest:this.seq,first:this.events[0]?.id||0,events:this.events.filter(e=>e.id>after)};} async connect(){this.lastAccess=Date.now();if(this.pending)return this.pending;if(this.socket&&!this.socket.destroyed)return this.snapshot();this.pending=this.open();try{return await this.pending}finally{this.pending=null;}} - async open(){const credentials=await this.credentials();this.state='connecting';this.error=null;this.auth='';const socket=net.createConnection({host:'127.0.0.1',port:8101});this.socket=socket;const decoder=new MonitorDecoder(frame=>{this.events.push({...frame,id:++this.seq,at:new Date().toISOString()});if(this.events.length>1000)this.events.shift()},ports=>this.ports=ports);socket.setTimeout(15000);socket.on('connect',()=>socket.write(credentials.user+'\r'+credentials.password+'\rBPQTermTCP\r'));socket.on('timeout',()=>socket.destroy(new Error('Timeout monitor BPQ')));socket.on('error',()=>{this.state='error';this.error='Monitor BPQ non disponibile'});socket.on('close',()=>{if(this.state!=='error')this.state='offline'});socket.on('data',chunk=>{if(this.state==='connecting'){this.auth=(this.auth+chunk.toString('utf8')).slice(-4096);if(/Connected to TelnetServer/i.test(this.auth)){this.state='online';this.auth='';socket.setTimeout(0);socket.write('\\'.repeat(4)+'7fffffffffffffff 1 1 1 1 0 1 1\r');}else if(/invalid|attempts|failed/i.test(this.auth)){socket.destroy(new Error('Accesso monitor fallito'));}}decoder.push(chunk)});return this.snapshot();} + async open(){const credentials=await this.credentials();this.state='connecting';this.error=null;this.auth='';const socket=net.createConnection({host:'127.0.0.1',port:this.options.port||8101});this.socket=socket;const decoder=new MonitorDecoder(frame=>{this.events.push({...frame,id:++this.seq,at:new Date().toISOString()});if(this.events.length>1000)this.events.shift()},ports=>this.ports=ports);socket.setTimeout(15000);socket.on('connect',()=>socket.write(credentials.user+'\r'+credentials.password+'\rBPQTermTCP\r'));socket.on('timeout',()=>socket.destroy(new Error('Timeout monitor BPQ')));socket.on('error',()=>{this.state='error';this.error='Monitor BPQ non disponibile'});socket.on('close',()=>{if(this.state!=='error')this.state='offline'});socket.on('data',chunk=>{if(this.state==='connecting'){this.auth=(this.auth+chunk.toString('utf8')).slice(-4096);if(/Connected to TelnetServer/i.test(this.auth)){this.state='online';this.auth='';socket.setTimeout(0);socket.write('\\'.repeat(4)+'7fffffffffffffff 1 1 1 1 0 1 1\r');}else if(/invalid|attempts|failed/i.test(this.auth)){socket.destroy(new Error('Accesso monitor fallito'));}}decoder.push(chunk)});return this.snapshot();} disconnect(){this.socket?.destroy();this.state='offline';} } diff --git a/package.json b/package.json index fafa338..5867d3c 100644 --- a/package.json +++ b/package.json @@ -1 +1 @@ -{"name":"alnode-console","version":"1.0.0","private":true,"type":"module","scripts":{"start":"node server.mjs","test":"node --test test.mjs"}} +{"name":"bpq-console","version":"1.1.0","private":true,"type":"module","scripts":{"start":"node server.mjs","test":"node --test test.mjs"}} diff --git a/public/app.js b/public/app.js index 30fa65d..8569518 100644 --- a/public/app.js +++ b/public/app.js @@ -1,31 +1,61 @@ const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)]; +let station={call:'',alias:'',features:{},apps:[]}; 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:{'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;} function toast(text){$('#toast').textContent=text;$('#toast').hidden=false;clearTimeout(toast.timer);toast.timer=setTimeout(()=>$('#toast').hidden=true,6500);} function showLogin(){$('#shell').hidden=true;$('#login').hidden=false;csrf='';} -function showShell(user){csrf=user.csrf;$('#login').hidden=true;$('#shell').hidden=false;loadDashboard();loadMessages();} +function showShell(user){station=user.config;applyStation(user);csrf=user.csrf;$('#login').hidden=true;$('#shell').hidden=false;loadDashboard();if(station.features.bbs)loadMessages();} 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('it-IT',{hour:'2-digit',minute:'2-digit'});} function categoryLabel(m){return m.type==='P'?'PERSONALE':m.to||'BOLLETTINO'} -function friendlyActivity(text){if(/Failure with/.test(text))return 'IW2OHX non ha risposto alla chiamata';if(/Connecting to BBS/.test(text))return 'Chiamata radio verso IW2OHX avviata';if(/Incoming Connect/.test(text))return 'IW2OHX si è collegato alla nostra BBS';if(/Uncompressing Message/.test(text))return 'Ricevuto e salvato un nuovo bollettino';if(/Disconnected/.test(text))return 'Sessione con IW2OHX terminata';return text;} +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 `
Percorso del messaggio nella rete
${esc(m[1])}
${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(){try{const d=await api('/dashboard');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?'VARA HF '+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('it-IT',{hour:'2-digit',minute:'2-digit'});$('#recent-list').innerHTML=d.recent.map(m=>`
${esc(categoryLabel(m))}
${esc(m.subject)}${esc(m.from)} · #${m.id}
${esc(m.date)}
`).join('')||'

Nessun messaggio disponibile.

';$$('#recent-list [data-id]').forEach(b=>{const open=()=>{navigate('bbs');readMessage(Number(b.dataset.id))};b.onclick=open;b.onkeydown=e=>{if(e.key==='Enter')open()}});$('#activity-list').innerHTML=d.activity.slice(0,8).map(a=>`
${esc(friendlyActivity(a.text))}${esc(logTime(a.at))} · ${mailTimezone()}
`).join('')||'

Nessuna attività di forwarding rilevata oggi.

';$('#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(){try{allMessages=await api('/messages');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)}} +async function loadDashboard(){try{const d=await api('/dashboard');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('it-IT',{hour:'2-digit',minute:'2-digit'});$('#recent-list').innerHTML=d.recent.map(m=>`
${esc(categoryLabel(m))}
${esc(m.subject)}${esc(m.from)} · #${m.id}
${esc(m.date)}
`).join('')||'

Nessun messaggio disponibile.

';$$('#recent-list [data-id]').forEach(b=>{const open=()=>{navigate('bbs');readMessage(Number(b.dataset.id))};b.onclick=open;b.onkeydown=e=>{if(e.key==='Enter')open()}});$('#activity-list').innerHTML=d.activity.slice(0,8).map(a=>`
${esc(friendlyActivity(a.text))}${esc(logTime(a.at))} · ${mailTimezone()}
`).join('')||'

Nessuna attività di forwarding rilevata oggi.

';$('#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(){if(!station.features.bbs)return;try{allMessages=await api('/messages');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('it-IT',{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('it-IT',{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==='IU2EUG')&&(!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)));} +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)}

`}} $$('[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)&&!confirm('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…';$('#compose-error').textContent='';try{const data=Object.fromEntries(new FormData(e.target));const created=await api('/messages',{method:'POST',body:JSON.stringify(data)});$('#compose').close();toast('Messaggio #'+created.id+' salvato nella BBS. L’inoltro sarà gestito da BPQ.');if(winlinkMode){navigate('winlink');wlFolder='queue';await wlLoad();wlRender();wlRead(created.id);}else{navigate('bbs');await loadMessages();readMessage(created.id);}loadDashboard();}catch(err){$('#compose-error').textContent=err.message}finally{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};$('#sync-open').onclick=()=>$('#sync-dialog').showModal();$('#sync-cancel').onclick=()=>$('#sync-dialog').close();$('#sync-confirm').onclick=async()=>{const b=$('#sync-confirm');b.disabled=true;try{await api('/sync',{method:'POST',body:'{}'});$('#sync-dialog').close();toast('Richiesta di forwarding inviata a BPQ. Segui l’esito nell’attività.');setTimeout(loadDashboard,2500)}catch(err){toast(err.message)}finally{b.disabled=false}}; -setInterval(()=>{if(csrf&&!document.hidden)loadDashboard()},20000);setInterval(()=>{$('#clock').textContent=new Date().toLocaleTimeString('it-IT',{timeZone:'Europe/Rome',hour:'2-digit',minute:'2-digit'})+' · '+mailTimezone()},1000); +setInterval(()=>{if(csrf&&!document.hidden)loadDashboard()},20000);setInterval(()=>{$('#clock').textContent=new Date().toLocaleTimeString('it-IT',{hour:'2-digit',minute:'2-digit'})+' · '+mailTimezone()},1000); api('/session').then(showShell).catch(()=>showLogin()); + +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+' · '+station.call; + $('.mission-heading h1').textContent=station.nodeCall+' / '+station.alias; + $('.mission-location').textContent=station.locator||'BPQ'; + $('.modem-brand').textContent=station.radio?.name||'Nessuna porta modem'; + $('#home .page-footer').firstChild.textContent='BPQ Console · '+station.nodeCall+' '; + $('#bbs .eyebrow').textContent=station.apps.find(a=>a.command==='BBS')?.call||'BBS'; + $('#compose .eyebrow').textContent=station.call; + $('.compose-help').textContent='Il messaggio sarà salvato nella BBS. L’inoltro segue i profili BPQ.'; + $('#sync-open').disabled=!station.forwardPeer;$('#sync-open').textContent=station.forwardPeer?'Sincronizza con '+station.forwardPeer:'Forwarding non selezionato'; + $('#sync-dialog h2').textContent='Avviare il forwarding verso '+station.forwardPeer+'?'; + $('.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.vara; + $('#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'); +} diff --git a/public/enhancements.js b/public/enhancements.js index 9806a0c..77b2ec2 100644 --- a/public/enhancements.js +++ b/public/enhancements.js @@ -7,12 +7,12 @@ function chime(){if(!soundOn||!audio||audio.state!=='running')return;const t=aud soundButton.onclick=()=>{soundOn=!soundOn;localStorage.setItem('alnode-sound',soundOn?'yes':'no');if(soundOn){prepareAudio();setTimeout(chime,60)}soundLabel()};document.addEventListener('pointerdown',()=>{if(soundOn)prepareAudio()},{once:true}); const stack=document.createElement('div');stack.className='notification-stack';stack.setAttribute('aria-live','polite');document.body.append(stack); function arrival(kind,title,detail,ids=[]){const item=document.createElement('div');item.className='arrival-toast '+kind;item.innerHTML=`${kind==='mail'?'✉':'▤'}
${esc(title)}${esc(detail)}
`;item.querySelector('button').onclick=e=>{e.stopPropagation();item.remove()};item.onclick=()=>{navigate('bbs');if(ids.length===1)readMessage(ids[0]);item.remove()};stack.append(item);while(stack.children.length>4)stack.firstChild.remove();setTimeout(()=>item.remove(),12000)} -let knownIds;try{const saved=JSON.parse(localStorage.getItem('alnode-message-ids')||'null');knownIds=Array.isArray(saved)?new Set(saved):null}catch{knownIds=null} +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(){await oldLoadMessages();if(!csrf||!allMessages.length)return;const arrivals=incoming(allMessages,knownIds);const fresh=[...arrivals.bulletins,...arrivals.mail];knownIds=new Set(allMessages.map(m=>m.id));localStorage.setItem('alnode-message-ids',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();}}; +loadMessages=async function(){await oldLoadMessages();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('alnode-message-ids',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)loadMessages()},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
◇

ALBCHT · IU2EUG-12

Connettiti come IU2EUG per partecipare alla chat.

`;$('main').append(chatPage); +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); const oldNavigate=navigate;navigate=function(next){oldNavigate(next);$('#breadcrumb').textContent='Stazione / '+({home:'Panoramica',bbs:'BBS',network:'Rete',chat:'Chat',winlink:'Winlink'}[next]);if(next==='chat')pollChat();window.scrollTo({top:0,behavior:'instant'})}; let chatFollowing=true,chatUnread=0,chatScrolling=false; @@ -26,20 +26,20 @@ new ResizeObserver(()=>{if(chatFollowing&&page==='chat')chatToBottom();}).observ const navigateWithChat=navigate;navigate=function(next){navigateWithChat(next);if(next==='chat'){if(chatFollowing)chatToBottom();else updateChatJump();}}; function renderChat(data){ chatState=data.state;const online=data.state==='online'; - $('#chat-state').className='chat-status '+data.state;$('#chat-state').textContent=({offline:'Disconnesso',connecting:'Connessione…',online:'● Connesso · IU2EUG',error:'Connessione interrotta'}[data.state]);$('#chat-connect').hidden=online;$('#chat-connect').disabled=data.state==='connecting';$('#chat-disconnect').hidden=!online;$('#chat-input').disabled=!online;$('#chat-send').disabled=!online;$('#chat-input').placeholder=online?'Scrivi alla stanza…':'Connettiti per scrivere…'; + $('#chat-state').className='chat-status '+data.state;$('#chat-state').textContent=({offline:'Disconnesso',connecting:'Connessione…',online:'● Connesso · '+station.call,error:'Connessione interrotta'}[data.state]);$('#chat-connect').hidden=online;$('#chat-connect').disabled=data.state==='connecting';$('#chat-disconnect').hidden=!online;$('#chat-input').disabled=!online;$('#chat-send').disabled=!online;$('#chat-input').placeholder=online?'Scrivi alla stanza…':'Connettiti per scrivere…'; $('#chat-room-name').textContent='# '+data.topic;$('#chat-presence-count').textContent=online?data.users.filter(u=>u.topic.toLowerCase()===data.topic.toLowerCase()).length+' nella stanza':'Non connesso';$('#chat-user-count').textContent=online?data.users.length:'—'; $('#chat-users').innerHTML=online?data.users.map(u=>``).join('')||'

Nessun utente rilevato

':'

Connettiti per vedere chi è presente.

'; - const recipient=$('#chat-recipient').value;$('#chat-recipient').innerHTML=''+data.users.filter(u=>u.call!=='IU2EUG').map(u=>``).join('');$('#chat-recipient').value=recipient;if(!$('#chat-recipient').value)$('#chat-recipient').value='';$('#chat-recipient').disabled=!online;if(online&&$('#chat-recipient').value)$('#chat-input').placeholder='Messaggio privato a '+$('#chat-recipient').value+'…'; - $$('.chat-user').forEach(b=>b.onclick=()=>{$('#chat-recipient').value=b.dataset.call==='IU2EUG'?'':b.dataset.call;$('#chat-input').placeholder=b.dataset.call==='IU2EUG'?'Scrivi alla stanza…':'Messaggio privato a '+b.dataset.call+'…';$('#chat-input').focus();}); + const recipient=$('#chat-recipient').value;$('#chat-recipient').innerHTML=''+data.users.filter(u=>u.call!==station.call).map(u=>``).join('');$('#chat-recipient').value=recipient;if(!$('#chat-recipient').value)$('#chat-recipient').value='';$('#chat-recipient').disabled=!online;if(online&&$('#chat-recipient').value)$('#chat-input').placeholder='Messaggio privato a '+$('#chat-recipient').value+'…'; + $$('.chat-user').forEach(b=>b.onclick=()=>{$('#chat-recipient').value=b.dataset.call===station.call?'':b.dataset.call;$('#chat-input').placeholder=b.dataset.call===station.call?'Scrivi alla stanza…':'Messaggio privato a '+b.dataset.call+'…';$('#chat-input').focus();}); $('#chat-topics').innerHTML=[...new Set(['General',...data.topics,data.topic])].map(t=>``).join(''); $$('[data-topic]').forEach(b=>b.onclick=async()=>{try{await api('/chat/topic',{method:'POST',body:JSON.stringify({topic:b.dataset.topic})});chatFollowing=true;chatUnread=0;pollChat();}catch(e){toast(e.message);}}); $('#chat-links').innerHTML=online?data.links.map(l=>``).join('')||'':''; const events=data.events.filter(e=>e.id>chatLastId),initial=chatLastId===0; if(events.length){if(chatArea.querySelector('.chat-empty'))chatArea.replaceChildren();const fragment=document.createDocumentFragment();let added=0; for(const event of events){chatLastId=Math.max(chatLastId,event.id);if(event.type==='system'&&/^[A-Z0-9]{3,6}(?:\s+[A-Z0-9]{3,6})*$/.test(event.text))continue; - const element=document.createElement('div');if(event.type==='message'&&!/\*\*\* (?:Joined|Left)/i.test(event.text)){element.className='chat-event '+(event.sender==='IU2EUG'?'own':'')+(event.to?' private':'');element.innerHTML=`
${esc(event.sender?.slice(0,2)||'?')}
${esc(event.sender)}${event.to?` → ${esc(event.to)} · privato`:''}

${esc(event.text)}

`;added++;}else{element.className='chat-system';element.textContent=(event.sender?event.sender+' · ':'')+event.text;}fragment.append(element);} + const element=document.createElement('div');if(event.type==='message'&&!/\*\*\* (?:Joined|Left)/i.test(event.text)){element.className='chat-event '+(event.sender===station.call?'own':'')+(event.to?' private':'');element.innerHTML=`
${esc(event.sender?.slice(0,2)||'?')}
${esc(event.sender)}${event.to?` → ${esc(event.to)} · privato`:''}

${esc(event.text)}

`;added++;}else{element.className='chat-system';element.textContent=(event.sender?event.sender+' · ':'')+event.text;}fragment.append(element);} chatArea.append(fragment);while(chatArea.children.length>300)chatArea.firstChild.remove(); - if(initial||chatFollowing||events.some(e=>e.sender==='IU2EUG'&&e.type==='message')){chatFollowing=true;if(page==='chat')chatToBottom();}else{chatUnread+=added;updateChatJump();} + if(initial||chatFollowing||events.some(e=>e.sender===station.call&&e.type==='message')){chatFollowing=true;if(page==='chat')chatToBottom();}else{chatUnread+=added;updateChatJump();} } } diff --git a/public/index.html b/public/index.html index e6cfd30..1386898 100644 --- a/public/index.html +++ b/public/index.html @@ -1,19 +1,19 @@ -ALNODE — Radio & BBS +BPQ — Radio & BBS - -