Make BPQ console station-independent with modem detection and Windows installer
This commit is contained in:
1 parent
5a50f0cfdf
commit
3bf26cec13
22 files changed
+283
-131
No files matched your search
@@ -15,3 +15,5 @@ outputs/
|
|||||||
work/
|
work/
|
||||||
.DS_Store
|
.DS_Store
|
||||||
Thumbs.db
|
Thumbs.db
|
||||||
|
|
||||||
|
console.config.json
|
||||||
+4
-5
@@ -1,6 +1,5 @@
|
|||||||
# Eseguire come amministratore solo se il pannello non si apre da altri PC della LAN.
|
|
||||||
$ErrorActionPreference='Stop'
|
$ErrorActionPreference='Stop'
|
||||||
$nodeExe = 'C:\Users\User1\.cache\codex-runtimes\codex-primary-runtime\dependencies\node\bin\node.exe'
|
$config=Get-Content -LiteralPath (Join-Path $PSScriptRoot 'console.config.json') -Raw | ConvertFrom-Json
|
||||||
if (!(Get-NetFirewallRule -DisplayName 'ALNODE Web Console LAN' -ErrorAction SilentlyContinue)) {
|
$nodeExe=if($config.nodeExe -and (Test-Path -LiteralPath $config.nodeExe)){$config.nodeExe}else{(Get-Command node.exe -ErrorAction Stop).Source}
|
||||||
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
|
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
|
||||||
+26
@@ -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"
|
||||||
@@ -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
|
```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 |
|
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.
|
||||||
| --- | --- |
|
|
||||||
| Interfaccia HTTP BPQ | 8080 |
|
|
||||||
| Telnet BPQ / chat | 8100 |
|
|
||||||
| BPQTermTCP / monitor FBB | 8101 |
|
|
||||||
| Pannello web | 8090 |
|
|
||||||
| Syslog VARA, UDP loopback | 18514 |
|
|
||||||
|
|
||||||
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.
|
-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.
|
||||||
- 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.
|
|
||||||
|
|
||||||
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
|
```powershell
|
||||||
node --test test.mjs
|
node --test test.mjs
|
||||||
```
|
```
|
||||||
|
|
||||||
I test coprono parsing BPQ, allegati binari, classificazione della posta Winlink, stato CMS, notifiche, chat, monitor, bitrate VARA e timestamp.
|
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.
|
||||||
|
|
||||||
PDF.js e le risorse font/CMap incluse mantengono le proprie licenze in public/vendor/pdfjs.
|
|
||||||
+8
-4
@@ -1,5 +1,9 @@
|
|||||||
$ErrorActionPreference='Stop'
|
$ErrorActionPreference='Stop'
|
||||||
$listener = Get-NetTCPConnection -LocalPort 8090 -State Listen -ErrorAction SilentlyContinue
|
$configPath=Join-Path $PSScriptRoot 'console.config.json'
|
||||||
if ($listener) { exit 0 }
|
$port=8090
|
||||||
$nodeExe = 'C:\Users\User1\.cache\codex-runtimes\codex-primary-runtime\dependencies\node\bin\node.exe'
|
if(Test-Path -LiteralPath $configPath){$settings=Get-Content -LiteralPath $configPath -Raw | ConvertFrom-Json;if($settings.port){$port=$settings.port}}
|
||||||
Start-Process -FilePath $nodeExe -ArgumentList 'server.mjs' -WorkingDirectory $PSScriptRoot -WindowStyle Hidden -RedirectStandardOutput (Join-Path $PSScriptRoot 'server.log') -RedirectStandardError (Join-Path $PSScriptRoot 'server-error.log')
|
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')
|
||||||
@@ -4,4 +4,4 @@ export function parseMessages(html){const result=[];const regex=/<a\s+href=\/Web
|
|||||||
export function parseRoutes(html){return [...html.matchAll(/<tr>([\s\S]*?)<\/tr>/gi)].flatMap(m=>{const cells=[...m[1].matchAll(/<td[^>]*>([\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 parseRoutes(html){return [...html.matchAll(/<tr>([\s\S]*?)<\/tr>/gi)].flatMap(m=>{const cells=[...m[1].matchAll(/<td[^>]*>([\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(/<textarea[^>]*>([\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 parseMessage(html){const m=html.match(/<textarea[^>]*>([\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 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)};}
|
||||||
@@ -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 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 {
|
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();}
|
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'};}
|
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: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')});
|
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);
|
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===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===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());});
|
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();}
|
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;}
|
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 IU2EUG. Se la connessione si chiude, premi Connetti.');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;}
|
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 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(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(/^\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)&&!/^IU2EUG$/.test(line)){this.topics.push(line);}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(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(/^(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*(?:\([^)]*\))?[: ]+(.+)$/);
|
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);}
|
this.event(message?'message':'system',message?message[2]:line,message?message[1]:null);}
|
||||||
write(text){this.socket?.write(text+'\r');}
|
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);}
|
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);}
|
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';}
|
disconnect(){if(this.socket&&!this.socket.destroyed){this.write('/QUIT');this.socket.end();}this.state='offline';}
|
||||||
}
|
}
|
||||||
+29
@@ -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+$/,'');}
|
||||||
+20
@@ -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.');}
|
||||||
@@ -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';}
|
import {ownCall} from './config.mjs';
|
||||||
export function mailFolder(m){if(mailDirection(m)==='incoming')return 'inbox';return ['F','D'].includes(m.status)?'sent':'queue';}
|
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'};}
|
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'};}
|
||||||
+2
-2
@@ -9,9 +9,9 @@ export class MonitorDecoder {
|
|||||||
}}
|
}}
|
||||||
}
|
}
|
||||||
export class Monitor {
|
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)};}
|
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 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';}
|
disconnect(){this.socket?.destroy();this.state='offline';}
|
||||||
}
|
}
|
||||||
+1
-1
@@ -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"}}
|
||||||
+36
-6
@@ -1,31 +1,61 @@
|
|||||||
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
|
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;
|
let csrf='',allMessages=[],dashboardData=null,filter='all',selected=null,page='home',loadGeneration=0;
|
||||||
const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
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;}
|
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 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 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 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 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 `<details class="routing-trace"><summary>Percorso del messaggio nella rete</summary><pre>${esc(m[1])}</pre></details>${esc(text.slice(m[1].length).replace(/^\n+/,''))}`;}
|
function readableBody(text){const m=text.match(/^((?:R:[^\n]*\n)+)/);if(!m)return esc(text);return `<details class="routing-trace"><summary>Percorso del messaggio nella rete</summary><pre>${esc(m[1])}</pre></details>${esc(text.slice(m[1].length).replace(/^\n+/,''))}`;}
|
||||||
function size(n){return n>1024?(n/1024).toFixed(1)+' KB':n+' B'}
|
function 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();}
|
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)));
|
$$('[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}});
|
$('#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()}};
|
$('#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=>`<div class="recent-item" tabindex="0" role="button" data-id="${m.id}"><span class="category-chip">${esc(categoryLabel(m))}</span><div><b>${esc(m.subject)}</b><small>${esc(m.from)} · #${m.id}</small></div><span>${esc(m.date)}</span></div>`).join('')||'<p class="empty">Nessun messaggio disponibile.</p>';$$('#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=>`<div class="activity"><b>${esc(friendlyActivity(a.text))}</b><small>${esc(logTime(a.at))} · ${mailTimezone()}</small></div>`).join('')||'<p class="empty">Nessuna attività di forwarding rilevata oggi.</p>';$('#routes').innerHTML=d.routes.map(r=>`<tr><td>${esc(r.call)}</td><td><span class="tag">${r.active?'ATTIVO':'INATTIVO'}</span></td><td>${esc(r.port)}</td><td>${r.quality}</td><td>${r.nodes}</td><td>${r.frames}</td><td>${r.retries}</td></tr>`).join('')||'<tr><td colspan="7">Nessuna rotta disponibile</td></tr>';$('#nodes').innerHTML=d.nodes.map(n=>{const [alias,call]=n.split(':');return `<div class="node"><strong>${esc(alias)}</strong><small>${esc(call)}</small></div>`}).join('');$('#node-total').textContent=d.nodes.length+' destinazioni';}catch(err){$('#connection').textContent='● Connessione assente';$('#notice').hidden=false;$('#notice').textContent=err.message;}}
|
async function 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=>`<div class="recent-item" tabindex="0" role="button" data-id="${m.id}"><span class="category-chip">${esc(categoryLabel(m))}</span><div><b>${esc(m.subject)}</b><small>${esc(m.from)} · #${m.id}</small></div><span>${esc(m.date)}</span></div>`).join('')||'<p class="empty">Nessun messaggio disponibile.</p>';$$('#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=>`<div class="activity"><b>${esc(friendlyActivity(a.text))}</b><small>${esc(logTime(a.at))} · ${mailTimezone()}</small></div>`).join('')||'<p class="empty">Nessuna attività di forwarding rilevata oggi.</p>';$('#routes').innerHTML=d.routes.map(r=>`<tr><td>${esc(r.call)}</td><td><span class="tag">${r.active?'ATTIVO':'INATTIVO'}</span></td><td>${esc(r.port)}</td><td>${r.quality}</td><td>${r.nodes}</td><td>${r.frames}</td><td>${r.retries}</td></tr>`).join('')||'<tr><td colspan="7">Nessuna rotta disponibile</td></tr>';$('#nodes').innerHTML=d.nodes.map(n=>{const [alias,call]=n.split(':');return `<div class="node"><strong>${esc(alias)}</strong><small>${esc(call)}</small></div>`}).join('');$('#node-total').textContent=d.nodes.length+' destinazioni';}catch(err){$('#connection').textContent='● Connessione assente';$('#notice').hidden=false;$('#notice').textContent=err.message;}}
|
||||||
async function loadMessages(){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='<option value="">Tutte le categorie</option>'+categories.map(c=>`<option>${esc(c)}</option>`).join('');$('#category').value=current;renderMessages();}catch(err){toast(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='<option value="">Tutte le categorie</option>'+categories.map(c=>`<option>${esc(c)}</option>`).join('');$('#category').value=current;renderMessages();}catch(err){toast(err.message)}}
|
||||||
function mailDate(m,kind='received'){const value=kind==='sent'?m.createdAt:(m.receivedAt||m.createdAt);if(!value)return m.date||'—';return new Date(value).toLocaleString('it-IT',{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'});}
|
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 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 <b>'+esc(stamp('sent'))+'</b>':'',stamp('received')?'Ricevuto <b>'+esc(stamp('received'))+'</b>':'','Timezone: '+esc(zone)].filter(Boolean).map(x=>'<span>'+x+'</span>').join('');}
|
function 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 <b>'+esc(stamp('sent'))+'</b>':'',stamp('received')?'Ricevuto <b>'+esc(stamp('received'))+'</b>':'','Timezone: '+esc(zone)].filter(Boolean).map(x=>'<span>'+x+'</span>').join('');}
|
||||||
function mailRow(m,selection,attribute,options={}){const unread=m.status==='N',current=selection===m.id;return `<button class="message-item mail-row ${current?'selected':''} ${unread?'unread':''}" ${attribute}="${m.id}" aria-pressed="${current}" title="${esc(m.subject)}"><span class="mail-indicator" aria-label="${unread?'Non letto':'Letto'}">${unread?'●':'○'}</span><span class="mail-from" title="${esc(options.from||m.from)}">${esc(options.from||m.from)}</span><span class="mail-subject">${esc(m.subject||'(Senza oggetto)')}</span><span class="mail-category">${esc(options.category||m.to)}</span><time class="mail-date" datetime="${esc(m.receivedAt||m.createdAt||'')}" title="${esc(mailDate(m,'sent'))}">${esc(mailDate(m,options.dateKind))}</time><span class="mail-size">${size(m.size)}</span><span class="mail-status">${esc(options.status||m.status)}</span></button>`;}
|
function mailRow(m,selection,attribute,options={}){const unread=m.status==='N',current=selection===m.id;return `<button class="message-item mail-row ${current?'selected':''} ${unread?'unread':''}" ${attribute}="${m.id}" aria-pressed="${current}" title="${esc(m.subject)}"><span class="mail-indicator" aria-label="${unread?'Non letto':'Letto'}">${unread?'●':'○'}</span><span class="mail-from" title="${esc(options.from||m.from)}">${esc(options.from||m.from)}</span><span class="mail-subject">${esc(m.subject||'(Senza oggetto)')}</span><span class="mail-category">${esc(options.category||m.to)}</span><time class="mail-date" datetime="${esc(m.receivedAt||m.createdAt||'')}" title="${esc(mailDate(m,'sent'))}">${esc(mailDate(m,options.dateKind))}</time><span class="mail-size">${size(m.size)}</span><span class="mail-status">${esc(options.status||m.status)}</span></button>`;}
|
||||||
function renderMessages(){const q=$('#search').value.toLowerCase(),cat=$('#category').value;const list=allMessages.filter(m=>(filter==='all'||m.type===filter||filter==='sent'&&m.from==='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('')||'<p class="empty">Nessun messaggio corrisponde ai filtri.</p>';$$('#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('')||'<p class="empty">Nessun messaggio corrisponde ai filtri.</p>';$$('#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='<div class="reader-empty"><h2>Caricamento messaggio…</h2></div>';try{const m=await api('/messages/'+id);if(generation!==loadGeneration)return;$('#reader').innerHTML=`<div class="reader-header"><span class="tag">${m.type==='B'?'BOLLETTINO':'MESSAGGIO PERSONALE'} · #${id}</span><h2>${esc(m.subject)}</h2><div class="reader-meta"><span>Da <b>${esc(m.from)}</b></span><span>A <b>${esc(m.to)}</b></span>${mailTimeMeta(m)}</div></div><div class="reader-body">${readableBody(m.text)}</div><footer class="reader-footer"><span>BID ${esc(m.bid||'—')}</span><button class="secondary" id="reply">↩ Rispondi</button></footer>`;$('#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=`<div class="reader-empty"><h2>Messaggio non disponibile</h2><p>${esc(err.message)}</p></div>`}}
|
async function readMessage(id){const generation=++loadGeneration;selected=id;renderMessages();$('#reader').innerHTML='<div class="reader-empty"><h2>Caricamento messaggio…</h2></div>';try{const m=await api('/messages/'+id);if(generation!==loadGeneration)return;$('#reader').innerHTML=`<div class="reader-header"><span class="tag">${m.type==='B'?'BOLLETTINO':'MESSAGGIO PERSONALE'} · #${id}</span><h2>${esc(m.subject)}</h2><div class="reader-meta"><span>Da <b>${esc(m.from)}</b></span><span>A <b>${esc(m.to)}</b></span>${mailTimeMeta(m)}</div></div><div class="reader-body">${readableBody(m.text)}</div><footer class="reader-footer"><span>BID ${esc(m.bid||'—')}</span><button class="secondary" id="reply">↩ Rispondi</button></footer>`;$('#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=`<div class="reader-empty"><h2>Messaggio non disponibile</h2><p>${esc(err.message)}</p></div>`}}
|
||||||
$$('[data-filter]').forEach(b=>b.onclick=()=>{filter=b.dataset.filter;$$('[data-filter]').forEach(x=>x.classList.toggle('active',x===b));renderMessages()});$('#search').oninput=renderMessages;$('#category').onchange=renderMessages;
|
$$('[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()}
|
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-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 →'}});
|
$('#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}};
|
$('#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());
|
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');
|
||||||
|
}
|
||||||
@@ -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});
|
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);
|
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=`<span>${kind==='mail'?'✉':'▤'}</span><div><strong>${esc(title)}</strong><small>${esc(detail)}</small></div><button aria-label="Chiudi notifica">×</button>`;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)}
|
function arrival(kind,title,detail,ids=[]){const item=document.createElement('div');item.className='arrival-toast '+kind;item.innerHTML=`<span>${kind==='mail'?'✉':'▤'}</span><div><strong>${esc(title)}</strong><small>${esc(detail)}</small></div><button aria-label="Chiudi notifica">×</button>`;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;
|
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);
|
setInterval(()=>{if(csrf)loadMessages()},15000);
|
||||||
const chatNav=document.createElement('button');chatNav.dataset.page='chat';chatNav.innerHTML='<span>◇</span> Chat';chatNav.onclick=()=>navigate('chat');$('nav').append(chatNav);
|
const chatNav=document.createElement('button');chatNav.dataset.page='chat';chatNav.innerHTML='<span>◇</span> Chat';chatNav.onclick=()=>navigate('chat');$('nav').append(chatNav);
|
||||||
const chatPage=document.createElement('section');chatPage.id='chat';chatPage.className='page';chatPage.hidden=true;chatPage.innerHTML=`<div class="chat-heading"><h1>Chat</h1><div class="chat-actions"><span id="chat-state" class="chat-status">Disconnesso</span><button id="chat-connect" class="primary">Connetti</button><button id="chat-disconnect" class="secondary" hidden>Esci</button></div></div><div class="chat-layout"><aside class="chat-rooms"><div class="chat-label">STANZE<button id="new-topic" aria-label="Crea stanza">+</button></div><div id="chat-topics"><button class="room-button active"># General</button></div><div class="chat-links"><div class="chat-label">COLLEGAMENTI</div><div id="chat-links"></div></div></aside><div class="chat-main"><header class="chat-room-header"><b id="chat-room-name"># General</b><small id="chat-presence-count">— presenti</small></header><div id="chat-messages" class="chat-messages"><div class="chat-empty"><span>◇</span><h2>ALBCHT · IU2EUG-12</h2><p>Connettiti come IU2EUG per partecipare alla chat.</p></div></div><form id="chat-form" class="chat-compose"><div class="chat-recipient"><label for="chat-recipient">Destinatario</label><select id="chat-recipient"><option value="">Tutta la stanza</option></select></div><div class="chat-input-row"><input id="chat-input" aria-label="Messaggio chat" placeholder="Scrivi un messaggio…" maxlength="500" autocomplete="off" disabled><button id="chat-send" class="primary" disabled>Invia ↗</button></div></form></div><aside class="chat-users"><div class="chat-label">PRESENTI <span id="chat-user-count">0</span></div><div id="chat-users"><p class="empty">Non connesso</p></div></aside></div>`;$('main').append(chatPage);
|
const chatPage=document.createElement('section');chatPage.id='chat';chatPage.className='page';chatPage.hidden=true;chatPage.innerHTML=`<div class="chat-heading"><h1>Chat</h1><div class="chat-actions"><span id="chat-state" class="chat-status">Disconnesso</span><button id="chat-connect" class="primary">Connetti</button><button id="chat-disconnect" class="secondary" hidden>Esci</button></div></div><div class="chat-layout"><aside class="chat-rooms"><div class="chat-label">STANZE<button id="new-topic" aria-label="Crea stanza">+</button></div><div id="chat-topics"><button class="room-button active"># General</button></div><div class="chat-links"><div class="chat-label">COLLEGAMENTI</div><div id="chat-links"></div></div></aside><div class="chat-main"><header class="chat-room-header"><b id="chat-room-name"># General</b><small id="chat-presence-count">— presenti</small></header><div id="chat-messages" class="chat-messages"><div class="chat-empty"><span>◇</span><h2>Chat BPQ</h2><p>Connettiti con il tuo account per partecipare alla chat.</p></div></div><form id="chat-form" class="chat-compose"><div class="chat-recipient"><label for="chat-recipient">Destinatario</label><select id="chat-recipient"><option value="">Tutta la stanza</option></select></div><div class="chat-input-row"><input id="chat-input" aria-label="Messaggio chat" placeholder="Scrivi un messaggio…" maxlength="500" autocomplete="off" disabled><button id="chat-send" class="primary" disabled>Invia ↗</button></div></form></div><aside class="chat-users"><div class="chat-label">PRESENTI <span id="chat-user-count">0</span></div><div id="chat-users"><p class="empty">Non connesso</p></div></aside></div>`;$('main').append(chatPage);
|
||||||
const topicDialog=document.createElement('dialog');topicDialog.innerHTML='<form id="topic-form"><h2>Crea o apri una stanza</h2><input id="topic-name" aria-label="Nome stanza" placeholder="Nome stanza" required pattern="[A-Za-z0-9_-]{1,24}" maxlength="24"><footer><button type="button" id="topic-cancel" class="secondary">Annulla</button><button class="primary">Entra</button></footer></form>';document.body.append(topicDialog);
|
const topicDialog=document.createElement('dialog');topicDialog.innerHTML='<form id="topic-form"><h2>Crea o apri una stanza</h2><input id="topic-name" aria-label="Nome stanza" placeholder="Nome stanza" required pattern="[A-Za-z0-9_-]{1,24}" maxlength="24"><footer><button type="button" id="topic-cancel" class="secondary">Annulla</button><button class="primary">Entra</button></footer></form>';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'})};
|
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;
|
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();}};
|
const navigateWithChat=navigate;navigate=function(next){navigateWithChat(next);if(next==='chat'){if(chatFollowing)chatToBottom();else updateChatJump();}};
|
||||||
function renderChat(data){
|
function renderChat(data){
|
||||||
chatState=data.state;const online=data.state==='online';
|
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-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=>`<button class="chat-user" data-call="${esc(u.call)}" title="${esc(u.qth)}" aria-label="Messaggio privato a ${esc(u.call)}"><span class="chat-avatar">${esc(u.call.slice(0,2))}</span><div><b>${esc(u.call)}</b><div class="chat-user-name">${esc(u.name)}</div><small>${esc(u.node)} · ${esc(u.topic)}</small></div><span class="presence-dot ${u.idle>300?'idle':''}" title="${u.idle>300?'Inattivo':'Attivo'}"></span></button>`).join('')||'<p class="empty">Nessun utente rilevato</p>':'<p class="chat-offline-note">Connettiti per vedere chi è presente.</p>';
|
$('#chat-users').innerHTML=online?data.users.map(u=>`<button class="chat-user" data-call="${esc(u.call)}" title="${esc(u.qth)}" aria-label="Messaggio privato a ${esc(u.call)}"><span class="chat-avatar">${esc(u.call.slice(0,2))}</span><div><b>${esc(u.call)}</b><div class="chat-user-name">${esc(u.name)}</div><small>${esc(u.node)} · ${esc(u.topic)}</small></div><span class="presence-dot ${u.idle>300?'idle':''}" title="${u.idle>300?'Inattivo':'Attivo'}"></span></button>`).join('')||'<p class="empty">Nessun utente rilevato</p>':'<p class="chat-offline-note">Connettiti per vedere chi è presente.</p>';
|
||||||
const recipient=$('#chat-recipient').value;$('#chat-recipient').innerHTML='<option value="">Tutta la stanza</option>'+data.users.filter(u=>u.call!=='IU2EUG').map(u=>`<option value="${esc(u.call)}">Privato · ${esc(u.call)}</option>`).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+'…';
|
const recipient=$('#chat-recipient').value;$('#chat-recipient').innerHTML='<option value="">Tutta la stanza</option>'+data.users.filter(u=>u.call!==station.call).map(u=>`<option value="${esc(u.call)}">Privato · ${esc(u.call)}</option>`).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();});
|
$$('.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=>`<button class="room-button ${t.toLowerCase()===data.topic.toLowerCase()?'active':''}" data-topic="${esc(t)}"># ${esc(t)}</button>`).join('');
|
$('#chat-topics').innerHTML=[...new Set(['General',...data.topics,data.topic])].map(t=>`<button class="room-button ${t.toLowerCase()===data.topic.toLowerCase()?'active':''}" data-topic="${esc(t)}"># ${esc(t)}</button>`).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);}});
|
$$('[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=>`<div class="chat-link"><span>${esc(l.call)}</span><span class="${l.state==='Open'?'open':'closed'}">${l.state==='Open'?'Attivo':'Non attivo'}</span></div>`).join('')||'<div class="chat-link">—</div>':'<div class="chat-link">Non connesso</div>';
|
$('#chat-links').innerHTML=online?data.links.map(l=>`<div class="chat-link"><span>${esc(l.call)}</span><span class="${l.state==='Open'?'open':'closed'}">${l.state==='Open'?'Attivo':'Non attivo'}</span></div>`).join('')||'<div class="chat-link">—</div>':'<div class="chat-link">Non connesso</div>';
|
||||||
const events=data.events.filter(e=>e.id>chatLastId),initial=chatLastId===0;
|
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;
|
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;
|
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=`<div class="chat-avatar">${esc(event.sender?.slice(0,2)||'?')}</div><div class="chat-message-content"><div class="chat-message-meta"><strong>${esc(event.sender)}${event.to?` <span class="chat-private-label">→ ${esc(event.to)} · privato</span>`:''}</strong><time datetime="${esc(event.at)}" title="${esc(new Date(event.at).toLocaleString('it-IT',{timeZone:'Europe/Rome'}))}">${new Date(event.at).toLocaleTimeString('it-IT',{hour:'2-digit',minute:'2-digit'})}</time></div><p>${esc(event.text)}</p></div>`;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=`<div class="chat-avatar">${esc(event.sender?.slice(0,2)||'?')}</div><div class="chat-message-content"><div class="chat-message-meta"><strong>${esc(event.sender)}${event.to?` <span class="chat-private-label">→ ${esc(event.to)} · privato</span>`:''}</strong><time datetime="${esc(event.at)}" title="${esc(new Date(event.at).toLocaleString('it-IT',{}))}">${new Date(event.at).toLocaleTimeString('it-IT',{hour:'2-digit',minute:'2-digit'})}</time></div><p>${esc(event.text)}</p></div>`;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();
|
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();}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+12
-12
@@ -1,19 +1,19 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="it"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#101916"><title>ALNODE — Radio & BBS</title><link rel="stylesheet" href="/style.css"><link rel="stylesheet" href="/dark.css"><link rel="stylesheet" href="/mission.css"><script defer src="/app.js"></script><script type="module" src="/enhancements.js"></script><script defer src="/winlink.js"></script><script defer src="/mission.js"></script><script defer src="/attachments.js"></script><link rel="stylesheet" href="/monitor.css"><script defer src="/monitor.js"></script></head>
|
<html lang="it"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#101916"><title>BPQ — Radio & BBS</title><link rel="stylesheet" href="/style.css"><link rel="stylesheet" href="/dark.css"><link rel="stylesheet" href="/mission.css"><script defer src="/app.js"></script><script type="module" src="/enhancements.js"></script><script defer src="/winlink.js"></script><script defer src="/mission.js"></script><script defer src="/attachments.js"></script><link rel="stylesheet" href="/monitor.css"><script defer src="/monitor.js"></script></head>
|
||||||
<body>
|
<body>
|
||||||
<section id="login" class="login-screen"><div class="login-art"><span class="eyebrow">SENAGO · JN45NN</span><h1>ALNODE<br><em>Radio Console</em></h1><div class="signal-art"><i></i><i></i><i></i><i></i><b>IU2EUG</b></div><p>IU2EUG · Senago · JN45NN</p></div><form id="login-form" class="login-card"><span class="brand">◉ ALNODE<span>CONSOLE</span></span><h2>Benvenuto in stazione.</h2><p>Accedi con l’utente e la password Telnet del tuo BPQ.</p><label>Utente<input name="user" autocomplete="username" required placeholder="Il tuo utente BPQ"></label><label>Password<input name="password" type="password" autocomplete="current-password" required></label><button class="primary" type="submit">Entra nel pannello <span>→</span></button><div id="login-error" class="error" role="alert"></div><small>Accesso sysop IU2EUG · PC e rete locale</small></form></section>
|
<section id="login" class="login-screen"><div class="login-art"><span class="eyebrow">BPQ NETWORK</span><h1>BPQ<br><em>Radio Console</em></h1><div class="signal-art"><i></i><i></i><i></i><i></i><b>STAZIONE</b></div><p>La tua stazione, in un unico pannello.</p></div><form id="login-form" class="login-card"><span class="brand">◉ BPQ<span>CONSOLE</span></span><h2>Benvenuto in stazione.</h2><p>Accedi con l’utente e la password Telnet del tuo BPQ.</p><label>Utente<input name="user" autocomplete="username" required placeholder="Il tuo utente BPQ"></label><label>Password<input name="password" type="password" autocomplete="current-password" required></label><button class="primary" type="submit">Entra nel pannello <span>→</span></button><div id="login-error" class="error" role="alert"></div><small>Created by IU2EUG · PC e rete locale</small></form></section>
|
||||||
<div id="shell" hidden><aside class="sidebar"><a class="brand" href="#home">◉ ALNODE<span>RADIO CONSOLE</span></a><div class="side-label">LA TUA STAZIONE</div><nav><button data-page="home" class="active"><span>▦</span> Panoramica</button><button data-page="bbs"><span>▤</span> BBS <b id="nav-count">—</b></button><button data-page="network"><span>⌘</span> Rete & nodi</button></nav><div class="side-station"><span class="dot"></span> IU2EUG-7<small>Senago, Italia · JN45NN</small><div class="side-frequency">40 m <span>7.050 MHz</span><br>20 m <span>14.122 MHz</span></div><small>USB · VARA HF 2300<br>07:00 — 00:00 · Roma</small></div><div class="profile"><div class="avatar">AE</div><div>Alberto<small>IU2EUG · Sysop</small></div><button id="logout" title="Esci" aria-label="Esci dal pannello">↗</button></div></aside>
|
<div id="shell" hidden><aside class="sidebar"><a class="brand" href="#home">◉ BPQ<span>RADIO CONSOLE</span></a><div class="side-label">LA TUA STAZIONE</div><nav><button data-page="home" class="active"><span>▦</span> Panoramica</button><button data-page="bbs"><span>▤</span> BBS <b id="nav-count">—</b></button><button data-page="network"><span>⌘</span> Rete & nodi</button></nav><div class="side-station">Stazione BPQ</div><div class="profile"><div class="avatar">BP</div><div>Sysop<small>BPQ</small></div><button id="logout" title="Esci" aria-label="Esci dal pannello">↗</button></div></aside>
|
||||||
<main><header class="topbar"><span id="breadcrumb">Stazione / Panoramica</span><div><span id="connection" class="live-badge">● Collegamento…</span><button id="refresh" class="icon-button" aria-label="Aggiorna dati">↻</button><span id="clock"></span></div></header><div id="notice" hidden class="notice" role="status"></div>
|
<main><header class="topbar"><span id="breadcrumb">Stazione / Panoramica</span><div><span id="connection" class="live-badge">● Collegamento…</span><button id="refresh" class="icon-button" aria-label="Aggiorna dati">↻</button><span id="clock"></span></div></header><div id="notice" hidden class="notice" role="status"></div>
|
||||||
<section id="home" class="page"><div class="page-heading"><div><span class="eyebrow">IL TUO PUNTO SULLA RETE</span><h1>Panoramica</h1><p>Radio, messaggi e collegamenti. Tutto nello stesso posto.</p></div><button class="primary compose-button">+ Nuovo messaggio</button></div>
|
<section id="home" class="page"><div class="page-heading"><div><span class="eyebrow">IL TUO PUNTO SULLA RETE</span><h1>Panoramica</h1><p>Radio, messaggi e collegamenti. Tutto nello stesso posto.</p></div><button class="primary compose-button">+ Nuovo messaggio</button></div>
|
||||||
<div class="metrics"><article><span>Messaggi nella BBS</span><strong id="k-messages">—</strong><small id="k-message-detail">In attesa di BPQ</small><i>▤</i></article><article><span>Nodi conosciuti</span><strong id="k-nodes">—</strong><small>Destinazioni NET/ROM</small><i>⌘</i></article><article><span>Collegamenti attivi</span><strong id="k-routes">—</strong><small>Vicini sulla rete AXUDP</small><i>↔</i></article><article><span>Ultimo sync BBS</span><strong id="k-sync">—</strong><small id="k-sync-detail">Nessuno rilevato oggi</small><i>↻</i></article></div>
|
<div class="metrics"><article><span>Messaggi nella BBS</span><strong id="k-messages">—</strong><small id="k-message-detail">In attesa di BPQ</small><i>▤</i></article><article><span>Nodi conosciuti</span><strong id="k-nodes">—</strong><small>Destinazioni NET/ROM</small><i>⌘</i></article><article><span>Collegamenti attivi</span><strong id="k-routes">—</strong><small>Vicini sulla rete BPQ</small><i>↔</i></article><article><span>Ultimo sync BBS</span><strong id="k-sync">—</strong><small id="k-sync-detail">Nessuno rilevato oggi</small><i>↻</i></article></div>
|
||||||
<div class="overview-grid"><article class="radio-card"><div class="card-header"><span class="eyebrow">ON AIR / FT-991A</span><span id="radio-status" class="tag">—</span></div><div class="radio-frequency"><span id="radio-freq">—</span><small>MHz / USB</small></div><div class="waveform" aria-hidden="true"></div><div class="radio-details"><div><span>Modem</span><b id="radio-modem">—</b></div><div><span>Canale</span><b id="radio-channel">—</b></div><div><span>S/N ultima sessione</span><b id="radio-snr">—</b></div></div><footer><span id="radio-scan">—</span><span>40 m ↔ 20 m</span></footer></article>
|
<div class="overview-grid"><article class="radio-card"><div class="card-header"><span class="eyebrow">PORTA RADIO</span><span id="radio-status" class="tag">—</span></div><div class="radio-frequency"><span id="radio-freq">—</span><small>MHz / USB</small></div><div class="waveform" aria-hidden="true"></div><div class="radio-details"><div><span>Modem</span><b id="radio-modem">—</b></div><div><span>Canale</span><b id="radio-channel">—</b></div><div><span>S/N ultima sessione</span><b id="radio-snr">—</b></div></div><footer><span id="radio-scan">—</span><span>Stato BPQ</span></footer></article>
|
||||||
<article class="card services-card"><div class="card-header"><h2>Servizi della stazione</h2><span class="muted">IU2EUG</span></div><button data-page="bbs" class="service"><span class="service-icon">▤</span><div><b>BBS & bollettini</b><small>Leggi, scrivi e condividi via radio</small></div><span class="service-call">IU2EUG-11 ↗</span></button><div class="service"><span class="service-icon">◇</span><div><b>Chat di rete</b><small>Accesso dal nodo con CHAT</small></div><span class="service-call">IU2EUG-12</span></div><div class="service"><span class="service-icon">↗</span><div><b>Gateway Winlink</b><small>Posta radio verso il CMS</small></div><span class="service-call">IU2EUG</span></div><div class="service"><span class="service-icon">⌘</span><div><b>Nodo interattivo</b><small>NET/ROM, ARICHAT e DX Cluster</small></div><span class="service-call">IU2EUG-7</span></div></article></div>
|
<article class="card services-card"><div class="card-header"><h2>Servizi della stazione</h2><span class="muted">STAZIONE</span></div><button data-page="bbs" class="service"><span class="service-icon">▤</span><div><b>BBS & bollettini</b><small>Leggi, scrivi e condividi via radio</small></div><span class="service-call">BBS ↗</span></button><div class="service"><span class="service-icon">◇</span><div><b>Chat di rete</b><small>Accesso dal nodo con CHAT</small></div><span class="service-call">CHAT</span></div><div class="service"><span class="service-icon">↗</span><div><b>Gateway Winlink</b><small>Posta radio verso il CMS</small></div><span class="service-call">STAZIONE</span></div><div class="service"><span class="service-icon">⌘</span><div><b>Nodo interattivo</b><small>Servizi configurati nel nodo</small></div><span class="service-call">NODO</span></div></article></div>
|
||||||
<div class="bottom-grid"><article class="card"><div class="card-header"><h2>Arrivati nella BBS</h2><button data-page="bbs" class="text-button">Apri BBS →</button></div><div id="recent-list" class="recent-list"></div></article><article class="card"><div class="card-header"><h2>Attività forwarding</h2><span class="tag">OGGI</span></div><div id="activity-list" class="activity-list"></div><button id="sync-open" class="secondary full">↻ Sincronizza con IW2OHX</button></article></div>
|
<div class="bottom-grid"><article class="card"><div class="card-header"><h2>Arrivati nella BBS</h2><button data-page="bbs" class="text-button">Apri BBS →</button></div><div id="recent-list" class="recent-list"></div></article><article class="card"><div class="card-header"><h2>Attività forwarding</h2><span class="tag">OGGI</span></div><div id="activity-list" class="activity-list"></div><button id="sync-open" class="secondary full">↻ Sincronizza con nodo remoto</button></article></div>
|
||||||
<footer class="page-footer">ALNODE · IU2EUG · Senago <span id="updated">—</span></footer></section>
|
<footer class="page-footer">BPQ Console · <span id="updated">—</span></footer></section>
|
||||||
<section id="bbs" class="page" hidden><div class="page-heading"><div><span class="eyebrow">ALBBS / IU2EUG-11</span><h1>BBS</h1><p>Bollettini dalla rete e messaggi personali, finalmente leggibili.</p></div><button class="primary compose-button">+ Nuovo messaggio</button></div><div class="mail-toolbar"><div class="tabs"><button class="active" data-filter="all">Tutti</button><button data-filter="B">Bollettini</button><button data-filter="P">Personali</button><button data-filter="sent">Inviati</button></div><input id="search" type="search" placeholder="Cerca oggetto, nominativo o categoria…" aria-label="Cerca messaggi"><select id="category" aria-label="Categoria"><option value="">Tutte le categorie</option></select></div><div class="mail-layout"><div class="card mail-list"><div class="mail-list-heading"><span id="list-count">— messaggi</span><span>Più recenti prima</span></div><div class="mail-columns" aria-hidden="true"><span></span><span>Da</span><span>Oggetto</span><span>Categoria</span><span>Ricevuto · data e ora</span><span>Dimensione</span><span>Stato</span></div><div id="message-list" class="mail-rows"></div></div><article class="card reader" id="reader"><div class="reader-empty"><span>▤</span><h2>Una finestra sulla rete.</h2><p>Scegli un messaggio per leggerlo qui.</p></div></article></div></section>
|
<section id="bbs" class="page" hidden><div class="page-heading"><div><span class="eyebrow">BBS / BBS</span><h1>BBS</h1><p>Bollettini dalla rete e messaggi personali, finalmente leggibili.</p></div><button class="primary compose-button">+ Nuovo messaggio</button></div><div class="mail-toolbar"><div class="tabs"><button class="active" data-filter="all">Tutti</button><button data-filter="B">Bollettini</button><button data-filter="P">Personali</button><button data-filter="sent">Inviati</button></div><input id="search" type="search" placeholder="Cerca oggetto, nominativo o categoria…" aria-label="Cerca messaggi"><select id="category" aria-label="Categoria"><option value="">Tutte le categorie</option></select></div><div class="mail-layout"><div class="card mail-list"><div class="mail-list-heading"><span id="list-count">— messaggi</span><span>Più recenti prima</span></div><div class="mail-columns" aria-hidden="true"><span></span><span>Da</span><span>Oggetto</span><span>Categoria</span><span>Ricevuto · data e ora</span><span>Dimensione</span><span>Stato</span></div><div id="message-list" class="mail-rows"></div></div><article class="card reader" id="reader"><div class="reader-empty"><span>▤</span><h2>Una finestra sulla rete.</h2><p>Scegli un messaggio per leggerlo qui.</p></div></article></div></section>
|
||||||
<section id="network" class="page" hidden><div class="page-heading"><div><span class="eyebrow">AXUDP / NET-ROM</span><h1>Rete</h1><p>Collegamenti Internet e destinazioni annunciate al tuo nodo.</p></div></div><article class="card"><div class="card-header"><h2>Rotte verso i vicini</h2><span class="tag">DATI BPQ</span></div><div class="table-wrap"><table><thead><tr><th>Nodo</th><th>Stato</th><th>Porta</th><th>Qualità</th><th>Destinazioni</th><th>Frame</th><th>Retry</th></tr></thead><tbody id="routes"></tbody></table></div></article><article class="card nodes-card"><div class="card-header"><h2>Destinazioni conosciute</h2><span id="node-total" class="muted"></span></div><div id="nodes" class="node-grid"></div></article><p class="network-note">Le tabelle viaggiano su AXUDP. Il forwarding BBS con IW2OHX usa invece VARA HF.</p></section>
|
<section id="network" class="page" hidden><div class="page-heading"><div><span class="eyebrow">NET/ROM</span><h1>Rete</h1><p>Collegamenti Internet e destinazioni annunciate al tuo nodo.</p></div></div><article class="card"><div class="card-header"><h2>Rotte verso i vicini</h2><span class="tag">DATI BPQ</span></div><div class="table-wrap"><table><thead><tr><th>Nodo</th><th>Stato</th><th>Porta</th><th>Qualità</th><th>Destinazioni</th><th>Frame</th><th>Retry</th></tr></thead><tbody id="routes"></tbody></table></div></article><article class="card nodes-card"><div class="card-header"><h2>Destinazioni conosciute</h2><span id="node-total" class="muted"></span></div><div id="nodes" class="node-grid"></div></article><p class="network-note">Rotte e destinazioni rilevate da BPQ.</p></section>
|
||||||
</main></div>
|
</main></div>
|
||||||
<dialog id="compose"><form id="compose-form"><div class="dialog-heading"><div><span class="eyebrow">ALBBS / IU2EUG</span><h2>Nuovo messaggio</h2></div><button type="button" class="icon-button close-compose" aria-label="Chiudi">×</button></div><div class="compose-row"><label>Destinatario<input name="to" required maxlength="80" placeholder="IW2OHX oppure [email protected]"></label><label>Tipo<select name="type"><option value="P">Messaggio personale</option><option value="B">Bollettino</option></select></label></div><label>Oggetto<input name="subject" required maxlength="80" placeholder="Di cosa vuoi parlare?"></label><label>Messaggio<textarea name="text" required rows="11" placeholder="Scrivi il tuo messaggio…"></textarea></label><p class="compose-help">Il messaggio sarà salvato nella BBS come IU2EUG. L’inoltro segue le rotte configurate in BPQ.</p><div id="compose-error" class="error" role="alert"></div><footer><button type="button" class="secondary close-compose">Annulla</button><button id="send-button" class="primary" type="submit">Salva e metti in coda →</button></footer></form></dialog>
|
<dialog id="compose"><form id="compose-form"><div class="dialog-heading"><div><span class="eyebrow">BBS / STAZIONE</span><h2>Nuovo messaggio</h2></div><button type="button" class="icon-button close-compose" aria-label="Chiudi">×</button></div><div class="compose-row"><label>Destinatario<input name="to" required maxlength="80" placeholder="Nominativo oppure indirizzo email"></label><label>Tipo<select name="type"><option value="P">Messaggio personale</option><option value="B">Bollettino</option></select></label></div><label>Oggetto<input name="subject" required maxlength="80" placeholder="Di cosa vuoi parlare?"></label><label>Messaggio<textarea name="text" required rows="11" placeholder="Scrivi il tuo messaggio…"></textarea></label><p class="compose-help">Il messaggio sarà salvato nella BBS come STAZIONE. L’inoltro segue le rotte configurate in BPQ.</p><div id="compose-error" class="error" role="alert"></div><footer><button type="button" class="secondary close-compose">Annulla</button><button id="send-button" class="primary" type="submit">Salva e metti in coda →</button></footer></form></dialog>
|
||||||
<dialog id="sync-dialog"><h2>Chiamare IW2OHX via radio?</h2><p>BPQ eseguirà il profilo di forwarding sui 20 metri. Questo comando avvia una trasmissione radio e usa i parametri configurati, incluso OVERRIDEBUSY.</p><footer><button class="secondary" id="sync-cancel">Annulla</button><button class="primary" id="sync-confirm">Avvia chiamata</button></footer></dialog>
|
<dialog id="sync-dialog"><h2>Chiamare nodo remoto via radio?</h2><p>BPQ eseguirà il profilo di forwarding selezionato. Il profilo può avviare una trasmissione radio.</p><footer><button class="secondary" id="sync-cancel">Annulla</button><button class="primary" id="sync-confirm">Avvia chiamata</button></footer></dialog>
|
||||||
<div id="toast" role="status" hidden></div>
|
<div id="toast" role="status" hidden></div>
|
||||||
</body></html>
|
</body></html>
|
||||||
+3
-3
@@ -1,9 +1,9 @@
|
|||||||
let modemTelemetry=null,modemPolling=false;
|
let modemTelemetry=null,modemPolling=false;
|
||||||
const radioCard=$('.radio-card');radioCard.innerHTML=`<div class="modem-top"><span class="modem-brand">VARA <small>HF / FT-991A</small></span><span id="radio-status" class="tag">—</span></div><div id="modem-session" class="modem-session idle"><span class="session-label" id="session-label">STAZIONE IN ASCOLTO</span><div class="callsign-pair"><div><small id="caller-label">NODO LOCALE</small><b id="caller-call">IU2EUG</b></div><span id="call-arrow">◉</span><div><small id="called-label">ALIAS</small><b id="called-call">ALNODE</b></div></div><div id="session-detail">40 m / 20 m · USB</div></div><div class="modem-frequency"><div><span id="radio-freq">—</span><small>MHz</small></div><span id="radio-scan">—</span><span id="radio-channel">—</span></div><div class="telemetry-grid"><article><header><span>BITRATE VARA</span><b><span id="bps-value">—</span><small> bit/s</small></b></header><div id="bps-chart" class="telemetry-chart"></div><footer><span class="tx-key">TX</span><span class="rx-key">RX</span><span id="bps-caption">Velocità del modem</span></footer></article><article><header><span>SNR / BPQ</span><b id="snr-value">—</b></header><div id="snr-chart" class="telemetry-chart"></div><footer><span id="snr-caption">Campioni durante le connessioni</span></footer></article><article><header><span>CPU VARA</span><b id="vara-cpu-value">—</b></header><div id="vara-cpu-chart" class="telemetry-chart"></div><footer><span>Processo modem · ogni 5 s</span></footer></article><article><header><span>CPU SISTEMA</span><b id="system-cpu-value">—</b></header><div id="system-cpu-chart" class="telemetry-chart"></div><footer><span>Carico totale del PC</span></footer></article></div><div class="modem-bottom"><span id="radio-modem">VARA HF 2300</span><span>SNR ultima sessione <b id="radio-snr">—</b></span><span id="modem-traffic">TX — / RX —</span></div>`;
|
const radioCard=$('.radio-card');radioCard.innerHTML=`<div class="modem-top"><span class="modem-brand">BPQ <small>MODEM</small></span><span id="radio-status" class="tag">—</span></div><div id="modem-session" class="modem-session idle"><span class="session-label" id="session-label">STAZIONE IN ASCOLTO</span><div class="callsign-pair"><div><small id="caller-label">NODO LOCALE</small><b id="caller-call">STAZIONE</b></div><span id="call-arrow">◉</span><div><small id="called-label">ALIAS</small><b id="called-call">BPQ</b></div></div><div id="session-detail">Porta radio BPQ</div></div><div class="modem-frequency"><div><span id="radio-freq">—</span><small>MHz</small></div><span id="radio-scan">—</span><span id="radio-channel">—</span></div><div class="telemetry-grid"><article><header><span>BITRATE VARA</span><b><span id="bps-value">—</span><small> bit/s</small></b></header><div id="bps-chart" class="telemetry-chart"></div><footer><span class="tx-key">TX</span><span class="rx-key">RX</span><span id="bps-caption">Velocità del modem</span></footer></article><article><header><span>SNR / BPQ</span><b id="snr-value">—</b></header><div id="snr-chart" class="telemetry-chart"></div><footer><span id="snr-caption">Campioni durante le connessioni</span></footer></article><article><header><span>CPU VARA</span><b id="vara-cpu-value">—</b></header><div id="vara-cpu-chart" class="telemetry-chart"></div><footer><span>Processo modem · ogni 5 s</span></footer></article><article><header><span>CPU SISTEMA</span><b id="system-cpu-value">—</b></header><div id="system-cpu-chart" class="telemetry-chart"></div><footer><span>Carico totale del PC</span></footer></article></div><div class="modem-bottom"><span id="radio-modem">Modem BPQ</span><span>SNR ultima sessione <b id="radio-snr">—</b></span><span id="modem-traffic">TX — / RX —</span></div>`;
|
||||||
const missionHead=document.createElement('div');missionHead.className='mission-heading';missionHead.innerHTML='<div><span class="mission-kicker">RADIO OPERATIONS</span><h1>IU2EUG<span> / ALNODE</span></h1></div><div class="mission-location"><span class="dot"></span> SENAGO · JN45NN <small>07:00 — 00:00 ROMA</small></div>';
|
const missionHead=document.createElement('div');missionHead.className='mission-heading';missionHead.innerHTML='<div><span class="mission-kicker">RADIO OPERATIONS</span><h1>STAZIONE<span> / BPQ</span></h1></div><div class="mission-location"><span class="dot"></span> STAZIONE BPQ <small></small></div>';
|
||||||
$('#home .page-heading').replaceWith(missionHead);
|
$('#home .page-heading').replaceWith(missionHead);
|
||||||
function graph(history,keys,id,minimum=1){const width=350,height=85,pad=5;const values=history.flatMap(s=>keys.map(k=>s[k])).filter(v=>typeof v==='number'&&Number.isFinite(v));if(!values.length)return '<div class="graph-empty">Nessun campione disponibile</div>';const min=Math.min(0,...values),max=Math.max(minimum,...values),range=max-min||1;const x=i=>pad+i*(width-pad*2)/Math.max(1,history.length-1),y=v=>height-pad-(v-min)*(height-pad*2)/range;const lines=keys.map((key,j)=>{let path='',breakLine=true;history.forEach((s,i)=>{const value=s[key];if(typeof value!=='number'||!Number.isFinite(value)){breakLine=true;return;}path+=(breakLine?'M':'L')+x(i).toFixed(2)+' '+y(value).toFixed(2)+' ';breakLine=false;});return `<path class="graph-line line-${j}" d="${path}"/>`}).join('');return `<svg viewBox="0 0 ${width} ${height}" preserveAspectRatio="none" role="img" aria-label="Grafico ${esc(id)}"><path class="graph-grid" d="M0 20 H350 M0 45 H350 M0 70 H350"/>${lines}</svg>`;}
|
function graph(history,keys,id,minimum=1){const width=350,height=85,pad=5;const values=history.flatMap(s=>keys.map(k=>s[k])).filter(v=>typeof v==='number'&&Number.isFinite(v));if(!values.length)return '<div class="graph-empty">Nessun campione disponibile</div>';const min=Math.min(0,...values),max=Math.max(minimum,...values),range=max-min||1;const x=i=>pad+i*(width-pad*2)/Math.max(1,history.length-1),y=v=>height-pad-(v-min)*(height-pad*2)/range;const lines=keys.map((key,j)=>{let path='',breakLine=true;history.forEach((s,i)=>{const value=s[key];if(typeof value!=='number'||!Number.isFinite(value)){breakLine=true;return;}path+=(breakLine?'M':'L')+x(i).toFixed(2)+' '+y(value).toFixed(2)+' ';breakLine=false;});return `<path class="graph-line line-${j}" d="${path}"/>`}).join('');return `<svg viewBox="0 0 ${width} ${height}" preserveAspectRatio="none" role="img" aria-label="Grafico ${esc(id)}"><path class="graph-grid" d="M0 20 H350 M0 45 H350 M0 70 H350"/>${lines}</svg>`;}
|
||||||
function renderTelemetry(data){modemTelemetry=data;const c=data.current;if(!c)return;const history=data.history.slice(-120);$('#radio-status').textContent=!c.available?'OFFLINE':c.active?'LINK ATTIVO':'IN ASCOLTO';$('#modem-session').classList.toggle('idle',!c.active);$('#modem-session').classList.toggle('connected',!!c.active);$('#session-label').textContent=c.connecting?'CHIAMATA IN CORSO':c.active?'CONNESSIONE RADIO':'STAZIONE IN ASCOLTO';$('#caller-call').textContent=c.active?c.caller||'—':'IU2EUG';$('#called-call').textContent=c.active?c.called||'—':'ALNODE';$('#call-arrow').textContent=c.active?'→':'◉';$('#caller-label').textContent=c.active?'CHIAMANTE':'NODO LOCALE';$('#called-label').textContent=c.active?'CHIAMATO':'ALIAS';$('#session-detail').textContent=c.active?(c.connecting?'Attendo risposta':/^IU2EUG/i.test(c.caller||'')?'Chiamata in uscita':'Chiamata in ingresso'):'VARA HF · scansione 40 / 20 metri';$('#radio-freq').textContent=c.frequency||'—';$('#radio-scan').textContent=c.scan?'● Scansione attiva':c.active?'● Frequenza bloccata':'—';$('#radio-channel').textContent=c.available?(c.busy?'Canale occupato':'Canale libero'):'—';$('#radio-modem').textContent=c.available?'VARA HF 2300':'Modem non disponibile';$('#radio-snr').textContent=c.lastSnr!=null?c.lastSnr.toFixed(1)+' dB':'—';$('#bps-value').textContent=c.nativeRate?.bps!=null?Math.round(c.nativeRate.bps).toLocaleString('it-IT'):c.available&&!c.active?'0':'—';$('#bps-caption').textContent=!c.nativeRate?.listening?'Telemetria VARA non disponibile':!c.active?'In attesa della connessione':c.nativeRate?.bps==null?'In attesa del bitrate VARA':(c.nativeRate.direction||'Modem')+(c.nativeRate.level?' · livello '+c.nativeRate.level:'');$('#snr-value').textContent=c.snr!=null?c.snr.toFixed(1)+' dB':'—';$('#vara-cpu-value').textContent=c.varaCpu!=null?c.varaCpu.toFixed(1)+'%':'—';$('#system-cpu-value').textContent=c.cpu!=null?c.cpu.toFixed(1)+'%':'—';$('#snr-caption').textContent=c.active?'SNR esposto da BPQ':'In attesa della prossima connessione';$('#modem-traffic').textContent='TX '+size(c.sent||0)+' / RX '+size(c.received||0);$('#bps-chart').innerHTML=graph(history,['varaTxBps','varaRxBps'],'bitrate VARA TX RX',100);$('#snr-chart').innerHTML=graph(history,['snr'],'SNR',10);$('#vara-cpu-chart').innerHTML=graph(history,['varaCpu'],'CPU VARA',5);$('#system-cpu-chart').innerHTML=graph(history,['cpu'],'CPU sistema',10);}
|
function renderTelemetry(data){modemTelemetry=data;const c=data.current;if(!c)return;const history=data.history.slice(-120);$('#radio-status').textContent=!c.available?'OFFLINE':c.active?'LINK ATTIVO':'IN ASCOLTO';$('#modem-session').classList.toggle('idle',!c.active);$('#modem-session').classList.toggle('connected',!!c.active);$('#session-label').textContent=c.connecting?'CHIAMATA IN CORSO':c.active?'CONNESSIONE RADIO':'STAZIONE IN ASCOLTO';$('#caller-call').textContent=c.active?c.caller||'—':station.nodeCall;$('#called-call').textContent=c.active?c.called||'—':station.alias;$('#call-arrow').textContent=c.active?'→':'◉';$('#caller-label').textContent=c.active?'CHIAMANTE':'NODO LOCALE';$('#called-label').textContent=c.active?'CHIAMATO':'ALIAS';$('#session-detail').textContent=c.active?(c.connecting?'Attendo risposta':(c.caller||'').replace(/-\d+$/,'')===station.call.replace(/-\d+$/,'')?'Chiamata in uscita':'Chiamata in ingresso'):station.radio?.name||'Nessuna porta modem configurata';$('#radio-freq').textContent=c.frequency||'—';$('#radio-scan').textContent=c.scan?'● Scansione attiva':c.active?'● Frequenza bloccata':'—';$('#radio-channel').textContent=c.available?(c.busy?'Canale occupato':'Canale libero'):'—';$('#radio-modem').textContent=c.available?station.radio?.name||'Modem BPQ':'Modem non disponibile';$('#radio-snr').textContent=c.lastSnr!=null?c.lastSnr.toFixed(1)+' dB':'—';$('#bps-value').textContent=c.nativeRate?.bps!=null?Math.round(c.nativeRate.bps).toLocaleString('it-IT'):c.available&&!c.active?'0':'—';$('#bps-caption').textContent=!c.nativeRate?.listening?'Telemetria VARA non disponibile':!c.active?'In attesa della connessione':c.nativeRate?.bps==null?'In attesa del bitrate VARA':(c.nativeRate.direction||'Modem')+(c.nativeRate.level?' · livello '+c.nativeRate.level:'');$('#snr-value').textContent=c.snr!=null?c.snr.toFixed(1)+' dB':'—';$('#vara-cpu-value').textContent=c.varaCpu!=null?c.varaCpu.toFixed(1)+'%':'—';$('#system-cpu-value').textContent=c.cpu!=null?c.cpu.toFixed(1)+'%':'—';$('#snr-caption').textContent=c.active?'SNR esposto da BPQ':'In attesa della prossima connessione';$('#modem-traffic').textContent='TX '+size(c.sent||0)+' / RX '+size(c.received||0);$('#bps-chart').innerHTML=graph(history,['varaTxBps','varaRxBps'],'bitrate VARA TX RX',100);$('#snr-chart').innerHTML=graph(history,['snr'],'SNR',10);$('#vara-cpu-chart').innerHTML=graph(history,['varaCpu'],'CPU VARA',5);$('#system-cpu-chart').innerHTML=graph(history,['cpu'],'CPU sistema',10);}
|
||||||
async function pollTelemetry(){if(!csrf||modemPolling)return;modemPolling=true;try{renderTelemetry(await api('/telemetry'))}catch{}finally{modemPolling=false}}
|
async function pollTelemetry(){if(!csrf||modemPolling)return;modemPolling=true;try{renderTelemetry(await api('/telemetry'))}catch{}finally{modemPolling=false}}
|
||||||
const missionDashboard=loadDashboard;loadDashboard=async function(){await missionDashboard();if(modemTelemetry)renderTelemetry(modemTelemetry);pollTelemetry();};setInterval(()=>{if(csrf&&!document.hidden)pollTelemetry()},2000);pollTelemetry();
|
const missionDashboard=loadDashboard;loadDashboard=async function(){await missionDashboard();if(modemTelemetry)renderTelemetry(modemTelemetry);pollTelemetry();};setInterval(()=>{if(csrf&&!document.hidden)pollTelemetry()},2000);pollTelemetry();
|
||||||
const fullscreenButton=document.createElement('button');fullscreenButton.id='fullscreen-toggle';fullscreenButton.className='icon-button';fullscreenButton.textContent='⛶';fullscreenButton.setAttribute('aria-label','Schermo intero');fullscreenButton.title='Schermo intero';$('#refresh').after(fullscreenButton);
|
const fullscreenButton=document.createElement('button');fullscreenButton.id='fullscreen-toggle';fullscreenButton.className='icon-button';fullscreenButton.textContent='⛶';fullscreenButton.setAttribute('aria-label','Schermo intero');fullscreenButton.title='Schermo intero';$('#refresh').after(fullscreenButton);
|
||||||
|
|||||||
+1
-1
@@ -12,7 +12,7 @@ $('#monitor-stop').onclick=async()=>{try{await api('/monitor/disconnect',{method
|
|||||||
$('#monitor-pause').onclick=()=>{paused=!paused;$('#monitor-pause').textContent=paused?'Riprendi':'Pausa';if(!paused)render();else $('#monitor-count').textContent+=' · visualizzazione in pausa';};
|
$('#monitor-pause').onclick=()=>{paused=!paused;$('#monitor-pause').textContent=paused?'Riprendi':'Pausa';if(!paused)render();else $('#monitor-count').textContent+=' · visualizzazione in pausa';};
|
||||||
$('#monitor-clear').onclick=()=>{events=[];render();};
|
$('#monitor-clear').onclick=()=>{events=[];render();};
|
||||||
for(const id of ['monitor-port','monitor-direction','monitor-search'])$('#'+id).addEventListener('input',()=>{if(!paused)render()});
|
for(const id of ['monitor-port','monitor-direction','monitor-search'])$('#'+id).addEventListener('input',()=>{if(!paused)render()});
|
||||||
$('#monitor-export').onclick=()=>{const list=filtered();if(!list.length){toast('Nessun frame da scaricare');return;}const blob=new Blob([list.map(e=>`[${e.at}] ${e.direction} P${e.port||'?'}\n${e.text}\n`).join('\n')],{type:'text/plain;charset=utf-8'}),url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download='ALNODE-monitor-'+new Date().toISOString().replace(/[:.]/g,'-')+'.txt';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
|
$('#monitor-export').onclick=()=>{const list=filtered();if(!list.length){toast('Nessun frame da scaricare');return;}const blob=new Blob([list.map(e=>`[${e.at}] ${e.direction} P${e.port||'?'}\n${e.text}\n`).join('\n')],{type:'text/plain;charset=utf-8'}),url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download='BPQ-monitor-'+new Date().toISOString().replace(/[:.]/g,'-')+'.txt';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
|
||||||
setInterval(()=>{if(csrf&&page==='monitor')poll()},1000);
|
setInterval(()=>{if(csrf&&page==='monitor')poll()},1000);
|
||||||
window.addEventListener('hashchange',()=>{if(location.hash==='#monitor')navigate('monitor')});
|
window.addEventListener('hashchange',()=>{if(location.hash==='#monitor')navigate('monitor')});
|
||||||
if(location.hash==='#monitor')navigate('monitor');
|
if(location.hash==='#monitor')navigate('monitor');
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
export function incoming(messages,known,call='IU2EUG'){
|
export function incoming(messages,known,call=''){
|
||||||
if(!known)return {bulletins:[],mail:[]};
|
if(!known)return {bulletins:[],mail:[]};
|
||||||
const fresh=messages.filter(m=>!known.has(m.id)&&m.from!==call);
|
const fresh=messages.filter(m=>!known.has(m.id)&&m.from!==call);
|
||||||
return {bulletins:fresh.filter(m=>m.type==='B'),mail:fresh.filter(m=>m.type==='P'||m.type==='T')};
|
return {bulletins:fresh.filter(m=>m.type==='B'),mail:fresh.filter(m=>m.type==='P'||m.type==='T')};
|
||||||
|
|||||||
+2
-2
@@ -1,13 +1,13 @@
|
|||||||
let wlData=null,wlFolder='inbox',wlSelected=null,wlLoading=false,wlGeneration=0,wlCompose=false;
|
let wlData=null,wlFolder='inbox',wlSelected=null,wlLoading=false,wlGeneration=0,wlCompose=false;
|
||||||
const wlNav=document.createElement('button');wlNav.dataset.page='winlink';wlNav.innerHTML='<span>✉</span> Winlink';wlNav.onclick=()=>navigate('winlink');$('nav').insertBefore(wlNav,$('nav').children[2]);
|
const wlNav=document.createElement('button');wlNav.dataset.page='winlink';wlNav.innerHTML='<span>✉</span> Winlink';wlNav.onclick=()=>navigate('winlink');$('nav').insertBefore(wlNav,$('nav').children[2]);
|
||||||
const wlPage=document.createElement('section');wlPage.className='page';wlPage.id='winlink';wlPage.hidden=true;wlPage.innerHTML=`<div class="chat-heading"><div><h1>Winlink</h1><p class="wl-account">[email protected]</p></div><div class="chat-actions"><button id="wl-sync" class="secondary">↻ Aggiorna mail</button><button id="wl-compose" class="primary">+ Nuova email</button></div></div><div class="wl-status"><span id="wl-sync-state">—</span><span id="wl-sync-time"></span><span>CMS · Internet</span></div><div class="mail-toolbar"><div class="tabs"><button data-wlfolder="inbox" class="active">Ricevute</button><button data-wlfolder="sent">Inviate</button><button data-wlfolder="queue">In coda</button><button data-wlfolder="all">Tutte</button></div><input id="wl-search" type="search" aria-label="Cerca email" placeholder="Cerca email…"></div><div class="mail-layout"><div class="card mail-list"><div class="mail-list-heading"><span id="wl-count">—</span><span>Più recenti prima</span></div><div class="mail-columns" aria-hidden="true"><span></span><span>Da / A</span><span>Oggetto</span><span>Categoria</span><span>Data e ora</span><span>Dimensione</span><span>Stato</span></div><div id="wl-list" class="mail-rows"></div></div><article class="card reader" id="wl-reader"><div class="reader-empty"><span>✉</span><h2>Seleziona una email</h2></div></article></div>`;$('main').append(wlPage);
|
const wlPage=document.createElement('section');wlPage.className='page';wlPage.id='winlink';wlPage.hidden=true;wlPage.innerHTML=`<div class="chat-heading"><div><h1>Winlink</h1><p class="wl-account">Posta della stazione</p></div><div class="chat-actions"><button id="wl-sync" class="secondary">↻ Aggiorna mail</button><button id="wl-compose" class="primary">+ Nuova email</button></div></div><div class="wl-status"><span id="wl-sync-state">—</span><span id="wl-sync-time"></span><span>CMS · Internet</span></div><div class="mail-toolbar"><div class="tabs"><button data-wlfolder="inbox" class="active">Ricevute</button><button data-wlfolder="sent">Inviate</button><button data-wlfolder="queue">In coda</button><button data-wlfolder="all">Tutte</button></div><input id="wl-search" type="search" aria-label="Cerca email" placeholder="Cerca email…"></div><div class="mail-layout"><div class="card mail-list"><div class="mail-list-heading"><span id="wl-count">—</span><span>Più recenti prima</span></div><div class="mail-columns" aria-hidden="true"><span></span><span>Da / A</span><span>Oggetto</span><span>Categoria</span><span>Data e ora</span><span>Dimensione</span><span>Stato</span></div><div id="wl-list" class="mail-rows"></div></div><article class="card reader" id="wl-reader"><div class="reader-empty"><span>✉</span><h2>Seleziona una email</h2></div></article></div>`;$('main').append(wlPage);
|
||||||
const wlNavigate=navigate;navigate=function(next){wlNavigate(next);if(next==='winlink'){$('#breadcrumb').textContent='Stazione / Winlink';wlLoad();}};
|
const wlNavigate=navigate;navigate=function(next){wlNavigate(next);if(next==='winlink'){$('#breadcrumb').textContent='Stazione / Winlink';wlLoad();}};
|
||||||
async function wlLoad(){if(wlLoading||!csrf)return;wlLoading=true;try{wlData=await api('/winlink');$('#wl-sync-state').textContent=wlData.sync.text;$('#wl-sync-state').className='wl-state '+wlData.sync.state;$('#wl-sync-time').textContent=wlData.sync.at?logTime(wlData.sync.at)+' · '+mailTimezone():'';wlRender();}catch(e){$('#wl-sync-state').textContent=e.message}finally{wlLoading=false}}
|
async function wlLoad(){if(wlLoading||!csrf)return;wlLoading=true;try{wlData=await api('/winlink');$('#wl-sync-state').textContent=wlData.sync.text;$('#wl-sync-state').className='wl-state '+wlData.sync.state;$('#wl-sync-time').textContent=wlData.sync.at?logTime(wlData.sync.at)+' · '+mailTimezone():'';wlRender();}catch(e){$('#wl-sync-state').textContent=e.message}finally{wlLoading=false}}
|
||||||
function wlRender(){if(!wlData)return;const q=$('#wl-search').value.toLowerCase();const list=wlData.messages.filter(m=>{return (wlFolder==='all'||m.folder===wlFolder)&&(!q||`${m.subject} ${m.fromAddress} ${m.address}`.toLowerCase().includes(q));});$('#wl-count').textContent=list.length+' email';$('#wl-list').innerHTML=list.map(m=>mailRow(m,wlSelected,'data-wlid',{from:m.direction==='outgoing'?m.address:m.fromAddress,category:'EMAIL',dateKind:m.direction==='outgoing'?'sent':'received',status:m.status==='F'?'Consegnata al CMS':m.status==='H'?'Trattenuta':m.direction==='outgoing'?'In coda':m.status==='N'?'Nuova':'Ricevuta'})).join('')||'<p class="empty">Nessuna email in questa cartella.</p>';$$('[data-wlid]').forEach(b=>b.onclick=()=>wlRead(Number(b.dataset.wlid)))}
|
function wlRender(){if(!wlData)return;const q=$('#wl-search').value.toLowerCase();const list=wlData.messages.filter(m=>{return (wlFolder==='all'||m.folder===wlFolder)&&(!q||`${m.subject} ${m.fromAddress} ${m.address}`.toLowerCase().includes(q));});$('#wl-count').textContent=list.length+' email';$('#wl-list').innerHTML=list.map(m=>mailRow(m,wlSelected,'data-wlid',{from:m.direction==='outgoing'?m.address:m.fromAddress,category:'EMAIL',dateKind:m.direction==='outgoing'?'sent':'received',status:m.status==='F'?'Consegnata al CMS':m.status==='H'?'Trattenuta':m.direction==='outgoing'?'In coda':m.status==='N'?'Nuova':'Ricevuta'})).join('')||'<p class="empty">Nessuna email in questa cartella.</p>';$$('[data-wlid]').forEach(b=>b.onclick=()=>wlRead(Number(b.dataset.wlid)))}
|
||||||
async function wlRead(id){wlSelected=id;const generation=++wlGeneration;wlRender();$('#wl-reader').innerHTML='<div class="reader-empty"><h2>Caricamento…</h2></div>';try{const m=await api('/messages/'+id);if(generation!==wlGeneration)return;const meta=wlData?.messages.find(x=>x.id===id);$('#wl-reader').innerHTML=`<div class="reader-header"><span class="tag">EMAIL · #${id}</span><h2>${esc(m.subject)}</h2><div class="reader-meta"><span>Da <b>${esc(meta?.fromAddress||m.from)}</b></span><span>A <b>${esc(meta?.address||m.to)}</b></span>${mailTimeMeta(m)}</div></div><div class="reader-body">${readableBody(m.text)}</div><footer class="reader-footer"><button id="wl-reply" class="secondary">↩ Rispondi</button><button id="wl-delete" class="danger">Elimina</button></footer>`;$('#wl-reply').onclick=()=>wlNew({to:meta?.fromAddress||m.from,subject:(/^Re:/i.test(m.subject)?m.subject:'Re: '+m.subject).slice(0,80)});$('#wl-delete').onclick=()=>askDelete(id,m.subject);}catch(e){$('#wl-reader').innerHTML=`<p class="empty">${esc(e.message)}</p>`}}
|
async function wlRead(id){wlSelected=id;const generation=++wlGeneration;wlRender();$('#wl-reader').innerHTML='<div class="reader-empty"><h2>Caricamento…</h2></div>';try{const m=await api('/messages/'+id);if(generation!==wlGeneration)return;const meta=wlData?.messages.find(x=>x.id===id);$('#wl-reader').innerHTML=`<div class="reader-header"><span class="tag">EMAIL · #${id}</span><h2>${esc(m.subject)}</h2><div class="reader-meta"><span>Da <b>${esc(meta?.fromAddress||m.from)}</b></span><span>A <b>${esc(meta?.address||m.to)}</b></span>${mailTimeMeta(m)}</div></div><div class="reader-body">${readableBody(m.text)}</div><footer class="reader-footer"><button id="wl-reply" class="secondary">↩ Rispondi</button><button id="wl-delete" class="danger">Elimina</button></footer>`;$('#wl-reply').onclick=()=>wlNew({to:meta?.fromAddress||m.from,subject:(/^Re:/i.test(m.subject)?m.subject:'Re: '+m.subject).slice(0,80)});$('#wl-delete').onclick=()=>askDelete(id,m.subject);}catch(e){$('#wl-reader').innerHTML=`<p class="empty">${esc(e.message)}</p>`}}
|
||||||
$$('[data-wlfolder]').forEach(b=>b.onclick=()=>{wlFolder=b.dataset.wlfolder;$$('[data-wlfolder]').forEach(x=>x.classList.toggle('active',x===b));wlRender()});$('#wl-search').oninput=wlRender;
|
$$('[data-wlfolder]').forEach(b=>b.onclick=()=>{wlFolder=b.dataset.wlfolder;$$('[data-wlfolder]').forEach(x=>x.classList.toggle('active',x===b));wlRender()});$('#wl-search').oninput=wlRender;
|
||||||
function wlNew(data={}){wlCompose=true;openCompose(data);$('#compose-form').elements.type.value='P';$('#compose-form').elements.type.closest('label').hidden=true;$('#compose-form').elements.to.placeholder='Nominativo Winlink oppure [email protected]';$('#compose .dialog-heading h2').textContent='Nuova email';}
|
function wlNew(data={}){wlCompose=true;openCompose(data);$('#compose-form').elements.type.value='P';$('#compose-form').elements.type.closest('label').hidden=true;$('#compose-form').elements.to.placeholder='Nominativo Winlink oppure [email protected]';$('#compose .dialog-heading h2').textContent='Nuova email';}
|
||||||
$('#wl-compose').onclick=()=>wlNew();$('#compose').addEventListener('close',()=>{wlCompose=false;$('#compose-form').elements.type.closest('label').hidden=false;$('#compose .dialog-heading h2').textContent='Nuovo messaggio';$('#compose-form').elements.to.placeholder='IW2OHX oppure [email protected]';});
|
$('#wl-compose').onclick=()=>wlNew();$('#compose').addEventListener('close',()=>{wlCompose=false;$('#compose-form').elements.type.closest('label').hidden=false;$('#compose .dialog-heading h2').textContent='Nuovo messaggio';$('#compose-form').elements.to.placeholder='Nominativo oppure indirizzo email';});
|
||||||
$('#compose-form').addEventListener('submit',e=>{if(!wlCompose)return;const field=e.target.elements.to;let address=field.value.trim().replace(/^RMS[/:]/i,'');if(!address.includes('@'))address+='@WINLINK.ORG';if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(address)){e.preventDefault();e.stopImmediatePropagation();$('#compose-error').textContent='Inserisci un nominativo Winlink o un indirizzo email valido';return;}field.value='RMS/'+address;e.target.elements.type.value='P';},true);
|
$('#compose-form').addEventListener('submit',e=>{if(!wlCompose)return;const field=e.target.elements.to;let address=field.value.trim().replace(/^RMS[/:]/i,'');if(!address.includes('@'))address+='@WINLINK.ORG';if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(address)){e.preventDefault();e.stopImmediatePropagation();$('#compose-error').textContent='Inserisci un nominativo Winlink o un indirizzo email valido';return;}field.value='RMS/'+address;e.target.elements.type.value='P';},true);
|
||||||
$('#wl-sync').onclick=async()=>{const b=$('#wl-sync');b.disabled=true;try{await api('/winlink/sync',{method:'POST',body:'{}'});$('#wl-sync-state').textContent='Sincronizzazione richiesta…';toast('Aggiornamento mail avviato via Internet');setTimeout(wlLoad,1500);setTimeout(async()=>{await wlLoad();await loadMessages()},5000);}catch(e){toast(e.message)}finally{setTimeout(()=>b.disabled=false,10000)}};
|
$('#wl-sync').onclick=async()=>{const b=$('#wl-sync');b.disabled=true;try{await api('/winlink/sync',{method:'POST',body:'{}'});$('#wl-sync-state').textContent='Sincronizzazione richiesta…';toast('Aggiornamento mail avviato via Internet');setTimeout(wlLoad,1500);setTimeout(async()=>{await wlLoad();await loadMessages()},5000);}catch(e){toast(e.message)}finally{setTimeout(()=>b.disabled=false,10000)}};
|
||||||
setInterval(()=>{if(csrf&&page==='winlink')wlLoad()},5000);
|
setInterval(()=>{if(csrf&&page==='winlink')wlLoad()},5000);
|
||||||
|
|||||||
+26
-26
@@ -1,4 +1,5 @@
|
|||||||
import http from 'node:http';
|
import http from 'node:http';
|
||||||
|
import {loadConfig,parseConfig,publicConfig,ownCall} from './config.mjs';
|
||||||
import {readFile, stat} from 'node:fs/promises';
|
import {readFile, stat} from 'node:fs/promises';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import {fileURLToPath} from 'node:url';
|
import {fileURLToPath} from 'node:url';
|
||||||
@@ -13,18 +14,20 @@ import {execFile} from 'node:child_process';
|
|||||||
import {parseAttachments,safeName,b2Body} from './attachments.mjs';
|
import {parseAttachments,safeName,b2Body} from './attachments.mjs';
|
||||||
|
|
||||||
const dir=path.dirname(fileURLToPath(import.meta.url));
|
const dir=path.dirname(fileURLToPath(import.meta.url));
|
||||||
const root=path.join(process.env.APPDATA||'C:/Users/User1/AppData/Roaming','BPQ32');
|
const config=await loadConfig();
|
||||||
const upstream='http://127.0.0.1:8080';
|
const root=config.root;
|
||||||
|
const upstream='http://127.0.0.1:'+config.httpPort;
|
||||||
const sessions=new Map(), attempts=new Map();
|
const sessions=new Map(), attempts=new Map();
|
||||||
const port=Number(process.env.BPQ_CONSOLE_PORT||8090);
|
const port=config.port;
|
||||||
const chat=new Chat(async()=>{const cfg=await readFile(path.join(root,'BPQ32.cfg'),'utf8');const line=cfg.split(/\r?\n/).find(l=>/^\s*USER=/i.test(l)&&/,IU2EUG,/i.test(l)&&/sysop/i.test(l));const m=line?.match(/^\s*USER=([^,]+),([^,]+),/i);if(!m)throw new Error('Utente Telnet IU2EUG non trovato');return {user:m[1],password:m[2]};});
|
const credentials=async()=>{const found=parseConfig(await readFile(path.join(root,'BPQ32.cfg'),'utf8')).users.find(u=>u.user===config.sysop.user);if(!found)throw new Error('Account sysop configurato non trovato');return found;};
|
||||||
const monitor=new Monitor(chat.credentials);
|
const chat=new Chat(credentials,{port:config.telnetPort,call:config.sysop.call,alias:config.alias});
|
||||||
const varaRate=new VaraRate();
|
const monitor=new Monitor(credentials,{port:config.monitorPort});
|
||||||
|
const varaRate=config.features.vara?new VaraRate(config.varaSyslogPort||18514):null;
|
||||||
let telemetry={current:null,history:[]},telemetryBusy=false,priorTraffic=null,priorCpu=null,varaCpu=null,priorVaraCpu=null;
|
let telemetry={current:null,history:[]},telemetryBusy=false,priorTraffic=null,priorCpu=null,varaCpu=null,priorVaraCpu=null;
|
||||||
function cpuSample(){const totals=os.cpus().reduce((a,c)=>({idle:a.idle+c.times.idle,total:a.total+Object.values(c.times).reduce((x,y)=>x+y,0)}),{idle:0,total:0});const result=priorCpu?Math.max(0,Math.min(100,100*(1-(totals.idle-priorCpu.idle)/(totals.total-priorCpu.total||1)))):null;priorCpu=totals;return result;}
|
function cpuSample(){const totals=os.cpus().reduce((a,c)=>({idle:a.idle+c.times.idle,total:a.total+Object.values(c.times).reduce((x,y)=>x+y,0)}),{idle:0,total:0});const result=priorCpu?Math.max(0,Math.min(100,100*(1-(totals.idle-priorCpu.idle)/(totals.total-priorCpu.total||1)))):null;priorCpu=totals;return result;}
|
||||||
function varaCpuSample(){execFile('powershell.exe',['-NoProfile','-NonInteractive','-Command',"$p=Get-Process -Name VARA -ErrorAction SilentlyContinue;if($p){$p|ForEach-Object {$_.TotalProcessorTime.TotalMilliseconds}|ConvertTo-Json -Compress}"],{windowsHide:true,timeout:5000},(err,out)=>{try{const value=JSON.parse(out);const ms=Array.isArray(value)?value.reduce((a,b)=>a+b,0):value;const now=Date.now();varaCpu=priorVaraCpu&&ms>=priorVaraCpu.ms?Math.min(100,Math.max(0,(ms-priorVaraCpu.ms)/(now-priorVaraCpu.at)/os.cpus().length*100)):null;priorVaraCpu={ms,at:now};}catch{varaCpu=null;priorVaraCpu=null;}});}
|
function varaCpuSample(){execFile('powershell.exe',['-NoProfile','-NonInteractive','-Command',"$p=Get-Process -Name VARA -ErrorAction SilentlyContinue;if($p){$p|ForEach-Object {$_.TotalProcessorTime.TotalMilliseconds}|ConvertTo-Json -Compress}"],{windowsHide:true,timeout:5000},(err,out)=>{try{const value=JSON.parse(out);const ms=Array.isArray(value)?value.reduce((a,b)=>a+b,0):value;const now=Date.now();varaCpu=priorVaraCpu&&ms>=priorVaraCpu.ms?Math.min(100,Math.max(0,(ms-priorVaraCpu.ms)/(now-priorVaraCpu.at)/os.cpus().length*100)):null;priorVaraCpu={ms,at:now};}catch{varaCpu=null;priorVaraCpu=null;}});}
|
||||||
async function sampleTelemetry(){if(telemetryBusy)return;telemetryBusy=true;try{const html=await bpq('/Node/Port?1');const radio=parseRadio(html);const now=Date.now();const active=radio.connected&&!/^(Free|Idle)$/i.test(radio.state)&&Boolean(radio.state.trim());const connecting=/connect|call/i.test(radio.state)&&!/connected/i.test(radio.state);const connections=[...plain(html).matchAll(/\bCONNECTED ([A-Z0-9]+(?:-\d+)?) ([A-Z0-9]+(?:-\d+)?) (\d+)/g)];const calls=connections.at(-1);const delta=priorTraffic?(now-priorTraffic.at)/1000:0;const txBps=delta&&radio.sent>=priorTraffic.sent?8*(radio.sent-priorTraffic.sent)/delta:0;const rxBps=delta&&radio.received>=priorTraffic.received?8*(radio.received-priorTraffic.received)/delta:0;const sn=Number(String(radio.snr).replace(',','.'));const nativeRate=varaRate.snapshot(active&&!connecting);const sample={at:now,available:true,active,connecting,nativeRate,varaTxBps:nativeRate.tx,varaRxBps:nativeRate.rx,varaBps:nativeRate.bps,state:radio.state,frequency:radio.frequency,scan:radio.scanning,busy:radio.busy,txBps,rxBps,cpu:cpuSample(),varaCpu,snr:active&&Number.isFinite(sn)?sn:null,lastSnr:Number.isFinite(sn)?sn:null,caller:active&&!connecting&&calls?calls[1]:null,called:active&&!connecting&&calls?calls[2]:null,sent:radio.sent,received:radio.received};priorTraffic={at:now,sent:radio.sent,received:radio.received};telemetry.current=sample;telemetry.history.push(sample);if(telemetry.history.length>180)telemetry.history.shift();}catch(e){telemetry.current={at:Date.now(),available:false,error:'Modem non disponibile',cpu:cpuSample(),varaCpu};priorTraffic=null;}finally{telemetryBusy=false;}}
|
async function sampleTelemetry(){if(telemetryBusy)return;telemetryBusy=true;try{const html=config.radio?await bpq('/Node/Port?'+config.radio.id):'';const radio=parseRadio(html||'');const now=Date.now();const active=radio.connected&&!/^(Free|Idle)$/i.test(radio.state)&&Boolean(radio.state.trim());const connecting=/connect|call/i.test(radio.state)&&!/connected/i.test(radio.state);const connections=[...plain(html||'').matchAll(/\bCONNECTED ([A-Z0-9]+(?:-\d+)?) ([A-Z0-9]+(?:-\d+)?) (\d+)/g)];const calls=connections.at(-1);const delta=priorTraffic?(now-priorTraffic.at)/1000:0;const txBps=delta&&radio.sent>=priorTraffic.sent?8*(radio.sent-priorTraffic.sent)/delta:0;const rxBps=delta&&radio.received>=priorTraffic.received?8*(radio.received-priorTraffic.received)/delta:0;const sn=Number(String(radio.snr).replace(',','.'));const nativeRate=varaRate?.snapshot(active&&!connecting)||{listening:false,bps:null,tx:null,rx:null};const sample={at:now,available:!!config.radio,active,connecting,nativeRate,varaTxBps:nativeRate.tx,varaRxBps:nativeRate.rx,varaBps:nativeRate.bps,state:radio.state,frequency:radio.frequency,scan:radio.scanning,busy:radio.busy,txBps,rxBps,cpu:cpuSample(),varaCpu,snr:active&&Number.isFinite(sn)?sn:null,lastSnr:Number.isFinite(sn)?sn:null,caller:active&&!connecting&&calls?calls[1]:null,called:active&&!connecting&&calls?calls[2]:null,sent:radio.sent,received:radio.received};priorTraffic={at:now,sent:radio.sent,received:radio.received};telemetry.current=sample;telemetry.history.push(sample);if(telemetry.history.length>180)telemetry.history.shift();}catch(e){telemetry.current={at:Date.now(),available:false,error:'Modem non disponibile',cpu:cpuSample(),varaCpu};priorTraffic=null;}finally{telemetryBusy=false;}}
|
||||||
setInterval(sampleTelemetry,2000).unref();setInterval(varaCpuSample,5000).unref();setTimeout(()=>{sampleTelemetry();varaCpuSample()},1000).unref();
|
setInterval(sampleTelemetry,2000).unref();if(config.features.vara)setInterval(varaCpuSample,5000).unref();setTimeout(()=>{sampleTelemetry();if(config.features.vara)varaCpuSample()},1000).unref();
|
||||||
let upstreamQueue=Promise.resolve(), mailKey=null, mailKeyAt=0;
|
let upstreamQueue=Promise.resolve(), mailKey=null, mailKeyAt=0;
|
||||||
function bpq(url,options={}){const work=upstreamQueue.then(()=>bpqRequest(url,options));upstreamQueue=work.catch(()=>{});return work;}
|
function bpq(url,options={}){const work=upstreamQueue.then(()=>bpqRequest(url,options));upstreamQueue=work.catch(()=>{});return work;}
|
||||||
async function bpqRequest(url, options={}) {
|
async function bpqRequest(url, options={}) {
|
||||||
@@ -38,35 +41,31 @@ async function bpqRequest(url, options={}) {
|
|||||||
async function mailContext(){if(mailKey&&Date.now()-mailKeyAt<1800000)return {key:mailKey};const html=await bpq('/Webmail');const key=html.match(/WMB\?([^>\s]+)/)?.[1];if(!key)throw new Error('WebMail BPQ non disponibile');mailKey=key;mailKeyAt=Date.now();return {html,key};}
|
async function mailContext(){if(mailKey&&Date.now()-mailKeyAt<1800000)return {key:mailKey};const html=await bpq('/Webmail');const key=html.match(/WMB\?([^>\s]+)/)?.[1];if(!key)throw new Error('WebMail BPQ non disponibile');mailKey=key;mailKeyAt=Date.now();return {html,key};}
|
||||||
async function messages(){let {key}=await mailContext();let html=await bpq('/WebMail/WMALL?'+key);if(!html.includes('Message List')){mailKey=null;({key}=await mailContext());html=await bpq('/WebMail/WMALL?'+key);if(!html.includes('Message List'))throw new Error('Lista messaggi BPQ non disponibile');}const list=parseMessages(html);for(const m of list.filter(m=>m.type==='P'&&(m.to==='RMS'||m.needsMetadata))){const f=await messageFields(m.id);m.from=f.From||m.from;m.to=f.To||m.to;m.subject=f.Title||m.subject;m.via=f.VIA||m.via;}for(const m of list)Object.assign(m,await messageTimes(m.id));return list;}
|
async function messages(){let {key}=await mailContext();let html=await bpq('/WebMail/WMALL?'+key);if(!html.includes('Message List')){mailKey=null;({key}=await mailContext());html=await bpq('/WebMail/WMALL?'+key);if(!html.includes('Message List'))throw new Error('Lista messaggi BPQ non disponibile');}const list=parseMessages(html);for(const m of list.filter(m=>m.type==='P'&&(m.to==='RMS'||m.needsMetadata))){const f=await messageFields(m.id);m.from=f.From||m.from;m.to=f.To||m.to;m.subject=f.Title||m.subject;m.via=f.VIA||m.via;}for(const m of list)Object.assign(m,await messageTimes(m.id));return list;}
|
||||||
function equal(a,b){const aa=Buffer.from(a),bb=Buffer.from(b);return aa.length===bb.length&&timingSafeEqual(aa,bb);}
|
function equal(a,b){const aa=Buffer.from(a),bb=Buffer.from(b);return aa.length===bb.length&&timingSafeEqual(aa,bb);}
|
||||||
async function authenticate(user,password){
|
async function authenticate(user,password){const users=parseConfig(await readFile(path.join(root,'BPQ32.cfg'),'utf8')).users;const found=users.find(u=>equal(u.user.toLowerCase(),user.toLowerCase())&&equal(u.password,password)&&u.user===config.sysop.user);return found?{call:found.call,name:found.user,config:publicConfig(config)}:null;}
|
||||||
const cfg=await readFile(path.join(root,'BPQ32.cfg'),'utf8');
|
|
||||||
for(const line of cfg.split(/\r?\n/)){const m=line.match(/^\s*USER=([^,]+),([^,]+),([^,]+),(.*)$/i);if(m&&equal(m[1].trim().toLowerCase(),user.toLowerCase())&&equal(m[2],password)&&m[3].trim().toUpperCase()==='IU2EUG'&&/sysop/i.test(m[4]))return {call:'IU2EUG',name:'Alberto'};}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
async function body(req){let chunks=[],size=0;for await(const chunk of req){size+=chunk.length;if(size>70000)throw new Error('Messaggio troppo grande');chunks.push(chunk)}return JSON.parse(Buffer.concat(chunks).toString()||'{}');}
|
async function body(req){let chunks=[],size=0;for await(const chunk of req){size+=chunk.length;if(size>70000)throw new Error('Messaggio troppo grande');chunks.push(chunk)}return JSON.parse(Buffer.concat(chunks).toString()||'{}');}
|
||||||
function json(res,status,data){res.writeHead(status,{'Content-Type':'application/json; charset=utf-8','Cache-Control':'no-store'});res.end(JSON.stringify(data));}
|
function json(res,status,data){res.writeHead(status,{'Content-Type':'application/json; charset=utf-8','Cache-Control':'no-store'});res.end(JSON.stringify(data));}
|
||||||
function session(req){const token=req.headers.cookie?.match(/(?:^|;\s*)alnode=([a-f0-9]+)/)?.[1];const s=sessions.get(token);if(s&&s.expires>Date.now()){s.expires=Date.now()+8*3600000;return s;}if(token)sessions.delete(token);return null;}
|
function session(req){const token=req.headers.cookie?.match(/(?:^|;\s*)alnode=([a-f0-9]+)/)?.[1];const s=sessions.get(token);if(s&&s.expires>Date.now()){s.expires=Date.now()+8*3600000;return s;}if(token)sessions.delete(token);return null;}
|
||||||
async function dashboard(){
|
async function dashboard(){
|
||||||
const jobs=await Promise.allSettled([bpq('/Node/Port?1'),bpq('/Node/Routes.html'),bpq('/Node/Nodes.html'),messages()]);
|
const jobs=await Promise.allSettled([config.radio?bpq('/Node/Port?'+config.radio.id):Promise.resolve(null),bpq('/Node/Routes.html'),bpq('/Node/Nodes.html'),config.features.bbs?messages():Promise.resolve([])]);
|
||||||
const val=i=>jobs[i].status==='fulfilled'?jobs[i].value:null;
|
const val=i=>jobs[i].status==='fulfilled'?jobs[i].value:null;
|
||||||
const list=val(3)||[];let activity=[],sync=null,cms=[];
|
const list=val(3)||[];let activity=[],sync=null,cms=[];
|
||||||
try{const date=new Date().toLocaleDateString('sv-SE',{timeZone:'UTC'}).replaceAll('-','').slice(2);const log=await readFile(path.join(root,'Logs',`log_${date}_BBS.txt`),'utf8');
|
try{const date=new Date().toLocaleDateString('sv-SE',{timeZone:'UTC'}).replaceAll('-','').slice(2);const log=await readFile(path.join(root,'Logs',`log_${date}_BBS.txt`),'utf8');
|
||||||
const lines=log.split(/\r?\n/);const relevant=lines.filter(l=>/Connecting to BBS IW2OHX|Incoming Connect from IW2OHX|\|IW2OHX\s+Uncompressing|Failure with IW2OHX|\|IW2OHX(?:-8)?\s+.*Disconnected/.test(l));
|
const lines=log.split(/\r?\n/);const relevant=lines.filter(l=>/Connecting to BBS|Incoming Connect|Uncompressing Message|Failure with|Disconnected/.test(l)&&!/[;](PR|PQ|FW):/.test(l));
|
||||||
activity=relevant.slice(-12).reverse().map(l=>({at:l.slice(0,15),text:l.slice(16).replace(/^[|<>?!][^ ]+\s*/, '')}));
|
activity=relevant.slice(-12).reverse().map(l=>({at:l.slice(0,15),text:l.slice(16).replace(/^[|<>?!][^ ]+\s*/, '')}));
|
||||||
const finish=lines.findLastIndex(l=>/<IW2OHX(?:-8)?\s+FQ/.test(l));if(finish>=0){let start=finish;while(start>0&&!/Connecting to BBS IW2OHX|Incoming Connect from IW2OHX/.test(lines[start]))start--;const count=lines.slice(start,finish).filter(l=>/Uncompressing Message/.test(l)).length;sync={at:lines[finish].slice(0,15),received:count};}
|
const finish=lines.findLastIndex(l=>/[<>][A-Z0-9-]+\s+FQ/.test(l));if(finish>=0){let start=finish;while(start>0&&!/Connecting to BBS|Incoming Connect/.test(lines[start]))start--;const count=lines.slice(start,finish).filter(l=>/Uncompressing Message/.test(l)).length;sync={at:lines[finish].slice(0,15),received:count};}
|
||||||
const cmsLog=await readFile(path.join(root,'Logs',`CMSAccess_20${date}.log`),'utf8').catch(()=> '');cms=cmsLog.split(/\r?\n/).filter(l=>/Connected to CMS/.test(l)&&!l.includes('IU2EUG-11')).map(l=>({at:l.slice(0,8),call:l.match(/\d+\s+(\S+) Connected/)?.[1]}));
|
const cmsLog=await readFile(path.join(root,'Logs',`CMSAccess_20${date}.log`),'utf8').catch(()=> '');cms=cmsLog.split(/\r?\n/).filter(l=>/Connected to CMS/.test(l)&&!l.includes((config.apps.find(a=>a.command==='BBS')?.call||'!')+' ')).map(l=>({at:l.slice(0,8),call:l.match(/\d+\s+(\S+) Connected/)?.[1]}));
|
||||||
}catch{}
|
}catch{}
|
||||||
const nodes=val(2)?[...plain(val(2)).matchAll(/\b([A-Z0-9]{1,6}:[A-Z0-9]+(?:-\d+)?)\b/g)].map(m=>m[1]):[];
|
const nodes=val(2)?[...plain(val(2)).matchAll(/\b([A-Z0-9]{1,6}:[A-Z0-9]+(?:-\d+)?)\b/g)].map(m=>m[1]):[];
|
||||||
return {updatedAt:new Date().toISOString(),radio:val(0)?parseRadio(val(0)):null,routes:val(1)?parseRoutes(val(1)):[],nodes:[...new Set(nodes)],counts:{messages:list.length,bulletins:list.filter(m=>m.type==='B').length,personal:list.filter(m=>m.type==='P').length},recent:list.slice(0,5),activity,sync,cms,errors:jobs.flatMap((r,i)=>r.status==='rejected'?[['Radio','Rete','Nodi','BBS'][i]+': '+r.reason.message]:[])};
|
return {updatedAt:new Date().toISOString(),radio:val(0)?parseRadio(val(0)):null,routes:val(1)?parseRoutes(val(1)):[],nodes:[...new Set(nodes)],counts:{messages:list.length,bulletins:list.filter(m=>m.type==='B').length,personal:list.filter(m=>m.type==='P').length},recent:list.slice(0,5),activity,sync,cms,errors:jobs.flatMap((r,i)=>r.status==='rejected'?[['Radio','Rete','Nodi','BBS'][i]+': '+r.reason.message]:[])};
|
||||||
}
|
}
|
||||||
let lastCmsRequest=0;
|
let lastCmsRequest=0;
|
||||||
async function syncNow(peer='IW2OHX'){const status=await bpq('/Mail/Status');const link=status.match(/href=(\/Mail\/FWD\?[^\s>]+)/)?.[1];if(!link)throw new Error('Forwarding non disponibile');const html=await bpq(link);const key=html.match(/var Key\s*=\s*"([^"]+)"/)?.[1];if(!key)throw new Error('Sessione forwarding non disponibile');await bpq('/Mail/FwdDetails?'+key,{method:'POST',body:peer});await bpq('/Mail/FWDSave?'+key,{method:'POST',body:'StartForward'});}
|
async function syncNow(peer=config.forwardPeer){if(!config.features.bbs||!peer||!/^[A-Z0-9-]{1,12}$/i.test(peer))throw new Error('Seleziona un profilo di forwarding nella configurazione');const status=await bpq('/Mail/Status');const link=status.match(/href=(\/Mail\/FWD\?[^\s>]+)/)?.[1];if(!link)throw new Error('Forwarding non disponibile');const html=await bpq(link);const key=html.match(/var Key\s*=\s*"([^"]+)"/)?.[1];if(!key)throw new Error('Sessione forwarding non disponibile');await bpq('/Mail/FwdDetails?'+key,{method:'POST',body:peer});await bpq('/Mail/FWDSave?'+key,{method:'POST',body:'StartForward'});}
|
||||||
const timestampCache=new Map();
|
const timestampCache=new Map();
|
||||||
async function messageTimes(id){if(timestampCache.has(id))return timestampCache.get(id);const pending=(async()=>{const f=await messageFields(id);let reference=new Date();try{reference=(await stat(path.join(root,'BPQMailChat','Mail','m_'+String(id).padStart(6,'0')+'.mes'))).mtime;}catch{}const receivedAt=bpqTimestamp(f.RX,reference);return {receivedAt,createdAt:bpqTimestamp(f.Sent,receivedAt?new Date(receivedAt):reference)};})().catch(()=>{timestampCache.delete(id);return {receivedAt:null,createdAt:null};});timestampCache.set(id,pending);return pending;}
|
async function messageTimes(id){if(timestampCache.has(id))return timestampCache.get(id);const pending=(async()=>{const f=await messageFields(id);let reference=new Date();try{reference=(await stat(path.join(root,'BPQMailChat','Mail','m_'+String(id).padStart(6,'0')+'.mes'))).mtime;}catch{}const receivedAt=bpqTimestamp(f.RX,reference);return {receivedAt,createdAt:bpqTimestamp(f.Sent,receivedAt?new Date(receivedAt):reference)};})().catch(()=>{timestampCache.delete(id);return {receivedAt:null,createdAt:null};});timestampCache.set(id,pending);return pending;}
|
||||||
const metadataCache=new Map();let metadataKey=null,metadataKeyAt=0;
|
const metadataCache=new Map();let metadataKey=null,metadataKeyAt=0;
|
||||||
async function messageFields(id){let cached=metadataCache.get(id);if(cached&&Date.now()-cached.at<60000)return cached.fields;if(!metadataKey||Date.now()-metadataKeyAt>600000){const status=await bpq('/Mail/Status');metadataKey=status.match(/href=\/Mail\/Msgs\?([^\s>]+)/)?.[1];metadataKeyAt=Date.now();}if(!metadataKey)throw new Error('Metadati BBS non disponibili');const html=await bpq('/Mail/MsgDetails?'+metadataKey,{method:'POST',body:String(id)});const fields={};for(const input of html.matchAll(/<input\b[^>]*>/gi)){const name=input[0].match(/\bname=(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i),value=input[0].match(/\bvalue=(?:"([^"]*)"|'([^']*)'|([^\s>]*))/i);if(name)fields[name[1]??name[2]??name[3]]=decode(value?.[1]??value?.[2]??value?.[3]??'');}metadataCache.set(id,{at:Date.now(),fields});return fields;}
|
async function messageFields(id){let cached=metadataCache.get(id);if(cached&&Date.now()-cached.at<60000)return cached.fields;if(!metadataKey||Date.now()-metadataKeyAt>600000){const status=await bpq('/Mail/Status');metadataKey=status.match(/href=\/Mail\/Msgs\?([^\s>]+)/)?.[1];metadataKeyAt=Date.now();}if(!metadataKey)throw new Error('Metadati BBS non disponibili');const html=await bpq('/Mail/MsgDetails?'+metadataKey,{method:'POST',body:String(id)});const fields={};for(const input of html.matchAll(/<input\b[^>]*>/gi)){const name=input[0].match(/\bname=(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i),value=input[0].match(/\bvalue=(?:"([^"]*)"|'([^']*)'|([^\s>]*))/i);if(name)fields[name[1]??name[2]??name[3]]=decode(value?.[1]??value?.[2]??value?.[3]??'');}metadataCache.set(id,{at:Date.now(),fields});return fields;}
|
||||||
async function mailMetadata(list){const out=[];for(const item of list.filter(m=>m.type==='P')){const f=await messageFields(item.id);const m={...item,from:f.From||item.from,to:f.To||item.to,subject:f.Title||item.subject};const via=f.VIA||m.via,emailFrom=f.EFROM||'';if(m.to==='RMS'||m.from==='RMS'||/WINLINK|@/i.test(via+emailFrom)){const full={...m,via,emailFrom,address:m.to==='RMS'?via:m.to,fromAddress:emailFrom?(emailFrom.startsWith('@')?m.from+emailFrom:emailFrom):m.from};out.push({...full,direction:mailDirection(full),folder:mailFolder(full)});}}return out;}
|
async function mailMetadata(list){const out=[];for(const item of list.filter(m=>m.type==='P')){const f=await messageFields(item.id);const m={...item,from:f.From||item.from,to:f.To||item.to,subject:f.Title||item.subject};const via=f.VIA||m.via,emailFrom=f.EFROM||'';if(m.to==='RMS'||m.from==='RMS'||/WINLINK|@/i.test(via+emailFrom)){const full={...m,via,emailFrom,address:m.to==='RMS'?via:m.to,fromAddress:emailFrom?(emailFrom.startsWith('@')?m.from+emailFrom:emailFrom):m.from};out.push({...full,direction:mailDirection(full,config.sysop.call),folder:mailFolder(full,config.sysop.call)});}}return out;}
|
||||||
async function winlink(){const list=await mailMetadata(await messages());const today=new Date().toLocaleDateString('sv-SE',{timeZone:'UTC'}).replaceAll('-','').slice(2);let sync=cmsStatus('');try{sync=cmsStatus(await readFile(path.join(root,'Logs',`log_${today}_BBS.txt`),'utf8'));}catch{}return {messages:list,sync,account:'IU2EUG@winlink.org',requestedAt:lastCmsRequest||null};}
|
async function winlink(){const list=await mailMetadata(await messages());const today=new Date().toLocaleDateString('sv-SE',{timeZone:'UTC'}).replaceAll('-','').slice(2);let sync=cmsStatus('');try{sync=cmsStatus(await readFile(path.join(root,'Logs',`log_${today}_BBS.txt`),'utf8'));}catch{}return {messages:list,sync,account:config.sysop.call.replace(/-\d+$/,'')+'@winlink.org',requestedAt:lastCmsRequest||null};}
|
||||||
async function deleteMessage(id){const list=await messages();if(!list.some(m=>m.id===id))throw new Error('Messaggio non presente');const {key}=await mailContext();await bpq('/WebMail/WMDel/'+id+'?'+key);metadataCache.delete(id);if((await messages()).some(m=>m.id===id))throw new Error('BPQ non ha confermato la cancellazione');return {ok:true};}
|
async function deleteMessage(id){const list=await messages();if(!list.some(m=>m.id===id))throw new Error('Messaggio non presente');const {key}=await mailContext();await bpq('/WebMail/WMDel/'+id+'?'+key);metadataCache.delete(id);if((await messages()).some(m=>m.id===id))throw new Error('BPQ non ha confermato la cancellazione');return {ok:true};}
|
||||||
async function attachedMessage(id){const item=(await messages()).find(m=>m.id===id);if(!item)throw new Error('Messaggio non disponibile');const file=path.join(root,'BPQMailChat','Mail','m_'+String(id).padStart(6,'0')+'.mes');const info=await stat(file);if(info.size>32*1024*1024)throw new Error('Messaggio troppo grande per il download web (32 MB)');const bytes=await readFile(file);const files=parseAttachments(bytes);const encoded=item.subject.match(/^7\+\s+(.+?)\s+(\d+)\/(\d+)$/i);return {item,bytes,files,encoded:encoded?{name:safeName(encoded[1]),part:Number(encoded[2]),total:Number(encoded[3])}:null};}
|
async function attachedMessage(id){const item=(await messages()).find(m=>m.id===id);if(!item)throw new Error('Messaggio non disponibile');const file=path.join(root,'BPQMailChat','Mail','m_'+String(id).padStart(6,'0')+'.mes');const info=await stat(file);if(info.size>32*1024*1024)throw new Error('Messaggio troppo grande per il download web (32 MB)');const bytes=await readFile(file);const files=parseAttachments(bytes);const encoded=item.subject.match(/^7\+\s+(.+?)\s+(\d+)\/(\d+)$/i);return {item,bytes,files,encoded:encoded?{name:safeName(encoded[1]),part:Number(encoded[2]),total:Number(encoded[3])}:null};}
|
||||||
async function sendMessage(data){
|
async function sendMessage(data){
|
||||||
@@ -78,26 +77,27 @@ async function sendMessage(data){
|
|||||||
const response=await bpq('/WebMail/EMSave?'+key,{method:'POST',body:form});
|
const response=await bpq('/WebMail/EMSave?'+key,{method:'POST',body:form});
|
||||||
if(/alert\(/i.test(response)&&!/(sent|saved|created)/i.test(response))throw new Error(plain(response.match(/alert\(["']([^"']+)/)?.[1]||'BPQ ha rifiutato il messaggio'));
|
if(/alert\(/i.test(response)&&!/(sent|saved|created)/i.test(response))throw new Error(plain(response.match(/alert\(["']([^"']+)/)?.[1]||'BPQ ha rifiutato il messaggio'));
|
||||||
// A successful write must be visible in BPQ's message list, not inferred from HTTP 200.
|
// A successful write must be visible in BPQ's message list, not inferred from HTTP 200.
|
||||||
const list=await messages();const expectedTo=/^RMS[/:]/.test(to)||/@[^@]*\./.test(to)?'RMS':to.split('@')[0];const created=list.find(m=>!previous.has(m.id)&&m.from==='IU2EUG'&&m.subject===subject&&(m.to===expectedTo||m.to===to.split('@')[0]));
|
const list=await messages();const expectedTo=/^RMS[/:]/.test(to)||/@[^@]*\./.test(to)?'RMS':to.split('@')[0];const created=list.find(m=>!previous.has(m.id)&&ownCall(m.from,config.sysop.call)&&m.subject===subject&&(m.to===expectedTo||m.to===to.split('@')[0]));
|
||||||
if(!created)throw new Error('BPQ non ha confermato il salvataggio. Controlla la lista prima di riprovare.');
|
if(!created)throw new Error('BPQ non ha confermato il salvataggio. Controlla la lista prima di riprovare.');
|
||||||
return {id:created.id};
|
return {id:created.id};
|
||||||
}
|
}
|
||||||
const server=http.createServer(async(req,res)=>{
|
const server=http.createServer(async(req,res)=>{
|
||||||
try{
|
try{
|
||||||
const host=req.headers.host||'';
|
const host=req.headers.host||'';
|
||||||
if(!/^(localhost|127\.0\.0\.1|192\.168\.\d{1,3}\.\d{1,3}|10\.\d{1,3}\.\d{1,3}\.\d{1,3}|172\.(1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}):8090$/.test(host)){json(res,403,{error:'Host non autorizzato'});return;}
|
if(!/^(localhost|127\.0\.0\.1|192\.168\.\d{1,3}\.\d{1,3}|10\.\d{1,3}\.\d{1,3}\.\d{1,3}|172\.(1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3})$/.test(host.split(':')[0])||host.split(':')[1]!==String(port)){json(res,403,{error:'Host non autorizzato'});return;}
|
||||||
res.setHeader('X-Content-Type-Options','nosniff');res.setHeader('X-Frame-Options','DENY');res.setHeader('Referrer-Policy','same-origin');res.setHeader('Content-Security-Policy',"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; worker-src 'self'; frame-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'");
|
res.setHeader('X-Content-Type-Options','nosniff');res.setHeader('X-Frame-Options','DENY');res.setHeader('Referrer-Policy','same-origin');res.setHeader('Content-Security-Policy',"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; worker-src 'self'; frame-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'");
|
||||||
const url=new URL(req.url,'http://'+host);
|
const url=new URL(req.url,'http://'+host);
|
||||||
if(req.method==='POST'&&req.headers.origin!=='http://'+host){json(res,403,{error:'Origine non autorizzata'});return;}
|
if(req.method==='POST'&&req.headers.origin!=='http://'+host){json(res,403,{error:'Origine non autorizzata'});return;}
|
||||||
if(url.pathname==='/api/login'&&req.method==='POST'){
|
if(url.pathname==='/api/login'&&req.method==='POST'){
|
||||||
const ip=req.socket.remoteAddress;let a=attempts.get(ip);if(a&&a.until>Date.now()&&a.count>=10){json(res,429,{error:'Troppi tentativi. Riprova tra 15 minuti.'});return;}if(!a||a.until<Date.now())a={count:0,until:Date.now()+15*60000};
|
const ip=req.socket.remoteAddress;let a=attempts.get(ip);if(a&&a.until>Date.now()&&a.count>=10){json(res,429,{error:'Troppi tentativi. Riprova tra 15 minuti.'});return;}if(!a||a.until<Date.now())a={count:0,until:Date.now()+15*60000};
|
||||||
const data=await body(req);const user=await authenticate(String(data.user||''),String(data.password||''));if(!user){a.count++;attempts.set(ip,a);json(res,401,{error:'Credenziali BPQ non valide per il pannello sysop IU2EUG'});return;}
|
const data=await body(req);const user=await authenticate(String(data.user||''),String(data.password||''));if(!user){a.count++;attempts.set(ip,a);json(res,401,{error:'Credenziali BPQ non valide per il pannello sysop'});return;}
|
||||||
attempts.delete(ip);const token=randomBytes(32).toString('hex'),csrf=randomBytes(24).toString('hex');sessions.set(token,{...user,csrf,expires:Date.now()+8*3600000});res.setHeader('Set-Cookie',`alnode=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=28800`);json(res,200,{...user,csrf});return;
|
attempts.delete(ip);const token=randomBytes(32).toString('hex'),csrf=randomBytes(24).toString('hex');sessions.set(token,{...user,csrf,expires:Date.now()+8*3600000});res.setHeader('Set-Cookie',`alnode=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=28800`);json(res,200,{...user,csrf});return;
|
||||||
}
|
}
|
||||||
if(url.pathname.startsWith('/api/')){
|
if(url.pathname.startsWith('/api/')){
|
||||||
const user=session(req);if(!user){json(res,401,{error:'Accedi con le credenziali BPQ'});return;}
|
const user=session(req);if(!user){json(res,401,{error:'Accedi con le credenziali BPQ'});return;}
|
||||||
|
const capability=url.pathname.startsWith('/api/chat')?'chat':url.pathname.startsWith('/api/monitor')?'monitor':url.pathname.startsWith('/api/winlink')?'winlink':url.pathname.startsWith('/api/messages')||url.pathname==='/api/sync'?'bbs':null;if(capability&&!config.features[capability]){json(res,409,{error:'Servizio non configurato in BPQ'});return;}
|
||||||
if(req.method==='POST'&&!equal(req.headers['x-csrf-token']||'',user.csrf)){json(res,403,{error:'Sessione non valida. Ricarica la pagina.'});return;}
|
if(req.method==='POST'&&!equal(req.headers['x-csrf-token']||'',user.csrf)){json(res,403,{error:'Sessione non valida. Ricarica la pagina.'});return;}
|
||||||
if(url.pathname==='/api/session'){json(res,200,{call:user.call,name:user.name,csrf:user.csrf});return;}
|
if(url.pathname==='/api/session'){json(res,200,{call:user.call,name:user.name,csrf:user.csrf,config:publicConfig(config)});return;}
|
||||||
if(url.pathname==='/api/monitor'&&req.method==='GET'){const after=Number(url.searchParams.get('after')||0);if(!Number.isSafeInteger(after)||after<0)throw new Error('Cursore monitor non valido');json(res,200,monitor.snapshot(after));return;}
|
if(url.pathname==='/api/monitor'&&req.method==='GET'){const after=Number(url.searchParams.get('after')||0);if(!Number.isSafeInteger(after)||after<0)throw new Error('Cursore monitor non valido');json(res,200,monitor.snapshot(after));return;}
|
||||||
if(url.pathname==='/api/monitor/connect'&&req.method==='POST'){json(res,200,await monitor.connect());return;}
|
if(url.pathname==='/api/monitor/connect'&&req.method==='POST'){json(res,200,await monitor.connect());return;}
|
||||||
if(url.pathname==='/api/monitor/disconnect'&&req.method==='POST'){monitor.disconnect();json(res,200,{ok:true});return;}
|
if(url.pathname==='/api/monitor/disconnect'&&req.method==='POST'){monitor.disconnect();json(res,200,{ok:true});return;}
|
||||||
@@ -114,7 +114,7 @@ const server=http.createServer(async(req,res)=>{
|
|||||||
if(attachmentRoute&&req.method==='GET'){const id=Number(attachmentRoute[1]),message=await attachedMessage(id);if(attachmentRoute[2]===undefined){json(res,200,{files:message.files.map(({data,...f})=>f),encoded:message.encoded});return;}const file=message.files[Number(attachmentRoute[2])];if(!file)throw new Error('Allegato non disponibile');if(url.searchParams.get('text')==='1'){if(file.mime!=='text/plain')throw new Error('Questo file non ha anteprima testuale');const bytes=file.data.subarray(0,128*1024);let text;try{text=new TextDecoder('utf8',{fatal:true}).decode(bytes);}catch{text=bytes.toString('latin1');}json(res,200,{text,truncated:file.size>bytes.length});return;}const preview=url.searchParams.get('preview')==='1'&&(file.mime.startsWith('image/')||file.mime==='application/pdf');res.setHeader('Content-Security-Policy',"default-src 'none'; sandbox; frame-ancestors 'self'");res.setHeader('X-Frame-Options','SAMEORIGIN');res.writeHead(200,{'Content-Type':preview?file.mime:'application/octet-stream','Content-Length':file.size,'Content-Disposition':`${preview?'inline':'attachment'}; filename="${file.name.replace(/[^A-Za-z0-9._ -]/g,'_')}"; filename*=UTF-8''${encodeURIComponent(file.name)}`,'Cache-Control':'no-store'});res.end(file.data);return;}
|
if(attachmentRoute&&req.method==='GET'){const id=Number(attachmentRoute[1]),message=await attachedMessage(id);if(attachmentRoute[2]===undefined){json(res,200,{files:message.files.map(({data,...f})=>f),encoded:message.encoded});return;}const file=message.files[Number(attachmentRoute[2])];if(!file)throw new Error('Allegato non disponibile');if(url.searchParams.get('text')==='1'){if(file.mime!=='text/plain')throw new Error('Questo file non ha anteprima testuale');const bytes=file.data.subarray(0,128*1024);let text;try{text=new TextDecoder('utf8',{fatal:true}).decode(bytes);}catch{text=bytes.toString('latin1');}json(res,200,{text,truncated:file.size>bytes.length});return;}const preview=url.searchParams.get('preview')==='1'&&(file.mime.startsWith('image/')||file.mime==='application/pdf');res.setHeader('Content-Security-Policy',"default-src 'none'; sandbox; frame-ancestors 'self'");res.setHeader('X-Frame-Options','SAMEORIGIN');res.writeHead(200,{'Content-Type':preview?file.mime:'application/octet-stream','Content-Length':file.size,'Content-Disposition':`${preview?'inline':'attachment'}; filename="${file.name.replace(/[^A-Za-z0-9._ -]/g,'_')}"; filename*=UTF-8''${encodeURIComponent(file.name)}`,'Cache-Control':'no-store'});res.end(file.data);return;}
|
||||||
const sourceRoute=url.pathname.match(/^\/api\/messages\/(\d+)\/source$/);if(sourceRoute&&req.method==='GET'){const m=await attachedMessage(Number(sourceRoute[1]));res.writeHead(200,{'Content-Type':'application/octet-stream','Content-Length':m.bytes.length,'Content-Disposition':`attachment; filename="messaggio-${m.item.id}.txt"`,'Cache-Control':'no-store'});res.end(m.bytes);return;}
|
const sourceRoute=url.pathname.match(/^\/api\/messages\/(\d+)\/source$/);if(sourceRoute&&req.method==='GET'){const m=await attachedMessage(Number(sourceRoute[1]));res.writeHead(200,{'Content-Type':'application/octet-stream','Content-Length':m.bytes.length,'Content-Disposition':`attachment; filename="messaggio-${m.item.id}.txt"`,'Cache-Control':'no-store'});res.end(m.bytes);return;}
|
||||||
if(url.pathname==='/api/winlink'&&req.method==='GET'){json(res,200,await winlink());return;}
|
if(url.pathname==='/api/winlink'&&req.method==='GET'){json(res,200,await winlink());return;}
|
||||||
if(url.pathname==='/api/winlink/sync'&&req.method==='POST'){if(Date.now()-lastCmsRequest<10000)throw new Error('Sincronizzazione già richiesta. Attendi qualche secondo.');await syncNow('RMS');lastCmsRequest=Date.now();json(res,200,{ok:true});return;}
|
if(url.pathname==='/api/winlink/sync'&&req.method==='POST'){if(Date.now()-lastCmsRequest<10000)throw new Error('Sincronizzazione già richiesta. Attendi qualche secondo.');await syncNow(config.cmsPeer||'RMS');lastCmsRequest=Date.now();json(res,200,{ok:true});return;}
|
||||||
if(/^\/api\/messages\/\d+\/delete$/.test(url.pathname)&&req.method==='POST'){json(res,200,await deleteMessage(Number(url.pathname.split('/')[3])));return;}
|
if(/^\/api\/messages\/\d+\/delete$/.test(url.pathname)&&req.method==='POST'){json(res,200,await deleteMessage(Number(url.pathname.split('/')[3])));return;}
|
||||||
if(/^\/api\/messages\/\d+$/.test(url.pathname)&&req.method==='GET'){const id=url.pathname.split('/').pop();const {key}=await mailContext();const msg=parseMessage(await bpq('/WebMail/WM?'+key+'&'+id));if(!msg)throw new Error('Messaggio non disponibile');try{const raw=await attachedMessage(Number(id));const text=b2Body(raw.bytes);if(text!==null)msg.text=text.replace(/\r\n|\r/g,'\n');}catch{}json(res,200,{id:Number(id),...msg,...await messageTimes(Number(id))});return;}
|
if(/^\/api\/messages\/\d+$/.test(url.pathname)&&req.method==='GET'){const id=url.pathname.split('/').pop();const {key}=await mailContext();const msg=parseMessage(await bpq('/WebMail/WM?'+key+'&'+id));if(!msg)throw new Error('Messaggio non disponibile');try{const raw=await attachedMessage(Number(id));const text=b2Body(raw.bytes);if(text!==null)msg.text=text.replace(/\r\n|\r/g,'\n');}catch{}json(res,200,{id:Number(id),...msg,...await messageTimes(Number(id))});return;}
|
||||||
if(url.pathname==='/api/messages'&&req.method==='POST'){json(res,201,await sendMessage(await body(req)));return;}
|
if(url.pathname==='/api/messages'&&req.method==='POST'){json(res,201,await sendMessage(await body(req)));return;}
|
||||||
@@ -126,4 +126,4 @@ const server=http.createServer(async(req,res)=>{
|
|||||||
const files={'/monitor.js':'monitor.js','/monitor.css':'monitor.css','/':'index.html','/app.js':'app.js','/enhancements.js':'enhancements.js','/notifications.js':'notifications.js','/winlink.js':'winlink.js','/mission.js':'mission.js','/attachments.js':'attachments.js','/mission.css':'mission.css','/style.css':'style.css','/dark.css':'dark.css'};const file=files[url.pathname];if(!file){json(res,404,{error:'Pagina non trovata'});return;}const bytes=await readFile(path.join(dir,'public',file));res.writeHead(200,{'Content-Type':file.endsWith('.css')?'text/css; charset=utf-8':file.endsWith('.js')?'text/javascript; charset=utf-8':'text/html; charset=utf-8','Cache-Control':'no-cache'});res.end(bytes);
|
const files={'/monitor.js':'monitor.js','/monitor.css':'monitor.css','/':'index.html','/app.js':'app.js','/enhancements.js':'enhancements.js','/notifications.js':'notifications.js','/winlink.js':'winlink.js','/mission.js':'mission.js','/attachments.js':'attachments.js','/mission.css':'mission.css','/style.css':'style.css','/dark.css':'dark.css'};const file=files[url.pathname];if(!file){json(res,404,{error:'Pagina non trovata'});return;}const bytes=await readFile(path.join(dir,'public',file));res.writeHead(200,{'Content-Type':file.endsWith('.css')?'text/css; charset=utf-8':file.endsWith('.js')?'text/javascript; charset=utf-8':'text/html; charset=utf-8','Cache-Control':'no-cache'});res.end(bytes);
|
||||||
}catch(e){json(res,502,{error:e.message||'BPQ temporaneamente non disponibile'});}
|
}catch(e){json(res,502,{error:e.message||'BPQ temporaneamente non disponibile'});}
|
||||||
});
|
});
|
||||||
server.listen(port,'0.0.0.0',()=>console.log(`ALNODE Console: http://127.0.0.1:${port}`));
|
server.listen(port,'0.0.0.0',()=>console.log(`BPQ Console: http://127.0.0.1:${port}`));
|
||||||
@@ -7,27 +7,27 @@ test('B2 body excludes attachment bytes and preserves UTF8',()=>{const body=Buff
|
|||||||
test('B2 attachments preserve binary bytes, byte lengths and multiple files',()=>{const body=Buffer.from('Caffè'),one=Buffer.from([0,255,13,10]),two=Buffer.from('hello');const header=Buffer.from(`Mid: test\r\nBody: ${body.length}\r\nFile: ${one.length} a.bin\r\nFile: ${two.length} notes.txt\r\n\r\n`);const message=Buffer.concat([header,body,Buffer.from('\r\n'),one,Buffer.from('\r\n'),two,Buffer.from('\r\n')]);const files=parseAttachments(message);assert.equal(files.length,2);assert.deepEqual(files[0].data,one);assert.deepEqual(files[1].data,two);assert.equal(files[1].mime,'text/plain');});
|
test('B2 attachments preserve binary bytes, byte lengths and multiple files',()=>{const body=Buffer.from('Caffè'),one=Buffer.from([0,255,13,10]),two=Buffer.from('hello');const header=Buffer.from(`Mid: test\r\nBody: ${body.length}\r\nFile: ${one.length} a.bin\r\nFile: ${two.length} notes.txt\r\n\r\n`);const message=Buffer.concat([header,body,Buffer.from('\r\n'),one,Buffer.from('\r\n'),two,Buffer.from('\r\n')]);const files=parseAttachments(message);assert.equal(files.length,2);assert.deepEqual(files[0].data,one);assert.deepEqual(files[1].data,two);assert.equal(files[1].mime,'text/plain');});
|
||||||
test('untrusted HTML/SVG is text and filename paths are removed',()=>{assert.equal(mimeOf(Buffer.from('<svg onload=alert(1)>'),'x.svg'),'text/plain');assert.equal(mimeOf(Buffer.from('<html>'),'x.jpg'),'application/octet-stream');assert.equal(safeName('../../secret.png'),'secret.png');});
|
test('untrusted HTML/SVG is text and filename paths are removed',()=>{assert.equal(mimeOf(Buffer.from('<svg onload=alert(1)>'),'x.svg'),'text/plain');assert.equal(mimeOf(Buffer.from('<html>'),'x.jpg'),'application/octet-stream');assert.equal(safeName('../../secret.png'),'secret.png');});
|
||||||
test('truncated B2 attachment is rejected, ordinary bulletin has no binary attachments',()=>{assert.throws(()=>parseAttachments(Buffer.from('Body: 1\r\nFile: 999 foo.png\r\n\r\na\r\nxx')));assert.deepEqual(parseAttachments(Buffer.from('R:261013\r\n\r\nBulletin')),[]);});
|
test('truncated B2 attachment is rejected, ordinary bulletin has no binary attachments',()=>{assert.throws(()=>parseAttachments(Buffer.from('Body: 1\r\nFile: 999 foo.png\r\n\r\na\r\nxx')));assert.deepEqual(parseAttachments(Buffer.from('R:261013\r\n\r\nBulletin')),[]);});
|
||||||
test('long RMS email route does not drop or shift the message row',()=>{const row='<a href=/WebMail/WM?W123&2482> 2482</a> 13-Oct PN 150 RMS IU2EUG@WINLINKIU2EUG Queue regression\r\n';const m=parseMessages(row)[0];assert.equal(m.id,2482);assert.equal(m.to,'RMS');assert.equal(m.from,'IU2EUG');assert.equal(m.subject,'Queue regression');});
|
test('long RMS email route does not drop or shift the message row',()=>{const row='<a href=/WebMail/WM?W123&2482> 2482</a> 13-Oct PN 150 RMS N0TEST@WINLINKN0TEST Queue regression\r\n';const m=parseMessages(row)[0];assert.equal(m.id,2482);assert.equal(m.to,'RMS');assert.equal(m.from,'N0TEST');assert.equal(m.subject,'Queue regression');});
|
||||||
test('own outgoing emails stay in queue even with an SSID or full email sender',()=>{for(const from of ['IU2EUG','IU2EUG-11','IU2EUG@WINLINK.ORG']){const m={from,fromAddress:from,to:'RMS',status:'N'};assert.equal(mailDirection(m),'outgoing');assert.equal(mailFolder(m),'queue')}assert.equal(mailFolder({from:'IU2EUG',status:'F'}),'sent');assert.equal(mailFolder({from:'K1AJD',status:'N'}),'inbox');});
|
test('own outgoing emails stay in queue even with an SSID or full email sender',()=>{for(const from of ['N0TEST','N0TEST-11','N0TEST@WINLINK.ORG']){const m={from,fromAddress:from,to:'RMS',status:'N'};assert.equal(mailDirection(m,'N0TEST'),'outgoing');assert.equal(mailFolder(m,'N0TEST'),'queue')}assert.equal(mailFolder({from:'N0TEST',status:'F'},'N0TEST'),'sent');assert.equal(mailFolder({from:'K1AJD',status:'N'}),'inbox');});
|
||||||
test('CMS clean close is recognized for both directions of FQ',()=>{for(const direction of ['<','>'])assert.equal(cmsStatus(`261013 20:52:23 |RMS Connecting to BBS RMS\n261013 20:52:26 ${direction}RMS FQ\n261013 20:52:28 |RMS RMS Disconnected`).state,'complete');});
|
test('CMS clean close is recognized for both directions of FQ',()=>{for(const direction of ['<','>'])assert.equal(cmsStatus(`261013 20:52:23 |RMS Connecting to BBS RMS\n261013 20:52:26 ${direction}RMS FQ\n261013 20:52:28 |RMS RMS Disconnected`).state,'complete');});
|
||||||
test('CMS disconnect alone is neutral, explicit protocol error is an error',()=>{const start='261013 20:52:23 |RMS Connecting to BBS RMS\n';assert.equal(cmsStatus(start+'261013 20:52:28 |RMS RMS Disconnected').state,'ended');assert.equal(cmsStatus(start+'261013 20:52:28 <RMS *** Protocol Error').state,'error');});
|
test('CMS disconnect alone is neutral, explicit protocol error is an error',()=>{const start='261013 20:52:23 |RMS Connecting to BBS RMS\n';assert.equal(cmsStatus(start+'261013 20:52:28 |RMS RMS Disconnected').state,'ended');assert.equal(cmsStatus(start+'261013 20:52:28 <RMS *** Protocol Error').state,'error');});
|
||||||
test('arrival alerts ignore first load and previously seen IDs',()=>{const messages=[{id:1,type:'B',from:'IW2OHX'},{id:2,type:'P',from:'K1AJD'}];assert.deepEqual(incoming(messages,null),{bulletins:[],mail:[]});assert.deepEqual(incoming(messages,new Set([1,2])),{bulletins:[],mail:[]});});
|
test('arrival alerts ignore first load and previously seen IDs',()=>{const messages=[{id:1,type:'B',from:'N1TEST'},{id:2,type:'P',from:'K1AJD'}];assert.deepEqual(incoming(messages,null),{bulletins:[],mail:[]});assert.deepEqual(incoming(messages,new Set([1,2])),{bulletins:[],mail:[]});});
|
||||||
test('arrival alerts distinguish downloaded bulletins and incoming mail, exclude own writes',()=>{const got=incoming([{id:1,type:'B',from:'IW2OHX'},{id:2,type:'P',from:'K1AJD'},{id:3,type:'P',from:'IU2EUG'}],new Set());assert.equal(got.bulletins.length,1);assert.equal(got.mail.length,1);assert.equal(got.mail[0].id,2);});
|
test('arrival alerts distinguish downloaded bulletins and incoming mail, exclude own writes',()=>{const got=incoming([{id:1,type:'B',from:'N1TEST'},{id:2,type:'P',from:'K1AJD'},{id:3,type:'P',from:'N0TEST'}],new Set(),'N0TEST');assert.equal(got.bulletins.length,1);assert.equal(got.mail.length,1);assert.equal(got.mail[0].id,2);});
|
||||||
test('chat roster extracts callsign, name, node, room and idle time',()=>{assert.deepEqual(parseUser('K1AJD at AGCHAT Tony, Augusta, GA [General] Idle for 1279 seconds'),{call:'K1AJD',node:'AGCHAT',name:'Tony',qth:'Augusta, GA',topic:'General',idle:1279});});
|
test('chat roster extracts callsign, name, node, room and idle time',()=>{assert.deepEqual(parseUser('K1AJD at AGCHAT Tony, Augusta, GA [General] Idle for 1279 seconds'),{call:'K1AJD',node:'AGCHAT',name:'Tony',qth:'Augusta, GA',topic:'General',idle:1279});});
|
||||||
test('chat rejects command injection before writing to socket',()=>{const c=new Chat(async()=>({}));c.state='online';assert.throws(()=>c.send('hello\r/QUIT'));assert.throws(()=>c.send('/F'));assert.throws(()=>c.changeTopic('General\r/QUIT'));assert.throws(()=>c.send('hello','K1AJD\rB'));clearInterval(c.timer)});
|
test('chat rejects command injection before writing to socket',()=>{const c=new Chat(async()=>({}));c.state='online';assert.throws(()=>c.send('hello\r/QUIT'));assert.throws(()=>c.send('/F'));assert.throws(()=>c.changeTopic('General\r/QUIT'));assert.throws(()=>c.send('hello','K1AJD\rB'));clearInterval(c.timer)});
|
||||||
test('polling roster lines do not become conversation messages',()=>{const c=new Chat(async()=>({}));c.line('1 Station(s) connected:');c.line('IU2EUG at ALBCHT IU2EUG, Senago Italy [General] Idle for 0 seconds');assert.equal(c.events.length,0);assert.equal(c.users.length,1);clearInterval(c.timer)});
|
test('polling roster lines do not become conversation messages',()=>{const c=new Chat(async()=>({}));c.line('1 Station(s) connected:');c.line('N0TEST at CHAT N0TEST, Town Italy [General] Idle for 0 seconds');assert.equal(c.events.length,0);assert.equal(c.users.length,1);clearInterval(c.timer)});
|
||||||
test('fixed-width BPQ list retains empty routing field and decodes subject',()=>{const row='<a href=/WebMail/WM?W123&2444> 2444</a> 13-Oct PF 157 IW2OHX IU2EUG Test & hello\r\n';assert.deepEqual(parseMessages(row),[{id:2444,date:'13-Oct',type:'P',status:'F',size:157,to:'IW2OHX',via:'',from:'IU2EUG',subject:'Test & hello'}]);});
|
test('fixed-width BPQ list retains empty routing field and decodes subject',()=>{const row='<a href=/WebMail/WM?W123&2444> 2444</a> 13-Oct PF 157 N1TEST N0TEST Test & hello\r\n';assert.deepEqual(parseMessages(row),[{id:2444,date:'13-Oct',type:'P',status:'F',size:157,to:'N1TEST',via:'',from:'N0TEST',subject:'Test & hello'}]);});
|
||||||
test('bulletin columns and routing',()=>{const row='<a href=/WebMail/WM?W123&2466> 2466</a> 13-Oct BN 1784 DX WW HP2DFA DX bulletin\r\n';const m=parseMessages(row)[0];assert.equal(m.to,'DX');assert.equal(m.from,'HP2DFA');assert.equal(m.subject,'DX bulletin');});
|
test('bulletin columns and routing',()=>{const row='<a href=/WebMail/WM?W123&2466> 2466</a> 13-Oct BN 1784 DX WW HP2DFA DX bulletin\r\n';const m=parseMessages(row)[0];assert.equal(m.to,'DX');assert.equal(m.from,'HP2DFA');assert.equal(m.subject,'DX bulletin');});
|
||||||
test('message content is extracted without executing HTML, CRs normalized',()=>{const m=parseMessage('<textarea id=txt>From: IU2EUG\nTo: TEST\nTitle: <script>\n\nhello\rworld & radio</textarea>');assert.equal(m.subject,'<script>');assert.equal(m.text,'hello\nworld & radio');});
|
test('message content is extracted without executing HTML, CRs normalized',()=>{const m=parseMessage('<textarea id=txt>From: N0TEST\nTo: TEST\nTitle: <script>\n\nhello\rworld & radio</textarea>');assert.equal(m.subject,'<script>');assert.equal(m.text,'hello\nworld & radio');});
|
||||||
test('route status is distinct from last-heard value',()=>{const html='<tr>'+['>4','IW2OHX-15','192','6','100','2','0','4','5000','18:10','0','161'].map(c=>'<td>'+c+'</td>').join('')+'</tr>';assert.equal(parseRoutes(html)[0].active,true);assert.equal(parseRoutes(html)[0].nodes,6);});
|
test('route status is distinct from last-heard value',()=>{const html='<tr>'+['>4','N1TEST-15','192','6','100','2','0','4','5000','18:10','0','161'].map(c=>'<td>'+c+'</td>').join('')+'</tr>';assert.equal(parseRoutes(html)[0].active,true);assert.equal(parseRoutes(html)[0].nodes,6);});
|
||||||
test('radio online/free/busy are separate states',()=>{const r=parseRadio('Comms State Connected to VARA TNC TNC State Free Mode 2300 Channel State Busy S/N 15,6 Traffic Sent 59 RXed 5480 FT991A 7.050 USB S');assert.equal(r.state,'Free');assert.equal(r.busy,true);assert.equal(r.frequency,'7.050');assert.equal(r.scanning,true)});
|
test('radio online/free/busy are separate states',()=>{const r=parseRadio('Comms State Connected to VARA TNC TNC State Free Mode 2300 Channel State Busy S/N 15,6 Traffic Sent 59 RXed 5480 FT991A 7.050 USB S');assert.equal(r.state,'Free');assert.equal(r.busy,true);assert.equal(r.frequency,'7.050');assert.equal(r.scanning,true)});
|
||||||
|
|
||||||
|
|
||||||
test('BPQ monitor decodes fragmented and joined frames, ports and direction', async()=>{
|
test('BPQ monitor decodes fragmented and joined frames, ports and direction', async()=>{
|
||||||
const {MonitorDecoder}=await import('./monitor.mjs');const frames=[],ports=[];const d=new MonitorDecoder(f=>frames.push(f),p=>ports.push(...p));
|
const {MonitorDecoder}=await import('./monitor.mjs');const frames=[],ports=[];const d=new MonitorDecoder(f=>frames.push(f),p=>ports.push(...p));
|
||||||
const definition=Buffer.concat([Buffer.from([255,255]),Buffer.from('3|1 VARA HF|2 Telnet|4 AXIP|')]);
|
const definition=Buffer.concat([Buffer.from([255,255]),Buffer.from('3|1 VARA HF|2 Telnet|4 AXIP|')]);
|
||||||
const rx=Buffer.concat([Buffer.from([255,27,17]),Buffer.from('12:00:00R IW2OHX-15>NODES Port=4 <UI>\rhello\r'),Buffer.from([254])]);
|
const rx=Buffer.concat([Buffer.from([255,27,17]),Buffer.from('12:00:00R N1TEST-15>NODES Port=4 <UI>\rhello\r'),Buffer.from([254])]);
|
||||||
const tx=Buffer.concat([Buffer.from([255,27,91]),Buffer.from('12:00:01T IU2EUG>IW2OHX Port=1\rtest\r'),Buffer.from([254])]);
|
const tx=Buffer.concat([Buffer.from([255,27,91]),Buffer.from('12:00:01T N0TEST>N1TEST Port=1\rtest\r'),Buffer.from([254])]);
|
||||||
const data=Buffer.concat([Buffer.from('node greeting'),definition,rx,tx]);for(const byte of data)d.push(Buffer.from([byte]));
|
const data=Buffer.concat([Buffer.from('node greeting'),definition,rx,tx]);for(const byte of data)d.push(Buffer.from([byte]));
|
||||||
assert.deepEqual(ports.map(p=>p.id),[1,2,4]);assert.equal(frames.length,2);assert.equal(frames[0].direction,'RX');assert.equal(frames[0].port,4);assert.match(frames[0].text,/hello/);assert.equal(frames[1].direction,'TX');assert.equal(frames[1].port,1);assert.equal(d.buffer.length,0);
|
assert.deepEqual(ports.map(p=>p.id),[1,2,4]);assert.equal(frames.length,2);assert.equal(frames[0].direction,'RX');assert.equal(frames[0].port,4);assert.match(frames[0].text,/hello/);assert.equal(frames[1].direction,'TX');assert.equal(frames[1].port,1);assert.equal(d.buffer.length,0);
|
||||||
});
|
});
|
||||||
@@ -39,3 +39,27 @@ test('native VARA bitrate keeps TX/RX separate and excludes speed-level number',
|
|||||||
|
|
||||||
|
|
||||||
test('BPQ message dates preserve UTC hours and infer previous year across January',async()=>{const {bpqTimestamp}=await import('./bpq.mjs');assert.equal(bpqTimestamp('14-Oct 12:11Z',new Date('2026-10-14T12:12:00Z')),'2026-10-14T12:11:00.000Z');assert.equal(bpqTimestamp('31-Dec 23:58Z',new Date('2026-01-01T01:00:00Z')),'2025-12-31T23:58:00.000Z');assert.equal(bpqTimestamp('31-Feb 12:00Z'),null);assert.equal(bpqTimestamp('14-Oct'),null);});
|
test('BPQ message dates preserve UTC hours and infer previous year across January',async()=>{const {bpqTimestamp}=await import('./bpq.mjs');assert.equal(bpqTimestamp('14-Oct 12:11Z',new Date('2026-10-14T12:12:00Z')),'2026-10-14T12:11:00.000Z');assert.equal(bpqTimestamp('31-Dec 23:58Z',new Date('2026-01-01T01:00:00Z')),'2025-12-31T23:58:00.000Z');assert.equal(bpqTimestamp('31-Feb 12:00Z'),null);assert.equal(bpqTimestamp('14-Oct'),null);});
|
||||||
|
|
||||||
|
|
||||||
|
test('generic PACTOR station runs without VARA, chat, monitor or BBS',async()=>{
|
||||||
|
const fs=await import('node:fs/promises'),os=await import('node:os'),path=await import('node:path'),http=await import('node:http'),cp=await import('node:child_process');
|
||||||
|
const {parseConfig,publicConfig,loadConfig}=await import('./config.mjs');
|
||||||
|
const tmp=await fs.mkdtemp(path.join(os.tmpdir(),'bpq-console-test-'));
|
||||||
|
const upstream=http.createServer((req,res)=>{res.end('BPQ Ports Comms State Connected to PACTOR TNC TNC State Free Mode PACTOR Channel State Clear Traffic Sent 12 RXed 34');});
|
||||||
|
await new Promise(r=>upstream.listen(0,'127.0.0.1',r));
|
||||||
|
const httpPort=upstream.address().port;
|
||||||
|
const cfg=['NODECALL=N9DEMO-7','NODEALIAS=DEMO','LOCATOR=AA00AA','PORT','PORTNUM=3','ID=PACTOR modem','DRIVER=SCSPACTOR','ENDPORT','PORT','PORTNUM=5','DRIVER=TELNET','HTTPPORT='+httpPort,'USER=admin,fixture,N9DEMO,sysop','ENDPORT'].join('\n');
|
||||||
|
await fs.writeFile(path.join(tmp,'BPQ32.cfg'),cfg);await fs.writeFile(path.join(tmp,'console.config.json'),JSON.stringify({bpqRoot:tmp,httpPort,port:18991}));
|
||||||
|
const parsed=parseConfig(cfg);assert.equal(parsed.radioPorts[0].id,3);assert.equal(parsed.call,'N9DEMO');
|
||||||
|
const child=cp.spawn(process.execPath,['server.mjs'],{cwd:process.cwd(),env:{...process.env,BPQ_ROOT:tmp,BPQ_CONSOLE_CONFIG:path.join(tmp,'console.config.json'),BPQ_CONSOLE_PORT:'18991'},windowsHide:true,stdio:['ignore','pipe','pipe']});
|
||||||
|
try{
|
||||||
|
await new Promise((resolve,reject)=>{const timeout=setTimeout(()=>reject(new Error('Server fixture timeout')),8000);child.stdout.once('data',()=>{clearTimeout(timeout);resolve()});child.once('exit',code=>{clearTimeout(timeout);reject(new Error('Server fixture exited '+code))})});
|
||||||
|
const base='http://127.0.0.1:18991';const login=await fetch(base+'/api/login',{method:'POST',headers:{Origin:base,'Content-Type':'application/json'},body:JSON.stringify({user:'admin',password:'fixture'})});assert.equal(login.status,200);const user=await login.json();assert.equal(user.call,'N9DEMO');assert.equal(user.config.features.vara,false);assert.equal(user.config.features.bbs,false);assert.equal(user.config.radio.id,3);assert.equal(JSON.stringify(user.config).includes('fixture'),false);
|
||||||
|
const headers={Cookie:login.headers.get('set-cookie').split(';')[0]};assert.equal((await fetch(base+'/api/chat',{headers})).status,409);assert.equal((await fetch(base+'/api/monitor',{headers})).status,409);assert.equal((await fetch(base+'/api/winlink',{headers})).status,409);
|
||||||
|
await new Promise(r=>setTimeout(r,1200));const telemetry=await (await fetch(base+'/api/telemetry',{headers})).json();assert.equal(telemetry.current.available,true);assert.equal(telemetry.current.nativeRate.listening,false);assert.equal(telemetry.current.varaCpu,null);assert.equal(telemetry.current.sent,12);
|
||||||
|
const dash=await (await fetch(base+'/api/dashboard',{headers})).json();assert.equal(dash.counts.messages,0);
|
||||||
|
}finally{child.kill();await new Promise(r=>child.once('exit',r));await new Promise(r=>upstream.close(r));await fs.rm(tmp,{recursive:true,force:true});}
|
||||||
|
});
|
||||||
|
test('generic own-call handling accepts SSIDs without station constants',()=>{assert.equal(mailFolder({from:'N9DEMO-11',status:'N'},'N9DEMO'),'queue');assert.equal(mailFolder({from:'[email protected]',status:'F'},'N9DEMO'),'sent');assert.equal(mailFolder({from:'N1OTHER',status:'N'},'N9DEMO'),'inbox');});
|
||||||
|
|
||||||
|
test('configuration detects a Telnet-only node without inventing a modem',async()=>{const {parseConfig}=await import('./config.mjs');const c=parseConfig('NODECALL=N8TEST-7\nPORT\nDRIVER=Telnet.dll\nPORTNUM=2\nHTTPPORT=8088\nTCPPORT=9000\nENDPORT');assert.equal(c.httpPort,8088);assert.equal(c.telnetPort,9000);assert.deepEqual(c.radioPorts,[]);assert.equal(c.call,'N8TEST');});
|
||||||
+1
-1
@@ -9,6 +9,6 @@ export function parseVaraRate(text){
|
|||||||
return {bps,direction,level:Number(line.match(/\((\d+)\)/)?.[1])||null};
|
return {bps,direction,level:Number(line.match(/\((\d+)\)/)?.[1])||null};
|
||||||
}
|
}
|
||||||
export class VaraRate {
|
export class VaraRate {
|
||||||
constructor(){this.lastPacket=0;this.lastRate=null;this.tx=null;this.rx=null;this.error=null;this.listening=false;this.socket=dgram.createSocket('udp4');this.socket.on('listening',()=>{this.listening=true});this.socket.on('error',()=>{this.error='Logging VARA non disponibile';this.listening=false});this.socket.on('message',(packet,remote)=>{if(remote.address!=='127.0.0.1')return;this.lastPacket=Date.now();const text=packet.toString('utf8');const rate=parseVaraRate(text);if(rate){const sample={...rate,at:this.lastPacket};this.lastRate=sample;if(rate.direction==='TX')this.tx=sample;if(rate.direction==='RX')this.rx=sample;}else if(/\bDISCONNECTED\b|\bDisconnected\b/.test(text)){this.lastRate=null;this.tx=null;this.rx=null;}});this.socket.bind(18514,'127.0.0.1');this.socket.unref();}
|
constructor(port=18514){this.lastPacket=0;this.lastRate=null;this.tx=null;this.rx=null;this.error=null;this.listening=false;this.socket=dgram.createSocket('udp4');this.socket.on('listening',()=>{this.listening=true});this.socket.on('error',()=>{this.error='Logging VARA non disponibile';this.listening=false});this.socket.on('message',(packet,remote)=>{if(remote.address!=='127.0.0.1')return;this.lastPacket=Date.now();const text=packet.toString('utf8');const rate=parseVaraRate(text);if(rate){const sample={...rate,at:this.lastPacket};this.lastRate=sample;if(rate.direction==='TX')this.tx=sample;if(rate.direction==='RX')this.rx=sample;}else if(/\bDISCONNECTED\b|\bDisconnected\b/.test(text)){this.lastRate=null;this.tx=null;this.rx=null;}});this.socket.bind(port,'127.0.0.1');this.socket.unref();}
|
||||||
snapshot(active){return {listening:this.listening,lastPacket:this.lastPacket||null,error:this.error,at:active?this.lastRate?.at||null:null,bps:active?this.lastRate?.bps??null:null,direction:active?this.lastRate?.direction||null:null,level:active?this.lastRate?.level??null:null,tx:active?this.tx?.bps??null:null,rx:active?this.rx?.bps??null:null};}
|
snapshot(active){return {listening:this.listening,lastPacket:this.lastPacket||null,error:this.error,at:active?this.lastRate?.at||null:null,bps:active?this.lastRate?.bps??null:null,direction:active?this.lastRate?.direction||null:null,level:active?this.lastRate?.level??null:null,tx:active?this.tx?.bps??null:null,rx:active?this.rx?.bps??null:null};}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user