Compare commits

..
38 Commits
Author SHA1 Message Date
alberto bd8e521711 Fix detached controls on LAN HTTP and late-loaded views 2026-10-29 17:14:53 +01:00
alberto 3643638090 Fix APRS counters, BBS reads and chat parsing; add reliable packet TX helpers 2026-10-29 16:37:51 +01:00
alberto 0668a73d40 Fix repeated login and forwarding alerts; add detached fullscreen controls 2026-10-23 18:00:33 +02:00
alberto c98c67e18b Add detached service windows and selectable terminal themes
Support standalone APRS, Monitor, Chat and Terminal views with courtesy screens, window focus and return controls, shared sessions and suspended embedded polling.

Add five persistent phosphor palettes, remove Console terminal idle disconnections, and display decoded Mic-E movement and altitude with expandable original packets.

Document the new behavior and add regression coverage. Validation: 182 tests passed; the known hanging PowerShell startup readiness test was excluded.
2026-10-19 22:15:15 +02:00
alberto 8ee4e9636a Decode APRS station symbols and improve map centering
Render local APRS symbol sprites with table and overlay details while preserving markers and open popups during refresh.

Open the map around the local station with a 30 km radius and fit the densest station group without distant outliers. Add localization, attribution and regression coverage.
2026-10-19 14:08:49 +02:00
alberto 2ef3c25eb3 Support multiple sysops and bulletin comments; complete UI translations
Allow native SYSOP accounts to sign in independently, with an optional sysopUsers allow-list and isolated browser sessions. Keep station services on the configured service account.

Add public bulletin comments that preserve category and distribution, alongside private replies to the author. Complete APRS and dynamic status translations and handle decorated button labels correctly.

Document configuration and reply behavior. Add authentication, installer, bulletin reply and translation regression coverage.
2026-10-19 13:04:39 +02:00
alberto 33f1294405 Polish dashboard layout and stabilize live map refreshes
Preserve map markers, zoom and open details during polling; consolidate technical notes and align interface spacing. Fix empty English translations inserting undefined text and add regression coverage.
2026-10-18 21:14:35 +02:00
alberto c8941dc199 Improve chat roster parsing, message read state and loading feedback 2026-10-18 14:35:41 +02:00
alberto c980ba10de Add multi-port radio controls and APRS activity dashboard 2026-10-17 21:29:53 +02:00
alberto 018c0f574e Fix sysop BBS deletion and keep confirmation errors visible 2026-10-17 15:50:22 +02:00
alberto 8cb4b6256f Keep Winlink folder selection and post-send refresh consistent 2026-10-17 14:42:08 +02:00
alberto 5fde09823b Add native Winlink attachment upload, reader indicators and verified storage 2026-10-17 14:33:34 +02:00
alberto 2b00b1cbbd Support custom BPQ Telnet prompts and banners, fix installer arguments 2026-10-17 14:14:16 +02:00
alberto 33d2cc4fbd Replace language menu with flag switch and refine login credit 2026-10-17 13:16:00 +02:00
alberto 4a0608b01e Add Italian and English UI with automatic browser language detection 2026-10-17 13:12:20 +02:00
alberto 74e84bb6b2 Keep idle chat links in the connections roster 2026-10-17 12:42:44 +02:00
alberto e64b69e50f Allow manual packet preparation outside the selected scan channels 2026-10-17 11:08:23 +02:00
alberto c0204f6b02 Recover idle radio scanning and reject stale sync progress responses 2026-10-17 10:19:33 +02:00
alberto 573e0aa24e Align mail columns and add live sync dialogs with targeted cancellation 2026-10-17 09:57:34 +02:00
alberto e536f0939c Prioritize idle packet radio preparation for forwarding and Winlink 2026-10-17 09:41:54 +02:00
alberto 9c93ec03e5 Show BBS messages immediately and enrich timestamps in background 2026-10-17 09:34:17 +02:00
alberto abfc8be078 Verify packet PTT readiness and isolate manual VHF forwarding status 2026-10-17 00:54:46 +02:00
alberto 9bb62cf731 Add home scan frequency controls and BPQ radio transmission pause 2026-10-17 00:42:47 +02:00
alberto 0c0a716985 Add VHF and UHF Packet channels to the Winlink radio client 2026-10-16 23:43:45 +02:00
alberto bf8c3a5146 Add manual alternate radio forwarding paths with profile recovery 2026-10-16 23:32:01 +02:00
alberto 7b5be2b9f0 Use BPQ Console branding and remove decorative logos 2026-10-16 21:10:50 +02:00
alberto 5358cad695 Harden generic installation and startup, preserve station settings and coalesce mail reads 2026-10-16 21:03:18 +02:00
alberto 3f6d35690b Add amber phosphor Telnet terminal with isolated BPQ sessions 2026-10-16 18:55:15 +02:00
alberto b5ee05f257 Show pending radio configuration while Winlink data loads 2026-10-16 18:30:31 +02:00
alberto 29b4064e82 Add official Winlink gateway selector and guarded radio mail sync 2026-10-16 18:29:50 +02:00
alberto 75a6d52e3b Display forwarding partners in compact table with row accordion 2026-10-16 17:56:49 +02:00
alberto 8f18ea81f7 Add forwarding partner dashboard with schedules, rules, queues and manual sync 2026-10-16 17:27:29 +02:00
alberto 94649dde33 Reconstruct 7plus multipart attachments with CRC checks and image previews 2026-10-16 13:19:23 +02:00
alberto bcc3cd7a19 Classify journal transports from BPQ ports and Telnet logs with explicit historical evidence 2026-10-16 12:55:23 +02:00
alberto 4f0ea5f008 Add cursor-centered mouse wheel zoom to station map 2026-10-16 00:10:36 +02:00
alberto 388bf3755a Keep map stations at their true locator positions and group coincident points 2026-10-16 00:08:25 +02:00
alberto 106b04d631 Add connection journal with service traffic details and interactive offline station map 2026-10-15 23:17:44 +02:00
alberto 78839f5bb4 Enlarge modem charts and notifications with clearer notification audio 2026-10-15 18:41:16 +02:00
122 changed files with 5741 additions and 189 deletions

No files matched your search

+18
View File
@@ -17,3 +17,21 @@ work/
Thumbs.db Thumbs.db
console.config.json console.config.json
console.config.json.*
station-locations.json
station-locations.json.tmp
winlink-gateways.cache.json*
winlink-radio.session.json*
manual-forwarding.session.json*
propagation.config.json*
aprs-activity.cache.json*
voacap-cache/
forwarding-schedule.state.json*
message-read-state.json*
# Python integration caches
__pycache__/
*.pyc
+10 -3
View File
@@ -1,5 +1,12 @@
$ErrorActionPreference='Stop' $ErrorActionPreference='Stop'
$config=Get-Content -LiteralPath (Join-Path $PSScriptRoot 'console.config.json') -Raw | ConvertFrom-Json $identity=[Security.Principal.WindowsIdentity]::GetCurrent()
if(!([Security.Principal.WindowsPrincipal]::new($identity)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)){throw 'Per creare la regola firewall aprire PowerShell come amministratore.'}
$configPath=if($env:BPQ_CONSOLE_CONFIG){$env:BPQ_CONSOLE_CONFIG}else{Join-Path $PSScriptRoot 'console.config.json'}
$config=Get-Content -LiteralPath $configPath -Raw | ConvertFrom-Json
$port=if($env:BPQ_CONSOLE_PORT){[int]$env:BPQ_CONSOLE_PORT}else{[int]$config.port}
if($port -lt 1024 -or $port -gt 65535){throw 'Porta pannello non valida.'}
$nodeExe=if($config.nodeExe -and (Test-Path -LiteralPath $config.nodeExe)){$config.nodeExe}else{(Get-Command node.exe -ErrorAction Stop).Source} $nodeExe=if($config.nodeExe -and (Test-Path -LiteralPath $config.nodeExe)){$config.nodeExe}else{(Get-Command node.exe -ErrorAction Stop).Source}
Get-NetFirewallRule -DisplayName 'BPQ Web Console LAN' -ErrorAction SilentlyContinue | Remove-NetFirewallRule # Create the replacement before removing the previous rule, so failure keeps it intact.
New-NetFirewallRule -DisplayName 'BPQ Web Console LAN' -Direction Inbound -Action Allow -Protocol TCP -LocalPort $config.port -RemoteAddress LocalSubnet -Program $nodeExe -Profile Private | Out-Null $rule=New-NetFirewallRule -DisplayName 'BPQ Web Console LAN' -Direction Inbound -Action Allow -Protocol TCP -LocalPort $port -RemoteAddress LocalSubnet -Program $nodeExe -Profile Private -ErrorAction Stop
Get-NetFirewallRule -DisplayName 'BPQ Web Console LAN' -ErrorAction SilentlyContinue | Where-Object {$_.Name -ne $rule.Name} | Remove-NetFirewallRule
Write-Host "Accesso LAN abilitato sulla porta $port (rete Privata, sottorete locale)."
+40 -13
View File
@@ -1,26 +1,53 @@
param([string]$BpqRoot,[int]$Port=8090,[int]$HttpPort,[int]$RadioPort,[string]$SysopUser,[string]$ForwardPeer,[switch]$CheckOnly,[switch]$AutoStart,[switch]$EnableLAN) param([string]$BpqRoot,[int]$Port,[int]$HttpPort,[int]$RadioPort,[string]$SysopUser,[string]$ForwardPeer,[string]$CmsPeer,[string]$VaraLogPath,[string]$NodeExe,[ValidateSet("it","en")][string]$Language,[switch]$EnableRadioCAT,[switch]$DisableRadioCAT,[switch]$CheckOnly,[switch]$AutoStart,[switch]$EnableLAN,[switch]$Restart)
$ErrorActionPreference='Stop' $ErrorActionPreference='Stop'
$nodeExe=(Get-Command node.exe -ErrorAction Stop).Source if($EnableRadioCAT -and $DisableRadioCAT){throw 'Scegliere una sola opzione CAT.'}
$major=[int]((& $nodeExe --version).TrimStart('v').Split('.')[0]) if($AutoStart -and !$CheckOnly -and ($env:BPQ_CONSOLE_CONFIG -or $env:BPQ_ROOT -or $env:BPQ_CONSOLE_PORT)){throw 'Per -AutoStart usare console.config.json nella cartella del progetto, senza override BPQ_* temporanei.'}
if($major -lt 20){throw 'Serve Node.js 20 o successivo nel PATH.'} $configPath=if($env:BPQ_CONSOLE_CONFIG){$env:BPQ_CONSOLE_CONFIG}else{Join-Path $PSScriptRoot 'console.config.json'}
$saved=$null
if(Test-Path -LiteralPath $configPath){try{$saved=Get-Content -LiteralPath $configPath -Raw | ConvertFrom-Json}catch{throw 'Configurazione locale non leggibile: correggere il JSON prima di reinstallare.'}}
if(!$NodeExe){$NodeExe=if($saved.nodeExe -and (Test-Path -LiteralPath $saved.nodeExe)){$saved.nodeExe}else{(Get-Command node.exe -ErrorAction SilentlyContinue).Source}}
if(!$NodeExe -or !(Test-Path -LiteralPath $NodeExe)){throw 'Installare Node.js 20 o successivo, oppure specificare -NodeExe con il percorso di node.exe.'}
$version=& $NodeExe --version
if($LASTEXITCODE -ne 0 -or $version -notmatch '^v(\d+)\.' -or [int]$Matches[1] -lt 20){throw 'Serve Node.js 20 o successivo.'}
if(!$BpqRoot){ if(!$BpqRoot){
if($env:BPQ_ROOT){$BpqRoot=$env:BPQ_ROOT}
elseif($saved.bpqRoot){$BpqRoot=$saved.bpqRoot}
else{
$candidates=@((Join-Path $env:APPDATA 'BPQ32')) $candidates=@((Join-Path $env:APPDATA 'BPQ32'))
$running=Get-CimInstance Win32_Process | Where-Object {$_.Name -match '^(BPQTerminal|BPQMail|BPQChat|bpq32)\.exe$'} $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}} 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 $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.'} 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") if(!$CheckOnly -and $Restart){
foreach($option in @(@('http-port',$HttpPort),@('radio-port',$RadioPort),@('sysop-user',$SysopUser),@('forward-peer',$ForwardPeer))){if($option[1]){$arguments+=@('--'+$option[0],"$($option[1])")}} $pending=Join-Path $PSScriptRoot 'winlink-radio.session.json'
if($CheckOnly){$arguments+='--check-only'} if((Test-Path -LiteralPath $pending) -and (Get-Content -LiteralPath $pending -Raw | ConvertFrom-Json).restoring){throw 'Attendere il ripristino della sessione Winlink radio prima di reinstallare e riavviare.'}
& $nodeExe @arguments }
$targetPort=if($PSBoundParameters.ContainsKey('Port')){$Port}elseif($env:BPQ_CONSOLE_PORT){[int]$env:BPQ_CONSOLE_PORT}elseif($saved.port){[int]$saved.port}else{8090}
if($targetPort -ge 1024 -and $targetPort -le 65535){
$listener=Get-NetTCPConnection -LocalPort $targetPort -State Listen -ErrorAction SilentlyContinue
if($listener){$owner=Get-CimInstance Win32_Process -Filter "ProcessId=$($listener[0].OwningProcess)";if($owner.Name -ne 'node.exe' -or !$owner.CommandLine -or $owner.CommandLine.IndexOf((Join-Path $PSScriptRoot 'server.mjs'),[StringComparison]::OrdinalIgnoreCase) -lt 0){throw "Porta $targetPort occupata da un altro processo. Specificare -Port con una porta libera."}}
}
$nodeArgs=@((Join-Path $PSScriptRoot 'install.mjs'),'--bpq-root',$BpqRoot,'--config-path',$configPath)
$mapping=@{Port='port';HttpPort='http-port';RadioPort='radio-port';SysopUser='sysop-user';ForwardPeer='forward-peer';CmsPeer='cms-peer';VaraLogPath='vara-log';Language='language'}
foreach($name in $mapping.Keys){if($PSBoundParameters.ContainsKey($name)){$nodeArgs+=@(('--'+$mapping[$name]),[string](Get-Variable -Name $name -ValueOnly))}}
if(!$VaraLogPath){$vara=Get-Process -Name VARA -ErrorAction SilentlyContinue | Select-Object -First 1;if($vara.Path){$varaLog=Join-Path (Split-Path $vara.Path) 'VARAHF.log';if(Test-Path -LiteralPath $varaLog){$nodeArgs+=@('--vara-log',$varaLog)}}}
if($EnableRadioCAT){$nodeArgs+='--enable-radio-cat'}
if($DisableRadioCAT){$nodeArgs+='--disable-radio-cat'}
if($CheckOnly){$nodeArgs+='--check-only'}
& $NodeExe @nodeArgs
if($LASTEXITCODE -ne 0){throw 'Installazione interrotta: verifica BPQ fallita.'} if($LASTEXITCODE -ne 0){throw 'Installazione interrotta: verifica BPQ fallita.'}
if($CheckOnly){return} if($CheckOnly){return}
if($AutoStart){ if($AutoStart){
$action=New-ScheduledTaskAction -Execute 'powershell.exe' -Argument ('-NoProfile -WindowStyle Hidden -File "'+(Join-Path $PSScriptRoot 'Start-Console.ps1')+'"') -WorkingDirectory $PSScriptRoot $identity=[Security.Principal.WindowsIdentity]::GetCurrent().Name
$trigger=New-ScheduledTaskTrigger -AtLogOn -User ([Security.Principal.WindowsIdentity]::GetCurrent().Name) $action=New-ScheduledTaskAction -Execute (Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe') -Argument ('-NoProfile -ExecutionPolicy RemoteSigned -WindowStyle Hidden -File "'+(Join-Path $PSScriptRoot 'Start-Console.ps1')+'"') -WorkingDirectory $PSScriptRoot
Register-ScheduledTask -TaskName 'BPQ-WebConsole' -Action $action -Trigger $trigger -Description 'BPQ web console locale' -Force | Out-Null $trigger=New-ScheduledTaskTrigger -AtLogOn -User $identity
$principal=New-ScheduledTaskPrincipal -UserId $identity -LogonType Interactive -RunLevel Limited
Register-ScheduledTask -TaskName 'BPQ-WebConsole' -Action $action -Trigger $trigger -Principal $principal -Description 'BPQ web console locale' -Force | Out-Null
} }
& (Join-Path $PSScriptRoot 'Start-Console.ps1') -Restart:$Restart
if($EnableLAN){& (Join-Path $PSScriptRoot 'Enable-LAN.ps1')} if($EnableLAN){& (Join-Path $PSScriptRoot 'Enable-LAN.ps1')}
& (Join-Path $PSScriptRoot 'Start-Console.ps1') $current=Get-Content -LiteralPath $configPath -Raw | ConvertFrom-Json
Write-Host "Pannello: http://127.0.0.1:$Port" $displayPort=if($env:BPQ_CONSOLE_PORT){$env:BPQ_CONSOLE_PORT}else{$current.port}
Write-Host "Pannello: http://127.0.0.1:$displayPort"
+257 -32
View File
@@ -1,77 +1,302 @@
# BPQ Console # BPQ Console
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. A local web dashboard for BPQ32: node status, BBS, Winlink, forwarding, chat, traffic monitor, contact journal and an amber Telnet terminal. Callsigns, aliases, locator and ports come from your station configuration. Node.js backend with no external npm dependencies; HTML/CSS/JavaScript frontend.
## Requisiti ## Interface language
- Windows con PowerShell e Node.js 20 o successivo disponibile nel PATH. Use the Italian / UK flag switch in the login screen or dashboard header to select **Italiano** or **English**. Set `"language": "en"` or `"language": "it"` in `console.config.json` to choose the default for new browsers (or install with `-Language en` / `node install.mjs --language en`). If omitted, the first preferred browser language selects Italian for `it` / `it-*`, English otherwise. A language already saved in a browser takes precedence. After that the saved choice is used; there is no Auto mode. Switching language applies immediately, without signing out or interrupting a radio session. Dates and numbers follow the selected language; the local timezone is unchanged. Mail, bulletin subjects and bodies, chat messages, attachment contents, terminal output and radio traffic remain original. No online translation service is used.
- 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 Interface copy is maintained in `public/i18n.js`; add new UI phrases and parameterised status patterns there. Mark custom data widgets with `data-no-i18n` so their content is preserved.
Scaricare o clonare il repository, aprire PowerShell nella cartella del progetto e avviare BPQ. Verificare prima il rilevamento senza modificare nulla: ## Sysop accounts
Every Telnet `USER=` account with the `SYSOP` flag in `BPQ32.cfg` can sign in with its own username and password. Usernames are case-insensitive; passwords are case-sensitive. Normal BPQ users cannot sign in. Each browser session has its own identity, cookie and CSRF token; signing out of one session leaves other sessions active. The profile shows the signed-in user's callsign.
`sysopUser` in `console.config.json` selects the station's service account. Terminal connections, the shared Chat, Monitor and native BBS operations continue to use that account. All authorised sysops administer the same station, BBS and Winlink mailbox; logging in with another callsign does not create a separate mailbox or change the station identity.
To restrict Console access to particular native sysops, add the optional `sysopUsers` allow-list:
```json
{
"sysopUser": "admin",
"sysopUsers": ["admin", "Marco"]
}
```
Use existing BPQ usernames, not callsigns. Every listed account must already have the native `SYSOP` flag. Entries are case-insensitive; credentials remain exclusively in `BPQ32.cfg`. Omitting `sysopUsers` allows all native sysops; an empty array allows nobody. Invalid lists stop startup/installation instead of being ignored. Restart BPQ Console after changing the list; BPQ does not need a restart. Reinstallation preserves the list for the same station folder and resets it when installing against another station.
## Bulletin comments and private replies
The BBS reader offers **Comment** for bulletins: it creates a new bulletin (`B`) addressed to the original category and distribution, for example `NEWS@WW`. **Reply** creates a personal message (`P`) addressed to the author. Personal messages only show Reply. Both actions open an editable draft with the original subject prefixed by `Re:` and the quoted text; nothing is published until Save and queue is selected. Comments use BPQ's normal bulletin forwarding rules and do not modify the original message.
## Message deletion
Deleting BBS or Winlink messages requires an authorised Console sysop login and that session's CSRF token. The Console opens a fresh BPQ WebMail session, issues the native delete action and verifies that the message disappeared or has status `K`. If WebMail rejects deleting another author’s bulletin, the authenticated sysop Console uses BPQ’s local administrative message action, preserving the other message fields and changing only status to `K`. BPQ updates its own database and forwarding flags. No account flags are changed. Already deleted messages are handled safely; failures are displayed inside the confirmation dialog.
## Winlink attachments
Incoming and queued Winlink messages show an attachment indicator in the list and file cards in the reader. Download original files or preview images, PDFs and plain text; HTML/SVG attachments are shown as text. Binary attachments use BPQ’s native B2 format.
In **New email**, use **Attach files** or drop files into the attachment panel. Review filenames, sizes and image thumbnails; remove files before saving. The Console accepts up to 10 files and 64 KiB total per outgoing email, with a combined message text/file limit of 80 KiB and the existing 32 KB body limit. These Console upload limits leave room for multipart headers within the native BPQ HTTP input buffer; BPQ, the receiving gateway and radio conditions may impose further limits. Small files are preferable over radio. Files stay in the browser until the message is saved and then use BPQ’s native WebMail attachment upload and normal Winlink queue, over Internet or radio. The Console verifies that BPQ stored the same filenames and file bytes before confirming success. If it reports a saved message with mismatched attachments, check the queue before retrying.
Use **Detach** in APRS, Monitor, Chat or Terminal to open a standalone window. The embedded section switches to a courtesy screen with **Show window** and **Bring back here**, and pauses its own polling. Returning or closing the detached window restores the embedded view without disconnecting the underlying service. Window ownership is coordinated per browser and origin; stale ownership expires if a window crashes. Popup blocking leaves the embedded view available.
Use **Detach** in the terminal toolbar to open a compact standalone window. Both views share the existing authenticated Telnet session and transcript; closing the window does not disconnect it. **Back to dashboard** returns to the original panel. Allow popups for the Console if the browser blocks the window. Amber, Green, Ice, Violet and White phosphor themes are saved per browser and synchronized between open views.
Terminal connections are not closed by BPQ Console for inactivity, including when another dashboard page is open. Disconnect or sign out to close the terminal. BPQ and remote applications may still enforce their own session limits.
## Telnet login compatibility
Terminal and Chat read `LOGINPROMPT` and `PASSWORDPROMPT` from the Telnet port in `BPQ32.cfg`. Standard `Username:`, `Login:`, `User:` and `Password:` prompts also work. `PASSWORD` is not the prompt setting. Custom CTEXT banners do not need the word Welcome or a node prompt; both `ALIAS:CALL>` and `ALIAS:CALL}` work. After the password, the clients wait for 400 ms of quiet after non-empty banner text; a repeated login/password prompt or explicit denial rejects the login. Password echoes are removed before displaying the terminal banner, and Chat discards the Telnet banner before sending `CHAT`. A server that sends no text at all after the password times out instead of reporting an unconfirmed login as successful. Restart BPQ Console after changing prompt settings.
## Requirements
- Windows and Windows PowerShell 5.1 or later.
- Node.js 20 or later. A portable `node.exe` can be selected with `-NodeExe`.
- BPQ32 installed and running, with `HTTPPORT` configured in its Telnet driver.
- A Telnet `USER` with the `sysop` role. The panel accepts native SYSOP accounts, subject to the optional `sysopUsers` allow-list; passwords stay in `BPQ32.cfg`.
- Optional: BPQMail for BBS/Winlink, BPQChat and `TCPPORT` for chat, `FBBPORT` for the monitor. The terminal only needs `TCPPORT`.
Service detection recognises the `BBS` and `CHAT` application command names, case-insensitively. Those applications must actually be running to use their pages. The installer does not install BPQ, configure a modem, change radio frequencies or create forwarding partners.
## Install
Clone or download and extract the project into a writable folder. Start BPQ first. Open PowerShell in the project folder and run a read-only check:
```powershell ```powershell
.\Install.ps1 -CheckOnly .\Install.ps1 -CheckOnly
``` ```
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. If your normal PowerShell policy blocks local scripts, after reviewing the files you can run them with a policy limited to that process:
Installazione e avvio del pannello: ```powershell
powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File .\Install.ps1 -CheckOnly
```
This does not change your user or machine execution policy. Downloaded files may still require unblocking after review; organisation Group Policy remains authoritative.
Install and start:
```powershell ```powershell
.\Install.ps1 .\Install.ps1
``` ```
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. Open **http://127.0.0.1:8090** and sign in with an authorised BPQ Telnet SYSOP account. No `npm install` or build step is required.
Per percorsi o porte diversi e per selezionare il modem e il profilo BBS: Detection uses an explicit `-BpqRoot`, `BPQ_ROOT`, the previously saved data folder, `%APPDATA%\BPQ32`, or the folders of running BPQ processes. The HTTP check must identify BPQ before any configuration is written. `-CheckOnly` never saves configuration, starts the panel, registers a task or changes the firewall, even if other switches are present.
Explicit settings:
```powershell ```powershell
.\Install.ps1 -BpqRoot 'D:\BPQ' -Port 8090 -HttpPort 8080 -RadioPort 3 -SysopUser 'sysop' -ForwardPeer 'N1TEST' .\Install.ps1 -BpqRoot 'D:\Radio\BPQ data' -Port 8095 -HttpPort 8080 -RadioPort 3 -SysopUser 'admin' -ForwardPeer 'N1TEST'
``` ```
-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. | Option | Purpose |
| --- | --- |
| `-BpqRoot` | Folder containing `BPQ32.cfg`, not necessarily the program installation folder. |
| `-Port` | Web panel port, 1024–65535; default 8090 on first install. |
| `-HttpPort` | BPQ HTTP port; defaults to the Telnet driver setting. Must differ from the panel port. |
| `-RadioPort` | Existing BPQ radio port number. The first is selected initially; multiple modems produce a warning. |
| `-SysopUser` | Native sysop account used by Terminal, Chat and station services; defaults to the first on initial installation. Console logins are controlled separately by `sysopUsers`. |
| `-ForwardPeer` | Existing BBS forwarding partner for the dashboard shortcut. No partner is created automatically. |
| `-CmsPeer` | Existing CMS forwarding profile; defaults to `RMS`. |
| `-NodeExe` | Full path to a Node.js 20+ `node.exe`. Saved for future startup. |
| `-VaraLogPath` | Optional local `VARAHF.log` used by the journal. A running local VARA log is detected when available. |
| `-EnableRadioCAT` / `-DisableRadioCAT` | Explicitly enable/disable Winlink radio tuning through BPQ. No tuning test or transmission is performed. |
| `-Restart` | Restart this project's web panel after installation/update. Does not restart BPQ or VARA. |
Opzioni aggiuntive: Without a selected forwarding partner the dashboard shortcut is disabled. The Forwarding page can still show and start other configured partners.
## Updates and local settings
Reinstalling for the same BPQ data folder preserves custom settings, including the panel port, CMS profile, VARA options and Winlink CAT opt-in. Changed configuration is backed up as `console.config.json.<timestamp>.backup`, then saved atomically. An unchanged configuration is not rewritten. Invalid JSON, missing selected ports/users or invalid explicit profiles stop installation with an error.
If you select a different station folder, station-specific selections are detected again. If the selected modem changes, CAT opt-in is cleared unless explicitly enabled. Use a separate project folder for each station so journals, caches and recovery state remain separate.
After updating the project:
```powershell ```powershell
# Avvio automatico al login Windows .\Install.ps1 -CheckOnly
.\Install.ps1 -Restart
```
For a normal start or restart without rerunning detection:
```powershell
.\Start-Console.ps1
.\Start-Console.ps1 -Restart
```
Startup checks the port, Node version and the new server's `/health` response. It reports failures instead of claiming success when Node exits. An existing panel on another port is not duplicated. Changed settings require a restart. A Winlink radio session awaiting profile restoration blocks `-Restart`; let that session finish first. Restarting the panel closes its browser/Telnet sessions.
Environment overrides: `BPQ_ROOT` selects the BPQ data folder; `BPQ_CONSOLE_PORT` selects the panel port; `BPQ_CONSOLE_CONFIG` selects a different local JSON configuration file. Install and startup scripts respect these overrides. Use the standard `console.config.json` without temporary environment overrides when registering automatic startup.
Station greetings, ASCII banners, radio schedules, routing and Winlink availability reports remain local BPQ settings. The installer does not overwrite them. Personal BPQ configuration and credentials are not part of this repository.
## Automatic startup and LAN
```powershell
# Start at this Windows user's logon
.\Install.ps1 -AutoStart .\Install.ps1 -AutoStart
# Accesso dalla sottorete locale, su profilo rete Privato # Optional access from the local subnet; requires an administrator shell
# Eseguire PowerShell come amministratore per la regola firewall
.\Install.ps1 -EnableLAN .\Install.ps1 -EnableLAN
``` ```
-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. `-AutoStart` registers **BPQ-WebConsole** for the current user, with interactive logon and limited privileges. It uses the saved Node path and process-scoped `RemoteSigned` execution policy. Windows policy may restrict task registration. Remove the task to disable automatic startup. BPQ must have its own startup arrangement.
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. `-EnableLAN` creates a firewall rule for the selected Node executable and panel port, restricted to the **Private** profile and **LocalSubnet**. Existing rules are replaced only after the new rule is created successfully. From another computer use the BPQ PC's private IPv4 address and panel port. The panel accepts loopback and private IPv4 hosts, not arbitrary DNS hostnames or public addresses.
## Modem e servizi opzionali This is an administrative panel for a trusted PC/LAN, using HTTP. Do not expose it directly to the Internet. Authentication uses HttpOnly/SameSite cookies and writes require Origin/CSRF checks. Configuration, logs, mail files, station locations and runtime caches are excluded from Git.
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. ## Modems and telemetry
Il grafico TRAFFICO BPQ mostra TX/RX in bit/s calcolati dalla variazione dei contatori byte BPQ nel tempo; indica traffico utile effettivo, non il bitrate negoziato dal modem. È disponibile per le porte radio, anche senza VARA. Il grafico CPU VARA è abilitato soltanto quando la porta selezionata usa il driver VARA. La ricezione syslog del bitrate VARA resta disponibile nel backend come diagnostica, ma non alimenta il KPI principale. 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. VARA is optional. PACTOR, ARDOP, KISS and other BPQ ports show the information their driver exposes; missing data remains unavailable. VARA-specific controls are disabled for other drivers.
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. **TRAFFICO BPQ** derives TX/RX bit/s from BPQ byte-counter changes, rather than claiming to show the negotiated modem bitrate. The VARA CPU chart only applies to a local VARA process. Remote VARA CPU usage cannot be measured locally. Optional VARA bitrate diagnostics listen on loopback UDP 18514; change `varaSyslogPort` in local configuration if needed. The VARA version must emit bitrate records with CommandsLog enabled. The panel does not open a second VARA TCP control connection.
## Funzioni e dati ## BBS, mail and attachments
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. BBS and Winlink provide folders, search, composition, replies, deletion and B2 attachments, with the message list above the reader. Delete marks a message `K` in BPQ and does not recall mail already delivered elsewhere. The panel uses BPQ's interfaces for writes, never edits `DIRMES.SYS` or `.mes` files directly.
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. Image, PDF and text attachments have previews and downloads. HTML/SVG are treated as text. Multipart 7plus files are reconstructed from the original message bytes when all parts and CRC checks are valid. Matching uses sender, filename, size, part count, block size and 7plus timestamp, not just the subject. Missing/damaged parts prevent downloading a false result. COR/ERR repair is not implemented. Limits: 32 MB per reconstructed file, 255 parts, 2 MB per scanned message and a 64 MB memory cache. Reference format: [7PLUS 2.25 source](https://ponce.cc/slackware/sources/repo/7pl225sr.zip).
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. Concurrent readers share in-flight BPQ requests. Dashboard counters and Winlink avoid loading timestamp metadata for every bulletin. The first full BBS listing can take longer on a large archive while exact BPQ timestamps are loaded; subsequent reads reuse the timestamp cache.
## Sicurezza e verifica Dates use the browser timezone. Arrival notifications distinguish downloaded bulletins and incoming mail from messages you composed; the first load does not announce old messages as new. Sound requires a browser gesture.
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. ## Winlink Internet and radio
Winlink requires `CMS=1`, the BBS application and a configured CMS forwarding profile. **Sync Internet** starts that profile; it does not create a gateway or forwarding configuration.
**Sync Radio** opens the [official public Winlink gateway directory](https://cms.winlink.org:444/GatewayChannels.aspx), without an API key. Search callsign/locator/location, filter by band and opening hours, and sort by distance, callsign or frequency. The modem family selects the directory mode. Cache: 15 minutes; manual refresh is throttled to once per minute. Calls require a directory no older than 30 minutes, an open UTC schedule and a report within six hours. A report does not guarantee reachability or a clear channel. Distance is geographical, not a propagation prediction; VOACAP is not required.
Displayed frequencies are **USB dial**, calculated as the published centre frequency minus 1500 Hz. Verify this offset against your modem setup. Scheduling is UTC; report timestamps use the browser timezone.
Radio connection requires a supported HF modem, available telemetry and working BPQ `RADIO` CAT control. Enable this deliberately:
```powershell ```powershell
node --test test.mjs .\Install.ps1 -EnableRadioCAT -Restart
``` ```
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. Selecting a row does not transmit. **Connetti e sincronizza** explicitly starts the selected gateway. Busy modem/BBS sessions block startup and the panel does not override a busy channel. The CMS profile must normally use `RMS` or `C port CMS` as its Internet script.
Before changing that profile, the panel backs up `BPQMail.cfg` under `BPQMailChat/Backup-winlink-radio-*`. It temporarily disables the profile timer, sets an ATTACH/RADIO/CONNECT script and enables compressed B2 personal mail. Once BPQ streams are idle, it restores the original profile. `winlink-radio.session.json` retains recovery state across panel restarts. Concurrent manual profile edits suspend automatic restoration and expose a restore button. Keep the panel running during the exchange. The initial status confirms a request to BPQ; results and counts come from logs.
## Forwarding, chat and terminal
The home modem card shows the configured `RADIO` scan frequencies, mode, dwell time and current channel. With a compatible local scan controller, checkboxes include/exclude channels (at least one must remain selected). **Sospendi TX** stops the BPQ radio ports and closes radio sessions; **Riprendi radio** reopens them and restores scanning. Internet mail/chat remain available. The panel blocks new radio forwarding while paused or while a change is being applied. These controls change local listening; `WL2KREPORT` channel publication remains separately configured in BPQ.
Rig controls are optional and read-only when no fresh controller acknowledgement is available. Configure local `radioControl` with `rig`, absolute `requestFile` and `statusFile` paths. The panel writes `{revision,enabled:["7050000-USB"],txSuspended:false}`; IDs are integer Hz plus mode, derived from the actual BPQ scan list. The controller must validate requests, wait for radio sessions before changing scan frequencies, apply changes and publish fresh `{at,frequency,txSuspended,appliedRevision,error}` status. Only matching `appliedRevision` confirms completion. The station's controller backs up `BPQ32.cfg`, preserves disabled entries as `; CONSOLE-OFF ...`, reloads rig control and confirms CAT readiness. The installer does not guess CAT/PTT commands or enable this write interface for unknown hardware; supply a compatible controller for that station.
The Winlink radio directory also downloads **PUBLIC Packet** channels when a UZ7HO/KISS/AX.25 port is present. Band filters include VHF (2 m), UHF (70 cm), both, and all bands. Packet channels use the published FM frequency exactly; the 1500 Hz USB offset applies only to HF channels. The channel details show the selected local port. Unsupported packet speeds stay visible with an explanation and cannot be selected; local support defaults to 1200 baud.
Optional `winlinkRadio.packetPort` selects a specific local packet port and `winlinkRadio.packetBaud` declares its configured speed. These settings do not reprogram a TNC: its modem, audio and PTT must already be set up. The current packet client limits selection to 144–146 MHz and 430–440 MHz. Shared-radio installations may configure `winlinkRadio.packetController` with the same request/status file handshake described below. Their controller must acknowledge the requested frequency and keep the modem active while attached/connected. Internet forwarding is temporarily suspended and restored with the same recovery mechanism as HF radio sync. Directory downloads use Internet; the selected mail exchange uses radio.
To publish a local packet gateway, configure BPQ's native `WL2KREPORT` on the packet port (before its `CONFIG` block), using mode `PKT1200`, the exact FM frequency in Hz, the RMS application's callsign, locator and actual UTC hours. BPQ must expose its RMS application on that port. The panel does not publish gateways itself. Reload BPQ after editing and verify the public directory after its next report; saving a line alone does not confirm publication. See the [official BPQ reporting documentation](https://www.cantab.net/users/john.wiseman/Documents/WL2KReporting.html).
**Forwarding** shows configured partners in a compact table. Click a row (or Enter/Space) to expand routing rules, scripts, schedules, queue counts and recent exchanges. Only one row opens at a time; focus survives refresh. Sync buttons are authenticated, serialised and protected against duplicate requests, active sessions and modem use. The next attempt is a log-based estimate; BPQ owns the real timer. Sensitive script commands are masked. Rules remain editable in BPQ.
Optional `manualForwardingRoutes` in local `console.config.json` adds alternate radio paths to an existing BBS partner, without duplicating its queue or creating an automatic schedule:
```json
"manualForwardingRoutes": [
{"id":"N0TEST-VHF","label":"N0TEST · VHF","peer":"N0TEST","port":3,"frequencyMHz":144.825,"mode":"DATA-FM","connectCall":"N0TEST-8"}
]
```
Use your partner's published frequency/callsign and a configured radio port. The button temporarily disables that partner's automatic timer and immediate forwarding, starts an ATTACH/RADIO/CONNECT script, then restores its original profile when BBS streams are idle. The panel saves a backup under `BPQMailChat/Backup-manual-forwarding-*` and recovery state in `manual-forwarding.session.json`; keep it running during the exchange. The normal path's schedule and all routing rules are preserved. Merely listing or expanding the path never calls the station.
Stations with an external scan controller may additionally supply absolute `controller.requestFile` and `controller.statusFile` paths. The panel writes `{id,frequencyMHz,expiresAt}` (90-second reservation); the controller must acknowledge the same `manualRequestId`, `phase:"vhf"`, matching MHz `frequency` and fresh ISO `at`. The selected BPQ port must report `Connected to TNC` and `1200bd` before forwarding starts. The controller must hold the frequency while attached/connected and release it after expiry or `expiresAt:0`. This handshake is intended for a locally configured packet scan controller; it is not installed automatically for other stations.
**Chat** uses the selected sysop's shared session, with rooms, connected users, peer links and private messages. **Monitor** uses BPQTermTCP, with port/direction filters and TXT export. They retain up to 300 chat events and 1000 monitor frames, and disconnect after two minutes without polling.
**Terminale** opens a real Telnet session to the local BPQ `TCPPORT`, automatically authenticating without returning login credentials to the browser. It has amber phosphor styling, scanlines, selectable text and a cursor that respects reduced-motion settings. Enter sends one command; Up/Down browse history. Pulisci clears the screen, Salva testo downloads it, and Disconnetti closes the socket. Scrolling upwards pauses following; the bottom button resumes it.
Each web login has its own terminal/socket and in-memory transcript. Logout/expiry closes it; so do 90 seconds without terminal polling or 15 minutes without commands. Limits: 1000 characters per command, 200,000 output characters and 100 history entries. It is a BPQ line terminal, not a full-screen VT100 or binary YAPP client. Remote HTML and ANSI controls are not executed.
## Journal and map
The journal reconstructs up to 30 days and 5000 sessions from BPQ BBS, Chat and CMSAccess logs, with optional VARA log enrichment. It shows service, direction, transport, outcome, recorded frequency, duration, SNR, attempts, counters and events; filters and CSV export apply to the visible records. Missing/rotated/incomplete logs may prevent reconstructing older contacts. Data is not invented; unknown transport is explained in details. Credential challenges, mail bodies and chat conversations are not exposed in journal events.
The local map uses [Natural Earth](https://www.naturalearthdata.com/about/terms-of-use/) geometry without external tiles or API keys. Your position comes from BPQ's locator. Save remote Maidenhead locators supplied by stations in `station-locations.json` (4, 6 or 8 characters). Points represent locator centres; stations sharing a locator share the point, without artificial displacement. Click a point or trace for callsign, time and contact details. Wheel zoom, drag, zoom buttons and fit-to-network are supported. Traces join stations, not propagation paths or NET/ROM hops. Stations without known locators remain unplotted.
## Verification and troubleshooting
```powershell
npm test
# Or, without npm:
node --test
```
Tests cover protocol parsing, mail/attachments, journal, gateway validation, profile restoration, generic station detection and installer behaviour. Windows tests exercise the PowerShell wrappers in temporary folders, including paths with spaces/apostrophes, duplicate starts, restart and startup failure. They do not create scheduled tasks or firewall rules.
- **BPQ unreachable:** start BPQ and check its Telnet `HTTPPORT`; rerun `-CheckOnly`.
- **Missing service:** check the matching application/port and that BPQMail/BPQChat is running.
- **Wrong modem/sysop after BPQ changes:** rerun installation with the appropriate selection.
- **Port already in use:** choose a different `-Port`; do not reuse BPQ's HTTP port.
- **Changed settings:** use `Start-Console.ps1 -Restart` when no radio profile restoration is pending.
- **Startup fails:** inspect local `server-error.log`. A failed start is not reported as success.
- **Script/task policy blocks execution:** review the files and your Windows policy; organisation restrictions cannot be overridden by the installer.
Third-party PDF.js, font and CMap licences are retained under `public/vendor/pdfjs`; map attribution is in `public/WORLD-MAP-LICENSE.txt`.
Packet controller integrations must acknowledge a reserved slot with `pttReady: true`, after checking that their BPQ PTT backend responds. A modem TCP connection alone is insufficient. The slot status must also contain the matching request ID, frequency, VHF phase and a fresh timestamp. Manual alternate routes share the partner queue; their native HF row is reserved during use and is not counted as a second active session.
The local packet controller can use `packet-preparation.mjs` to prioritize an idle manual Packet request by advancing BPQ's native scan toward its configured packet entry. This retains the native modem interlock (for example VARA V0/LISTEN OFF), rather than directly retuning from an HF receive slot. Do not advance while attached, connecting, transmitting, or paused. Forwarding and Winlink share the same slot handshake; its measured `preparationMs` is saved with the reservation. A single radio still requires exclusive access to the selected frequency.
Manual forwarding and Winlink sync buttons open a live progress dialog (preparation, calling, message exchange, restoration and outcome). Minimize keeps the session running. Interrupt cancels pending packet preparation or disconnects only the matching native BBS partner, then restores the temporary radio profile. Progress jobs are kept by the Console process; restarting the Console clears their visual history. Mail column headings share the same scroll area as their rows.
Sync status responses carry a revision; the browser rejects late responses for previous jobs and never revives a terminal session. The local radio controller can use `canRecoverIdleScan` to release stale scan holds only after eight seconds of verified RF inactivity, without overriding active links, manual packet reservations or TX pause.
Manual packet sync is independent of the listening scan selection. When the packet channel is excluded from scanning, the local station adapter can reserve it directly: stop the idle HF modem, verify the packet frequency and DATA-FM mode through CAT, and start the packet modem. After release, restore HF and the original scan selection without editing the scan configuration. TX pause and active radio sessions still prevent transmission. Forwarding and Winlink use the same reservation path.
### Multiple radio ports
Overview discovers all radio ports in BPQ32.cfg. Each port has separate telemetry and history; select its tab to view charts. Packet ports show BPQ AX.25 frame and timeout counters instead of unsupported SNR/modem CPU readings. Missing telemetry is displayed as unavailable.
Independent controls require an installed station controller. Configure `radioPortsControl` in the private `console.config.json`:
```json
"radioPortsControl": {
"requestFile": "C:/BPQ32/Automation/RadioPorts-request.json",
"ports": [
{ "port": 1, "kind": "native", "independent": true },
{
"port": 3, "kind": "packet", "independent": true,
"statusFile": "C:/BPQ32/Automation/Packet-status.json",
"channels": [
{ "id": "144950000-FM", "frequencyMHz": 144.95, "mode": "FM", "dwellSeconds": 15, "enabled": true }
]
}
]
}
```
The `native` integration uses the existing primary `radioControl` controller. The shared request file contains `ports[portNumber]` with `revision`, `listening`, `txSuspended` and `channels`. Controllers must honor both per-port policy and the existing global TX suspension. Packet status includes a fresh `at`, `frequency`, `pttReady`, `connections`, `appliedPortRevision` and optional `txBytes`, `rxBytes`, `sessionActive`, `caller`, `called`, `scanning`, `busy`. Only expose controls after the controller acknowledges readiness. Keep frequencies fixed during active links and manual reservations; resume the selected listening channels after release. Packet scan edits accept 144–146 or 430–440 MHz with a dwell of 5–300 seconds. Native HF scan selection retains BPQ's configured channels and dwell times.
The Windows Bluetooth adapter and HF station scripts are local integrations, not installed by the generic installer. Without compatible controllers, additional ports remain visible for statistics and their control buttons are disabled. The browser sampling interval does not start transmissions. Native KISS radio connect scripts use `C <port> !<call>` to force RF and bypass an existing NET/ROM route.
### APRS configuration
The APRS page edits station identity, beacon, APRS-IS server and per-port routing. Listening, RF → APRS-IS, RF digipeating, APRS-IS messages → RF and RF beacons are independent choices. Saving creates a native configuration backup and requests `APRS RECONFIG` over authenticated BPQ Telnet; a rejected request restores the previous native file. Existing passcodes remain private and are retained when the password field is empty. Changes are applied only when **Save and apply** is selected.
APRS frequency controls are exposed for packet controllers explicitly advertising `aprsGuard: true` in their `radioPortsControl.ports` descriptor. That controller must enforce `Automation/AprsConsole-policy.json` at the RF boundary: APRS UI frames are allowed only on the selected APRS frequency and only in the configured direction, including separate handling of third-party Internet messages and the station's own beacons. Connected AX.25 sessions remain available for manual sync on other frequencies. Merely advertising the flag without implementing the RF guard is unsupported. The local VR-N7500 integration includes this guard; generic installers do not install hardware-specific adapters or enable APRS retransmission.
Enabling APRS listening selects that port's APRS frequency as its fixed listening channel. Manual Winlink/BBS reservations temporarily override it, then restore the port's listening selection. Disabling APRS routing does not power down the radio; listening channels remain manageable from Overview. Native APRS digipeating handles paths, hop limits and duplicates. Broad geographic APRS-IS → RF forwarding is not enabled by this page.
APRS RX monitoring can optionally use a receive-only TCP KISS endpoint that explicitly supports multiple clients: set aprsKissMonitor to an array of objects with port (BPQ port number), host and tcpPort in console.config.json. This connection never sends data or commands. Do not enable it on a single-client TNC. Radio TX still comes from the BPQ monitor; historical native station entries are not counted as received packets.
### Scheduled packet forwarding
Optional `forwardingSchedules` in the private `console.config.json` schedules an existing `manualForwardingRoutes` entry, for example:
```json
"forwardingSchedules": [
{ "route": "N0TEST-VHF", "enabled": true, "intervalSeconds": 3600 }
]
```
The Console server must remain running. Hourly calls start on hour boundaries, independently of the browser. The scheduler uses the same radio reservation, BBS queue, routing rules and recovery as a manual call. It does not edit listening channels: after completion, failure or cancellation, the packet adapter releases the temporary frequency and resumes the current listening/APRS selection. TX suspension, active radio links and BBS sessions still block calls; a blocked attempt is skipped until the next boundary. Persisted schedule state prevents replay after a server restart. Disable the native HF forwarding timer for that partner when replacing it with a packet schedule, to avoid competing calls. The Forwarding table shows the interval and next attempt.
An optional schedule hours object, for example { "timeZone": "Europe/Rome", "start": 7, "end": 24 }, limits attempts to local operating hours. The next attempt skips closed hours and follows daylight-saving changes. Hardware power scheduling is provided by the local station adapter; the generic installer does not create power-off tasks.
+39 -7
View File
@@ -1,9 +1,41 @@
param([switch]$Restart)
$ErrorActionPreference='Stop' $ErrorActionPreference='Stop'
$configPath=Join-Path $PSScriptRoot 'console.config.json' $configPath=if($env:BPQ_CONSOLE_CONFIG){$env:BPQ_CONSOLE_CONFIG}else{Join-Path $PSScriptRoot 'console.config.json'}
$port=8090 if(!(Test-Path -LiteralPath $configPath)){throw 'Configurazione assente: eseguire Install.ps1 prima di avviare il pannello.'}
if(Test-Path -LiteralPath $configPath){$settings=Get-Content -LiteralPath $configPath -Raw | ConvertFrom-Json;if($settings.port){$port=$settings.port}} $settings=Get-Content -LiteralPath $configPath -Raw | ConvertFrom-Json
if($env:BPQ_CONSOLE_PORT){$port=[int]$env:BPQ_CONSOLE_PORT} $port=if($env:BPQ_CONSOLE_PORT){[int]$env:BPQ_CONSOLE_PORT}elseif($settings.port){[int]$settings.port}else{8090}
if($port -lt 1024 -or $port -gt 65535){throw 'Porta pannello non valida.'}
$nodeExe=if($settings.nodeExe -and (Test-Path -LiteralPath $settings.nodeExe)){$settings.nodeExe}else{(Get-Command node.exe -ErrorAction SilentlyContinue).Source}
if(!$nodeExe){throw 'Node.js non trovato. Eseguire Install.ps1 -NodeExe con il percorso corretto.'}
$version=& $nodeExe --version
if($LASTEXITCODE -ne 0 -or $version -notmatch '^v(\d+)\.' -or [int]$Matches[1] -lt 20){throw 'Serve Node.js 20 o successivo.'}
$serverPath=Join-Path $PSScriptRoot 'server.mjs'
$owned=@(Get-CimInstance Win32_Process -Filter "Name='node.exe'" | Where-Object {$_.CommandLine -and $_.CommandLine.IndexOf($serverPath,[StringComparison]::OrdinalIgnoreCase) -ge 0})
$target=Get-NetTCPConnection -LocalPort $port -State Listen -ErrorAction SilentlyContinue
if($target -and @($owned.ProcessId) -notcontains $target[0].OwningProcess){throw "Porta $port occupata da un altro processo: scegliere un'altra porta con Install.ps1 -Port."}
if($Restart -and $owned.Count){
foreach($stateFile in @('winlink-radio.session.json','manual-forwarding.session.json')){
$pending=Join-Path $PSScriptRoot $stateFile
if((Test-Path -LiteralPath $pending) -and (Get-Content -LiteralPath $pending -Raw | ConvertFrom-Json).restoring){throw 'Attendere il ripristino della sessione radio prima di riavviare il pannello.'}
}
foreach($proc in $owned){Stop-Process -Id $proc.ProcessId -ErrorAction Stop;Wait-Process -Id $proc.ProcessId -Timeout 10 -ErrorAction SilentlyContinue}
}
$listener=Get-NetTCPConnection -LocalPort $port -State Listen -ErrorAction SilentlyContinue $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"} if($listener){
$nodeExe=if($settings.nodeExe -and (Test-Path -LiteralPath $settings.nodeExe)){$settings.nodeExe}else{(Get-Command node.exe -ErrorAction Stop).Source} $proc=Get-CimInstance Win32_Process -Filter "ProcessId=$($listener[0].OwningProcess)"
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') if($proc.Name -eq 'node.exe' -and $proc.CommandLine -and $proc.CommandLine.IndexOf($serverPath,[StringComparison]::OrdinalIgnoreCase) -ge 0){
if((Get-Item -LiteralPath $configPath).LastWriteTime -gt $proc.CreationDate){throw 'Configurazione modificata: usare Start-Console.ps1 -Restart per applicarla.'}
Write-Host "Pannello gia in esecuzione su http://127.0.0.1:$port";return
}
throw "Porta $port occupata da un altro processo: scegliere un'altra porta con Install.ps1 -Port."
}
if(!$Restart -and $owned.Count){throw "Il pannello di questa cartella e gia in esecuzione su un'altra porta: usare -Restart."}
$child=Start-Process -FilePath $nodeExe -ArgumentList ('"'+$serverPath+'"') -WorkingDirectory $PSScriptRoot -WindowStyle Hidden -RedirectStandardOutput (Join-Path $PSScriptRoot 'server.log') -RedirectStandardError (Join-Path $PSScriptRoot 'server-error.log') -PassThru
$ready=$false
for($attempt=0;$attempt -lt 40;$attempt++){
$child.Refresh();if($child.HasExited){break}
try{$health=Invoke-RestMethod -Uri "http://127.0.0.1:$port/health" -TimeoutSec 1;if($health.service -eq 'bpq-console' -and $health.pid -eq $child.Id){$ready=$true;break}}catch{}
Start-Sleep -Milliseconds 250
}
if(!$ready){if(!$child.HasExited){Stop-Process -Id $child.Id -ErrorAction SilentlyContinue};throw 'Avvio pannello non confermato: consultare server-error.log e correggere la configurazione.'}
Write-Host "Pannello avviato su http://127.0.0.1:$port"
+25
View File
@@ -0,0 +1,25 @@
import {aprsSymbol,nativeSymbol} from './aprs-symbols.mjs';
import {AprsKiss} from './aprs-kiss.mjs';
import {readFile,writeFile,rename,open,stat,readdir} from 'node:fs/promises';import path from 'node:path';
import {plain,decode} from './bpq.mjs';import {Monitor} from './monitor.mjs';
export function aprsType(body){return body.startsWith('T#')?'telemetry':({ '!':'position','=':'position','/':'position','@':'position',"'":'position','`':'position',':':'message','>':'status',';':'object',')':'object','_':'weather','$':'position','}':'third-party','?':'query'})[body[0]]||null;}
export function parseTnc2(packet){const m=packet.match(/^([A-Z0-9]{1,9}(?:-\d{1,2})?)>([A-Z0-9-]{1,12})([^:]*):([\s\S]*)$/i);if(!m)return null;const type=aprsType(m[4]);if(!type)return null;return {from:m[1].toUpperCase(),to:m[2].toUpperCase(),path:m[3].replace(/^,/,''),body:m[4].slice(0,2048),type,packet:packet.slice(0,2300)};}
export function parseRadioAprs(frame){const lines=frame.text.split('\n'),m=lines[0]?.match(/\b([A-Z0-9-]+)>(.*?)\s+Port=(\d+)\s+<UI\b/i);if(!m||!lines[1])return null;const p=parseTnc2(m[1]+'>'+m[2]+':'+lines.slice(1).join('\n'));return p?{...p,at:frame.at,direction:frame.direction,transport:'Radio',port:Number(m[3]),evidence:'BPQ monitor'}:null;}
export function parseIsAprs(line,date){const m=line.match(/^(\d{2}:\d{2}:\d{2})([RT])\s+(.*)$/);if(!m)return null;const packet=parseTnc2(m[3]);return packet?{...packet,at:date+'T'+m[1]+'Z',direction:m[2]==='T'?'TX':'RX',transport:'Internet',port:null,evidence:'BPQ APRS-IS log'}:null;}
export function positionOf(body){let text=body;if(/[\/@]/.test(text[0]))text=text.slice(8);else if(/[!=]/.test(text[0]))text=text.slice(1);else return null;
const m=text.match(/^(\d{2})(\d{2}\.\d{2})([NS])(.)(\d{3})(\d{2}\.\d{2})([EW])(.)(.*)$/);if(!m||Number(m[2])>=60||Number(m[6])>=60)return null;const lat=(+m[1]+Number(m[2])/60)*(m[3]==='S'?-1:1),lon=(+m[5]+Number(m[6])/60)*(m[7]==='W'?-1:1);return Math.abs(lat)<=90&&Math.abs(lon)<=180?{lat,lon,symbol:m[8],symset:m[4]}:null;}
export function parseNativeStations(text,now=Date.now()){const out=[];for(const row of text.split(/\r?\n\|/)){const m=row.trim().match(/^A,(-?[\d.]+),(-?[\d.]+),([^,]+),([\s\S]*),([A-Fa-f0-9]{4}.),(\d+)$/);if(!m)continue;const lat=Number(m[1]),lon=Number(m[2]),call=m[3];if(!/^[A-Z0-9-]{2,12}$/i.test(call)||!Number.isFinite(lat)||!Number.isFinite(lon)||Math.abs(lat)>90||Math.abs(lon)>180)continue;const detail=m[4],port=Number(detail.match(/Last Heard:.*?on Port (\d+)/)?.[1])||0,lines=detail.split(/<br\s*\/?\s*>/i).map(s=>decode(s.replace(/<[^>]+>/g,''))).filter(s=>s.trim());out.push({call,position:{lat,lon,...nativeSymbol(m[5])},lastAt:new Date(now-Number(m[6])*1000).toISOString(),transport:port?'Radio':'Internet',port:port||null,path:lines[0]||'',lastBody:lines[1]||'',status:lines.find(s=>!s.startsWith('Last Heard')&&!s.startsWith('Distance')&&s!==lines[0]&&s!==lines[1])||'',heardRadio:port>0,positionSource:'BPQ APRS decoder',native:true});}return out;}
export class AprsActivity{
constructor(config,dir,bpq,credentials,settings){this.config=config;this.bpq=bpq;this.settings=settings;this.file=path.join(dir,'aprs-activity.cache.json');this.events=[];this.counts={radioRx:0,radioTx:0,internetRx:0,internetTx:0};this.stations=new Map();this.seq=0;this.cursor=0;this.monitor=new Monitor(credentials,{port:config.monitorPort});this.kiss=(config.aprsKissMonitor||[]).map(endpoint=>new AprsKiss(endpoint,(packet,port)=>this.ingest({...parseTnc2(packet),at:new Date().toISOString(),direction:'RX',transport:'Radio',port,evidence:'KISS receive-only monitor'})));this.lastNative=0;this.lastPersist=0;this.logFile=null;this.logOffset=null;this.partial='';this.errors=[];this.started=false;this.busy=false;this.init=this.restore();this.timer=setInterval(()=>{if(this.started)this.sample().catch(()=>{});},2000);this.timer.unref();}
async restore(){try{const data=JSON.parse(await readFile(this.file,'utf8'));this.events=(data.events||[]).slice(-2000);this.seq=this.events.at(-1)?.id||0;this.counts=data.counts||{radioRx:this.events.filter(e=>e.transport==='Radio'&&e.direction==='RX').length,radioTx:this.events.filter(e=>e.transport==='Radio'&&e.direction==='TX').length,internetRx:this.events.filter(e=>e.transport==='Internet'&&e.direction==='RX').length,internetTx:this.events.filter(e=>e.transport==='Internet'&&e.direction==='TX').length};this.logFile=data.logFile||null;this.logOffset=data.logOffset??null;this.partial=data.partial||'';this.ownPosition=data.ownPosition;for(const s of data.stations||[])if(s.call)this.stations.set(s.call,s);}catch{} }
async start(){await this.init;if(this.starting)return this.starting;if(this.started)return this.snapshot();this.starting=(async()=>{this.started=true;await this.native();try{await this.settings.enableLogging();this.logging=true;}catch{this.logging=false;}if(this.config.monitorPort)await this.monitor.connect();await this.sample();return this.snapshot();})();try{return await this.starting;}finally{this.starting=null;}}
ingest(event){if(!event?.type)return;if(this.events.slice(-40).some(e=>e.packet===event.packet&&e.direction===event.direction&&e.port===event.port&&Math.abs(Date.parse(e.at)-Date.parse(event.at))<1000))return;const counter=(event.transport==='Radio'?'radio':'internet')+(event.direction==='RX'?'Rx':'Tx');this.counts[counter]++;event={...event,id:++this.seq};this.events.push(event);if(this.events.length>2000)this.events.shift();if(event.direction==='RX'){const old=this.stations.get(event.from)||{call:event.from},position=positionOf(event.body)||old.position;this.stations.set(event.from,{...old,lastAt:event.at,transport:event.transport,port:event.port,path:event.path,lastBody:event.body,heardRadio:old.heardRadio||event.transport==='Radio',position,positionSource:positionOf(event.body)?'APRS position':old.positionSource});}}
async native(){try{const html=await this.bpq('/aprsdata.txt?90|-90|-180|180|1|0|0');const home=html.match(/(?:^|\|)H,(-?[\d.]+),(-?[\d.]+),/);if(home&&Math.abs(+home[1])<=90&&Math.abs(+home[2])<=180)this.ownPosition={lat:+home[1],lon:+home[2]};try{const settings=await this.settings.snapshot?.();if(settings&&this.ownPosition)this.ownPosition={...this.ownPosition,...aprsSymbol(settings.symset,settings.symbol)};}catch{}for(const station of parseNativeStations(html)){const old=this.stations.get(station.call);this.stations.set(station.call,{...old,...station,position:{...old?.position,...station.position},heardRadio:station.heardRadio||old?.heardRadio});}this.nativeAvailable=true;}catch{this.nativeAvailable=false;}this.lastNative=Date.now();}
async readLog(){const now=new Date(),date=now.toISOString().slice(0,10),day=date.replaceAll('-','').slice(2);let file=null;for(const folder of [this.config.aprsLogDirectory,path.join(this.config.root,'Logs'),path.join(this.config.root,'logs')].filter(Boolean)){const candidate=path.join(folder,'APRS_'+day+'.log');try{await stat(candidate);file=candidate;break;}catch{}}if(!file)return;
const info=await stat(file);if(file!==this.logFile){this.logFile=file;this.logOffset=Math.max(0,info.size-262144);this.partial='';}if(info.size<this.logOffset){this.logOffset=0;this.partial='';}if(info.size===this.logOffset)return;const handle=await open(file,'r');try{const data=Buffer.alloc(Math.min(262144,info.size-this.logOffset)),read=await handle.read(data,0,data.length,this.logOffset);this.logOffset+=read.bytesRead;const lines=(this.partial+data.subarray(0,read.bytesRead).toString('utf8')).split(/\r?\n/);this.partial=lines.pop().slice(-4096);for(const line of lines)this.ingest(parseIsAprs(line,date));}finally{await handle.close();}}
async sample(){if(this.busy)return;this.busy=true;try{this.errors=[];for(const source of this.kiss)source.connect();if(this.config.monitorPort){const s=this.monitor.snapshot(this.cursor);if(['offline','error'].includes(s.state))await this.monitor.connect();for(const e of s.events)this.ingest(parseRadioAprs(e));this.cursor=s.latest;}
try{await this.readLog();}catch{this.errors.push('Registro APRS-IS non disponibile');}if(Date.now()-this.lastNative>15000)await this.native();
if(Date.now()-this.lastPersist>10000){await writeFile(this.file+'.tmp',JSON.stringify({events:this.events,counts:this.counts,stations:[...this.stations.values()].slice(-1000),ownPosition:this.ownPosition,logFile:this.logFile,logOffset:this.logOffset,partial:this.partial}));await rename(this.file+'.tmp',this.file);this.lastPersist=Date.now();}
}finally{this.busy=false;}}
snapshot(){return {counts:{...this.counts},started:this.started,monitor:this.kiss.some(k=>k.state==='online')?'online':this.monitor.state,loggingInternet:this.logging!==false,logAvailable:Boolean(this.logFile),updatedAt:new Date().toISOString(),events:this.events,stations:[...this.stations.values()].filter(s=>Date.now()-Date.parse(s.lastAt)<24*3600000).sort((a,b)=>Date.parse(b.lastAt)-Date.parse(a.lastAt)),errors:this.errors,limit:2000,own:{call:this.config.sysop.call,locator:this.config.locator,position:this.ownPosition},sources:{radio:'BPQ monitor',internet:'BPQ APRS-IS log',positions:'BPQ APRS decoder'},txScope:'I TX radio sono richieste di trasmissione registrate dal monitor BPQ.'};}
}
+26
View File
@@ -0,0 +1,26 @@
import {test} from 'node:test';import assert from 'node:assert/strict';
import {parseRadioAprs,parseIsAprs,positionOf,parseNativeStations,AprsActivity} from './aprs-activity.mjs';
import {mkdtemp,mkdir,writeFile,readFile,rm} from 'node:fs/promises';import path from 'node:path';import os from 'node:os';
test('APRS monitor parsing separates RF RX/TX and excludes connected traffic and NET/ROM broadcasts',()=>{
const rx=parseRadioAprs({text:'18:55:01R N0TEST>APBPQ1,WIDE1-1 Port=3 <UI R>:\n!4534.18N/00907.89E]Hello',at:'2026-10-17T18:55:01Z',direction:'RX'});assert.equal(rx.transport,'Radio');assert.equal(rx.port,3);assert.equal(rx.path,'WIDE1-1');assert.equal(rx.type,'position');
assert.equal(parseRadioAprs({text:'18:55:01R N0TEST>NODES Port=4 <UI C> NODES broadcast\nROUTE',direction:'RX'}),null);assert.equal(parseRadioAprs({text:'18:55:01R N0TEST>N1PEER Port=3 <I>:\n!not-aprs',direction:'RX'}),null);
const mic=parseRadioAprs({text:'18:55:01T N0TEST>TU3UU1,WIDE1-1 Port=3 <UI R>:\n`abc123',direction:'TX'});assert.equal(mic.type,'position');assert.equal(mic.direction,'TX');
});
test('APRS Internet log parsing never exposes login/passcodes and preserves real transport and date',()=>{
assert.equal(parseIsAprs('18:00:00T user N0TEST pass 12345 vers BPQ','2026-10-17'),null);assert.equal(parseIsAprs('18:00:00R # server greeting','2026-10-17'),null);
const p=parseIsAprs('18:00:01T N0TEST>APBPQ1,qAR,N0IGATE:>Online','2026-10-17');assert.equal(p.direction,'TX');assert.equal(p.transport,'Internet');assert.equal(p.at,'2026-10-17T18:00:01Z');assert.equal(p.type,'status');
});
test('positions use packet coordinates or native BPQ Mic-E decoding rather than callsign/locator guesses',()=>{
const p=positionOf('!4534.18N/00907.89E]Hello');assert.ok(Math.abs(p.lat-45.5696667)<.000001);assert.ok(Math.abs(p.lon-9.1315)<.000001);assert.equal(positionOf('!4599.99N/00907.89E]Bad'),null);assert.equal(positionOf('`MicE'),null);
const stations=parseNativeStations('A,45.5910,9.0718,N0TEST,TU3UT6&#44;WIDE1-1<br>`MicE<br>Last Heard: 18:56:06 on Port 3<br>,010D@,25\r\n|A,45.6000,9.2000,N1PEER,APRS<br>!position<br>Last Heard: 18:56:06 on Port 0<br>,010D@,5\r\n|',Date.parse('2026-10-17T18:57:00Z'));
assert.equal(stations.length,2);assert.equal(stations[0].transport,'Radio');assert.equal(stations[0].position.lat,45.591);assert.equal(stations[0].lastAt,'2026-10-17T18:56:35.000Z');assert.equal(stations[1].transport,'Internet');
});
test('activity starts without changing APRS routing, tails native logs and restores its cursor without duplicating history',async()=>{
const dir=await mkdtemp(path.join(os.tmpdir(),'aprs-live-'));await mkdir(path.join(dir,'Logs'));const today=new Date().toISOString().slice(0,10),day=today.replaceAll('-','').slice(2);let logRequests=0;const config={root:dir,sysop:{call:'N0TEST'},locator:'JN45NN'},bpq=async()=>`A,45.5910,9.0718,N1PEER,APRS<br>!pos<br>Last Heard: 18:00:00 on Port 3<br>,010D@,5\r\n|H,45.569667,9.131500,\r\n|`;
await writeFile(path.join(dir,'Logs','APRS_'+day+'.log'),'18:00:00T user N0TEST pass 12345\n18:00:01R N1PEER>APRS:>Hi\n');const a=new AprsActivity(config,dir,bpq,async()=>({}),{enableLogging:async()=>{logRequests++;}});
let b;try{await a.start();assert.equal(logRequests,1);assert.equal(a.events.length,1);assert.equal(a.snapshot().stations[0].call,'N1PEER');assert.equal(a.snapshot().own.position.lon,9.1315);await a.readLog();assert.equal(a.events.length,1);const cache=JSON.parse(await readFile(a.file));assert.ok(!JSON.stringify(cache).includes('12345'));clearInterval(a.timer);clearInterval(a.monitor.timer);b=new AprsActivity(config,dir,bpq,async()=>({}),{enableLogging:async()=>{}});await b.init;await b.readLog();assert.equal(b.events.length,1);}finally{clearInterval(a.timer);clearInterval(a.monitor.timer);if(b){clearInterval(b.timer);clearInterval(b.monitor.timer);}await rm(dir,{recursive:true,force:true});}
});
test('cumulative APRS counters survive ring eviction, duplicate events and restart',async()=>{
const dir=await mkdtemp(path.join(os.tmpdir(),'aprs-counts-'));const config={root:dir,sysop:{call:'N0TEST'}};const a=new AprsActivity(config,dir,async()=>'',async()=>({}),{});let b;
try{await a.init;for(let i=0;i<2005;i++)a.ingest({type:'status',packet:'N1TEST>APRS:>'+i,body:'>'+i,from:'N1TEST',at:new Date(i*2000).toISOString(),transport:'Radio',direction:'RX',port:3});a.ingest({...a.events.at(-1)});a.ingest({type:'status',packet:'N0TEST>APRS:>Hi',body:'>Hi',from:'N0TEST',at:new Date().toISOString(),transport:'Radio',direction:'TX',port:3});assert.equal(a.events.length,2000);assert.equal(a.snapshot().counts.radioRx,2005);assert.equal(a.snapshot().counts.radioTx,1);await a.sample();b=new AprsActivity(config,dir,async()=>'',async()=>({}),{});await b.init;assert.deepEqual(b.snapshot().counts,a.snapshot().counts);}finally{for(const instance of [a,b].filter(Boolean)){clearInterval(instance.timer);clearInterval(instance.monitor.timer);}await rm(dir,{recursive:true,force:true});}
});
+14
View File
@@ -0,0 +1,14 @@
import net from 'node:net';
export function kissAprs(frame){
if(frame.length<17||(frame[0]&15)!==0)return null;
const addresses=[];let pos=1,ended=false;
while(pos+7<=frame.length&&addresses.length<10){const a=frame.subarray(pos,pos+7),ssid=(a[6]>>1)&15;addresses.push([...a.subarray(0,6)].map(c=>String.fromCharCode(c>>1)).join('').trim()+(ssid?'-'+ssid:''));pos+=7;if(a[6]&1){ended=true;break;}}
if(!ended||addresses.length<2||(frame[pos]&0xef)!==3||frame[pos+1]!==240)return null;
return addresses[1]+'>'+addresses[0]+(addresses.length>2?','+addresses.slice(2).join(','):'')+':'+frame.subarray(pos+2).toString('latin1');
}
// Receive-only connection: never writes commands or AX.25 data to the modem.
export class AprsKiss {
constructor(endpoint,receive){this.endpoint=endpoint;this.receive=receive;this.state='offline';this.bytes=[];this.escape=false;}
connect(){if(this.socket&&!this.socket.destroyed)return;this.state='connecting';this.bytes=[];this.escape=false;const socket=net.connect(this.endpoint.tcpPort,this.endpoint.host||'127.0.0.1');this.socket=socket;socket.on('connect',()=>this.state='online');socket.on('error',()=>this.state='error');socket.on('close',()=>{if(this.state!=='error')this.state='offline';});socket.on('data',data=>{for(let x of data){if(x===192){const packet=kissAprs(Buffer.from(this.bytes));if(packet)this.receive(packet,this.endpoint.port);this.bytes=[];this.escape=false;continue;}if(x===219){this.escape=true;continue;}if(this.escape){x=x===220?192:x===221?219:x;this.escape=false;}this.bytes.push(x);if(this.bytes.length>4096)this.bytes=[];}});}
close(){this.socket?.destroy();}
}
+10
View File
@@ -0,0 +1,10 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {kissAprs} from './aprs-kiss.mjs';
const address=(call,last)=>Buffer.from([...call.padEnd(6)].map(c=>c.charCodeAt(0)<<1).concat(0x60|Number(last)));
test('receive-only KISS decoder preserves APRS addresses and rejects connected frames',()=>{
const frame=Buffer.concat([Buffer.from([0]),address('APMI03',false),address('IZ1XBB',true),Buffer.from([3,240]),Buffer.from('T#089,183,050')]);
assert.equal(kissAprs(frame),'IZ1XBB>APMI03:T#089,183,050');
const connected=Buffer.from(frame);connected[15]=0;assert.equal(kissAprs(connected),null);
assert.equal(kissAprs(Buffer.from([0,1,2])),null);
});
+9
View File
@@ -0,0 +1,9 @@
import {Terminal} from './terminal.mjs';
const sleep=ms=>new Promise(r=>setTimeout(r,ms));
export async function reconfigureAprs(credentials,config){
const terminal=new Terminal(credentials,{port:config.telnetPort,...config.telnetPrompts});
try{await terminal.connect();for(let i=0;i<60&&terminal.state==='connecting';i++)await sleep(100);if(terminal.state!=='online')throw Error('Telnet BPQ non disponibile');terminal.send('PASSWORD');await sleep(700);const after=terminal.seq;terminal.send('APRS RECONFIG');
for(let i=0;i<60;i++){await sleep(100);const output=terminal.events.filter(e=>e.id>after).map(e=>e.text).join('');if(/Reconfiguration requested/i.test(output))return;if(/check failed|invalid|denied|not permitted|password|sysop/i.test(output))throw Error('BPQ ha rifiutato la configurazione APRS');}
throw Error('BPQ non ha confermato la configurazione APRS');
}finally{terminal.close();}
}
+35
View File
@@ -0,0 +1,35 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import vm from 'node:vm';
import {readFileSync} from 'node:fs';
import {parseNativeStations} from './aprs-activity.mjs';
const context=vm.createContext({window:{}});
vm.runInContext(readFileSync(new URL('./public/aprs-symbols.js',import.meta.url),'utf8'),context);
const decode=context.window.BPQAprsPacket.decode;
const mic='`\x7f^U!n^>/';
test('Mic-E station descriptions decode movement and base91 altitude instead of showing binary position bytes',()=>{
const info=decode(mic+'"5J}');
assert.equal(info.format,'Mic-E');assert.equal(info.speedKmh,107);assert.equal(info.course,266);assert.equal(info.altitudeM,142);assert.equal(info.comment,'');
assert.equal(decode(mic+'"5J}Hello from the car').comment,'Hello from the car');
assert.equal(decode('`short').speedKmh,null);assert.equal(decode('`short').comment,'');
});
test('known Mic-E device identifiers are separated from comments; unknown suffixes and real comments are preserved',()=>{
const info=decode(mic+'`"5J}Test_3');assert.equal(info.device,'Yaesu FT5D');assert.equal(info.altitudeM,142);assert.equal(info.comment,'Test');
assert.equal(decode(mic+'>Hello=').device,'Kenwood TH-D72');
assert.equal(decode(mic+'`Hello?Z').comment,'Hello?Z');
assert.equal(decode(mic+'<hello & world>').comment,'<hello & world>');
});
test('plain position descriptions omit position fields without damaging the transmitted text',()=>{
assert.equal(decode('!4534.18N/00907.89E]Local BBS').comment,'Local BBS');
assert.equal(decode('@191200z4534.18N/00907.89E]Local BBS').comment,'Local BBS');
assert.equal(decode('>191200zOn air').comment,'On air');
assert.equal(decode('Comment\x7f with controls').comment,'Comment with controls');
});
test('native HTML decoding preserves Mic-E byte positions, literal angle brackets and repeated spaces',()=>{
const body='`\x7f&lt;U ^&gt;/"5J}';
const row='A,45.5,9.1,N0TEST,TEST,WIDE1-1<br>'+body+'<br>Last Heard: 12:00:00 on Port 3<br>,010D@,1\r\n|';
const station=parseNativeStations(row)[0];
assert.equal(station.lastBody,'`\x7f<U ^>/"5J}');assert.equal(station.lastBody[7],'>');assert.equal(station.lastBody[8],'/');
assert.equal(decode(station.lastBody).altitudeM,142);
});
+38
View File
@@ -0,0 +1,38 @@
import {readFile,writeFile,rename,mkdir,copyFile} from 'node:fs/promises';import path from 'node:path';
export function aprsBlocks(text){return [...text.matchAll(/^APRSDIGI\s*\r?\n([\s\S]*?)^\*\*\*[^\r\n]*/gm)];}
const field=(text,name)=>text.match(new RegExp('^\\s*'+name+'\\s*=\\s*([^\\r\\n;]*)','im'))?.[1].trim()||'';
export function readAprs(text,ports,policy={}){const blocks=aprsBlocks(text),block=blocks.at(-1)?.[1]||'';return {call:field(block,'APRSCALL'),status:field(block,'STATUSMSG'),latitude:field(block,'LAT'),longitude:field(block,'LON'),symbol:field(block,'Symbol')||']',symset:field(block,'Symset')||'/',beaconMinutes:Number(field(block,'BeaconInterval'))||30,beaconInternet:field(block,'BeacontoIS')!=='0',internetEnabled:Boolean(field(block,'ISHost')),host:field(block,'ISHost')||'euro.aprs2.net',port:Number(field(block,'ISPort'))||14580,filter:field(block,'ISFilter'),passcodeConfigured:Boolean(field(block,'ISPasscode')),blocks:blocks.length,ports:ports.map(p=>{const active=new RegExp('^\\s*APRSPATH\\s+'+p.id+'\\s*=','im').test(block),map=field(block,'DIGIMAP\\s+'+p.id).split(',').map(x=>x.trim()),saved=policy.ports?.find(r=>r.port===p.id);return {port:p.id,name:p.name,driver:p.driver,enabled:active,frequencyMHz:saved?.frequencyMHz||144.8,radioRepeat:active&&map.includes(String(p.id)),radioToInternet:active&&map.includes('IS'),internetToRadio:saved?.internetToRadio===true,beaconRadio:saved?.beaconRadio===true,path:field(block,'APRSPATH\\s+'+p.id)||'APRS,WIDE1-1',...(!active?{radioRepeat:false,radioToInternet:false,internetToRadio:false,beaconRadio:false}:{})};})};}
export function validateAprs(data,ports){
if(!data||typeof data!=='object'||! /^[A-Z0-9]{3,7}(?:-\d{1,2})?$/.test(data.call||'')||! /\d/.test(data.call))throw Error('Nominativo APRS non valido');
const line=v=>typeof v==='string'&&!/[\r\n\0;]/.test(v);for(const k of ['status','latitude','longitude','symbol','symset','host','filter'])if(!line(data[k]))throw Error('Campo APRS non valido');
if(data.status.length>180||! /^\d{4}\.\d{2}[NS]$/.test(data.latitude)||! /^\d{5}\.\d{2}[EW]$/.test(data.longitude)||data.symbol.length!==1||data.symset.length!==1||! /^[a-zA-Z0-9.-]{1,250}$/.test(data.host)||!Number.isInteger(data.port)||data.port<1||data.port>65535||!Number.isInteger(data.beaconMinutes)||data.beaconMinutes<5||data.beaconMinutes>120||data.filter.length>200)throw Error('Posizione, server o intervallo APRS non validi');
for(const k of ['internetEnabled','beaconInternet'])if(typeof data[k]!=='boolean')throw Error('Stato APRS non valido');
if(Number(data.call.split('-')[1]||0)>15)throw Error('SSID APRS non valido');
if(data.passcode!==undefined&&data.passcode!==''&&(! /^\d{1,5}$/.test(data.passcode)||Number(data.passcode)>32767))throw Error('Passcode APRS non valido');
if(!Array.isArray(data.ports)||data.ports.length!==ports.length||new Set(data.ports.map(r=>r.port)).size!==ports.length)throw Error('Porte APRS non valide');
for(const r of data.ports){if(!ports.some(p=>p.id===r.port))throw Error('Porta APRS non disponibile');for(const k of ['enabled','radioRepeat','radioToInternet','internetToRadio','beaconRadio'])if(typeof r[k]!=='boolean')throw Error('Stato porta APRS non valido');if(!Number.isFinite(r.frequencyMHz)||!((r.frequencyMHz>=144&&r.frequencyMHz<=146)||(r.frequencyMHz>=430&&r.frequencyMHz<=440))||! /^APRS(?:,[A-Z0-9]{1,6}(?:-\d{1,2})?){0,3}$/.test(r.path||''))throw Error('Frequenza o percorso APRS non validi');if((r.radioToInternet||r.internetToRadio)&&!data.internetEnabled)throw Error('Abilita APRS-IS per usare gli inoltri Internet');}
return data;
}
export function writeAprs(text,data){const blocks=aprsBlocks(text),old=blocks.at(-1)?.[1]||'',managed=/^\s*(?:APRSCALL|STATUSMSG|LAT|LON|SYMBOL|SYMSET|BEACONINTERVAL|BEACONTOIS|ISHOST|ISPORT|ISFILTER|ISPASSCODE|RXONLY|GATELOCALDISTANCE|APRSPATH|GATEDPATH|DIGIMAP|TRACECALLS|FLOODCALLS|DIGICALLS|REPLACEDIGICALLS|MAXTRACEHOPS|MAXFLOODHOPS)\b/i;const retained=old.split(/\r?\n/).filter(l=>l.trim()&&!managed.test(l));
const out=['APRSDIGI',...retained,' APRSCALL='+data.call,' STATUSMSG='+data.status,' LAT='+data.latitude,' LON='+data.longitude,' Symbol='+data.symbol,' Symset='+data.symset,' BeaconInterval='+data.beaconMinutes,' BeacontoIS='+(data.beaconInternet?1:0),' TraceCalls=WIDE,TRACE',' MaxTraceHops=2',' MaxFloodHops=2'];
const pass=data.passcode||field(old,'ISPasscode');if(pass)out.push(' ISPasscode='+pass);
if(data.internetEnabled){out.push(' ISHost='+data.host,' ISPort='+data.port);if(data.filter)out.push(' ISFilter='+data.filter);}
for(const r of data.ports){if(!r.enabled)continue;const tx=r.radioRepeat||r.beaconRadio||r.internetToRadio;out.push(' APRSPATH '+r.port+'='+(tx?r.path:''),' DIGIMAP '+r.port+'='+[...(r.radioRepeat?[r.port]:[]),...(r.radioToInternet?['IS']:[])].join(','));if(r.internetToRadio)out.push(' GATEDPATH '+r.port+'=APRS');}
out.push('***');let written=false;return text.replace(/^APRSDIGI\s*\r?\n[\s\S]*?^\*\*\*[^\r\n]*/gm,()=>{if(written)return '';written=true;return out.join('\r\n');})+(written?'':'\r\n'+out.join('\r\n')+'\r\n');
}
export class AprsSettings{
constructor(config,radioPorts,run){this.config=config;this.radioPorts=radioPorts;this.run=run;this.cfg=path.join(config.root,'BPQ32.cfg');this.policy=path.join(config.root,'Automation','AprsConsole-policy.json');this.ports=config.radioPorts.filter(p=>/KISS|AX25|AX\.25|UZ7HO/i.test(p.driver)&&config.radioPortsControl?.ports?.some(r=>r.port===p.id&&r.kind==='packet'&&r.aprsGuard===true));this.chain=Promise.resolve();}
async snapshot(){let policy={};try{policy=JSON.parse(await readFile(this.policy,'utf8'));}catch{}const state=readAprs(await readFile(this.cfg,'utf8'),this.ports,policy);return {...state,appliedAt:policy.appliedAt||null};}
save(data){const task=this.chain.then(()=>this.apply(data));this.chain=task.catch(()=>{});return task;}
enableLogging(){const task=this.chain.then(async()=>{const old=await readFile(this.cfg,'utf8'),block=aprsBlocks(old).at(-1);if(!block)throw Error('APRS non configurato');if(/^\s*LOGAPRSIS\b/im.test(block[1]))return;
const folder=path.dirname(this.policy);await mkdir(folder,{recursive:true});await copyFile(this.cfg,path.join(folder,'Backup-APRS-log-'+Date.now()+'.cfg'));const replacement=block[0].replace(/^\*\*\*/m,' LOGAPRSIS=1\r\n***'),next=old.slice(0,block.index)+replacement+old.slice(block.index+block[0].length);await writeFile(this.cfg,next);try{await this.run('APRS RECONFIG');}catch(e){await writeFile(this.cfg,old);throw e;}});this.chain=task.catch(()=>{});return task;}
async apply(input){const data=validateAprs(input,this.ports),old=await readFile(this.cfg,'utf8'),current=readAprs(old,this.ports);if(data.internetEnabled&&data.ports.some(r=>r.enabled&&r.radioToInternet)&&!data.passcode&&!current.passcodeConfigured)throw Error('Inserisci il passcode APRS-IS per inoltrare i pacchetti ricevuti');
if(this.radioPorts.state?.ports.some(p=>data.ports.some(r=>r.port===p.id&&r.enabled)&&p.current.active))throw Error('Attendi la fine del collegamento radio prima di applicare APRS');
for(const row of data.ports.filter(r=>r.enabled))if(!this.radioPorts.state?.ports.find(p=>p.id===row.port)?.supported)throw Error('Controller della porta APRS non disponibile');
const folder=path.dirname(this.policy);await mkdir(folder,{recursive:true});const backup=path.join(folder,'Backup-APRS-'+Date.now()+'.cfg');await copyFile(this.cfg,backup);const next=writeAprs(old,data);await writeFile(this.cfg+'.aprs-tmp',next);await rename(this.cfg+'.aprs-tmp',this.cfg);
let priorPolicy;try{priorPolicy=await readFile(this.policy,'utf8');}catch{}
const policy={ports:data.ports,appliedAt:null};await writeFile(this.policy,JSON.stringify(policy));
try{await this.run('APRS RECONFIG');for(const row of data.ports.filter(r=>r.enabled)){const port=this.radioPorts.state?.ports.find(p=>p.id===row.port);if(!port?.supported)throw Error('Controller della porta APRS non disponibile');let channels=port.channels.map(c=>({...c,enabled:Math.abs(c.frequencyMHz-row.frequencyMHz)<.000001}));if(!channels.some(c=>c.enabled))channels.push({id:Math.round(row.frequencyMHz*1e6)+'-FM',frequencyMHz:row.frequencyMHz,mode:'FM',dwellSeconds:15,enabled:true});await this.radioPorts.update(row.port,{channels,txSuspended:port.control.txSuspended,listening:true});}policy.appliedAt=new Date().toISOString();await writeFile(this.policy,JSON.stringify(policy));return this.snapshot();}
catch(e){await writeFile(this.cfg,old);if(priorPolicy)await writeFile(this.policy,priorPolicy);else await writeFile(this.policy,JSON.stringify({ports:[]}));await this.run('APRS RECONFIG').catch(()=>{});throw e;}
}
}
+19
View File
@@ -0,0 +1,19 @@
import {test} from 'node:test';import assert from 'node:assert/strict';
import {readAprs,writeAprs,validateAprs,AprsSettings,aprsBlocks} from './aprs-settings.mjs';
import {mkdtemp,mkdir,readFile,writeFile,rm} from 'node:fs/promises';import path from 'node:path';import os from 'node:os';
const ports=[{id:3,name:'Packet',driver:'KISS'}];
const original='NODECALL=N0TEST\r\nAPRSDIGI\r\n APRSCALL=N0TEST-11\r\n***\r\nAPRSDIGI\r\n APRSCALL=N0TEST\r\n LAT=4534.18N\r\n LON=00907.89E\r\n ISHost=euro.aprs2.net\r\n ISPasscode=12345\r\n SaveAPRSMsgs=1\r\n***\r\nAPPLICATION 1,BBS,,N0TEST-11\r\n';
const settings=()=>({...readAprs(original,ports),ports:[{port:3,name:'Packet',driver:'KISS',enabled:true,frequencyMHz:144.8,radioRepeat:false,radioToInternet:true,internetToRadio:false,beaconRadio:false,path:'APRS,WIDE1-1'}]});
test('APRS settings read native config without exposing the passcode and consolidate duplicate blocks',()=>{
const data=settings();assert.equal(data.call,'N0TEST');assert.equal(data.passcodeConfigured,true);assert.ok(!JSON.stringify(data).includes('12345'));const updated=writeAprs(original,data);assert.equal(aprsBlocks(updated).length,1);assert.match(updated,/SaveAPRSMsgs=1/);assert.match(updated,/ISPasscode=12345/);assert.match(updated,/APRSPATH 3=\r\n/);assert.match(updated,/DIGIMAP 3=IS/);assert.match(updated,/APPLICATION 1,BBS,,N0TEST-11/);assert.ok(!updated.includes('GATEDPATH'));
const both=writeAprs(original,{...data,ports:data.ports.map(p=>({...p,radioRepeat:true,internetToRadio:true}))});assert.match(both,/DIGIMAP 3=3,IS/);assert.match(both,/GATEDPATH 3=APRS/);
const off=writeAprs(original,{...data,internetEnabled:false});assert.ok(!off.includes('ISHost='));assert.match(off,/ISPasscode=12345/);
});
test('APRS validation rejects injected config, invalid ports, unsupported frequency and ambiguous state',()=>{
const data=settings();validateAprs(data,ports);for(const patch of [{call:'N0TEST-99'},{host:'host\nRUN bad'},{passcode:'99999'},{latitude:'bad'},{beaconMinutes:0},{ports:[{...data.ports[0],port:1}]},{ports:[{...data.ports[0],frequencyMHz:7.05}]},{internetEnabled:false}])assert.throws(()=>validateAprs({...data,...patch},ports));
});
test('failed native APRS reconfiguration restores the exact file and policy, successful save backs up and sets the listening frequency',async()=>{
const root=await mkdtemp(path.join(os.tmpdir(),'aprs-'));await mkdir(path.join(root,'Automation'));await writeFile(path.join(root,'BPQ32.cfg'),original);const config={root,radioPorts:ports,radioPortsControl:{ports:[{port:3,kind:'packet',aprsGuard:true}]}};const updates=[];let fail=true;
const radio={state:{ports:[{id:3,supported:true,current:{active:false},channels:[{frequencyMHz:144.95,enabled:true}],control:{txSuspended:false}}]},update:async(id,value)=>updates.push({id,value})};const service=new AprsSettings(config,radio,async()=>{if(fail)throw Error('Native rejected')});
try{await assert.rejects(service.save(settings()),/Native rejected/);assert.equal(await readFile(path.join(root,'BPQ32.cfg'),'utf8'),original);assert.equal(updates.length,0);fail=false;const state=await service.save(settings());assert.ok(state.appliedAt);assert.equal(updates[0].value.channels.filter(c=>c.enabled)[0].frequencyMHz,144.8);assert.ok(!JSON.stringify(state).includes('12345'));}finally{await rm(root,{recursive:true,force:true});}
});
+13
View File
@@ -0,0 +1,13 @@
// APRS table identifiers and BPQ's row/column icon keys (APRSCode.c).
export function aprsSymbol(symset,symbol){
if(typeof symbol!=='string'||symbol.length!==1||symbol<'!'||symbol>'~'||!/^[/\\A-Z0-9]$/.test(symset||''))return null;
return {symbol,symset,table:symset==='/'?'primary':'alternate',overlay:/^[A-Z0-9]$/.test(symset)?symset:null};
}
export function nativeSymbol(key){
if(!/^[0-9a-f]{4}[@A-Z0-9]$/i.test(key||''))return null;
const row=parseInt(key.slice(0,2),16),col=parseInt(key.slice(2,4),16);
if(row>11||col>15)return null;
const index=(row%6)*16+col;if(index>93)return null;
const overlay=key[4]==='@'?null:key[4];if(overlay&&row<6)return null;
return aprsSymbol(overlay||(row<6?'/':'\\'),String.fromCharCode(33+index));
}
+30
View File
@@ -0,0 +1,30 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {aprsSymbol,nativeSymbol} from './aprs-symbols.mjs';
import {parseNativeStations,positionOf} from './aprs-activity.mjs';
import vm from 'node:vm';
import {readFileSync} from 'node:fs';
test('APRS codes distinguish the primary, alternate and overlay tables without guessing a station type',()=>{
assert.deepEqual(nativeSymbol('010D@'),aprsSymbol('/','>'));
assert.deepEqual(nativeSymbol('0602W'),aprsSymbol('W','#'));
assert.deepEqual(nativeSymbol('0602@'),aprsSymbol('\\','#'));
for(const key of ['FFFF@','000FZ','0B0E@','bad'])assert.equal(nativeSymbol(key),null);
assert.equal(aprsSymbol('?','>'),null);assert.equal(aprsSymbol('/','<script>'),null);
const station=parseNativeStations('A,45,9,N0TEST,APRS<br>Mic-E<br>,0602W,10\r\n|')[0];
assert.equal(station.position.symbol,'#');assert.equal(station.position.symset,'W');assert.equal(station.position.overlay,'W');
assert.deepEqual(aprsSymbol(positionOf('!4534.18NW00907.89E#').symset,'#'),aprsSymbol('W','#'));
});
test('local sprites use the correct ASCII slot and escaped, validated overlay characters',()=>{
const context=vm.createContext({window:{}});vm.runInContext(readFileSync(new URL('./public/aprs-symbols.js',import.meta.url),'utf8'),context);
const symbols=context.window.BPQAprsSymbols;
assert.equal(symbols.decode({symset:'/',symbol:'>'}).name,'Car');
assert.match(symbols.html({symset:'/',symbol:'>'}),/primary.*col-13.*row-1/);
assert.match(symbols.html({symset:'W',symbol:'#'}),/alternate.*col-2.*row-0.*overlay">W/);
assert.match(symbols.html({symset:'<',symbol:'>'}),/unknown/);
assert.equal(symbols.decode({}),null);
assert.doesNotMatch(symbols.html({symset:'/',symbol:'>'}),/style=|class="primary/);
const css=readFileSync(new URL('./public/aprs-activity.css',import.meta.url),'utf8');
assert.match(css,/\.aprs-symbol-col-13\{background-position-x:-312px\}/);
assert.match(css,/\.aprs-symbol-row-1\{background-position-y:-24px\}/);
});
+1
View File
@@ -1,4 +1,5 @@
import path from 'node:path'; import path from 'node:path';
export function attachmentSummary(bytes){const end=bytes.indexOf('\r\n\r\n');if(end<0||end>65536)return {attachmentCount:0,attachmentBytes:0};const header=bytes.subarray(0,end).toString('utf8');if(!/^MID:/mi.test(header)||!/^Body:\s*\d+\s*$/mi.test(header))return {attachmentCount:0,attachmentBytes:0};const files=[...header.matchAll(/^File:\s*(\d+)\s+[^\r\n]+\r?$/gmi)];return {attachmentCount:files.length,attachmentBytes:files.reduce((sum,f)=>sum+Number(f[1]),0)};}
export function safeName(name){return path.win32.basename(String(name).replaceAll('/','\\')).replace(/[\x00-\x1f\x7f]/g,'').slice(0,200)||'allegato.bin';} export function safeName(name){return path.win32.basename(String(name).replaceAll('/','\\')).replace(/[\x00-\x1f\x7f]/g,'').slice(0,200)||'allegato.bin';}
export function mimeOf(bytes,name){if(bytes.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return 'image/png';if(bytes[0]===255&&bytes[1]===216&&bytes[2]===255)return 'image/jpeg';if(/^GIF8[79]a$/.test(bytes.subarray(0,6).toString('ascii')))return 'image/gif';if(bytes.subarray(0,4).toString()==='RIFF'&&bytes.subarray(8,12).toString()==='WEBP')return 'image/webp';if(bytes.subarray(0,5).toString()==='%PDF-')return 'application/pdf';if(/\.(txt|csv|log|json|xml|html?|svg|md|7pl)$/i.test(name)&&!bytes.subarray(0,4096).includes(0))return 'text/plain';return 'application/octet-stream';} export function mimeOf(bytes,name){if(bytes.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return 'image/png';if(bytes[0]===255&&bytes[1]===216&&bytes[2]===255)return 'image/jpeg';if(/^GIF8[79]a$/.test(bytes.subarray(0,6).toString('ascii')))return 'image/gif';if(bytes.subarray(0,4).toString()==='RIFF'&&bytes.subarray(8,12).toString()==='WEBP')return 'image/webp';if(bytes.subarray(0,5).toString()==='%PDF-')return 'application/pdf';if(/\.(txt|csv|log|json|xml|html?|svg|md|7pl)$/i.test(name)&&!bytes.subarray(0,4096).includes(0))return 'text/plain';return 'application/octet-stream';}
export function b2Body(bytes){const end=bytes.indexOf('\r\n\r\n');if(end<0||end>65536)return null;const header=bytes.subarray(0,end).toString('utf8'),body=header.match(/^Body:\s*(\d+)\s*$/m);if(!body||!/^Mid:/mi.test(header))return null;const length=Number(body[1]);if(end+4+length>bytes.length)throw new Error('Corpo B2 incompleto');const data=bytes.subarray(end+4,end+4+length);try{return new TextDecoder('utf8',{fatal:true}).decode(data);}catch{return data.toString('latin1');}} export function b2Body(bytes){const end=bytes.indexOf('\r\n\r\n');if(end<0||end>65536)return null;const header=bytes.subarray(0,end).toString('utf8'),body=header.match(/^Body:\s*(\d+)\s*$/m);if(!body||!/^Mid:/mi.test(header))return null;const length=Number(body[1]);if(end+4+length>bytes.length)throw new Error('Corpo B2 incompleto');const data=bytes.subarray(end+4,end+4+length);try{return new TextDecoder('utf8',{fatal:true}).decode(data);}catch{return data.toString('latin1');}}
+1 -1
View File
@@ -2,6 +2,6 @@ export function decode(s){return s.replace(/&#(\d+);/g,(_,n)=>String.fromCodePoi
export function plain(html){return decode(html.replace(/<script[\s\S]*?<\/script>/gi,'').replace(/<style[\s\S]*?<\/style>/gi,'').replace(/<[^>]+>/g,' ')).replace(/\s+/g,' ').trim();} export function plain(html){return decode(html.replace(/<script[\s\S]*?<\/script>/gi,'').replace(/<style[\s\S]*?<\/style>/gi,'').replace(/<[^>]+>/g,' ')).replace(/\s+/g,' ').trim();}
export function parseMessages(html){const result=[];const regex=/<a\s+href=\/WebMail\/WM\?[^>&\s]+&(\d+)>[^<]+<\/a>([^\r\n<]+)/gi;for(const m of html.matchAll(regex)){const line=m[2];const a=line.match(/^\s*(\S+)\s+([BPT])([A-Z$])\s+(\d+)\s(.{7})\s(.{7})\s(.{7})(.*)$/);if(a){result.push({id:Number(m[1]),date:a[1],type:a[2],status:a[3],size:Number(a[4]),to:a[5].trim(),via:a[6].trim(),from:a[7].trim(),subject:decode(a[8].trim())});continue;}const header=line.match(/^\s*(\S+)\s+([BPT])([A-Z$])\s+(\d+) (.{8})(.*)$/);if(!header)continue;const tail=header[6].match(/^(.*?)([A-Z0-9]{1,6}) {2,}(.*)$/);if(tail)result.push({id:Number(m[1]),date:header[1],type:header[2],status:header[3],size:Number(header[4]),to:header[5].trim(),via:tail[1].trim(),from:tail[2],subject:decode(tail[3].trim()),needsMetadata:true});}return result;} export function parseMessages(html){const result=[];const regex=/<a\s+href=\/WebMail\/WM\?[^>&\s]+&(\d+)>[^<]+<\/a>([^\r\n<]+)/gi;for(const m of html.matchAll(regex)){const line=m[2];const a=line.match(/^\s*(\S+)\s+([BPT])([A-Z$])\s+(\d+)\s(.{7})\s(.{7})\s(.{7})(.*)$/);if(a){result.push({id:Number(m[1]),date:a[1],type:a[2],status:a[3],size:Number(a[4]),to:a[5].trim(),via:a[6].trim(),from:a[7].trim(),subject:decode(a[8].trim())});continue;}const header=line.match(/^\s*(\S+)\s+([BPT])([A-Z$])\s+(\d+) (.{8})(.*)$/);if(!header)continue;const tail=header[6].match(/^(.*?)([A-Z0-9]{1,6}) {2,}(.*)$/);if(tail)result.push({id:Number(m[1]),date:header[1],type:header[2],status:header[3],size:Number(header[4]),to:header[5].trim(),via:tail[1].trim(),from:tail[2],subject:decode(tail[3].trim()),needsMetadata:true});}return result;}
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||'',via:header.Via||header.VIA||'',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:/Connected to .*?(?:TNC|Modem)|Comms State Connected/i.test(t),state:t.match(/TNC State\s+(.*?)(?=Mode\b|Channel\b|Traffic\b|$)/)?.[1]?.trim()||'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)};} 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\s+(.*?)(?=Mode\b|Channel\b|Traffic\b|$)/)?.[1]?.trim()||'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)};}
+44
View File
@@ -0,0 +1,44 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import vm from 'node:vm';
import {readFileSync} from 'node:fs';
import {outgoingForm} from './mail-upload.mjs';
import {parseMessage} from './bpq.mjs';
const source=readFileSync(new URL('./public/app.js',import.meta.url),'utf8');
const bulletin={id:10,type:'B',from:'N1AUTHOR',to:'NEWS',via:'WW',subject:'Radio news',text:'First line\nSecond line'};
function client(message){
const elements=new Map(),field=()=>({value:'',focus(){}}),form={elements:{to:field(),type:field(),subject:field(),text:field()},reset(){for(const input of Object.values(this.elements))input.value='';this.elements.type.value='P';}};
const $=selector=>{if(selector==='#compose-form')return form;if(!elements.has(selector))elements.set(selector,{innerHTML:'',textContent:'',showModal(){this.open=true;}});return elements.get(selector);};
const context=vm.createContext({$,loadGeneration:0,selected:null,renderMessages(){},esc:v=>String(v??''),readableBody:v=>v,mailTimeMeta:()=>'',markMessageRead:async()=>{},toast(){},api:async()=>structuredClone(message)});
for(const name of ['replyDraft','readMessage','openCompose'])vm.runInContext(source.split('\n').find(line=>line.startsWith('function '+name+'(')||line.startsWith('async function '+name+'(')),context);
return {context,$,form};
}
test('Comment keeps bulletin type, category and distribution; Reply privately targets the author',async()=>{
const view=client(bulletin);await view.context.readMessage(10);
assert.match(view.$('#reader').innerHTML,/id="comment"/);assert.match(view.$('#reader').innerHTML,/id="reply"/);
view.$('#comment').onclick();assert.equal(view.form.elements.type.value,'B');assert.equal(view.form.elements.to.value,'NEWS@WW');assert.equal(view.form.elements.subject.value,'Re: Radio news');assert.match(view.form.elements.text.value,/> First line\n> Second line/);
assert.equal(view.$('#compose').open,true);
view.$('#reply').onclick();assert.equal(view.form.elements.type.value,'P');assert.equal(view.form.elements.to.value,'N1AUTHOR');
for(const kind of [false,true]){
const draft=view.context.replyDraft(bulletin,kind),native=outgoingForm(draft);
assert.equal(native.get('Type'),kind?'B':'P');assert.equal(native.get('To'),kind?'NEWS@WW':'N1AUTHOR');assert.equal(native.get('BID'),'');
}
});
test('personal messages only offer Reply, and replying explicitly clears a previously selected bulletin type',async()=>{
const view=client({...bulletin,type:'P',to:'N0LOCAL'});await view.context.readMessage(10);
assert.doesNotMatch(view.$('#reader').innerHTML,/id="comment"/);
view.form.elements.type.value='B';view.$('#reply').onclick();assert.equal(view.form.elements.type.value,'P');assert.equal(view.form.elements.to.value,'N1AUTHOR');
});
test('comments preserve embedded routes, do not invent a distribution, and avoid duplicate Re prefixes',()=>{
const {context}=client(bulletin);
assert.equal(context.replyDraft({...bulletin,to:'NEWS @ EU',via:'EU'},true).to,'NEWS@EU');
assert.equal(context.replyDraft({...bulletin,via:''},true).to,'NEWS');
assert.equal(context.replyDraft({...bulletin,subject:'Re: Radio news'},true).subject,'Re: Radio news');
assert.equal(context.replyDraft({...bulletin,subject:'x'.repeat(80)},true).subject.length,80);
assert.equal(context.replyDraft(bulletin).to,'N1AUTHOR');
});
test('native bulletin header preserves the distribution for reply drafts',()=>{
const message=parseMessage('<textarea>From: N1AUTHOR\nTo: NEWS\nVia: EU\nTitle: Radio news\nType/Status: BN\n\nHello</textarea>');
assert.equal(message.type,'B');assert.equal(message.via,'EU');const {context}=client(message);assert.equal(context.replyDraft(message,true).to,'NEWS@EU');
});
+26
View File
@@ -0,0 +1,26 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {Chat} from './chat.mjs';
test('wrapped node lists stay out of chat, including seven character aliases and single trailing nodes',()=>{
const chat=new Chat(async()=>({}));
try{
for(let i=0;i<3;i++){
chat.line('90 Node(s)');chat.line('Here ALBCHT <- DM4CHT CHTMI');
chat.line('TSVCHAT KTCHAT NPRCHT CAMCHT TVLCHT UTHCHT KYCHAT JTQSO OCGCHT GYBCHT');
chat.line('Nodes via DM4CHT(5) - DM4CHT CHTMI');
chat.line('TSVCHAT');
chat.line('PBOCHT LNZCHT ONBBS ZTMCHT XTCCHT GYBCHT AGMCHT $RSACHAT LSECHT BSACHT');
chat.line('$RSACHAT LSECHT BSACHT EKGCHT MJACHT #USECH CMNCHT #USWCH');
chat.line('$RSACHAT');
chat.line('IW2OHX : T');
chat.line('Links Defined:');chat.line('DM4RW-4 Open RTT 1');chat.line('IW2OHX-5 Idle');
}
assert.deepEqual(chat.events.map(e=>[e.type,e.sender,e.text]),Array.from({length:3},()=>['message','IW2OHX','T']));
assert.equal(chat.links.length,2);
chat.line('IW2OHX : TSVCHAT KTCHAT NPRCHT');
assert.equal(chat.events.at(-1).text,'TSVCHAT KTCHAT NPRCHT');
chat.line('IW2OHX : $RSACHAT #USECH');
assert.equal(chat.events.at(-1).text,'$RSACHAT #USECH');
}finally{clearInterval(chat.timer);}
});
+19 -10
View File
@@ -1,28 +1,37 @@
import net from 'node:net'; import net from 'node:net';
import {StringDecoder} from 'node:string_decoder'; import {StringDecoder} from 'node:string_decoder';
import {TelnetText,TelnetLogin} from './telnet-login.mjs';
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,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();} 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:this.call};} snapshot(){this.lastAccess=Date.now();return {state:this.state,events:this.events,users:this.users,topics:this.topics,links:this.links,topic:this.topic,call:this.call};}
async connect(){if(this.socket&&!this.socket.destroyed)return this.snapshot();const {user,password}=await this.credentials();this.users=[];this.links=[];this.events=[];this.state='connecting';this.section='';this.stage=0;this.buffer='';this.authBuffer='';this.decoder=new StringDecoder('utf8');this.iac=0;this.socket=net.createConnection({host:'127.0.0.1',port:this.options.port||8100});this.socket.setTimeout(15000);this.socket.on('timeout',()=>{if(this.state!=='online')this.socket.destroy(new Error('Timeout di accesso chat'));});this.socket.on('error',e=>{this.state='error';this.event('system','Chat non disponibile: '+e.message)});this.socket.on('close',()=>{if(this.state!=='error')this.state='offline';this.event('system','Disconnesso dalla chat')}); async connect(){
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.state==='connecting'||this.socket&&!this.socket.destroyed)return this.snapshot();this.state='connecting';
if(this.stage===0&&/Username:/i.test(this.authBuffer)){this.write(user);this.stage=1;this.authBuffer='';return;} let credentials;try{credentials=await this.credentials();}catch{this.state='error';throw new Error('Credenziali Telnet BPQ non disponibili');}
if(this.stage===1&&/Password:/i.test(this.authBuffer)){this.write(password);this.stage=2;this.authBuffer='';return;} if(this.state!=='connecting')return this.snapshot();this.users=[];this.links=[];this.events=[];this.section='';this.stage=0;this.buffer='';this.decoder=new StringDecoder('utf8');
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;} const socket=net.createConnection({host:'127.0.0.1',port:this.options.port||8100});this.socket=socket;const telnet=new TelnetText(b=>socket.write(b));socket.setTimeout(15000);
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.login=new TelnetLogin(socket,credentials,this.options,()=>{if(this.socket!==socket)return;this.stage=3;this.buffer='';this.write('CHAT');});
socket.on('timeout',()=>{if(this.state!=='online')socket.destroy(new Error('Timeout di accesso chat'));});
socket.on('error',e=>{if(this.socket!==socket)return;this.state='error';this.event('system','Chat non disponibile: '+e.message)});
socket.on('close',()=>{if(this.socket!==socket)return;this.login?.close();if(this.state!=='error')this.state='offline';this.event('system','Disconnesso dalla chat')});
socket.on('data',chunk=>{if(this.socket!==socket)return;const text=this.decoder.write(telnet.read(chunk)).replace(/\x1b\[[0-9;]*m/g,'');
if(this.stage<3){this.login.read(text);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 alla chat come '+this.call);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. 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===this.call)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 [A-Z0-9-]+|^Links Defined:/.test(line)){if(line==='Links Defined:'){this.section='links';this.links=[]}else this.section='';return;} if(/^\d+ Node\(s\)|^Here |^User [A-Z0-9-]+|^Links Defined:/.test(line)){if(line==='Links Defined:'){this.section='links';this.links=[]}else this.section=/^(?:\d+ Node\(s\)|Here )/.test(line)?'nodes':'';return;}
if(this.section==='topics'){if(/^[A-Za-z0-9_-]+$/.test(line)&&line!==this.call){this.topics.push(line);}return;} if(this.section==='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|Idle)(.*)$/i);if(m){this.links.push({call:m[1],state:m[2],detail:m[3].trim()});return;}this.section='';}
if(/^(Nodes via|\s*[A-Z0-9#]{3,6}(?:\s+[A-Z0-9#]{3,6}){2,})/.test(line))return; if(/^Nodes via /.test(line)){this.section='nodes';return;}
if(this.section==='nodes'&&/^[A-Z0-9#$][A-Z0-9#$_-]{0,31}(?:\s+[A-Z0-9#$][A-Z0-9#$_-]{0,31})*$/.test(line))return;
if(/^[A-Z0-9-]+ Chat Server|^Type \/h|^Bringing up links|^This may take|^The \/p|^[A-Z0-9]{1,6}:/.test(line))return; 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);}
@@ -30,5 +39,5 @@ export class Chat {
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,this.call,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(){this.login?.close();if(this.socket&&!this.socket.destroyed){this.write('/QUIT');this.socket.end();}this.state='offline';}
} }
+35 -9
View File
@@ -2,28 +2,54 @@ import {readFile} from 'node:fs/promises';
import path from 'node:path'; import path from 'node:path';
import os from 'node:os'; import os from 'node:os';
import {fileURLToPath} from 'node:url'; import {fileURLToPath} from 'node:url';
import {timingSafeEqual} from 'node:crypto';
export function validateSysopUsers(value,users){
if(value===undefined)return undefined;
if(!Array.isArray(value)||value.some(name=>typeof name!=='string'||!name.trim()))throw new Error('sysopUsers deve essere una lista di nomi utente SYSOP');
const known=new Set(users.map(u=>u.user.toLowerCase()));
const names=value.map(name=>name.trim());
if(names.some(name=>!known.has(name.toLowerCase())))throw new Error('sysopUsers contiene un utente SYSOP non rilevato in BPQ32.cfg');
return names.filter((name,index)=>names.findIndex(other=>other.toLowerCase()===name.toLowerCase())===index);
}
export function authenticateSysop(users,user,password,allowedUsers){
const equal=(a,b)=>{const aa=Buffer.from(a),bb=Buffer.from(b);return aa.length===bb.length&&timingSafeEqual(aa,bb);};
const found=users.find(u=>equal(u.user.toLowerCase(),user.toLowerCase())&&equal(u.password,password));
if(!found||allowedUsers!==undefined&&!allowedUsers.some(name=>name.toLowerCase()===found.user.toLowerCase()))return null;
return {call:found.call,name:found.user};
}
export function parseConfig(text){ export function parseConfig(text){
const lines=text.split(/\r?\n/).map(l=>l.split(';')[0].trim()).filter(Boolean); let inText=false,inComment=false;const lines=[];
for(let line of text.split(/\r?\n/)){line=line.trim();if(inText){if(line.startsWith('***'))inText=false;continue;}if(inComment){if(line.startsWith('*/'))inComment=false;continue;}if(line.startsWith('/*')){inComment=!line.includes('*/');continue;}if(/^(?:IDMSG|INFOMSG|BTEXT|CTEXT):/i.test(line)){inText=true;continue;}line=line.split(';')[0].trim();if(line)lines.push(line);}
const value=(name)=>lines.find(l=>new RegExp('^'+name+'\\s*=','i').test(l))?.split('=').slice(1).join('=').trim()||''; 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 users=lines.flatMap(l=>{const m=l.match(/^USER\s*=\s*([^,]+),([^,]+),([^,]+),(.*)$/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]}]:[]}); const apps=lines.flatMap(l=>{const m=l.match(/^APPLICATION\s+\d+\s*,(.*)$/i);if(!m)return [];const fields=m[1].split(',').map(s=>s.trim());return fields[0]?[{command:fields[0].split('/')[0].toUpperCase(),call:(fields[2]||'').toUpperCase(),alias:fields[3]||''}]:[]});
let ports=[],current=null; 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];}} for(const l of lines){if(/^PORT$/i.test(l)){current={id:ports.length+1,name:'',driver:'',settings:{}};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)\s*=\s*(.*)$/i);if(m)current[({PORTNUM:'id',ID:'name',DRIVER:'driver',TYPE:'type',PROTOCOL:'protocol'})[m[1].toUpperCase()]]=m[1].toUpperCase()==='PORTNUM'?Number(m[2].trim()):m[2].trim();const s=l.match(/^(HTTPPORT|TCPPORT|FBBPORT|CMS|LOGINPROMPT|PASSWORDPROMPT)\s*=\s*(.*)$/i);if(s)current.settings[s[1].toUpperCase()]=s[2].trim();}}
const telnet=ports.find(p=>/^TELNET(?:\.DLL)?$/i.test(p.driver)),settings=telnet?.settings||{};
for(const p of ports)delete p.settings;
const radioPorts=ports.filter(p=>!/TELNET|AXIP|LOOPBACK/i.test(p.driver)&&p.driver); const radioPorts=ports.filter(p=>!/TELNET|AXIP|LOOPBACK/i.test(p.driver)&&p.driver);
const nodeCall=value('NODECALL'),sysop=users[0]; 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'}; return {nodeCall,call:sysop?.call||nodeCall.replace(/-\d+$/,''),alias:value('NODEALIAS'),locator:value('LOCATOR'),apps,ports,radioPorts,users,httpPort:Number(settings.HTTPPORT)||null,telnetPort:Number(settings.TCPPORT)||null,monitorPort:Number(settings.FBBPORT)||null,telnetPrompts:{loginPrompt:settings.LOGINPROMPT||'',passwordPrompt:settings.PASSWORDPROMPT||''},winlink:settings.CMS==='1'};
} }
export async function loadConfig(){ export async function loadConfig(){
const dir=path.dirname(fileURLToPath(import.meta.url));let saved={}; 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;} 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;}
if(!saved||typeof saved!=='object'||Array.isArray(saved))throw new Error('La configurazione locale deve essere un oggetto JSON');
const root=process.env.BPQ_ROOT||saved.bpqRoot||path.join(process.env.APPDATA||path.join(os.homedir(),'AppData','Roaming'),'BPQ32'); const root=process.env.BPQ_ROOT||saved.bpqRoot||path.join(process.env.APPDATA||path.join(os.homedir(),'AppData','Roaming'),'BPQ32');
if(saved.language!=null&&!['it','en'].includes(saved.language))throw new Error('language deve essere it oppure en');
const detected=parseConfig(await readFile(path.join(root,'BPQ32.cfg'),'utf8')); 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'); 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 sysopUsers=validateSysopUsers(saved.sysopUsers,detected.users);
const httpPort=saved.httpPort||detected.httpPort;if(!httpPort)throw new Error('HTTPPORT BPQ non rilevata: eseguire Install.ps1'); if(saved.radioPort!=null&&!detected.radioPorts.some(p=>p.id===Number(saved.radioPort)))throw new Error('Porta radio configurata non rilevata: rieseguire 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}; if(saved.sysopUser&&!detected.users.some(u=>u.user===saved.sysopUser))throw new Error('Utente sysop configurato non rilevato: rieseguire Install.ps1');
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]}; const radio=detected.radioPorts.find(p=>p.id===Number(saved.radioPort))||detected.radioPorts[0]||null;
const httpPort=Number(saved.httpPort||detected.httpPort);if(!validPort(httpPort))throw new Error('HTTPPORT BPQ non valida o assente: eseguire Install.ps1');
const port=Number(process.env.BPQ_CONSOLE_PORT||saved.port||8090);if(!validPort(port,1024)||port===httpPort)throw new Error('Porta pannello non valida o in conflitto con HTTPPORT BPQ');
const features={terminal:!!detected.telnetPort,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,...(sysopUsers===undefined?{}:{sysopUsers}),root,httpPort,radio,features,port,sysop:detected.users.find(u=>u.user===saved.sysopUser)||detected.users[0]};
} }
export const validPort=(n,min=1)=>Number.isInteger(n)&&n>=min&&n<=65535;
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 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+$/,'');} export function ownCall(sender,call){return !!call&&String(sender||'').replace(/^RMS[/:]/i,'').toUpperCase().split('@')[0].replace(/-\d+$/,'')===String(call).toUpperCase().split('@')[0].replace(/-\d+$/,'');}
+34
View File
@@ -0,0 +1,34 @@
import {parseMessages,decode} from './bpq.mjs';
async function killAsSysop(id,item,bpq){
const status=await bpq('/Mail/Status'),key=status.match(/href=\/Mail\/Msgs\?([^\s>]+)/)?.[1];if(!key)throw Error('Sessione amministrativa BPQ non disponibile');
const html=await bpq('/Mail/MsgDetails?'+key,{method:'POST',body:String(id)});
if(!new RegExp('Message\\s+'+id+'(?!\\d)').test(html))throw Error('BPQ non ha confermato il messaggio da cancellare');
const fields={};for(const match of html.matchAll(/<input\b[^>]*>/gi)){
const name=match[0].match(/\bname=(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i),value=match[0].match(/\bvalue=(?:"([^"]*)"|'([^']*)'|([^\s>]*))/i);
if(name&&value)fields[name[1]??name[2]??name[3]]=decode(value[1]??value[2]??value[3]);
}
const names=['From','To','BID','EFROM','VIA','Title'];
if(names.some(name=>!(name in fields)||/[|\r\n\0]/.test(fields[name])))throw Error('Metadati BPQ non verificabili: cancellazione interrotta');
const typeBlock=html.match(/<select\b[^>]*name=["']?Type["']?[^>]*>([\s\S]*?)<\/select>/i)?.[1];
const selected=typeBlock&&[...typeBlock.matchAll(/<option\b([^>]*)>/gi)].find(m=>/\bselected\b/i.test(m[1]));
const type=selected?.[1].match(/\bvalue=["']?([BPT])/i)?.[1];if(type!==item.type)throw Error('Metadati BPQ non verificabili: cancellazione interrotta');
// MsgSave is the native sysop action. Preserve all editable fields and change
// only Status to K; BPQ clears forwarding bits and saves its own database.
await bpq('/Mail/MsgSave?'+key,{method:'POST',body:[...names.map(name=>fields[name]),type,'K',''].join('|')});
}
export async function deleteNativeMessage(id,bpq,{sysop=false}={}){
if(!Number.isSafeInteger(id)||id<1)throw Error('Messaggio non valido');
// A cached WebMail key may survive a BPQ restart. With an expired key BPQ
// returns a new session's message list instead of executing WMDel.
const page=await bpq('/Webmail'),key=page.match(/WMB\?([^>\s]+)/)?.[1];if(!key)throw Error('WebMail BPQ non disponibile');
const read=async()=>{const html=await bpq('/WebMail/WMALL?'+key);if(!html.includes('Message List'))throw Error('Lista messaggi BPQ non disponibile');return parseMessages(html);};
const visible=message=>message.id===id&&message.status!=='K';
const item=(await read()).find(visible);if(!item)return {ok:true,alreadyDeleted:true};
const response=await bpq('/WebMail/WMDel/'+id+'?'+key);
if(/Not your message|not allowed|permission denied/i.test(response)){
if(!sysop)throw Error('BPQ non autorizza la cancellazione: verifica i permessi sysop della BBS');
await killAsSysop(id,item,bpq);
}
if((await read()).some(visible))throw Error('BPQ non ha confermato la cancellazione');
return {ok:true};
}
+36
View File
@@ -0,0 +1,36 @@
import test from 'node:test';import assert from 'node:assert/strict';import {deleteNativeMessage} from './delete-message.mjs';
const list=(status='N')=>'Message List\r\n<a href=/WebMail/WM?fresh&7> 7</a> 17-Oct B'+status+' 100 '+['ALL','WW','N1TEST'].map(s=>s.padEnd(7)).join(' ')+' Test bulletin\r\n';
test('delete uses a fresh private WebMail session and confirms the message is gone',async()=>{
const calls=[];let killed=false;
const bpq=async url=>{calls.push(url);if(url==='/Webmail')return '<a href=/WebMail/WMB?fresh>Bulls</a>';if(url==='/WebMail/WMALL?fresh')return killed?'Message List':list();if(url==='/WebMail/WMDel/7?fresh'){killed=true;return 'Message #7 Killed';}throw Error('Unexpected or stale WebMail key');};
assert.deepEqual(await deleteNativeMessage(7,bpq),{ok:true});assert.deepEqual(calls,['/Webmail','/WebMail/WMALL?fresh','/WebMail/WMDel/7?fresh','/WebMail/WMALL?fresh']);
});
test('a BPQ permission denial is reported instead of pretending the message was deleted',async()=>{
await assert.rejects(deleteNativeMessage(7,async url=>url==='/Webmail'?'<a href=/WebMail/WMB?fresh>Mail</a>':url.includes('WMDel')?'Not your message':list()),/permessi sysop/);
});
test('a native HTTP 200 or session-redirect page is insufficient if the message remains visible',async()=>{
await assert.rejects(deleteNativeMessage(7,async url=>url==='/Webmail'?'<a href=/WebMail/WMB?fresh>Mail</a>':list()),/non ha confermato/);
});
test('already absent or killed messages are idempotent and never issue another delete',async()=>{
for(const html of ['Message List',list('K')]){const calls=[];const result=await deleteNativeMessage(7,async url=>{calls.push(url);return url==='/Webmail'?'<a href=/WebMail/WMB?fresh>Mail</a>':html;});assert.equal(result.alreadyDeleted,true);assert.ok(!calls.some(url=>url.includes('WMDel')));}
});
test('BPQ may retain the killed row for sysop inspection; status K confirms deletion',async()=>{
let killed=false;assert.deepEqual(await deleteNativeMessage(7,async url=>{if(url==='/Webmail')return '<a href=/WebMail/WMB?fresh>Mail</a>';if(url.includes('WMDel')){killed=true;return 'Killed';}return list(killed?'K':'N');}),{ok:true});
});
test('unverifiable sessions and invalid message IDs cannot issue a deletion',async()=>{
await assert.rejects(deleteNativeMessage(0,async()=>{throw Error('Must not contact BPQ');}),/non valido/);
await assert.rejects(deleteNativeMessage(7,async()=>'<h1>Sign in</h1>'),/WebMail/);
await assert.rejects(deleteNativeMessage(7,async url=>url==='/Webmail'?'<a href=/WebMail/WMB?fresh>Mail</a>':'Sign in'),/Lista messaggi/);
});
test('sysop Console can delete another author bulletin through the native admin action, preserving metadata',async()=>{
let killed=false,save=null;const fields={From:'N1TEST',To:'ALL',BID:'BID_123',EFROM:'',VIA:'WW',Title:'Test & bulletin'};
const bpq=async(url,options)=>{if(url==='/Webmail')return '<a href=/WebMail/WMB?fresh>Mail</a>';if(url.includes('WMALL'))return killed?'Message List':list();if(url.includes('WMDel'))return 'Not your message';if(url==='/Mail/Status')return '<a href=/Mail/Msgs?private>Messages</a>';if(url.startsWith('/Mail/MsgDetails'))return '<h2>Message 7</h2>'+Object.entries(fields).map(([k,v])=>'<input name="'+k+'" value="'+v.replace('&','&amp;')+'">').join('')+'<select name="Type"><option value="P">Personal</option><option value="B" selected>Bulletin</option></select>';if(url.startsWith('/Mail/MsgSave')){save=options.body;killed=true;return 'Saved';}throw Error(url);};
assert.deepEqual(await deleteNativeMessage(7,bpq,{sysop:true}),{ok:true});assert.equal(save,'N1TEST|ALL|BID_123||WW|Test & bulletin|B|K|');
});
test('admin fallback refuses to modify the wrong message or incomplete metadata',async()=>{
let saves=0;const bpq=async url=>{if(url==='/Webmail')return '<a href=/WebMail/WMB?fresh>Mail</a>';if(url.includes('WMALL'))return list();if(url.includes('WMDel'))return 'Not your message';if(url==='/Mail/Status')return '<a href=/Mail/Msgs?admin>Messages</a>';if(url.includes('MsgDetails'))return '<h2>Message 8</h2><input name="From" value="N1TEST">';if(url.includes('MsgSave'))saves++;return '';};
await assert.rejects(deleteNativeMessage(7,bpq,{sysop:true}),/non ha confermato il messaggio/);assert.equal(saves,0);
});
+64
View File
@@ -0,0 +1,64 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import vm from 'node:vm';
import {readFileSync} from 'node:fs';
const source=readFileSync(new URL('./public/detach.js',import.meta.url),'utf8');
function harness(search='',shared=new Map(),options={}){
const docEvents={},events={},sections={},calls=[];let serial=0,tick,popup;
function element(){const children=new Map();return {hidden:false,dataset:{},textContent:'',className:'',innerHTML:'',classes:new Set(),
setAttribute(name,value){this[name]=value;},classList:{toggle(name,on){this.owner.classes[on?'add':'delete'](name);}},append(child){this.child=child;},
querySelector(selector){if(selector==='.detached-placeholder')return this.child||null;if(!children.has(selector))children.set(selector,element());return children.get(selector);},
querySelectorAll(){return [this.querySelector('first'),this.querySelector('second')];}};}
for(const id of ['terminal','aprs','monitor','chat']){sections[id]=element();sections[id].classList.owner=sections[id];}
const main={hidden:false};const document={body:{append(node){calls.push(['notice',node.className]);}},querySelector:()=>main,readyState:'complete',documentElement:{dataset:{}},getElementById:id=>options.late?.includes(id)?null:sections[id],createElement:element,addEventListener:(name,fn)=>docEvents[name]=fn};
const window={name:'',addEventListener:(name,fn)=>events[name]=fn,focus:()=>calls.push('focus'),close:()=>calls.push('close'),
open:(...args)=>{calls.push(args);popup={closed:false,focus(){},close(){this.closed=true;}};return popup;}};
const location={pathname:'/',search,hash:'',assign:url=>calls.push(['assign',url])};
const context=vm.createContext({window,document,location,URLSearchParams,crypto:options.insecure?{}:{randomUUID:()=>String(++serial)},
localStorage:{getItem:key=>shared.get(key)||null,setItem:(key,value)=>shared.set(key,value),removeItem:key=>shared.delete(key)},
Date,Set,Map,BPQI18n:{t:s=>s},toast:text=>calls.push(['toast',text]),navigate:id=>calls.push(['navigate',id]),setInterval:fn=>{tick=fn;}});
vm.runInContext(source,context);docEvents.DOMContentLoaded();
return {api:window.BPQDetached,window,document,docEvents,events,sections,calls,shared,main,tick:()=>tick(),popup:()=>popup};
}
test('a page shows courtesy only after its detached view is ready, and another page stays usable',()=>{
const h=harness();h.api.open('aprs');assert.equal(h.api.isAway('aprs'),false);
assert.match(h.calls[0][0],/^\/\?detached=aprs&window=\d+#aprs$/);
h.shared.set('bpq-detached:aprs',JSON.stringify({owner:'2',at:Date.now()}));h.tick();
assert.equal(h.sections.aprs.child.hidden,false);assert.equal(h.api.shouldPoll('aprs'),false);assert.equal(h.api.shouldPoll('chat'),true);
assert.equal(h.sections.aprs.classes.has('section-detached-away'),true);
h.api.dock('aprs');assert.equal(h.sections.aprs.child.hidden,true);assert.equal(h.api.shouldPoll('aprs'),true);assert.equal(h.popup().closed,true);
});
test('closing a child restores its parent and stale records cannot strand a page on the courtesy screen',()=>{
const h=harness();h.api.open('monitor');h.shared.set('bpq-detached:monitor',JSON.stringify({owner:'2',at:Date.now()}));h.tick();
h.popup().closed=true;h.tick();assert.equal(h.api.isAway('monitor'),false);assert.equal(h.sections.monitor.child.hidden,true);
h.shared.set('bpq-detached:chat',JSON.stringify({owner:'old',at:Date.now()-130000}));h.tick();assert.equal(h.api.isAway('chat'),false);
});
test('blocked popups keep the embedded view and never claim a detached session',()=>{
const h=harness();h.window.open=()=>null;h.api.open('chat');assert.equal(h.api.isAway('chat'),false);assert.equal(h.shared.has('bpq-detached:chat'),false);assert.match(h.calls[0][1],/popup/);
});
test('a standalone page claims just its service, releases on close and never reconnects or disconnects BPQ',()=>{
const shared=new Map(),h=harness('?detached=chat&window=child',shared);h.docEvents['station-ready']();
assert.equal(h.api.view,'chat');assert.equal(h.api.shouldPoll('chat'),true);assert.equal(h.api.shouldPoll('aprs'),false);
assert.equal(JSON.parse(shared.get('bpq-detached:chat')).owner,'child');assert.equal(h.document.documentElement.dataset.detachedView,'chat');
h.events.pagehide();assert.equal(shared.has('bpq-detached:chat'),false);h.tick();assert.equal(shared.has('bpq-detached:chat'),false);
assert.ok(h.calls.every(call=>call[0]==='navigate'));
});
test('a dock request stops the detached view even when its browser refuses scripted window closing',()=>{
const h=harness('?detached=monitor&window=child');h.docEvents['station-ready']();
h.events.storage({key:'bpq-detached-command',newValue:JSON.stringify({id:'monitor',action:'dock',at:Date.now()})});
assert.equal(h.shared.has('bpq-detached:monitor'),false);assert.equal(h.api.shouldPoll('monitor'),false);assert.equal(h.main.hidden,true);assert.ok(h.calls.includes('close'));
});
test('LAN HTTP without randomUUID supports all detached services',()=>{
const h=harness('',new Map(),{insecure:true});
for(const id of ['terminal','aprs','monitor','chat'])h.api.open(id);
assert.equal(h.calls.filter(c=>Array.isArray(c)&&typeof c[0]==='string'&&c[0].includes('window=')).length,4);
});
test('late sections receive controls and courtesy placeholders on the next setup pass',()=>{
const options={late:['chat','monitor','aprs']},h=harness('',new Map(),options);
assert.equal(h.sections.chat.child,undefined);options.late=[];h.tick();
for(const id of ['chat','monitor','aprs'])assert.ok(h.sections[id].child);
const placeholder=h.sections.chat.child;h.tick();assert.equal(h.sections.chat.child,placeholder);
});
+31
View File
@@ -0,0 +1,31 @@
import {readFile,writeFile,rename} from 'node:fs/promises';
import path from 'node:path';
export class ForwardingScheduler {
constructor(config,dir,client,{clock=Date.now}={}){
this.client=client;this.clock=clock;this.file=path.join(dir,'forwarding-schedule.state.json');this.jobs={};this.busy=false;
this.schedules=(config.forwardingSchedules||[]).map(s=>{
if(!client.routes.some(r=>r.id===s.route)||!Number.isInteger(s.intervalSeconds)||s.intervalSeconds<300||s.intervalSeconds>86400||typeof s.enabled!=='boolean')throw Error('Programmazione forwarding non valida');
if(s.hours){const h=s.hours;if(!Number.isInteger(h.start)||!Number.isInteger(h.end)||h.start<0||h.end>24||h.start>=h.end)throw Error('Orari forwarding non validi');new Intl.DateTimeFormat('en',{timeZone:h.timeZone}).format();}
return {...s,intervalMs:s.intervalSeconds*1000};
});
if(new Set(this.schedules.map(s=>s.route)).size!==this.schedules.length)throw Error('Programmazione forwarding duplicata');
this.init=this.restore();this.timer=setInterval(()=>this.tick().catch(()=>{}),5000);this.timer.unref();
}
allowed(schedule,now){if(!schedule.hours)return true;const h=schedule.hours,hour=Number(new Intl.DateTimeFormat('en-GB',{timeZone:h.timeZone,hour:'2-digit',hourCycle:'h23'}).format(new Date(now)));return hour>=h.start&&hour<h.end;}
boundary(schedule,now){let next=(Math.floor(now/schedule.intervalMs)+1)*schedule.intervalMs;for(let i=0;i<600&& !this.allowed(schedule,next);i++)next+=schedule.intervalMs;return next;}
async restore(){try{this.jobs=JSON.parse(await readFile(this.file,'utf8'));}catch{}
const now=this.clock();for(const s of this.schedules){const old=this.jobs[s.route];if(!old||old.intervalSeconds!==s.intervalSeconds||old.nextAt<now-300000)this.jobs[s.route]={intervalSeconds:s.intervalSeconds,nextAt:this.boundary(s,now)};else if(!this.allowed(s,old.nextAt))old.nextAt=this.boundary(s,old.nextAt);}
}
async persist(){await writeFile(this.file+'.tmp',JSON.stringify(this.jobs));await rename(this.file+'.tmp',this.file);}
snapshot(){return this.schedules.map(s=>({...s,...this.jobs[s.route],nextAt:s.enabled?new Date(this.jobs[s.route]?.nextAt||this.boundary(s,this.clock())).toISOString():null,enabled:s.enabled}));}
async tick(){await this.init;if(this.busy)return;this.busy=true;
try{for(const s of this.schedules){const j=this.jobs[s.route],now=this.clock();if(!s.enabled||now<j.nextAt)continue;
// Persist the next boundary before dispatch: a restart must not replay a call.
j.nextAt=this.boundary(s,now);if(!this.allowed(s,now)){await this.persist();continue;}j.lastAttemptAt=new Date(now).toISOString();j.error=null;await this.persist();
try{await this.client.startRoute(s.route);j.lastRequestedAt=new Date(now).toISOString();}
catch(error){j.error=error.message;}
await this.persist();
}}finally{this.busy=false;}
}
}
+18
View File
@@ -0,0 +1,18 @@
import {test} from 'node:test';import assert from 'node:assert/strict';import {mkdtemp,rm} from 'node:fs/promises';import os from 'node:os';import path from 'node:path';
import {ForwardingScheduler} from './forwarding-scheduler.mjs';
test('hourly forwarding reserves its configured VHF route once, persists across restart and skips occupied hours',async()=>{
const dir=await mkdtemp(path.join(os.tmpdir(),'fwd-schedule-'));let now=Date.parse('2026-10-17T19:37:00Z'),calls=[],blocked=false;
const client={routes:[{id:'N0TEST-VHF'}],startRoute:async id=>{calls.push(id);if(blocked)throw Error('Radio occupata');}};
const config={forwardingSchedules:[{route:'N0TEST-VHF',intervalSeconds:3600,enabled:true}]};let first,second;
try{first=new ForwardingScheduler(config,dir,client,{clock:()=>now});await first.init;assert.equal(first.snapshot()[0].nextAt,'2026-10-17T20:00:00.000Z');await first.tick();assert.equal(calls.length,0);
now=Date.parse('2026-10-17T20:00:00Z');await Promise.all([first.tick(),first.tick()]);assert.deepEqual(calls,['N0TEST-VHF']);
second=new ForwardingScheduler(config,dir,client,{clock:()=>now});await second.init;await second.tick();assert.equal(calls.length,1);
blocked=true;now+=3600000;await second.tick();assert.equal(calls.length,2);assert.equal(second.snapshot()[0].error,'Radio occupata');await second.tick();assert.equal(calls.length,2);
assert.equal(second.snapshot()[0].nextAt,new Date(now+3600000).toISOString());
}finally{if(first)clearInterval(first.timer);if(second)clearInterval(second.timer);await rm(dir,{recursive:true,force:true});}
});
test('Rome operating hours skip midnight and follow summer/winter UTC offsets',async()=>{
const dir=await mkdtemp(path.join(os.tmpdir(),'fwd-hours-'));const config={forwardingSchedules:[{route:'N0TEST-VHF',intervalSeconds:3600,enabled:true,hours:{timeZone:'Europe/Rome',start:7,end:24}}]};const scheduler=new ForwardingScheduler(config,dir,{routes:[{id:'N0TEST-VHF'}]});
try{await scheduler.init;const s=scheduler.schedules[0];assert.equal(new Date(scheduler.boundary(s,Date.parse('2026-10-17T21:00:00Z'))).toISOString(),'2026-10-18T05:00:00.000Z');assert.equal(new Date(scheduler.boundary(s,Date.parse('2026-11-17T22:00:00Z'))).toISOString(),'2026-11-18T06:00:00.000Z');assert.equal(scheduler.allowed(s,Date.parse('2026-10-17T22:00:00Z')),false);assert.equal(scheduler.allowed(s,Date.parse('2026-10-18T05:00:00Z')),true);
}finally{clearInterval(scheduler.timer);await rm(dir,{recursive:true,force:true});}
});
+65
View File
@@ -0,0 +1,65 @@
import {readFile,readdir} from 'node:fs/promises';
import path from 'node:path';
import {parseBbsLog} from './journal.mjs';
const lines=value=>String(value||'').split(/[|\r\n]+/).map(s=>s.trim()).filter(Boolean);
export function safeScript(value){return lines(value).map(l=>/^(?:RMS|CMS|ATTACH\s+\d+|RADIO\s+[\d.]+\s+[A-Z0-9 -]+|PAUSE\s+\d+|OVERRIDEBUSY|INTERLOCK\s+\d+|TIMES\s+[\d-]+|ELSE|C(?:ONNECT)?\s+(?:\d+\s+)?!?[A-Z0-9:-]+|MSGTYPES\s+[A-Z0-9]+)$/i.test(l)?l:'[Comando riservato o non visualizzabile]');}
export function parseForwarding(text,ports=[]){
const section=text.split(/BBSForwarding\s*:\s*\{/)[1]?.split(/\nBBSUsers\s*:/)[0]||'';const profiles=[];
for(const m of section.matchAll(/\b([A-Z0-9-]+)\s*:\s*\{([^{}]*)\}/g)){
const fields={};for(const f of m[2].matchAll(/\b(\w+)\s*=\s*(?:"([^"\r\n]*)"|(\d+))\s*;/g))fields[f[1]]=f[2]??f[3];
// BPQ may persist empty forwarding records for ordinary connected users.
if(![fields.ConnectScript,fields.TOCalls,fields.ATCalls,fields.HRoutes,fields.HRoutesP].some(v=>v?.trim())&&fields.Enabled!=='1'&&fields.RequestReverse!=='1')continue;
const script=fields.ConnectScript||'',port=Number(script.match(/\bATTACH\s+(\d+)/i)?.[1]||script.match(/\bC\s+(\d+)\s/i)?.[1])||null,driver=ports.find(p=>p.id===port)?.driver||'';
profiles.push({timesLocal:/^\s*Localtime\s*=\s*1\s*;/m.test(text),call:m[1],enabled:fields.Enabled==='1',interval:Number(fields.FwdInterval)||0,reverse:fields.RequestReverse==='1',reverseInterval:Number(fields.RevFWDInterval)||0,immediate:fields.FWDNewImmediately==='1',times:lines(fields.FWDTimes),ha:fields.BBSHA||'',to:lines(fields.TOCalls),at:lines(fields.ATCalls),bulletins:lines(fields.HRoutes),personal:lines(fields.HRoutesP),personalOnly:fields.FWDPersonalsOnly==='1',script:safeScript(script),port,driver,transport:/\b(?:CMS|RMS)\b/i.test(script)||/TELNET/i.test(driver)?'Internet':port&&!/AXIP/i.test(driver)?'Radio':/AXIP/i.test(driver)?'Rete AXIP':'Percorso BPQ',frequency:script.match(/\bRADIO\s+([\d.]+)\s+([A-Z0-9-]+)/i)?.slice(1)||null,configured:Boolean(script.trim())});
}
return profiles;
}
export function nextForwarding(profile,last,now=Date.now(),queued=null){
if(!profile.enabled||!profile.configured||!profile.interval||(!profile.reverse&&queued===0))return null;
if(!last?.startedAt)return null;
const bands=profile.times.length?profile.times:['0000-2359'];const valid=bands.map(b=>b.match(/^(\d{2})(\d{2})-(\d{2})(\d{2})$/)).filter(Boolean).map(m=>[Number(m[1])*60+Number(m[2]),Number(m[3])*60+Number(m[4])]).filter(([a,b])=>a<=b&&b<1440);
if(!valid.length)return null;
let target=Date.parse(last.startedAt)+profile.interval*1000;if(!Number.isFinite(target))return null;
// BPQ owns the real timer; a missed estimate must not appear as a firm countdown.
if(target<now)target=now;
const day=new Date(target);if(profile.timesLocal)day.setHours(0,0,0,0);else day.setUTCHours(0,0,0,0);
for(let d=0;d<3;d++)for(const [start,end]of valid){let a,b;if(profile.timesLocal){const t=new Date(day);t.setDate(t.getDate()+d);t.setHours(Math.floor(start/60),start%60,0,0);a=+t;t.setHours(Math.floor(end/60),end%60,59,999);b=+t;}else{a=+day+d*86400000+start*60000;b=+day+d*86400000+(end+1)*60000-1;}if(target<=b)return new Date(Math.max(target,a)).toISOString();}
return null;
}
export function forwardingHistory(text,peer,now=Date.now()){
const filtered=text.split(/\r?\n/).filter(l=>l.match(/^\d{6} \d{2}:\d{2}:\d{2} [|<>?!]([A-Z0-9-]+)\s/)?.[1]===peer).join('\n');
// Some BPQ builds omit outgoing compression records. A remote turn after FS
// acknowledges the accepted outgoing batch; FS alone is not delivery evidence.
const confirmed=new Map();let session=null,proposals=0,accepted=0;
for(const line of filtered.split('\n')){const m=line.match(/^(\d{2})(\d{2})(\d{2}) (\d{2}:\d{2}:\d{2}) ([|<>?!])[A-Z0-9-]+\s+(.*)$/);if(!m)continue;const t=m[6];if(/Connecting to BBS|Incoming Connect from/i.test(t)){session=`20${m[1]}-${m[2]}-${m[3]}T${m[4]}Z`;proposals=0;accepted=0;}
if(m[5]==='>'&&/^F[ABC]\s/.test(t))proposals++;
if(m[5]==='<'&&/^FS\s/.test(t)){accepted=Math.min(proposals,(t.slice(3).match(/[+Y!]/g)||[]).length);proposals=0;}
else if(m[5]==='<'&&/^(?:FF|FQ|F[ABC]\s)/.test(t)&&accepted){confirmed.set(session,(confirmed.get(session)||0)+accepted);accepted=0;}
}
return parseBbsLog(filtered).map(s=>({startedAt:s.startedAt,endedAt:s.endedAt,connectedAt:s.connectedAt,sent:Math.max(s.sentMessages,confirmed.get(s.startedAt)||0),received:s.receivedMessages,status:s.endedAt?s.status:now-Date.parse(s.startedAt)>30*60000?'unknown':s.connectedAt?'connected':'calling',direction:s.direction,error:s.error||null,complete:s.exchangeComplete||false})).sort((a,b)=>Date.parse(b.startedAt)-Date.parse(a.startedAt)).slice(0,8);
}
export class Forwarding{
constructor(config,bpq,radio){this.config=config;this.bpq=bpq;this.radio=radio;this.chain=Promise.resolve();this.requested=new Map();this.lockedPeers=new Map();this.cached=null;this.cachedAt=0;}
exclusive(fn){const result=this.chain.then(fn);this.chain=result.catch(()=>{});return result;}
async profiles(){return parseForwarding(await readFile(path.join(this.config.root,'BPQMailChat','BPQMail.cfg'),'utf8'),this.config.ports);}
async context(){const status=await this.bpq('/Mail/Status');const link=status.match(/href=(\/Mail\/FWD\?[^\s>]+)/)?.[1];if(!link)throw new Error('Forwarding BPQ non disponibile');const page=await this.bpq(link);const key=page.match(/var Key\s*=\s*"([^"]+)"/)?.[1];if(!key)throw new Error('Sessione forwarding non disponibile');return key;}
async logs(){const dir=path.join(this.config.root,'Logs');const names=(await readdir(dir)).filter(n=>/^log_\d{6}_BBS\.txt$/i.test(n)).sort().slice(-7);return (await Promise.all(names.map(n=>readFile(path.join(dir,n),'utf8').catch(()=>'')))).join('\n');}
snapshot(){return this.exclusive(async()=>{
if(this.cached&&Date.now()-this.cachedAt<4000)return this.cached;
const profiles=await this.profiles(),log=await this.logs().catch(()=>''),errors=[];let key;try{key=await this.context();}catch{errors.push('BPQ non disponibile: le code non sono aggiornate.');}
const out=[];for(const p of profiles){let queued=null;if(key)try{const html=await this.bpq('/Mail/FwdDetails?'+key,{method:'POST',body:p.call});const n=html.match(/-\s*(\d+) Messages Queued/i);if(n)queued=Number(n[1]);}catch{errors.push('Coda '+p.call+' non disponibile');}
const history=forwardingHistory(log,p.call),last=history[0]||null;out.push({...p,queued,history,last,active:Boolean(last&&!last.endedAt&&['calling','connected'].includes(last.status)),requestedAt:this.requested.get(p.call)||null,nextEstimated:nextForwarding(p,last,Date.now(),queued)});
}
this.cached={profiles:out,updatedAt:new Date().toISOString(),scheduleTimezone:profiles.some(p=>p.timesLocal)?'Locale server BPQ':'UTC',radio:this.radio(),errors};this.cachedAt=Date.now();return this.cached;
});}
start(peer,{signal}={}){return this.exclusive(async()=>{
signal?.throwIfAborted();if(this.lockedPeers.has(peer))throw new Error(this.lockedPeers.get(peer));
const p=(await this.profiles()).find(p=>p.call===peer);if(!p?.configured)throw new Error('Profilo di forwarding non configurato');
if(Date.now()-(this.requested.get(peer)||0)<30000)throw new Error('Sincronizzazione già richiesta: attendi 30 secondi');
const last=forwardingHistory(await this.logs().catch(()=>''),peer)[0];if(last&&!last.endedAt&&['calling','connected'].includes(last.status))throw new Error('Forwarding già in corso per questo partner');
const radio=this.radio();if(p.transport==='Radio'&&(radio?.txSuspended||radio?.portsPaused?.[p.port]))throw Error('Trasmissioni radio sospese dalla console');if(p.transport==='Radio'&&(radio?.active||radio?.connecting))throw new Error('Modem occupato da una connessione: riprova al termine');
const key=await this.context();await this.bpq('/Mail/FwdDetails?'+key,{method:'POST',body:peer});signal?.throwIfAborted();await this.bpq('/Mail/FWDSave?'+key,{method:'POST',body:'StartForward'});
this.requested.set(peer,Date.now());this.cached=null;return {ok:true,peer,requestedAt:new Date().toISOString()};
});}
}
+31
View File
@@ -0,0 +1,31 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {parseForwarding,safeScript,nextForwarding,forwardingHistory,Forwarding} from './forwarding.mjs';
import {mkdtemp,mkdir,writeFile,rm} from 'node:fs/promises';
import os from 'node:os';import path from 'node:path';
const fixture=`BBSForwarding : {
N0TEST : { ConnectScript = "ATTACH 3|RADIO 14.100 USB|C N0TEST-8"; Enabled = 1; HRoutes = "WW"; HRoutesP = "WW"; FwdInterval = 3600; RequestReverse = 1; RevFWDInterval = 7200; FWDTimes = "0500-2159"; BBSHA = "N0TEST.TEST.USA.NOAM"; }
RMS : { ConnectScript = "C 5 CMS"; Enabled = 1; FwdInterval = 1800; }
LOCAL : { Enabled = 0; }
}
BBSUsers : { SECRET = "private credentials"; }`;
test('forwarding profiles detect generic modem, Internet and redact secret commands',()=>{
const p=parseForwarding(fixture,[{id:3,driver:'SCSPACTOR'},{id:5,driver:'TELNET'}]);assert.equal(p.length,2);assert.equal(parseForwarding('Localtime = 1;\n'+fixture)[0].timesLocal,true);assert.equal(p[0].transport,'Radio');assert.equal(p[0].driver,'SCSPACTOR');assert.deepEqual(p[0].personal,['WW']);assert.equal(p[1].transport,'Internet');assert.ok(!p.some(row=>row.call==='LOCAL'));assert.ok(!JSON.stringify(p).includes('private credentials'));assert.ok(!safeScript('PASSWORD secret|RRADIO AUTH key|C 5 host user password').join().includes('secret'));assert.ok(!safeScript('PASSWORD secret|RRADIO AUTH key|C 5 host user password').join().includes('key'));
});
test('next forwarding estimate respects UTC windows and never invents a timer without history',()=>{
const p=parseForwarding(fixture)[0];const last={startedAt:'2026-10-16T21:30:00Z'};assert.equal(nextForwarding(p,last,Date.parse('2026-10-16T21:40:00Z')),'2026-10-17T05:00:00.000Z');assert.equal(nextForwarding(p,null),null);assert.equal(nextForwarding({...p,enabled:false},last),null);assert.equal(nextForwarding({...p,reverse:false},last,Date.now(),0),null);assert.equal(nextForwarding({...p,times:['2500-2600']},last),null);
});
test('forwarding history isolates peers and distinguishes clean completion from failed calls',()=>{
const log=['261016 10:00:00 |N0TEST Connecting to BBS N0TEST','261016 10:00:05 <N0TEST *** Connected to N0TEST-8','261016 10:00:06 |N0TEST Compressing Message Comp Len 30 Msg Len 100','261016 10:00:08 <N0TEST FF','261016 10:00:09 >N0TEST FQ','261016 10:00:10 |N0TEST N0TEST Disconnected','261016 11:00:00 |RMS Connecting to BBS RMS','261016 11:00:01 <RMS password private','261016 12:00:00 |N0TEST Connecting to BBS N0TEST','261016 12:01:00 <N0TEST Failure with N0TEST-8','261016 12:01:01 |N0TEST N0TEST Disconnected'].join('\n');const h=forwardingHistory(log,'N0TEST');assert.equal(h.length,2);assert.equal(h[0].status,'failed');assert.equal(h[1].status,'complete');assert.equal(h[1].sent,1);assert.ok(!JSON.stringify(h).includes('private'));assert.equal(forwardingHistory('261016 12:00:00 |N0TEST Connecting to BBS N0TEST','N0TEST',Date.parse('2026-10-16T13:00:00Z'))[0].status,'unknown');
});
test('forwarding starts configured peers only, serializes native context, prevents duplicates and occupied radio',async()=>{
const root=await mkdtemp(path.join(os.tmpdir(),'bpq-forward-'));await mkdir(path.join(root,'BPQMailChat'));await mkdir(path.join(root,'Logs'));await writeFile(path.join(root,'BPQMailChat','BPQMail.cfg'),fixture);const calls=[];let busy=false;
const f=new Forwarding({root,ports:[{id:3,driver:'SCSPACTOR'},{id:5,driver:'TELNET'}]},async(url,opts)=>{calls.push([url,opts?.body]);if(url==='/Mail/Status')return 'href=/Mail/FWD?fixture';if(url==='/Mail/FWD?fixture')return 'var Key = "fixture"';if(url.startsWith('/Mail/FwdDetails'))return 'Forwarding Config - 2 Messages Queued';return 'ok';},()=>({active:busy}));
try{await assert.rejects(f.start('UNKNOWN'));await assert.rejects(f.start('LOCAL'));busy=true;await assert.rejects(f.start('N0TEST'),/Modem occupato/);busy=false;await Promise.all([f.start('N0TEST'),f.start('RMS')]);assert.deepEqual(calls.filter(c=>c[0].includes('FwdDetails')||c[0].includes('FWDSave')).map(c=>c[1]),['N0TEST','StartForward','RMS','StartForward']);await assert.rejects(f.start('N0TEST'),/già richiesta/);const snapshot=await f.snapshot();assert.equal(snapshot.profiles[0].queued,2);assert.equal(snapshot.scheduleTimezone,'UTC');}finally{await rm(root,{recursive:true,force:true});}
});
test('outgoing FBB count requires remote turn acknowledgement after acceptance',()=>{const prefix='261016 10:00:00 |N0TEST Connecting to BBS N0TEST\n261016 10:00:01 >N0TEST FA B N9DEMO EU BBS 1_N9DEMO 100\n261016 10:00:02 <N0TEST FS +';assert.equal(forwardingHistory(prefix,'N0TEST')[0].sent,0);assert.equal(forwardingHistory(prefix+'\n261016 10:00:05 <N0TEST FF','N0TEST')[0].sent,1);assert.equal(forwardingHistory(prefix.replace('FS +','FS -')+'\n261016 10:00:05 <N0TEST FF','N0TEST')[0].sent,0);});
test('TX suspension rejects radio forwarding before native commands and preserves Internet sync',async()=>{
const calls=[],f=new Forwarding({root:'',ports:[]},async(url,opts)=>{calls.push([url,opts]);return 'ok';},()=>({txSuspended:true}));f.profiles=async()=>[{call:'N0TEST',configured:true,transport:'Radio'},{call:'RMS',configured:true,transport:'Internet'}];f.logs=async()=>'';f.context=async()=>'fixture';await assert.rejects(f.start('N0TEST'),/sospese/);assert.equal(calls.length,0);await f.start('RMS');assert.equal(calls.length,2);
});
+74
View File
@@ -0,0 +1,74 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import vm from 'node:vm';
import {readFileSync} from 'node:fs';
const source=readFileSync(new URL('./public/i18n.js',import.meta.url),'utf8');
function client(languages=['it-IT'],saved=null,defaultLanguage=null){
const storage=new Map(saved?[['bpq-language',saved]]:[]),events=[];
const context=vm.createContext({BPQ_DEFAULT_LANGUAGE:defaultLanguage,navigator:{languages},localStorage:{getItem:k=>storage.get(k),setItem:(k,v)=>storage.set(k,v)},document:{documentElement:{lang:''},readyState:'loading',body:null,addEventListener(){},querySelectorAll:()=>[],dispatchEvent:e=>events.push(e)},addEventListener(){},CustomEvent:class{constructor(type,options){Object.assign(this,{type,...options});}}});
vm.runInContext(source,context);return {api:context.BPQI18n,document:context.document,storage,events};
}
test('first visit chooses a concrete saved language from the browser, with English fallback',()=>{
for(const [languages,expected]of [[['it-IT','en-US'],'it'],[['en-US','it'],'en'],[['de-DE'],'en'],[[],'en']]){
const {api,document,storage}=client(languages);assert.equal(api.language,expected);assert.equal(document.documentElement.lang,expected);assert.equal(api.preference,expected);assert.equal(storage.get('bpq-language'),expected);
}
});
test('explicit language overrides automatic detection and is saved per browser',()=>{
const {api,storage,document}=client(['en-US'],'it');assert.equal(api.t('Connetti'),'Connetti');
api.setLanguage('en');assert.equal(api.t('Connetti'),'Connect');assert.equal(storage.get('bpq-language'),'en');assert.equal(document.documentElement.lang,'en');assert.equal(api.locale(),'en-GB');
api.setLanguage('it');assert.equal(api.t('Connetti'),'Connetti');assert.equal(api.locale(),'it-IT');
api.setLanguage('auto');assert.equal(api.language,'it');assert.equal(api.preference,'it');
api.setLanguage('invalid');assert.equal(api.preference,'it');
});
test('UI translations handle counters, statuses, decorative icons and dynamic values',()=>{
const {api}=client(['en']);
assert.equal(api.t('↻ Sincronizza ora'),'↻ Sync now');
assert.equal(api.t('▤ Commenta'),'▤ Comment');
assert.equal(api.t('▦ Panoramica'),'▦ Overview');
assert.equal(api.t('⌖ APRS'),'⌖ APRS');
assert.equal(api.t('≋ Monitor'),'≋ Monitor');
assert.equal(api.t('◷ Diario'),'◷ Logbook');
assert.equal(api.t('▸_ Terminale'),'▸_ Terminal');
assert.equal(api.t('📎 Allegati'),'📎 Attachments');
assert.equal(api.t('Salva e metti in coda →'),'Save and queue →');
assert.equal(api.t('12 bollettini · 3 personali'),'12 bulletins · 3 personal');
assert.equal(api.t('● Connesso · N0TEST'),'● Connected · N0TEST');
assert.equal(api.t('Stazione / Panoramica'),'Station / Overview');
assert.equal(api.t('Aggiornato 13:10 · UTC+02:00'),'Updated 13:10 · UTC+02:00');
assert.equal(api.t('2 nuovi messaggi ↓'),'2 new messages ↓');
assert.equal(api.t('HB9ON-2'),'HB9ON-2');
assert.equal(api.t('Custom unknown text'),'Custom unknown text');
});
test('legacy Auto preference migrates to a concrete language',()=>{const {api,storage}=client(['en-US'],'auto');assert.equal(api.preference,'en');assert.equal(storage.get('bpq-language'),'en');});
test('configured default language precedes browser detection, saved choice wins',()=>{assert.equal(client(['it-IT'],null,'en').api.language,'en');assert.equal(client(['en-US'],'it','en').api.language,'it');});
test('English preserves empty HTML text nodes and whitespace instead of inserting undefined',()=>{
const {api}=client(['en-US']);
for(const value of ['', ' ', '\n', '\r\n \t', ' · ', '● ', ' →'])assert.equal(api.t(value),value);
assert.equal(api.t(null),'');assert.equal(api.t(undefined),'');
assert.equal(api.t(' Seleziona un messaggio '),' Select a message ');
});
test('live APRS, radio controls, map counters and attachment statuses translate when built dynamically',()=>{
const {api}=client(['en-US']);
const labels=[
['● APRS in tempo reale','● Live APRS'],
['Attività','Activity'],['Configurazione','Configuration'],['Stazioni ricevute','Heard stations'],
['Centra stazioni','Fit stations'],['Pausa vista','Pause display'],['Riprendi vista','Resume display'],
['Tipo / pacchetto','Type / packet'],['Da → A','From → To'],['Oggetto APRS','APRS object'],
['86 sulla mappa · 2 senza posizione','86 on map · 2 without position'],
['2000 pacchetti nel registro','2000 packets in the log'],
['Posizioni dai locator · UTC+02:00','Positions from locators · UTC+02:00'],
['Dal 2026-10-04 · UTC+02:00','Since 2026-10-04 · UTC+02:00'],
['● Frequenza fissa','● Fixed frequency'],['+ Frequenza','+ Frequency'],['PORTE RADIO','RADIO PORTS'],['Salva','Save'],
['Frequenza APRS Port 3','APRS frequency port 3'],
['Ricostruito da 3 parti · CRC verificati','Rebuilt from 3 parts · CRCs verified'],
['3 parti ricostruite · CRC verificati','3 reconstructed parts · CRCs verified'],
['Ricevute 2/3 parti. Mancano: 3.','Received 2/3 parts. Missing: 3.'],
['Parte 1/3. Nessun blocco 7plus riconoscibile nel messaggio.','Part 1/3. No recognisable 7plus block in the message.'],
];
for(const [it,en]of labels){assert.equal(api.t(it),en,it);api.setLanguage('it');assert.equal(api.t(it),it);api.setLanguage('en');}
assert.equal(api.t('image.jpg · 3 parti ricostruite · CRC verificati'),'image.jpg · 3 reconstructed parts · CRCs verified');
});
+22
View File
@@ -0,0 +1,22 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {manualRoutes} from './manual-forwarding.mjs';
import {radioProfile} from './winlink-radio.mjs';
import {reservePacketSlot,releasePacketSlot,renewPacketSlot} from './radio-slot.mjs';
import {mkdtemp,writeFile,readFile,rm} from 'node:fs/promises';
import path from 'node:path';import os from 'node:os';
test('dedicated KISS forwarding connects by native AX25 port without tuning or attaching the HF rig',()=>{
const route={id:'N0TEST-VHF',peer:'N0TEST',port:3,frequencyMHz:144.825,mode:'FM',connectCall:'N0TEST-8',nativeKiss:true,controller:{independent:true,requestFile:'C:/radio/request.json',statusFile:'C:/radio/status.json'}};
const config={ports:[{id:3,driver:'KISS'}],manualForwardingRoutes:[route]};
assert.equal(manualRoutes(config)[0].script,'C 3 !N0TEST-8');
assert.match(manualRoutes({...config,ports:[{id:3,driver:'UZ7HO'}]})[0].script,/^ATTACH 3\|RADIO/);
const channel={call:'N0TEST',family:'Packet',dialHz:144950000};
assert.equal(radioProfile({},channel,3,{nativeKiss:true}).ConnectScript,'C 3 !N0TEST');
assert.match(radioProfile({},channel,3).ConnectScript,/^ATTACH 3\|RADIO/);
});
test('dedicated packet preparation accepts a fresh hardware bridge acknowledgement without querying the HF modem',async()=>{
const dir=await mkdtemp(path.join(os.tmpdir(),'dedicated-kiss-'));
const controller={independent:true,requestFile:path.join(dir,'request.json'),statusFile:path.join(dir,'status.json')};
const client={job:{},persist:async()=>writeFile(controller.statusFile,JSON.stringify({manualRequestId:client.job.controller.id,phase:'vhf',pttReady:true,frequency:144.825,at:new Date().toISOString(),independent:true,connections:1})),fwd:{bpq:async()=>assert.fail('Independent KISS must not query an external HF driver page')}};
try{await reservePacketSlot(client,controller,144.825,3);assert.ok(client.job.controller.preparationMs>=0);const request=JSON.parse(await readFile(controller.requestFile));request.expiresAt=Date.now()+1000;await writeFile(controller.requestFile,JSON.stringify(request));await renewPacketSlot(client);assert.ok(JSON.parse(await readFile(controller.requestFile)).expiresAt>Date.now()+80000);await releasePacketSlot(client);await renewPacketSlot(client);assert.equal(JSON.parse(await readFile(controller.requestFile)).expiresAt,0);}finally{await rm(dir,{recursive:true,force:true});}
});
+59 -20
View File
@@ -1,20 +1,59 @@
process.on('uncaughtException',e=>{console.error('Installazione interrotta: '+e.message);process.exit(1)}); import {readFile,writeFile,copyFile,rename} from 'node:fs/promises';
import {readFile,writeFile} from 'node:fs/promises'; import http from 'node:http';
import http from 'node:http';import path from 'node:path';import {fileURLToPath} from 'node:url';import {parseConfig} from './config.mjs'; import path from 'node:path';
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}; import os from 'node:os';
const root=arg('bpq-root')||path.join(process.env.APPDATA||'','BPQ32'); import {fileURLToPath} from 'node:url';
const detected=parseConfig(await readFile(path.join(root,'BPQ32.cfg'),'utf8')); import {parseConfig,validPort,validateSysopUsers} from './config.mjs';
if(!detected.users.length)throw new Error('Configurare un USER Telnet sysop in BPQ32.cfg'); import {parseForwarding} from './forwarding.mjs';
const port=Number(arg('port')||8090),httpPort=Number(arg('http-port')||detected.httpPort); import {modemFamily} from './winlink-gateways.mjs';
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')))}); const dir=path.dirname(fileURLToPath(import.meta.url));
let previous={};try{previous=JSON.parse(await readFile(path.join(dir,'console.config.json'),'utf8'))}catch{} export async function readLocalConfig(file){try{const value=JSON.parse(await readFile(file,'utf8'));if(!value||typeof value!=='object'||Array.isArray(value))throw new Error('Object required');return value;}catch(e){if(e.code==='ENOENT')return {};throw new Error('Configurazione locale non leggibile: correggere il JSON prima di reinstallare');}}
const radioPort=Number(arg('radio-port')||previous.radioPort)||detected.radioPorts[0]?.id||null; export function probeBpq(port){return new Promise((resolve,reject)=>{
if(radioPort&&!detected.radioPorts.some(p=>p.id===radioPort))throw new Error('Porta radio selezionata non rilevata'); const request=http.get({hostname:'127.0.0.1',port,path:'/Node/Ports.html',headers:{Connection:'close'},agent:false},response=>{let text='';response.on('data',b=>{text+=b;if(text.length>2e6)response.destroy(new Error('Risposta HTTP troppo grande'));});response.on('error',reject);response.on('end',()=>response.statusCode===200&&/\/Node\//i.test(text)&&/\bPorts\b/i.test(text)?resolve():reject(new Error('Il server HTTP non conferma BPQ')));});
const sysopUser=arg('sysop-user')||previous.sysopUser||detected.users[0].user; request.setTimeout(8000,()=>request.destroy(new Error('Timeout BPQ')));request.on('error',()=>reject(new Error('BPQ non raggiungibile: avviare BPQ e verificare HTTPPORT')));
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 samePath=(a,b)=>process.platform==='win32'?path.resolve(a).toLowerCase()===path.resolve(b).toLowerCase():path.resolve(a)===path.resolve(b);
const config={nodeExe:process.execPath,bpqRoot:root,httpPort,port,radioPort,sysopUser,forwardPeer:arg('forward-peer')||previous.forwardPeer||'',cmsPeer:'RMS',varaSyslogPort:18514}; export async function prepareInstall(options={},dependencies={}){
if(config.forwardPeer&&!peers.includes(config.forwardPeer))throw new Error('Profilo forwarding selezionato non rilevato'); const configPath=path.resolve(options.configPath||process.env.BPQ_CONSOLE_CONFIG||path.join(dir,'console.config.json'));
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)); const previous=await readLocalConfig(configPath);
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.');} const root=path.resolve(options.bpqRoot||process.env.BPQ_ROOT||previous.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.nodeCall)throw new Error('NODECALL non rilevato in BPQ32.cfg');
if(!detected.users.length)throw new Error('Configurare un USER Telnet sysop in BPQ32.cfg');
const sameStation=Boolean(previous.bpqRoot&&samePath(previous.bpqRoot,root)),saved=sameStation?previous:{};
const port=Number(options.port??process.env.BPQ_CONSOLE_PORT??previous.port??8090),httpPort=Number(options.httpPort??saved.httpPort??detected.httpPort);
if(!validPort(port,1024)||!validPort(httpPort)||port===httpPort)throw new Error('Porte non valide o in conflitto: pannello 1024-65535, HTTP BPQ 1-65535, diverse fra loro');
const chosen=options.radioPort??saved.radioPort??detected.radioPorts[0]?.id??null;
const radio=chosen==null?null:detected.radioPorts.find(p=>p.id===Number(chosen));
if(chosen!=null&&!radio)throw new Error('Porta radio selezionata non rilevata: specificare -RadioPort');
const sysopUser=options.sysopUser??saved.sysopUser??detected.users[0].user;
if(!detected.users.some(u=>u.user===sysopUser))throw new Error('Utente sysop non rilevato: specificare -SysopUser');
const sysopUsers=validateSysopUsers(saved.sysopUsers,detected.users);
let profiles=[];try{profiles=parseForwarding(await readFile(path.join(root,'BPQMailChat','BPQMail.cfg'),'utf8'),detected.ports);}catch(e){if(e.code!=='ENOENT')throw e;}
const peers=profiles.map(p=>p.call),forwardPeer=String(options.forwardPeer??saved.forwardPeer??'').toUpperCase(),cmsPeer=String(options.cmsPeer??saved.cmsPeer??'RMS').toUpperCase();
if(forwardPeer&&!peers.includes(forwardPeer))throw new Error('Profilo forwarding selezionato non rilevato');
if(!/^[A-Z0-9-]{1,12}$/.test(cmsPeer))throw new Error('Nome profilo CMS non valido');
if(options.cmsPeer&&!peers.includes(cmsPeer))throw new Error('Profilo CMS selezionato non rilevato');
const sameRadio=sameStation&&Number(saved.radioPort)===radio?.id&&(!saved.radioDriver||saved.radioDriver===radio.driver);
const catControl=options.catControl??(sameRadio&&saved.winlinkRadio?.catControl===true);
if(catControl&&(!radio||!modemFamily(radio.driver)))throw new Error('Winlink radio richiede un modem HF VARA, Pactor o ARDOP');
const vara=Boolean(radio&&/^VARA/i.test(radio.driver));
const language=options.language??previous.language??null;if(language!=null&&!['it','en'].includes(language))throw new Error('language deve essere it oppure en');
const config={...saved,...(sysopUsers===undefined?{}:{sysopUsers}),...(language?{language}:{}),nodeExe:process.execPath,bpqRoot:root,httpPort,port,radioPort:radio?.id??null,radioDriver:radio?.driver??null,sysopUser,forwardPeer,cmsPeer,varaSyslogPort:saved.varaSyslogPort??18514,varaLogPath:vara?(options.varaLogPath??(sameRadio?saved.varaLogPath:null)??null):null,winlinkRadio:{...(sameRadio?saved.winlinkRadio:{}),catControl:Boolean(catControl)}};
if(!validPort(Number(config.varaSyslogPort)))throw new Error('Porta syslog VARA non valida');
const warnings=[];if(detected.radioPorts.length>1&&options.radioPort==null&&saved.radioPort==null)warnings.push('Più modem rilevati: selezionata la prima porta; usare -RadioPort per cambiarla.');
if(detected.winlink&&!peers.includes(cmsPeer))warnings.push('Profilo CMS non presente: configurarlo in BPQ prima di usare il sync Winlink.');
if(options.catControl===true)warnings.push('CAT abilitato su richiesta: verificare RADIO in BPQ prima di una chiamata; nessuna trasmissione eseguita dall’installer.');
await (dependencies.probe||probeBpq)(httpPort);
return {config,configPath,previous,report:{bpq:'in esecuzione, HTTP verificato',nodeCall:detected.nodeCall,ports:detected.ports,services:detected.apps.map(a=>a.command),terminal:Boolean(detected.telnetPort),forwardProfiles:peers,selectedRadio:radio?.id??null,sysopUser,warnings}};
}
export async function saveInstall(plan){
if(JSON.stringify(plan.previous)===JSON.stringify(plan.config))return {changed:false};
let backup=null;try{backup=plan.configPath+'.'+new Date().toISOString().replace(/[:.]/g,'-')+'.backup';await copyFile(plan.configPath,backup);}catch(e){if(e.code!=='ENOENT')throw e;backup=null;}
await writeFile(plan.configPath+'.tmp',JSON.stringify(plan.config,null,2)+'\n');await rename(plan.configPath+'.tmp',plan.configPath);return {changed:true,backup};
}
export function parseArgs(args){const names={'bpq-root':'bpqRoot',port:'port','http-port':'httpPort','radio-port':'radioPort','sysop-user':'sysopUser','forward-peer':'forwardPeer','cms-peer':'cmsPeer','vara-log':'varaLogPath','config-path':'configPath',language:'language'},options={};
for(let i=0;i<args.length;i++){const n=args[i];if(n==='--check-only'){options.checkOnly=true;continue;}if(n==='--enable-radio-cat'||n==='--disable-radio-cat'){if(options.catControl!==undefined)throw new Error('Specificare una sola opzione CAT');options.catControl=n==='--enable-radio-cat';continue;}const key=names[n.slice(2)];if(!n.startsWith('--')||!key||args[i+1]===undefined||args[i+1].startsWith('--'))throw new Error('Opzione installer non valida o valore mancante');options[key]=args[++i];}return options;
}
if(process.argv[1]&&samePath(process.argv[1],fileURLToPath(import.meta.url))){try{const options=parseArgs(process.argv.slice(2)),plan=await prepareInstall(options);console.log(JSON.stringify(plan.report,null,2));if(!options.checkOnly){const saved=await saveInstall(plan);console.log(saved.changed?'Configurazione salvata senza password. Backup precedente: '+(saved.backup||'prima installazione'):'Configurazione invariata.');}}catch(e){console.error('Installazione interrotta: '+e.message);process.exitCode=1;}}
+98
View File
@@ -0,0 +1,98 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import http from 'node:http';
import net from 'node:net';
import {execFile} from 'node:child_process';
import {promisify} from 'node:util';
import {prepareInstall,saveInstall,parseArgs,probeBpq} from './install.mjs';
import {parseConfig} from './config.mjs';
const run=promisify(execFile),probe=async()=>{};
const cfg=(driver='VARA',call='N9DEMO')=>`NODECALL = ${call}-7
NODEALIAS=DEMO
LOCATOR=IO91AA
PORT
PORTNUM=3
ID=HF modem
DRIVER = ${driver}
ENDPORT
PORT
PORTNUM=7
DRIVER = Telnet.dll
HTTPPORT = 8088
TCPPORT=9000
CMS=1
USER=admin,fixture-secret,${call},sysop
USER=operator,another-fixture,${call}-1,sysop
ENDPORT
APPLICATION 1, bbs, ,${call}-11,MAIL
`;
async function fixture(t,driver='VARA'){
const dir=await fs.mkdtemp(path.join(os.tmpdir(),"bpq install O'Brien "));t.after(()=>fs.rm(dir,{recursive:true,force:true}));const root=path.join(dir,'station');await fs.mkdir(path.join(root,'BPQMailChat'),{recursive:true});await fs.writeFile(path.join(root,'BPQ32.cfg'),cfg(driver));await fs.writeFile(path.join(root,'BPQMailChat','BPQMail.cfg'),'BBSForwarding : {\n CMS2 : { ConnectScript="RMS"; Enabled=1; }\n N1PEER : { ConnectScript="ATTACH 3|C N1PEER"; Enabled=1; }\n}\nBBSUsers : {}');
return {dir,root,options:{bpqRoot:root,configPath:path.join(dir,'console.config.json')}};
}
test('configuration ignores banners and comments, accepts whitespace, DLL drivers and Telnet-specific ports',()=>{
const parsed=parseConfig('/* single line comment */\nINFOMSG:\nNODECALL=N0WRONG\nUSER=wrong,not-a-secret,N0WRONG,sysop\n***\n'+cfg('ARDOP')+'\nPORT\nDRIVER=OTHER\nHTTPPORT=9999\nTCPPORT=9998\nENDPORT');
assert.equal(parsed.nodeCall,'N9DEMO-7');assert.equal(parsed.users.length,2);assert.equal(parsed.httpPort,8088);assert.equal(parsed.telnetPort,9000);assert.equal(parsed.apps[0].command,'BBS');assert.equal(parsed.radioPorts[0].driver,'ARDOP');assert.equal(parsed.radioPorts.length,2);
const short=parseConfig('APPLICATION 1,bbs\nAPPLICATION 2,CHAT/TALK,,N9DEMO-12');assert.equal(short.apps[0].command,'BBS');assert.equal(short.apps[0].call,'');assert.equal(short.apps[1].command,'CHAT');assert.equal(short.apps[1].call,'N9DEMO-12');
});
test('fresh install detects profiles and modem without copying credentials or enabling CAT',async t=>{
const f=await fixture(t),plan=await prepareInstall(f.options,{probe});assert.equal(plan.config.radioPort,3);assert.equal(plan.config.winlinkRadio.catControl,false);assert.equal(plan.report.terminal,true);assert.deepEqual(plan.report.forwardProfiles,['CMS2','N1PEER']);assert.ok(!JSON.stringify(plan).includes('fixture-secret'));assert.equal((await saveInstall(plan)).changed,true);assert.ok(!await fs.readFile(plan.configPath,'utf8').then(s=>s.includes('fixture-secret')));
});
test('reinstallation preserves custom settings, backs up once and is idempotent',async t=>{
const f=await fixture(t),saved={bpqRoot:f.root,port:18099,httpPort:8088,radioPort:3,radioDriver:'VARA',sysopUser:'operator',cmsPeer:'CMS2',forwardPeer:'N1PEER',varaSyslogPort:19001,varaLogPath:'D:/Radio/VARAHF.log',winlinkRadio:{catControl:true},customOption:{theme:'dark'}};await fs.writeFile(f.options.configPath,JSON.stringify(saved));
const p=await prepareInstall(f.options,{probe});assert.equal(p.config.port,18099);assert.equal(p.config.sysopUser,'operator');assert.equal(p.config.cmsPeer,'CMS2');assert.equal(p.config.winlinkRadio.catControl,true);assert.equal(p.config.varaSyslogPort,19001);assert.deepEqual(p.config.customOption,saved.customOption);const result=await saveInstall(p);assert.deepEqual(JSON.parse(await fs.readFile(result.backup,'utf8')),saved);const again=await prepareInstall(f.options,{probe});assert.equal((await saveInstall(again)).changed,false);
});
test('a different station and changed modem do not inherit CAT, peers or VARA paths',async t=>{
const f=await fixture(t);await fs.writeFile(f.options.configPath,JSON.stringify({bpqRoot:f.root,radioPort:3,radioDriver:'VARA',sysopUser:'operator',cmsPeer:'CMS2',forwardPeer:'N1PEER',varaLogPath:'D:/old/VARAHF.log',winlinkRadio:{catControl:true}}));
await fs.writeFile(path.join(f.root,'BPQ32.cfg'),cfg('SCSPACTOR'));const changed=await prepareInstall(f.options,{probe});assert.equal(changed.config.winlinkRadio.catControl,false);assert.equal(changed.config.varaLogPath,null);
const root=path.join(f.dir,'another station');await fs.mkdir(root);await fs.writeFile(path.join(root,'BPQ32.cfg'),cfg('ARDOP','N8OTHER'));const other=await prepareInstall({...f.options,bpqRoot:root},{probe});assert.equal(other.config.sysopUser,'admin');assert.equal(other.config.forwardPeer,'');assert.equal(other.config.cmsPeer,'RMS');assert.equal(other.config.winlinkRadio.catControl,false);assert.equal(other.config.varaLogPath,null);
});
test('Telnet-only and non-VARA stations install with absent services and no fake modem',async t=>{
const f=await fixture(t);await fs.writeFile(path.join(f.root,'BPQ32.cfg'),cfg().replace(/PORT\nPORTNUM=3[\s\S]*?ENDPORT\n/,'').replace(/^APPLICATION.*$/m,''));await fs.rm(path.join(f.root,'BPQMailChat'),{recursive:true,force:true});const p=await prepareInstall(f.options,{probe});assert.equal(p.config.radioPort,null);assert.equal(p.config.varaLogPath,null);assert.equal(p.config.winlinkRadio.catControl,false);assert.deepEqual(p.report.forwardProfiles,[]);
for(const driver of ['SCSPACTOR','ARDOP','KISS']){await fs.writeFile(path.join(f.root,'BPQ32.cfg'),cfg(driver));const p=await prepareInstall(f.options,{probe});assert.equal(p.config.radioDriver,driver);assert.equal(p.config.varaLogPath,null);}
await assert.rejects(prepareInstall({...f.options,catControl:true},{probe}),/modem HF/);
});
test('invalid ports, users, profiles and local JSON fail without overwriting settings',async t=>{
const f=await fixture(t);for(const options of [{port:8088},{httpPort:70000},{httpPort:0},{port:1},{radioPort:99},{sysopUser:'missing'},{forwardPeer:'MISSING'},{cmsPeer:'MISSING'}])await assert.rejects(prepareInstall({...f.options,...options},{probe}));
for(const value of ['{bad json','null','[]']){await fs.writeFile(f.options.configPath,value);await assert.rejects(prepareInstall(f.options,{probe}),/JSON/);assert.equal(await fs.readFile(f.options.configPath,'utf8'),value);}
});
test('offline BPQ and failed checks never create local configuration',async t=>{
const f=await fixture(t);await assert.rejects(prepareInstall(f.options,{probe:async()=>{throw new Error('BPQ offline');}}),/offline/);await assert.rejects(fs.stat(f.options.configPath),{code:'ENOENT'});
});
test('HTTP check recognises BPQ and rejects an unrelated web service',async t=>{
let real=false;const server=http.createServer((req,res)=>res.end(real?'<a href=/Node/Ports.html>BPQ Ports</a>':'Unrelated ports page'));await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>server.close(r)));await assert.rejects(probeBpq(server.address().port),/non conferma/);real=true;await probeBpq(server.address().port);
});
test('CLI parses explicit options and rejects typos or missing values',()=>{
assert.deepEqual(parseArgs(['--port','8099','--enable-radio-cat','--check-only']),{port:'8099',catControl:true,checkOnly:true});assert.throws(()=>parseArgs(['--port']));assert.throws(()=>parseArgs(['--unknown','x']));assert.throws(()=>parseArgs(['--enable-radio-cat','--disable-radio-cat']));
});
test('PowerShell installer CheckOnly supports paths with spaces and skips startup, task and firewall', {skip:process.platform!=='win32'},async t=>{
const f=await fixture(t);const fake=http.createServer((req,res)=>res.end('<a href=/Node/Ports.html>BPQ Ports</a>'));await new Promise(r=>fake.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>fake.close(r)));await fs.writeFile(path.join(f.root,'BPQ32.cfg'),cfg().replace('8088',String(fake.address().port)));
const env={...process.env,BPQ_CONSOLE_CONFIG:f.options.configPath};delete env.BPQ_ROOT;delete env.BPQ_CONSOLE_PORT;
const result=await run('powershell.exe',['-NoProfile','-NonInteractive','-ExecutionPolicy','RemoteSigned','-File',path.resolve('Install.ps1'),'-NodeExe',process.execPath,'-BpqRoot',f.root,'-CheckOnly','-AutoStart','-EnableLAN','-Restart','-RadioPort','3','-SysopUser','operator','-Language','en','-ForwardPeer','N1PEER','-CmsPeer','CMS2'],{env,windowsHide:true,timeout:20000});assert.match(result.stdout,/N9DEMO-7/);const report=JSON.parse(result.stdout);assert.equal(report.selectedRadio,3);assert.equal(report.sysopUser,'operator');assert.ok(!result.stdout.includes('fixture-secret'));await assert.rejects(fs.stat(f.options.configPath),{code:'ENOENT'});
});
const freePort=async()=>{const s=net.createServer();await new Promise(r=>s.listen(0,'127.0.0.1',r));const p=s.address().port;await new Promise(r=>s.close(r));return p;};
test('PowerShell startup confirms readiness, handles duplicate starts, restart and failed startup', {skip:process.platform!=='win32'},async t=>{
const f=await fixture(t),script=path.join(f.dir,'Start-Console.ps1');await fs.copyFile('Start-Console.ps1',script);const configFile=path.join(f.dir,'console.config.json');let pid=null;t.after(()=>{if(pid)try{process.kill(pid);}catch{}});
const source="import http from 'node:http';import fs from 'node:fs';const c=JSON.parse(fs.readFileSync('console.config.json','utf8'));http.createServer((q,r)=>{r.setHeader('Content-Type','application/json');r.end(JSON.stringify({service:'bpq-console',pid:process.pid}));}).listen(c.port,'127.0.0.1');";await fs.writeFile(path.join(f.dir,'server.mjs'),source);let port=await freePort();await fs.writeFile(configFile,JSON.stringify({port,nodeExe:process.execPath}));const env={...process.env};delete env.BPQ_CONSOLE_CONFIG;delete env.BPQ_CONSOLE_PORT;delete env.BPQ_ROOT;
const start=extra=>run('powershell.exe',['-NoProfile','-NonInteractive','-ExecutionPolicy','RemoteSigned','-File',script,...extra],{env,windowsHide:true,timeout:25000});assert.match((await start([])).stdout,/avviato/);pid=(await(await fetch('http://127.0.0.1:'+port+'/health')).json()).pid;assert.match((await start([])).stdout,/gia in esecuzione/);
const unrelated=net.createServer();await new Promise(r=>unrelated.listen(0,'127.0.0.1',r));try{await fs.writeFile(configFile,JSON.stringify({port:unrelated.address().port,nodeExe:process.execPath}));await assert.rejects(start(['-Restart']));assert.equal((await(await fetch('http://127.0.0.1:'+port+'/health')).json()).pid,pid);}finally{await new Promise(r=>unrelated.close(r));}
port=await freePort();await fs.writeFile(configFile,JSON.stringify({port,nodeExe:process.execPath}));await assert.rejects(start([]));assert.match((await start(['-Restart'])).stdout,/avviato/);pid=(await(await fetch('http://127.0.0.1:'+port+'/health')).json()).pid;
await fs.writeFile(path.join(f.dir,'server.mjs'),"throw new Error('fixture startup failure');");await assert.rejects(start(['-Restart']));pid=null;assert.match(await fs.readFile(path.join(f.dir,'server-error.log'),'utf8'),/fixture startup failure/);
});
test('installer language defaults can be selected, preserved and validated',async t=>{
const f=await fixture(t);const plan=await prepareInstall({...f.options,language:'en'},{probe});assert.equal(plan.config.language,'en');await saveInstall(plan);assert.equal((await prepareInstall(f.options,{probe})).config.language,'en');assert.equal((await prepareInstall({...f.options,language:'it'},{probe})).config.language,'it');await assert.rejects(prepareInstall({...f.options,language:'fr'},{probe}),/language/);assert.equal(parseArgs(['--language','en']).language,'en');
});
test('installer preserves the sysop allow-list for the same station, validates it and clears it for a different station',async t=>{
const f=await fixture(t),saved={bpqRoot:f.root,sysopUser:'admin',sysopUsers:['OPERATOR']};
await fs.writeFile(f.options.configPath,JSON.stringify(saved));
const plan=await prepareInstall(f.options,{probe});assert.deepEqual(plan.config.sysopUsers,['OPERATOR']);await saveInstall(plan);
assert.equal((await saveInstall(await prepareInstall(f.options,{probe}))).changed,false);
await fs.writeFile(f.options.configPath,JSON.stringify({...saved,sysopUsers:['missing']}));await assert.rejects(prepareInstall(f.options,{probe}),/sysopUsers/);
const other=path.join(f.dir,'other-station');await fs.mkdir(other);await fs.writeFile(path.join(other,'BPQ32.cfg'),cfg('ARDOP','N8OTHER'));
assert.equal((await prepareInstall({...f.options,bpqRoot:other},{probe})).config.sysopUsers,undefined);
});
+15
View File
@@ -0,0 +1,15 @@
# VR-N7500 Bluetooth bridge helpers
`packet_tx.py` provides a bounded AX.25 packet queue and a fresh-status transmit gate for custom Bluetooth bridges. It does not configure a radio or open a serial port. Station-specific bridge scripts and radio settings are not distributed here.
Integration:
- Call `RadioGate.update(monotonic_time, transmitting_or_receiving_or_rssi_nonzero)` on each radio status notification.
- Poll status every 150 ms while packets are queued. `allows()` requires status no older than 350 ms and 300 ms of quiet before starting a packet. Pass `starting=False` for continuation fragments.
- Enqueue complete packets with `PacketTx.add()`. Send only the fragment returned by `next()` and wait for its acknowledgement before requesting another.
- Pass the reply status to `ack()`. Status 6 restarts only the affected packet, with backoff and at most three retries. Other pending packets are retained. Permanent errors discard only the affected packet.
- Clear the queue on disconnect, frequency changes or transmission suspension. Never carry stale frames to another channel. Retain an acknowledgement timeout in the bridge.
The module uses monotonic timestamps. Pending packets expire after 20 seconds; one second separates complete packets. These controls reduce incorrect-state replies but cannot eliminate races with incoming RF traffic.
Run tests with `python integrations/vr-n7500/test_packet_tx.py`.
+42
View File
@@ -0,0 +1,42 @@
"""Bounded, packet-aware transmit queue for the Bluetooth TNC."""
from collections import deque
class PacketTx:
def __init__(self):self.pending=deque();self.current=None;self.index=0;self.retries=0;self.waiting=False;self.sentAt=0;self.readyAt=0;self.dropped=0;self.retried=0
def __bool__(self):return self.current is not None or bool(self.pending)
def __len__(self):return len(self.pending)+(self.current is not None)
def clear(self):self.pending.clear();self.current=None;self.waiting=False;self.index=0
def add(self,packet,now):
if len(self)>=128:return False
parts=[]
for i,pos in enumerate(range(0,len(packet),50)):
part=packet[pos:pos+50];parts.append(bytes([i|64|(128 if pos+len(part)==len(packet) else 0)])+part+b'\x00')
self.pending.append((now,parts));return True
def next(self,now):
if self.waiting or now<self.readyAt:return None
if self.current is None:
while self.pending and now-self.pending[0][0]>20:self.pending.popleft();self.dropped+=1
if not self.pending:return None
self.current=self.pending.popleft();self.index=0;self.retries=0
if now-self.current[0]>20:self.current=None;self.dropped+=1;return None
self.waiting=True;self.sentAt=now;return self.current[1][self.index]
def ack(self,status,now):
if not self.waiting:return 'unsolicited'
self.waiting=False
if status==0:
self.index+=1
if self.index==len(self.current[1]):self.current=None;self.readyAt=now+1.0
return 'accepted'
if status==6 and self.retries<3 and now-self.current[0]<20:
self.retries+=1;self.retried+=1;self.index=0;self.readyAt=now+1.5
return 'retry'
self.current=None;self.dropped+=1;self.readyAt=now+1.5;return 'dropped'
class RadioGate:
"""Require fresh status and a quiet channel before starting a packet."""
def __init__(self):self.updated=None;self.quietSince=None;self.blocked=True
def update(self,now,blocked):
self.updated=now;self.blocked=blocked
if blocked:self.quietSince=None
elif self.quietSince is None:self.quietSince=now
def allows(self,now,starting=True):
return self.updated is not None and 0<=now-self.updated<=0.35 and not self.blocked and (not starting or self.quietSince is not None and now-self.quietSince>=0.3)
+25
View File
@@ -0,0 +1,25 @@
import sys,pathlib,unittest
sys.path.insert(0,str(pathlib.Path(__file__).parent))
from packet_tx import PacketTx,RadioGate
class Tests(unittest.TestCase):
def test_retry_restarts_packet_and_preserves_next(self):
q=PacketTx();q.add(b'A'*80,0);q.add(b'B'*10,0)
first=q.next(0);q.ack(0,.1);second=q.next(.2);self.assertNotEqual(first,second)
self.assertEqual(q.ack(6,.3),'retry');self.assertIsNone(q.next(1));self.assertEqual(q.next(2),first)
q.ack(0,2.1);q.next(2.2);q.ack(0,2.3);self.assertIsNone(q.next(2.4));self.assertIn(b'B'*10,q.next(4))
def test_retry_limit_drops_only_current(self):
q=PacketTx();q.add(b'A',0);q.add(b'B',0)
for i in range(4):q.next(i*2);action=q.ack(6,i*2+.1)
self.assertEqual(action,'dropped');self.assertEqual(q.dropped,1);self.assertIn(b'B',q.next(9))
def test_expiry_and_no_unacknowledged_advance(self):
q=PacketTx();q.add(b'A'*80,0);q.next(0);self.assertIsNone(q.next(1));q.ack(0,1);self.assertIsNone(q.next(21));self.assertEqual(q.dropped,1)
def test_permanent_error_preserves_pending(self):
q=PacketTx();q.add(b'A',0);q.add(b'B',0);q.next(0);self.assertEqual(q.ack(5,.1),'dropped');self.assertIn(b'B',q.next(2))
class GateTests(unittest.TestCase):
def test_unknown_stale_and_recent_busy_never_start(self):
g=RadioGate();self.assertFalse(g.allows(1));g.update(1,False);self.assertFalse(g.allows(1.1));g.update(1.2,False);self.assertTrue(g.allows(1.31));self.assertFalse(g.allows(2));g.update(2,True);g.update(2.1,False);self.assertFalse(g.allows(2.2))
def test_fragments_continue_without_repeated_quiet_delay(self):
g=RadioGate();g.update(1,False);self.assertTrue(g.allows(1.1,starting=False));g.update(1.2,True);self.assertFalse(g.allows(1.21,starting=False));g.update(1.3,False);self.assertTrue(g.allows(1.31,starting=False));self.assertFalse(g.allows(1.31))
def test_new_reception_resets_quiet_period(self):
g=RadioGate();g.update(0,False);g.update(.2,False);self.assertTrue(g.allows(.31));g.update(.32,True);g.update(.4,False);g.update(.6,False);self.assertFalse(g.allows(.65));self.assertTrue(g.allows(.71))
unittest.main()
+108
View File
@@ -0,0 +1,108 @@
import {readFile,readdir,stat,writeFile,rename} from 'node:fs/promises';
import path from 'node:path';
const base=call=>String(call||'').toUpperCase().replace(/-\d+$/,'');
const validCall=call=>/^[A-Z0-9]*\d[A-Z0-9]*(?:-\d{1,2})?$/.test(call||'');
export function locatorPosition(locator){
const l=String(locator||'').trim().toUpperCase();if(!/^[A-R]{2}\d{2}(?:[A-X]{2}(?:\d{2})?)?$/.test(l))return null;
let lon=(l.charCodeAt(0)-65)*20-180+Number(l[2])*2,lat=(l.charCodeAt(1)-65)*10-90+Number(l[3]);let dx=2,dy=1;
if(l.length>=6){dx=2/24;dy=1/24;lon+=(l.charCodeAt(4)-65)*dx;lat+=(l.charCodeAt(5)-65)*dy;}
if(l.length===8){dx/=10;dy/=10;lon+=Number(l[6])*dx;lat+=Number(l[7])*dy;}
return {locator:l,lat:lat+dy/2,lon:lon+dx/2};
}
export function distanceKm(a,b){const r=x=>x*Math.PI/180,dlat=r(b.lat-a.lat),dlon=r(b.lon-a.lon);return Math.round(6371*2*Math.asin(Math.min(1,Math.sqrt(Math.sin(dlat/2)**2+Math.cos(r(a.lat))*Math.cos(r(b.lat))*Math.sin(dlon/2)**2))));}
function stamp(date,time){return `${date.length===6?'20'+date.slice(0,2)+'-'+date.slice(2,4)+'-'+date.slice(4):date}T${time}Z`;}
function record(call,at,service,transport,direction,source){return {id:service+'-'+call+'-'+at,call,localCall:null,startedAt:at,connectedAt:null,endedAt:null,service,transport,direction,status:'incomplete',txBytes:null,rxBytes:null,trafficScope:null,snr:null,frequency:null,port:null,receivedMessages:0,sentMessages:0,messages:[],events:[],sources:[source]};}
function event(s,at,text){if(s.events.length<120)s.events.push({at,text});}
export function parseTelnetLog(text,source='Telnet'){
const rows=[],streams=new Map();
for(const line of text.split(/\r?\n/)){
const m=line.match(/^(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2}):(\d{2})\s+(\d+)\s+(\S+)\s+(.*)$/);if(!m)continue;
const at=new Date(Number(m[3]),Number(m[2])-1,Number(m[1]),Number(m[4]),Number(m[5]),Number(m[6])).toISOString(),stream=m[7],ip=m[8],text=m[9];let a;
if(a=text.match(/^Incoming Connect on Port (\d+)$/i))streams.set(stream,{port:Number(a[1]),ip});
if(a=text.match(/^Call Accepted\.?\s+Callsign=([A-Z0-9-]+)\s*$/i)){const connection=streams.get(stream);rows.push({at,call:a[1].toUpperCase(),local:/^(127\.|::1$)/.test(ip),port:connection?.ip===ip?connection.port:null,source});}
}
return rows;
}
export function classifyTransport(s,config,telnet=[]){
if(s.transport==='Unknown'&&s.frequency){s.transport='Radio';s.transportEvidence='Comando RADIO registrato nella sessione';}
const port=config.ports?.find(p=>p.id===s.port);
if(port){s.transport=/TELNET/i.test(port.driver)?'Internet':/AXIP/i.test(port.driver)?'NET/ROM':'Radio';s.transportEvidence='Porta BPQ '+port.id+' · '+(port.name||port.driver);}
if(s.transport==='Unknown'){
const match=telnet.filter(t=>base(t.call)===base(s.call)&&Math.abs(Date.parse(t.at)-Date.parse(s.startedAt))<=20000).sort((a,b)=>Math.abs(Date.parse(a.at)-Date.parse(s.startedAt))-Math.abs(Date.parse(b.at)-Date.parse(s.startedAt)))[0];
if(match){s.transport=match.local?'Local':'Internet';s.transportEvidence='Correlazione con accesso Telnet BPQ in '+match.source;if(!s.sources.includes(match.source))s.sources.push(match.source);}
}
if(s.transport==='Unknown'){
s.transport=s.service==='Winlink'?'CMS':'BPQ';
s.transportEvidence=s.service==='Winlink'?'Accesso al gateway Winlink confermato dal log CMS. Il mezzo di ingresso al nodo non è archiviato.':'Accesso al servizio '+s.service+' del nodo BPQ confermato. La porta di ingresso non è archiviata.';
}
if(!s.transportEvidence)s.transportEvidence=s.transport==='Radio'?'Sessione radio registrata dal modem':s.transport==='NET/ROM'?'Collegamento NET/ROM registrato da BPQ':'Trasporto registrato dal servizio';
return s;
}
export function parseVaraLog(text,source='VARAHF.log',own=''){
const out=[];let current=null,incoming=false,pendingSnr=null;
const start=(call,at,direction)=>{if(current)out.push(current);current=record(call,at,'Radio','Radio',direction,source);current.mode='VARA';};
for(const line of text.split(/\r?\n/)){
const m=line.match(/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})\s+(.*)$/);if(!m)continue;const at=stamp(m[1],m[2]),t=m[3];let a;
if(/Incoming connection/i.test(t)){incoming=true;continue;}
if(a=t.match(/(?:->CONNECT|CONNECT)\s+([A-Z0-9-]+)\s+([A-Z0-9-]+)/)){start(a[2],at,'outgoing');current.localCall=a[1];incoming=false;event(current,at,'Chiamata radio avviata');}
else if(a=t.match(/Connecting to ([A-Z0-9-]+).*?(\d+)\/(\d+)/)){if(!current)start(a[1],at,'outgoing');current.attempts=Number(a[2]);current.maxAttempts=Number(a[3]);}
else if(a=t.match(/<-CONNECTED\s+([A-Z0-9-]+)\s+([A-Z0-9-]+)(?:\s+(\d+))?/)){if(!current||base(current.call)!==base(a[2]))start(a[2],at,incoming?'incoming':'unknown');current.localCall=a[1];current.connectedAt=at;current.bandwidth=a[3]?Number(a[3]):null;event(current,at,'Collegamento radio stabilito');incoming=false;}
else if(a=t.match(/^([A-Z0-9-]+) connected\s+VARA/i)){if(!current||base(current.call)!==base(a[1]))start(a[1],at,incoming?'incoming':'unknown');current.localCall=own;current.connectedAt=at;event(current,at,'Collegamento radio stabilito');incoming=false;}
else if(a=t.match(/^([A-Z0-9-]+) Average S\/N:\s*([\d,.-]+)/)){pendingSnr=Number(a[2].replace(',','.'));if(current)current.snr=pendingSnr;}
else if(a=t.match(/Disconnected\s+TX:\s*(\d+) Bytes \(Max:\s*(\d+) bps\)\s+RX:\s*(\d+) Bytes \(Max:\s*(\d+) bps\)/i)){if(current){current.endedAt=at;current.txBytes=Number(a[1]);current.peakTxBps=Number(a[2]);current.rxBytes=Number(a[3]);current.peakRxBps=Number(a[4]);current.trafficScope='Contatori della sessione VARA';current.status=current.connectedAt?'connected':'failed';event(current,at,'Sessione radio conclusa');out.push(current);current=null;}pendingSnr=null;}
else if(current&&/Connection failed|Connection timeout|No response|Disconnected\s*$/i.test(t)){current.endedAt=at;current.status=current.connectedAt?'connected':'failed';event(current,at,current.connectedAt?'Disconnessione':'Nessuna risposta');out.push(current);current=null;}
}
if(current)out.push(current);return out;
}
export function parseBbsLog(text,source='BBS',service='BBS'){
const out=[],open=new Map();
for(const line of text.split(/\r?\n/)){
const m=line.match(/^(\d{6}) (\d{2}:\d{2}:\d{2}) ([|<>?!])([A-Z0-9-]+)\s+(.*)$/);if(!m)continue;const at=stamp(m[1],m[2]),peer=m[4],t=m[5];let s=open.get(peer),a;
if(/Connecting to (?:BBS|Chat Node)|Incoming Connect from/i.test(t)){if(s)out.push(s);s=record(peer,at,peer==='RMS'?'Winlink':service,peer==='RMS'?'Internet':'Unknown',/Incoming/i.test(t)?'incoming':'outgoing',source);open.set(peer,s);event(s,at,'Avvio '+s.service);}
if(!s)continue;
if(a=t.match(/ATTACH\s+(\d+)/i)){s.port=Number(a[1]);s.transport='Radio';event(s,at,'Porta BPQ '+s.port);}
if(a=t.match(/^(?:C|CONNECT)\s+(\d+)\s+\S+/i)){s.port=Number(a[1]);event(s,at,'Connessione sulla porta BPQ '+s.port);}
if(s.transport==='Unknown'&&/^(?:C|CONNECT)\s+[A-Z0-9]+:[A-Z0-9-]+\s*$/i.test(t))s.transport='NET/ROM';
if(a=t.match(/^RADIO\s+([\d.]+)\s+(\S+)/i)){s.frequency=Number(a[1]);event(s,at,'Frequenza '+a[1]+' MHz '+a[2]);}
if(a=t.match(/(?:\*\*\* Connected to|Connected to\s+(?:[A-Z0-9]+:)?)([A-Z0-9-]+)/i)){if(validCall(a[1]))s.call=a[1];s.connectedAt=at;event(s,at,'Connessione al nodo '+s.call);}
if(service==='Chat'&&/Connected to [A-Z0-9]+:[A-Z0-9-]+/.test(t)){s.transport='NET/ROM';s.connectedAt=at;}
if(a=t.match(/Uncompressing Message Comp Len\s+(\d+) Msg Len\s+(\d+)/i)){s.receivedMessages++;s.messages.push({direction:'RX',compressedBytes:Number(a[1]),bytes:Number(a[2]),at});event(s,at,'Messaggio ricevuto · '+a[2]+' byte');}
if(a=t.match(/^Compressing Message Comp Len\s+(\d+) Msg Len\s+(\d+)/i)){s.sentMessages++;s.messages.push({direction:'TX',compressedBytes:Number(a[1]),bytes:Number(a[2]),at});}
if(a=t.match(/^Msg\s+(\d+) Routing Trace/)){const last=s.messages.at(-1);if(last&&!last.id)last.id=Number(a[1]);}
if(/^[<>]$/.test(m[3])&&/^FQ\s*$/.test(t)){s.exchangeComplete=true;event(s,at,'Scambio forwarding concluso (FQ)');}
if(/Application not available|Already Connected|Failure with|Invalid command|Unexpected Response|does not have .* defined/i.test(t)){s.error=/Already Connected/i.test(t)?'Sessione già presente':/Application not available/i.test(t)?'Applicazione remota non disponibile':/does not have .* defined/i.test(t)?'Nodo chat remoto non configurato per questo collegamento':'Connessione o protocollo non riuscito';event(s,at,s.error);}
if(/Disconnected\s*$/i.test(t)){s.endedAt=at;s.status=s.error?'failed':s.exchangeComplete?'complete':s.connectedAt?'connected':'incomplete';event(s,at,'Disconnessione');out.push(s);open.delete(peer);}
}
out.push(...open.values());return out;
}
export function parseCmsLog(text,date,own,source='CMSAccess'){
const out=[],open=new Map();
for(const line of text.split(/\r?\n/)){const m=line.match(/^(\d{2}:\d{2}:\d{2})\s+(\d+)\s+(.*)$/);if(!m)continue;const at=stamp(date,m[1]),stream=m[2],t=m[3];let a;
if(a=t.match(/^([A-Z0-9-]+) Connected to CMS/)){const self=base(a[1])===base(own);const s=record(self?'CMS':a[1],at,'Winlink',self?'Internet':'Unknown',self?'outgoing':'incoming',source);s.localCall=own;s.connectedAt=at;event(s,at,'Accesso al CMS Winlink');if(open.has(stream))out.push(open.get(stream));open.set(stream,s);}
if(a=t.match(/^Disconnected\. Bytes Sent = (\d+) Bytes Received (\d+) Time (\d+) Seconds/)){const s=open.get(stream);if(s){s.txBytes=Number(a[1]);s.rxBytes=Number(a[2]);s.trafficScope='Contatori della connessione BPQ → CMS';s.endedAt=at;s.status='connected';event(s,at,'Connessione CMS conclusa');out.push(s);open.delete(stream);}}
}out.push(...open.values());return out;
}
export function mergeSessions(bbs,radio,cms){
const out=[...radio.map(s=>({...s,events:[...s.events],sources:[...s.sources]}))],used=new Set();
for(const b of bbs){const candidates=out.filter(r=>r.service==='Radio'&&(r.direction==='unknown'||b.direction==='unknown'||r.direction===b.direction)&&base(r.call)===base(b.call)&&Math.abs(Date.parse(r.startedAt)-Date.parse(b.startedAt))<90000&&!used.has(r.id));const r=candidates.sort((a,c)=>Math.abs(Date.parse(a.startedAt)-Date.parse(b.startedAt))-Math.abs(Date.parse(c.startedAt)-Date.parse(b.startedAt)))[0];
if(r){used.add(r.id);const stats={txBytes:r.txBytes,rxBytes:r.rxBytes,trafficScope:r.trafficScope};Object.assign(r,{...b,call:r.call,localCall:r.localCall||b.localCall,mode:r.mode,snr:r.snr,bandwidth:r.bandwidth,peakTxBps:r.peakTxBps,peakRxBps:r.peakRxBps,attempts:r.attempts,maxAttempts:r.maxAttempts,transport:'Radio',connectedAt:r.connectedAt||b.connectedAt,endedAt:r.endedAt||b.endedAt,...stats,status:b.error?'failed':b.exchangeComplete?'complete':r.status,events:[...b.events,...r.events].sort((a,c)=>a.at.localeCompare(c.at)),sources:[...new Set([...r.sources,...b.sources])]});}else out.push({...b,events:[...b.events]});
}
for(const c of cms){const r=out.find(r=>r.service!=='Winlink'&&(r.direction==='unknown'||r.direction===c.direction)&&base(r.call)===base(c.call)&&r.connectedAt&&Date.parse(c.startedAt)>=Date.parse(r.startedAt)-5000&&Date.parse(c.startedAt)<=Date.parse(r.endedAt||new Date().toISOString())+5000);if(r){r.service='Winlink';r.cmsTraffic={txBytes:c.txBytes,rxBytes:c.rxBytes};r.events.push(...c.events);r.sources.push(...c.sources);}else{const b=c.call==='CMS'?out.find(b=>b.service==='Winlink'&&Math.abs(Date.parse(b.startedAt)-Date.parse(c.startedAt))<10000):null;if(b){b.txBytes=c.txBytes;b.rxBytes=c.rxBytes;b.trafficScope=c.trafficScope;b.connectedAt=c.connectedAt;b.endedAt=c.endedAt||b.endedAt;b.status=b.exchangeComplete?'complete':c.status;b.sources.push(...c.sources);b.events.push(...c.events);}else out.push(c);}}
return out.map(s=>({...s,events:s.events.sort((a,b)=>a.at.localeCompare(b.at)),duration:s.connectedAt&&s.endedAt?Math.max(0,Math.round((Date.parse(s.endedAt)-Date.parse(s.connectedAt))/1000)):null})).sort((a,b)=>b.startedAt.localeCompare(a.startedAt));
}
export class Journal{
constructor(config,dir){this.config=config;this.dir=dir;this.cache=new Map();this.pending=null;this.savedAt=0;this.locationQueue=Promise.resolve();}
async parsed(file,parse){try{const info=await stat(file);const key=info.size+':'+info.mtimeMs;const prior=this.cache.get(file);if(prior?.key===key)return prior.value;let text=await readFile(file,'utf8');const truncated=Buffer.byteLength(text)>16*1024*1024;if(truncated)text=text.slice(-8*1024*1024).split('\n').slice(1).join('\n');const value={rows:parse(text,path.basename(file)),truncated};this.cache.set(file,{key,value});return value;}catch{return {rows:[],unavailable:true};}}
async snapshot(){if(this.pending)return this.pending;if(this.last&&Date.now()-this.savedAt<10000)return this.last;this.pending=this.read();try{this.last=await this.pending;this.savedAt=Date.now();return this.last}finally{this.pending=null}}
async read(){const root=this.config.root,logs=path.join(root,'Logs');let files=[];try{files=await readdir(logs)}catch{}const after=Date.now()-30*86400000;const bbs=[],cms=[],radio=[],telnet=[],warnings=[];let first=null;
for(const name of files.sort()){let m,kind,date;if(m=name.match(/^Telnet_(\d{6})\.log$/)){date='20'+m[1].slice(0,2)+'-'+m[1].slice(2,4)+'-'+m[1].slice(4);if(Date.parse(date+'T23:59:59Z')>=after){const result=await this.parsed(path.join(logs,name),parseTelnetLog);telnet.push(...result.rows);if(result.truncated)warnings.push(name+': letta la parte finale (file grande)');}continue;}if(m=name.match(/^log_(\d{6})_(BBS|CHAT)\.txt$/)){date='20'+m[1].slice(0,2)+'-'+m[1].slice(2,4)+'-'+m[1].slice(4);kind=m[2];}else if(m=name.match(/^CMSAccess_(\d{4})(\d{2})(\d{2})\.log$/)){date=m[1]+'-'+m[2]+'-'+m[3];kind='CMS';}else continue;if(Date.parse(date+'T23:59:59Z')<after)continue;first=!first||date<first?date:first;const result=await this.parsed(path.join(logs,name),(text,source)=>kind==='CMS'?parseCmsLog(text,date,this.config.sysop.call,source):parseBbsLog(text,source,kind==='CHAT'?'Chat':'BBS'));(kind==='CMS'?cms:bbs).push(...result.rows);if(result.truncated)warnings.push(name+': letta la parte finale (file grande)');}
const varaLog=this.config.varaLogPath; if(varaLog){const result=await this.parsed(varaLog,(t,s)=>parseVaraLog(t,s,this.config.sysop.call));radio.push(...result.rows.filter(s=>Date.parse(s.startedAt)>=after));if(result.unavailable)warnings.push('Log VARA non disponibile: traffico radio storico incompleto');}
for(const s of bbs){const port=this.config.ports?.find(p=>p.id===s.port);if(port&&/TELNET/i.test(port.driver))s.transport='Internet';else if(port&&/AXIP/i.test(port.driver))s.transport='NET/ROM';}
const sessions=mergeSessions(bbs,radio,cms).map(s=>classifyTransport(s,this.config,telnet)).slice(0,5000);let locations={};try{locations=JSON.parse(await readFile(path.join(this.dir,'station-locations.json'),'utf8'))}catch{}
const stations=new Map();for(const s of sessions){if(!validCall(s.call)||base(s.call)===base(this.config.sysop.call))continue;const call=base(s.call);let station=stations.get(call);if(!station){const position=locatorPosition(locations[call]?.locator);station={call,position:position?{...position,source:locations[call]?.source||'Locator inserito manualmente'}:null,lastSeen:s.startedAt,sessions:0,services:[],txBytes:0,rxBytes:0};stations.set(call,station);}station.sessions++;if(!station.services.includes(s.service))station.services.push(s.service);station.txBytes+=s.txBytes||0;station.rxBytes+=s.rxBytes||0;}
const own={call:this.config.nodeCall,position:locatorPosition(this.config.locator)};if(own.position)own.position.source='LOCATOR di BPQ';for(const s of stations.values())s.distance=own.position&&s.position?distanceKm(own.position,s.position):null;
return {updatedAt:new Date().toISOString(),since:first,sessions,stations:[...stations.values()],own,warnings,limited:sessions.length>=5000};
}
saveLocation(call,locator){const work=this.locationQueue.then(async()=>{const key=base(call),position=locatorPosition(locator);if(!validCall(key)||!position)throw new Error('Indica un nominativo e un locator Maidenhead valido (4, 6 o 8 caratteri)');const known=(await this.snapshot()).stations.some(s=>s.call===key);if(!known)throw new Error('Stazione non presente nel diario');const file=path.join(this.dir,'station-locations.json');let data={};try{data=JSON.parse(await readFile(file,'utf8'))}catch{}data[key]={locator:position.locator};await writeFile(file+'.tmp',JSON.stringify(data,null,2));await rename(file+'.tmp',file);this.savedAt=0;return this.snapshot();});this.locationQueue=work.catch(()=>{});return work;}
}
+54
View File
@@ -0,0 +1,54 @@
import test from 'node:test';import assert from 'node:assert/strict';
import fs from 'node:fs/promises';import path from 'node:path';import os from 'node:os';import http from 'node:http';import net from 'node:net';import {spawn} from 'node:child_process';import {once} from 'node:events';
import {parseAttachments,b2Body} from './attachments.mjs';
const listen=server=>new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
test('Winlink API uploads to native WebMail, verifies storage, lists and downloads received attachments',async()=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpq-upload-')),root=path.join(dir,'station');let child,stored=null,nativePosts=0,nextId=0,killed=false,adminSaves=0;
const mail=path.join(root,'BPQMailChat','Mail');await fs.mkdir(mail,{recursive:true});
const server=http.createServer(async(req,res)=>{try{
if(req.url==='/Webmail'){res.end('<a href=/WebMail/WMB?fixture>Mail</a>');return;}
if(req.url.startsWith('/WebMail/NewMsg')){res.end('Compose');return;}
if(req.url.startsWith('/WebMail/EMSave')){
nativePosts++;const chunks=[];for await(const chunk of req)chunks.push(chunk);
const form=await new Request('http://localhost/',{method:'POST',headers:{'Content-Type':req.headers['content-type']},body:Buffer.concat(chunks)}).formData();
assert.equal(form.get('To'),'RMS/[email protected]');const files=await Promise.all(form.getAll('myFile[]').map(async f=>({name:f.name,data:Buffer.from(await f.arrayBuffer())})));assert.equal(files.length,2);
const body=Buffer.from(form.get('Msg'));stored=Buffer.concat([Buffer.from('MID: local-fixture\r\nBody: '+body.length+'\r\n'+files.map(f=>'File: '+f.data.length+' '+f.name+'\r\n').join('')+'\r\n'),body,Buffer.from('\r\n'),...files.flatMap(f=>[f.data,Buffer.from('\r\n')])]);
nextId=1;await fs.writeFile(path.join(mail,'m_000001.mes'),stored);res.end('Message Saved');return;
}
if(req.url.startsWith('/WebMail/WMDel/')){res.end('Not your message');return;}
if(req.url.startsWith('/Mail/MsgSave')){let payload='';for await(const chunk of req)payload+=chunk;assert.equal(payload,'N0TEST|RMS|BID-fixture||[email protected]|Attachment fixture|P|K|');killed=true;adminSaves++;res.end('Saved');return;}
if(req.url.startsWith('/WebMail/WMALL')){res.end('Message List\r\n'+(nextId?'<a href=/WebMail/WM?fixture&1> 1</a> 17-Oct P'+(killed?'K':'N')+' 100 '+['RMS','','N0TEST'].map(s=>s.padEnd(7)).join(' ')+' Attachment fixture\r\n':''));return;}
if(req.url==='/Mail/Status'){res.end('<a href=/Mail/Msgs?fixture>Messages</a>');return;}
if(req.url.startsWith('/Mail/MsgDetails')){res.end('<h2>Message 1</h2><select name=Type><option selected value=P>P</option></select>'+Object.entries({BID:'BID-fixture',EFROM:'',From:'N0TEST',To:'RMS',Title:'Attachment fixture',VIA:'[email protected]',Sent:'17-Oct 12:00Z',RX:'17-Oct 12:00Z'}).map(([k,v])=>'<input name="'+k+'" value="'+v+'">').join(''));return;}
if(req.url.startsWith('/WebMail/WM?')){res.end('<textarea>From: N0TEST\r\nTo: RMS\r\nTitle: Attachment fixture\r\nType/Status: PN\r\n\r\nNative body with binary attachments stripped by Console</textarea>');return;}
res.end('BPQ Ports');
}catch(e){res.statusCode=500;res.end(e.message);}});
try{
await listen(server);const probe=net.createServer();await listen(probe);const port=probe.address().port;await new Promise(resolve=>probe.close(resolve));
await fs.writeFile(path.join(root,'BPQ32.cfg'),'NODECALL=N0TEST-7\nPORT\nDRIVER=TELNET\nHTTPPORT='+server.address().port+'\nCMS=1\nUSER=admin,fixture-secret,N0TEST,sysop\nENDPORT\nAPPLICATION 1,BBS,,N0TEST-11,MAIL\n');
await fs.writeFile(path.join(root,'BPQMailChat','BPQMail.cfg'),'BBSForwarding : {}\nBBSUsers : {}');
await fs.writeFile(path.join(dir,'package.json'),' {"type":"module"} ');await fs.writeFile(path.join(dir,'console.config.json'),JSON.stringify({bpqRoot:root,port}));
for(const name of await fs.readdir('.'))if(name.endsWith('.mjs')&&!name.includes('.test.')&&name!=='test.mjs')await fs.copyFile(name,path.join(dir,name));
child=spawn(process.execPath,[path.join(dir,'server.mjs')],{cwd:dir,env:{...process.env,BPQ_ROOT:root,BPQ_CONSOLE_CONFIG:path.join(dir,'console.config.json'),BPQ_CONSOLE_PORT:String(port)},windowsHide:true,stdio:['ignore','pipe','pipe']});
await Promise.race([once(child.stdout,'data'),once(child,'exit').then(()=>{throw Error('Fixture server failed');}),new Promise((_,reject)=>{const timer=setTimeout(()=>reject(Error('Fixture timeout')),8000);timer.unref();})]);
const base='http://127.0.0.1:'+port,headers={origin:base,'content-type':'application/json'};
const login=await fetch(base+'/api/login',{method:'POST',headers,body:JSON.stringify({user:'admin',password:'fixture-secret'})});const auth=await login.json();headers.cookie=login.headers.get('set-cookie').split(';')[0];headers['x-csrf-token']=auth.csrf;
const bytes=[Buffer.from([255,216,255,0,13,10,255]),Buffer.from('Città 📻')],form=new FormData();
for(const [key,value]of Object.entries({to:'RMS/[email protected]',subject:'Attachment fixture',text:'Hello à',type:'P'}))form.set(key,value);
form.append('files',new Blob([bytes[0]]),'image.jpg');form.append('files',new Blob([bytes[1]]),'note.txt');delete headers['content-type'];
const created=await fetch(base+'/api/messages',{method:'POST',headers,body:form});assert.equal(created.status,201,await created.clone().text());assert.deepEqual(await created.json(),{id:1,attachmentCount:2});assert.equal(nativePosts,1);
assert.equal(b2Body(stored),'Hello à');assert.deepEqual(parseAttachments(stored).map(f=>f.data),bytes);
const files=await (await fetch(base+'/api/messages/1/attachments',{headers})).json();assert.equal(files.files.length,2);assert.equal(files.files[0].mime,'image/jpeg');assert.ok(!('data' in files.files[0]));
const download=await fetch(base+'/api/messages/1/attachments/0',{headers});assert.match(download.headers.get('content-disposition'),/^attachment/);assert.deepEqual(Buffer.from(await download.arrayBuffer()),bytes[0]);
const preview=await fetch(base+'/api/messages/1/attachments/0?preview=1',{headers});assert.equal(preview.headers.get('content-type'),'image/jpeg');
const text=await (await fetch(base+'/api/messages/1/attachments/1?text=1',{headers})).json();assert.equal(text.text,'Città 📻');
const reader=await (await fetch(base+'/api/messages/1',{headers})).json();assert.equal(reader.text,'Hello à');
const inbox=await (await fetch(base+'/api/winlink',{headers})).json();assert.equal(inbox.messages[0].attachmentCount,2);assert.equal(inbox.messages[0].folder,'queue');
const denied=await fetch(base+'/api/messages/1/attachments/0');assert.equal(denied.status,401);
const oversized=new FormData();for(const [key,value]of Object.entries({to:'RMS/[email protected]',subject:'Too big',text:'x'.repeat(30000),type:'P'}))oversized.set(key,value);oversized.append('files',new Blob([Buffer.alloc(60000)]),'large.bin');const rejected=await fetch(base+'/api/messages',{method:'POST',headers,body:oversized});assert.match((await rejected.json()).error,/80 KB/);assert.equal(nativePosts,1);
const badHeaders={...headers,'x-csrf-token':'wrong'};assert.equal((await fetch(base+'/api/messages',{method:'POST',headers:badHeaders,body:form})).status,403);assert.equal(nativePosts,1);
const deleted=await fetch(base+'/api/messages/1/delete',{method:'POST',headers,body:'{}'});assert.equal(deleted.status,200,await deleted.clone().text());assert.equal((await deleted.json()).ok,true);assert.equal(adminSaves,1);
const remaining=await (await fetch(base+'/api/messages',{headers})).json();assert.equal(remaining.length,0);
const again=await fetch(base+'/api/messages/1/delete',{method:'POST',headers,body:'{}'});assert.equal((await again.json()).alreadyDeleted,true);assert.equal(adminSaves,1);
}finally{if(child&&child.exitCode===null){child.kill();await once(child,'exit');}server.closeAllConnections();await new Promise(resolve=>server.close(resolve));await fs.rm(dir,{recursive:true,force:true});}
});
+33
View File
@@ -0,0 +1,33 @@
import {safeName,mimeOf,parseAttachments} from './attachments.mjs';
export const uploadLimits={files:10,bytes:64*1024,messageBytes:80*1024,requestBytes:96000};
export async function readSubmission(req){
const chunks=[];let length=0;
for await(const chunk of req){length+=chunk.length;if(length>uploadLimits.requestBytes)throw Error('Allegati troppo grandi: massimo 64 KB complessivi');chunks.push(chunk);}
const bytes=Buffer.concat(chunks),contentType=req.headers['content-type']||'';
if(!/^multipart\/form-data\s*;/i.test(contentType)){
if(bytes.length>70000)throw Error('Messaggio troppo grande');
const data=JSON.parse(bytes.toString()||'{}');if(data.files||data.attachments)throw Error('Usa il caricamento file per gli allegati');return {...data,files:[]};
}
const form=await new Request('http://localhost/upload',{method:'POST',headers:{'Content-Type':contentType},body:bytes}).formData();
const data={},files=[];let total=0;
for(const [key,value]of form){
if(typeof value==='string'){if(!['to','subject','text','type'].includes(key)||key in data)throw Error('Campi del messaggio non validi');data[key]=value;continue;}
if(key!=='files')throw Error('Campo allegato non valido');
if(files.length>=uploadLimits.files)throw Error('Massimo 10 allegati per messaggio');
total+=value.size;if(total>uploadLimits.bytes)throw Error('Allegati troppo grandi: massimo 64 KB complessivi');
const name=safeName(value.name).replace(/[";]/g,'_'),buffer=Buffer.from(await value.arrayBuffer());
if(files.some(f=>f.name.toLowerCase()===name.toLowerCase()))throw Error('Nomi allegati duplicati: rinomina i file');
files.push({name,size:buffer.length,data:buffer,mime:mimeOf(buffer,name)});
}
return {...data,files};
}
export function outgoingForm({to,subject,text,type,files=[]}){
const form=new FormData();for(const [key,value]of Object.entries({To:to,Subj:subject,Type:type,BID:'',Msg:text.replace(/\r?\n/g,'\r\n'),Send:'Send'}))form.set(key,value);
for(const file of files)form.append('myFile[]',new Blob([file.data],{type:'application/octet-stream'}),file.name);
return form;
}
export function verifySavedAttachments(bytes,expected){
const actual=parseAttachments(bytes);
if(actual.length!==expected.length||expected.some((file,i)=>file.name!==actual[i].name||!file.data.equals(actual[i].data)))throw Error('BPQ ha salvato il messaggio ma gli allegati non corrispondono. Controlla la coda prima di riprovare.');
return actual.map(({data,...file})=>file);
}
+31
View File
@@ -0,0 +1,31 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {Readable} from 'node:stream';
import {readSubmission,outgoingForm,verifySavedAttachments,uploadLimits} from './mail-upload.mjs';
import {parseAttachments,b2Body,attachmentSummary} from './attachments.mjs';
async function request(form){const r=new Request('http://localhost/messages',{method:'POST',body:form}),stream=Readable.from([Buffer.from(await r.arrayBuffer())]);stream.headers={'content-type':r.headers.get('content-type')};return stream;}
function b2(body,files){return Buffer.concat([Buffer.from('MID: fixture\r\nBody: '+Buffer.byteLength(body)+'\r\n'+files.map(f=>'File: '+f.data.length+' '+f.name+'\r\n').join('')+'\r\n'+body+'\r\n'),...files.flatMap(f=>[f.data,Buffer.from('\r\n')])]);}
test('multipart upload reaches native BPQ fields with byte-exact binary and UTF8 files',async()=>{
const files=[{name:'image.jpg',data:Buffer.from([255,216,255,0,13,10,255])},{name:'note.txt',data:Buffer.from('Città e radio 📻')}];
const form=new FormData();for(const [k,v]of Object.entries({to:'RMS/[email protected]',subject:'Attachments',text:'Hello à',type:'P'}))form.set(k,v);for(const f of files)form.append('files',new Blob([f.data]),f.name);
const data=await readSubmission(await request(form));assert.equal(data.files.length,2);for(let i=0;i<files.length;i++)assert.deepEqual(data.files[i].data,files[i].data);
const native=outgoingForm(data);assert.equal(native.get('To'),data.to);assert.equal(native.get('Msg'),'Hello à');const nativeFiles=native.getAll('myFile[]');assert.equal(nativeFiles.length,2);for(let i=0;i<files.length;i++)assert.deepEqual(Buffer.from(await nativeFiles[i].arrayBuffer()),files[i].data);
const bytes=b2('Hello à',data.files);assert.equal(b2Body(bytes),'Hello à');assert.equal(verifySavedAttachments(bytes,data.files).length,2);assert.deepEqual(attachmentSummary(bytes),{attachmentCount:2,attachmentBytes:files.reduce((n,f)=>n+f.data.length,0)});
});
test('attachment count ignores plain text and requires a B2 header',()=>{assert.equal(attachmentSummary(Buffer.from('Body: 4\r\nFile: 3 test\r\n\r\ntext')).attachmentCount,0);});
test('upload rejects oversize files, too many files, duplicates and unsafe fields before contacting BPQ',async()=>{
const make=files=>{const f=new FormData();for(const [name,data]of files)f.append('files',new Blob([data]),name);return f;};
await assert.rejects(readSubmission(await request(make([['large.bin',Buffer.alloc(uploadLimits.bytes+1)]]))),/64 KB/);
await assert.rejects(readSubmission(await request(make(Array.from({length:11},(_,i)=>[i+'.txt','x'])))),/10 allegati/);
await assert.rejects(readSubmission(await request(make([['same.txt','a'],['SAME.txt','b']]))),/duplicati/);
const f=new FormData();f.set('to','a');f.append('to','b');await assert.rejects(readSubmission(await request(f)),/Campi/);
const req=Readable.from([Buffer.from(JSON.stringify({files:[{name:'bypass'}]}))]);req.headers={'content-type':'application/json'};await assert.rejects(readSubmission(req),/caricamento/);
});
test('filenames cannot inject headers, preserve paths, or silently collide after sanitisation',async()=>{
const form=new FormData();form.append('files',new Blob(['x']),'../../unsafe;name.txt');const data=await readSubmission(await request(form));assert.equal(data.files[0].name,'unsafe_name.txt');
const both=new FormData();both.append('files',new Blob(['x']),'one;two.txt');both.append('files',new Blob(['y']),'one_two.txt');await assert.rejects(readSubmission(await request(both)),/duplicati/);
});
test('saved message is rejected if BPQ drops, truncates or substitutes an attachment',()=>{
const files=[{name:'test.bin',data:Buffer.from([0,255,1])}];const bytes=b2('test',files);assert.deepEqual(parseAttachments(bytes)[0].data,files[0].data);assert.throws(()=>verifySavedAttachments(b2('test',[]),files),/allegati non corrispondono/);assert.throws(()=>verifySavedAttachments(b2('test',[{...files[0],data:Buffer.from([0,255,2])}]),files),/allegati non corrispondono/);assert.throws(()=>verifySavedAttachments(bytes.subarray(0,bytes.length-4),files),/incompleto/);
});
+42
View File
@@ -0,0 +1,42 @@
import {readFile,writeFile,rename,mkdir,copyFile} from 'node:fs/promises';
import path from 'node:path';
import {reservePacketSlot,releasePacketSlot} from './radio-slot.mjs';
import {WinlinkRadio,rawProfile,activeMailStreams} from './winlink-radio.mjs';
import {safeScript,parseForwarding} from './forwarding.mjs';
export function manualRoutes(config){
const ids=new Set();return (config.manualForwardingRoutes||[]).map(route=>{
if(!/^[A-Z0-9-]{1,32}$/.test(route.id)||route.id===route.peer||ids.has(route.id)||! /^[A-Z0-9]{1,6}$/.test(route.peer)||! /^[A-Z0-9]{3,7}(?:-\d{1,2})?$/.test(route.connectCall)||!Number.isFinite(route.frequencyMHz)||route.frequencyMHz<1||route.frequencyMHz>500||! /^(USB|LSB|FM|DATA-FM)$/.test(route.mode)||!config.ports.some(p=>p.id===route.port&&!/TELNET|AXIP/i.test(p.driver)))throw Error('Percorso manuale di forwarding non valido');
if(route.controller&&(!path.isAbsolute(route.controller.requestFile||'')||!path.isAbsolute(route.controller.statusFile||'')))throw Error('Percorsi del controllo radio non validi');
const nativeKiss=route.nativeKiss===true&&route.controller?.independent===true&&/KISS/i.test(config.ports.find(p=>p.id===route.port)?.driver||'');
ids.add(route.id);return {...route,label:String(route.label||route.id).slice(0,80),script:nativeKiss?`C ${route.port} !${route.connectCall}`:`ATTACH ${route.port}|RADIO ${route.frequencyMHz.toFixed(6)} ${route.mode}|PAUSE 2|C ${route.connectCall}`};
});
}
export class ManualForwarding extends WinlinkRadio{
constructor(config,dir,forwarding){super(config,dir,forwarding,null,{stateFile:'manual-forwarding.session.json'});this.routes=manualRoutes(config);}
snapshot(){const state=super.snapshot();if(state?.error)state.error=state.error.replaceAll('profilo RMS','profilo del partner');return state;}
async restore(){const state=await super.restore();await this.release();return state;}
profiles(native){return this.routes.flatMap(route=>{const p=native.find(p=>p.call===route.peer);if(!p)return [];const j=this.job?.channel?.id===route.id?this.job:null;const history=j?p.history.filter(s=>Date.parse(s.startedAt)>=Date.parse(j.startedAt)-1500&&(!j.endedAt||Date.parse(s.startedAt)<=Date.parse(j.endedAt))):[];return [{...p,call:route.id,label:route.label,peer:route.peer,manualOnly:true,independentRadio:route.controller?.independent===true,enabled:false,interval:0,immediate:false,reverseInterval:0,times:[],configured:true,port:route.port,driver:this.config.ports.find(p=>p.id===route.port)?.driver||'',transport:'Radio',frequency:[String(route.frequencyMHz),route.mode],script:safeScript(route.script),history,last:history[0]||null,active:Boolean(j?.restoring),preparing:j?.state==='preparing',requestedAt:j?.startedAt||null,nextEstimated:null}];});}
async prepare(route,signal){await reservePacketSlot(this,route.controller,route.frequencyMHz,route.port,{signal});}
async release(){await releasePacketSlot(this);}
displayProfiles(native){const j=this.job;const base=native.map(p=>{if(!j||j.peer!==p.call)return p;const history=p.history.filter(s=>!(Date.parse(s.startedAt)>=Date.parse(j.startedAt)-1500&&(!j.endedAt||Date.parse(s.startedAt)<=Date.parse(j.endedAt))));const original=parseForwarding('BBSForwarding : { '+p.call+' : { '+Object.entries(j.original||{}).map(([k,v])=>k+' = "'+String(v).replaceAll('"','')+'";').join(' ')+' } }',this.config.ports)[0];return {...p,...(j.restoring?original:{}),history,last:history[0]||null,active:j.restoring?false:p.active,reservedBy:j.restoring?j.channel.id:null};});return [...base,...this.profiles(native)];}
async startRoute(id,{signal}={}){await this.init;return this.fwd.exclusive(async()=>{
signal?.throwIfAborted();const route=this.routes.find(r=>r.id===id);if(!route)throw Error('Percorso manuale non configurato');
if(this.job?.restoring||this.fwd.lockedPeers.has(route.peer))throw Error('Un inoltro per questo partner è già in corso');
if(!(await this.fwd.profiles()).some(p=>p.call===route.peer&&p.configured))throw Error('Partner BBS non configurato');
const radio=this.fwd.radio();if(radio?.txSuspended||radio?.portsPaused?.[route.port])throw Error('Trasmissioni radio sospese');if(!route.controller?.independent&&(!radio?.available||radio.active||radio.connecting||Date.now()-radio.at>20000))throw Error('Radio non disponibile o impegnata');
if(activeMailStreams(await this.fwd.bpq('/Mail/Status')).length)throw Error('Attendi la fine delle sessioni BBS');
const file=path.join(this.config.root,'BPQMailChat','BPQMail.cfg'),original=rawProfile(await readFile(file,'utf8'),route.peer);
const backup=path.join(this.config.root,'BPQMailChat','Backup-manual-forwarding-'+new Date().toISOString().replace(/[:.]/g,'-'));await mkdir(backup);await copyFile(file,path.join(backup,'BPQMail.cfg'));
const disabled={...original,Enabled:'0',FWDNewImmediately:'0'};
this.job={peer:route.peer,channel:{id:route.id,call:route.connectCall,dialHz:Math.round(route.frequencyMHz*1e6),mode:route.mode},original,temporary:disabled,startedAt:new Date().toISOString(),state:'preparing',restoring:true};
this.busy=true;this.fwd.lockedPeers.set(route.peer,'Inoltro manuale in preparazione o in corso');
try{await this.persist();await this.saveNative(disabled);await this.prepare(route,signal);signal?.throwIfAborted();
if(activeMailStreams(await this.fwd.bpq('/Mail/Status')).length)throw Error('Una sessione BBS è iniziata: riprova al termine');
this.job.temporary={...disabled,ConnectScript:route.script};this.job.startedAt=new Date().toISOString();await this.persist();await this.saveNative(this.job.temporary);
const key=await this.fwd.context();await this.fwd.bpq('/Mail/FwdDetails?'+key,{method:'POST',body:route.peer});signal?.throwIfAborted();await this.fwd.bpq('/Mail/FWDSave?'+key,{method:'POST',body:'StartForward'});
this.job.state='requested';this.fwd.requested.set(route.peer,Date.now());await this.persist();return {ok:true,peer:route.peer,route:id,requestedAt:this.job.startedAt};
}catch(error){this.job.state=signal?.aborted?'cancelled':'failed';this.job.error=signal?.aborted?null:error.message;if(!activeMailStreams(await this.fwd.bpq('/Mail/Status')).length){await this.saveNative(original);this.job.restoring=false;this.job.endedAt=new Date().toISOString();this.fwd.lockedPeers.delete(route.peer);await this.release();}await this.persist();throw error;}
finally{this.busy=false;}
});}
async tick(){await super.tick();if(this.job&&!this.job.restoring)await this.release();}
}
+45
View File
@@ -0,0 +1,45 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {mkdtemp,mkdir,readFile,writeFile,rm} from 'node:fs/promises';
import path from 'node:path';import os from 'node:os';
import {ManualForwarding,manualRoutes} from './manual-forwarding.mjs';
import {Forwarding} from './forwarding.mjs';
import {rawProfile,profilePayload} from './winlink-radio.mjs';
const original={ConnectScript:'ATTACH 1|RADIO 14.122 USB|C N0TEST-8',Enabled:'1',FwdInterval:'3600',FWDNewImmediately:'1',HRoutes:'WW',HRoutesP:'WW',RequestReverse:'1'};
const text=fields=>'BBSForwarding : { N0TEST : { '+Object.entries(fields).map(([k,v])=>`${k} = "${v}";`).join(' ')+' } }';
const route={id:'N0TEST-VHF',peer:'N0TEST',port:3,frequencyMHz:144.825,mode:'DATA-FM',connectCall:'N0TEST-8'};
test('manual routes validate radio ports and expose the alternate DATA-FM script',()=>{
const config={ports:[{id:3,driver:'UZ7HO'}],manualForwardingRoutes:[route]};
assert.equal(manualRoutes(config)[0].script,'ATTACH 3|RADIO 144.825000 DATA-FM|PAUSE 2|C N0TEST-8');
for(const bad of [{port:2},{connectCall:'BAD|CALL'},{id:'N0TEST'},{frequencyMHz:NaN}])assert.throws(()=>manualRoutes({...config,manualForwardingRoutes:[{...route,...bad}]}));
assert.throws(()=>manualRoutes({...config,ports:[{id:3,driver:'TELNET'}]}));
assert.deepEqual(manualRoutes({ports:[]}),[]);
});
test('manual forwarding shares the queue, disables timers only during use and restores the exact HF profile',async()=>{
const dir=await mkdtemp(path.join(os.tmpdir(),'manual-fwd-'));await mkdir(path.join(dir,'BPQMailChat'));const file=path.join(dir,'BPQMailChat','BPQMail.cfg');await writeFile(file,text(original));
const config={root:dir,ports:[{id:1,driver:'VARA'},{id:3,driver:'UZ7HO'}],manualForwardingRoutes:[route]};let client,starts=0,occupied=false;
const fw=new Forwarding(config,async(url,opts)=>{
if(url==='/Mail/Status')return `href=/Mail/FWD?fixture <option value=1>${occupied?'Connected':'Idle'}</option>`;
if(url.startsWith('/Mail/FWD?'))return 'var Key = "fixture"';
if(url.startsWith('/Mail/FWDSave')){if(opts.body==='StartForward')starts++;else await writeFile(file,text(opts.body===profilePayload(original)?original:client.job.temporary));}
return 'ok';
},()=>({available:true,at:Date.now(),active:false,connecting:false}));fw.logs=async()=>'';
client=new ManualForwarding(config,dir,fw);let prepared=0;client.prepare=async()=>{prepared++;assert.equal(rawProfile(await readFile(file,'utf8'),'N0TEST').Enabled,'0');};
try{
await client.init;const [row]=client.profiles([{call:'N0TEST',queued:7,history:[],configured:true,enabled:true,interval:3600}]);
assert.equal(row.queued,7);assert.equal(row.enabled,false);assert.equal(row.manualOnly,true);assert.equal(row.interval,0);assert.ok(row.script.includes('RADIO 144.825000 DATA-FM'));assert.equal(starts,0);
occupied=true;await assert.rejects(client.startRoute(route.id),/sessioni BBS/);assert.equal(prepared,0);occupied=false;
const prepare=client.prepare;client.prepare=async()=>{throw Error('Modem non pronto');};
await assert.rejects(client.startRoute(route.id),/Modem non pronto/);assert.equal(starts,0);assert.equal(client.job.restoring,false);assert.equal(fw.lockedPeers.has('N0TEST'),false);assert.deepEqual(rawProfile(await readFile(file,'utf8'),'N0TEST'),original);client.prepare=prepare;
await client.startRoute(route.id);assert.equal(starts,1);assert.equal(prepared,1);assert.equal(client.job.temporary.HRoutes,'WW');assert.equal(client.job.temporary.FWDNewImmediately,'0');assert.equal(client.job.temporary.ConnectScript,manualRoutes(config)[0].script);
await assert.rejects(fw.start('N0TEST'),/Inoltro manuale/);await assert.rejects(client.startRoute(route.id),/già in corso/);
client.job.startedAt=new Date(Date.now()-60000).toISOString();await client.tick();
assert.equal(client.job.restoring,false);assert.deepEqual(rawProfile(await readFile(file,'utf8'),'N0TEST'),original);assert.equal(fw.lockedPeers.has('N0TEST'),false);
}finally{clearInterval(client.timer);await rm(dir,{recursive:true,force:true});}
});
test('a manual VHF session occupies one route and reserves its HF partner',()=>{
const client={job:{peer:'N0TEST',channel:{id:'N0TEST-VHF'},original,startedAt:'2026-10-16T22:00:00Z',restoring:true},config:{ports:[{id:1,driver:'VARA'}]},profiles:()=>[{call:'N0TEST-VHF',active:true}]};
const rows=ManualForwarding.prototype.displayProfiles.call(client,[{call:'N0TEST',active:true,history:[{startedAt:'2026-10-16T22:00:01Z'}]}]);
assert.equal(rows.filter(p=>p.active).length,1);assert.equal(rows[0].port,1);assert.equal(rows[0].reservedBy,'N0TEST-VHF');assert.equal(rows[0].history.length,0);
});
+114
View File
@@ -0,0 +1,114 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import vm from 'node:vm';
import {readFileSync} from 'node:fs';
function element(){
let html='';
return {writes:0,value:'',defaultValue:'',dataset:{},attributes:{},clientWidth:700,clientHeight:440,hidden:false,textContent:'',
get innerHTML(){return html;},set innerHTML(value){html=value;this.writes++;},
querySelector(){return element();},querySelectorAll(){return [];},setAttribute(k,v){this.attributes[k]=v;},
addEventListener(){},append(){},prepend(){},after(){},contains(){return false;},classList:{toggle(){}}};
}
function harness(file,exportCode,api=async()=>{}){
const nodes=new Map(),$=selector=>{if(!nodes.has(selector))nodes.set(selector,element());return nodes.get(selector);};
const context=vm.createContext({$, $$:()=>[],window:{},document:{hidden:false,activeElement:null,createElement:element,addEventListener(){},getElementById(){return null;}},
BPQI18n:{t:s=>s,locale:()=> 'en-GB'},csrf:'test',page:'none',navigate(){},api,fetch:async()=>({ok:true,json:async()=>({features:[]})}),
size:n=>String(n),mailTimezone:()=> 'UTC',esc:s=>String(s??''),toast(){},setInterval(){},setTimeout(){},requestAnimationFrame:f=>f()});
vm.runInContext(readFileSync(new URL('./public/aprs-symbols.js',import.meta.url),'utf8'),context);
const source=readFileSync(new URL('./public/'+file,import.meta.url),'utf8');
vm.runInContext(source.replace(/\}\)\(\);\s*$/,exportCode+'\n})();'),context);
return {context,$,fixture:context.fixture};
}
function leaflet(){
const state={created:[],fits:0,removals:[],zoom:9},map={setView(){return this;},fitBounds(bounds,options){state.fits++;state.bounds=bounds;state.fitOptions=options;return this;},getZoom:()=>state.zoom};
const layers={addTo(){return this;},removeLayer(m){state.removals.push(m);}};
function marker(point,options){
let popup='',tooltip='';const m={point,options,moves:0,popupWrites:0,open:false,
bindTooltip(s){tooltip=s;return this;},bindPopup(s,o){popup=s;this.popupOptions=o;return this;},on(){return this;},addTo(){return this;},
setIcon(icon){this.options.icon=icon;this.iconWrites=(this.iconWrites||0)+1;return this;},getLatLng(){return {lat:this.point[0],lng:this.point[1]};},setLatLng(p){this.point=p;this.moves++;return this;},setStyle(o){Object.assign(this.options,o);},
getPopup(){return {getContent:()=>popup};},setPopupContent(s){popup=s;this.popupWrites++;},
getTooltip(){return {getContent:()=>tooltip};},setTooltipContent(s){tooltip=s;},openPopup(){this.open=true;}};
state.created.push(m);return m;
}
return {state,L:{map:()=>map,tileLayer:()=>({addTo(){}}),layerGroup:()=>layers,circleMarker:marker,marker,divIcon:options=>options,latLngBounds:p=>p}};
}
const station=(call,lat=45)=>({call,transport:'Radio',position:{lat,lon:9,locator:'JN45MM'},lastAt:'2026-01-01T12:00:00Z',status:'On air',lastBody:'',path:'TEST',services:['BBS']});
const aprsData=()=>({stations:[station('N0AAA'),station('N0BBB',46)],own:{call:'N0LOCAL',position:{lat:44,lon:9}}});
test('APRS polling keeps marker identity, popup and viewport; changed positions update in place',()=>{
const h=harness('aprs-activity.js','globalThis.fixture={setData(value){data=value;},renderMap};'),l=leaflet();
h.context.L=l.L;h.context.window.L=l.L;h.context.page='aprs';h.$('#aprs-source').value='Radio';
let data=aprsData();h.fixture.setData(data);h.fixture.renderMap();
const [first,second,own]=l.state.created;first.openPopup();
for(let i=0;i<5;i++){h.fixture.setData(structuredClone(data));h.fixture.renderMap();}
assert.equal(l.state.created.length,3);assert.equal(l.state.fits,1);assert.equal(l.state.removals.length,0);
assert.equal(first.open,true);assert.equal(first.moves,0);assert.equal(first.popupWrites,0);assert.equal(own.moves,0);
data=structuredClone(data);data.stations[0].position.lat=45.1;data.stations[0].status='Updated';h.fixture.setData(data);h.fixture.renderMap();
assert.equal(first.moves,1);assert.equal(first.popupWrites,1);assert.equal(first.open,true);assert.equal(second.moves,0);assert.equal(l.state.fits,1);
assert.equal(first.popupOptions.autoPan,false);
data.stations[0].position.symset='W';data.stations[0].position.symbol='#';h.fixture.setData(data);h.fixture.renderMap();
assert.equal(first.iconWrites,1);assert.match(first.options.icon.html,/alternate.*overlay/);assert.equal(first.open,true);
h.fixture.setData(structuredClone(data));h.fixture.renderMap();assert.equal(first.iconWrites,1);assert.equal(l.state.created.length,3);assert.equal(l.state.fits,1);
});
test('APRS removes only stations outside the filter and retains the local marker',()=>{
const h=harness('aprs-activity.js','globalThis.fixture={setData(value){data=value;},renderMap};'),l=leaflet();
h.context.L=l.L;h.context.window.L=l.L;h.context.page='aprs';const data=aprsData();h.fixture.setData(data);h.fixture.renderMap();
const [first,second]=l.state.created;h.$('#aprs-search').value='N0AAA';h.fixture.renderMap();
assert.deepEqual(l.state.removals,[second]);assert.equal(l.state.created.length,3);assert.equal(first.moves,0);assert.equal(l.state.fits,1);
});
const journalData=()=>({since:'2026-01-01',warnings:['fixture.log: partial tail'],limited:false,own:{call:'N0LOCAL',position:{lat:44,lon:9}},stations:[station('N0AAA')],sessions:[{id:'one',call:'N0AAA',startedAt:new Date().toISOString(),connectedAt:new Date().toISOString(),service:'BBS',direction:'incoming',transport:'Radio',status:'complete',duration:12}]});
test('journal loads without the removed station map and preserves coverage warnings',async()=>{
const h=harness('journal.js','globalThis.fixture={load};',async()=>journalData());
h.context.page='journal';h.$('#journal-period').value='7';await h.fixture.load();
assert.equal(h.$('#journal-warning').hidden,false);assert.match(h.$('#journal-warning-detail').textContent,/partial tail/);
});
test('background API polls stay quiet, while interactive requests finish the busy indicator even on error',async()=>{
let starts=0,finishes=0,request,fail=false;
const context=vm.createContext({FormData,csrf:'test',window:{BPQBusy:{start(){starts++;return ()=>finishes++;}}},
fetch:async(url,options)=>{request=options;if(fail)throw Error('offline');return {ok:true,json:async()=>({ok:true})};}});
const source=readFileSync(new URL('./public/app.js',import.meta.url),'utf8').split('\n').find(line=>line.startsWith('async function api('));
vm.runInContext(source,context);
await context.api('/journal',{busy:false});assert.equal(starts,0);assert.equal(finishes,0);assert.equal('busy' in request,false);
await context.api('/journal');assert.equal(starts,1);assert.equal(finishes,1);
fail=true;await assert.rejects(context.api('/journal'),/offline/);assert.equal(starts,2);assert.equal(finishes,2);
});
test('APRS density fit excludes isolated distant stations and favours a tied group near home',()=>{
const h=harness('aprs-activity.js','globalThis.fixture={densePositions,distanceKm,localBounds};');
const home={lat:45.57,lon:9.13},near=[home,{lat:45.7,lon:9.4},{lat:45.4,lon:9.3}],remote=[{lat:51.5,lon:-.1},{lat:51.6,lon:-.2},{lat:51.4,lon:0}];
const result=h.fixture.densePositions([...remote,...near,{lat:30,lon:120},null,{lat:NaN,lon:4}],home);
assert.equal(result.length,4);assert.ok(result.every(p=>h.fixture.distanceKm(home,p)<100));
assert.equal(h.fixture.densePositions([],null).length,0);
assert.equal(h.fixture.densePositions([],home).length,1);
});
test('APRS opens at a 30 km radius and refresh does not reset a manually selected density fit',()=>{
const h=harness('aprs-activity.js','globalThis.fixture={setData(value){data=value;},renderMap,fit,fitLocal,distanceKm};'),l=leaflet();
h.context.L=l.L;h.context.window.L=l.L;h.context.page='aprs';
const data=aprsData();data.own.position={lat:45.57,lon:9.13};data.stations.push(station('DISTANT',-30));
h.fixture.setData(data);h.fixture.renderMap();
const [southwest,northeast]=l.state.bounds,home=data.own.position;
assert.ok(Math.abs(h.fixture.distanceKm(home,{lat:southwest[0],lon:home.lon})-30)<.001);
assert.ok(Math.abs(h.fixture.distanceKm(home,{lat:home.lat,lon:northeast[1]})-30)<.01);
assert.equal(h.$('#aprs-map-local').attributes['aria-pressed'],'true');assert.equal((southwest[0]+northeast[0])/2,home.lat);assert.equal(h.$('#aprs-map-local').disabled,false);
h.fixture.fit();assert.equal(h.$('#aprs-map-fit').attributes['aria-pressed'],'true');const bounds=JSON.stringify(l.state.bounds);assert.ok(l.state.bounds.every(p=>p[0]>0));
h.fixture.setData(structuredClone(data));h.fixture.renderMap();assert.equal(l.state.fits,2);assert.equal(JSON.stringify(l.state.bounds),bounds);
h.fixture.fitLocal();assert.equal(l.state.fits,3);
data.own.position=null;h.fixture.setData(data);h.fixture.renderMap();assert.equal(h.$('#aprs-map-local').disabled,true);h.fixture.fitLocal();assert.equal(l.state.fits,3);
});
test('APRS popups show decoded Mic-E values and keep encoded bytes only in a collapsed original-packet detail',()=>{
const h=harness('aprs-activity.js','globalThis.fixture={popup,stationDescription};');
const body='`'+String.fromCharCode(127)+'^U!n^>/"5J}';
const s={...station('N0TEST'),status:'',lastBody:body};
const description=h.fixture.stationDescription(s);assert.equal(description,'Mic-E · 107 km/h · 266° · Quota 142 m');
const html=h.fixture.popup(s);assert.match(html,/<details class="aprs-raw-packet"><summary>Pacchetto originale/);
assert.ok(html.includes(String.fromCharCode(92)+'x7f'));assert.ok(!html.includes(String.fromCharCode(127)));
assert.equal(s.lastBody,body);
});
+10
View File
@@ -0,0 +1,10 @@
import {readFile,writeFile,rename} from 'node:fs/promises';
import {createHash} from 'node:crypto';
// Keep reading separate from BPQ delivery/forwarding flags.
export class MessageReadState {
constructor(file){this.file=file;this.entries={};this.chain=Promise.resolve();this.ready=readFile(file,'utf8').then(text=>{this.entries=JSON.parse(text);}).catch(error=>{if(error.code!=='ENOENT')throw error;});}
key(message){return createHash('sha256').update(JSON.stringify([message.id,message.from,message.to,message.subject])).digest('hex');}
decorate(messages){return messages.map(message=>({...message,read:message.status==='Y'||Boolean(this.entries[this.key(message)]),readAt:this.entries[this.key(message)]||null}));}
mark(message){const run=this.chain.then(async()=>{await this.ready;const key=this.key(message),at=this.entries[key]||new Date().toISOString();const entries={...this.entries,[key]:at};await writeFile(this.file+'.tmp',JSON.stringify(entries),'utf8');await rename(this.file+'.tmp',this.file);this.entries=entries;return {id:message.id,read:true,readAt:at};});this.chain=run.catch(()=>{});return run;}
}
+23
View File
@@ -0,0 +1,23 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {mkdtemp,rm} from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import {MessageReadState} from './message-read-state.mjs';
test('reading persists independently of delivery status, including concurrent opens',async()=>{
const dir=await mkdtemp(path.join(os.tmpdir(),'bpq-read-'));
try{
const file=path.join(dir,'read.json'),store=new MessageReadState(file);await store.ready;
const first={id:1,from:'N0ABC',to:'N0TEST',subject:'Hello',status:'N'};
const queued={...first,id:2};
assert.equal(store.decorate([first])[0].read,false);
await Promise.all([store.mark(first),store.mark(queued)]);
const reloaded=new MessageReadState(file);await reloaded.ready;
const results=reloaded.decorate([first,{...queued,status:'F'}]);
assert.deepEqual(results.map(m=>[m.read,m.status]),[[true,'N'],[true,'F']]);
assert.equal(first.read,undefined);
assert.equal(reloaded.decorate([{...first,subject:'Different message'}])[0].read,false);
assert.equal(reloaded.decorate([{...first,id:3,status:'Y'}])[0].read,true);
}finally{await rm(dir,{recursive:true,force:true});}
});
+1 -1
View File
@@ -1 +1 @@
{"name":"bpq-console","version":"1.1.0","private":true,"type":"module","scripts":{"start":"node server.mjs","test":"node --test test.mjs"}} {"name":"bpq-console","version":"1.2.0","private":true,"type":"module","engines":{"node":">=20"},"scripts":{"start":"node server.mjs","test":"node --test"}}
+12
View File
@@ -0,0 +1,12 @@
// Accelerate BPQ's native scanner rather than bypassing its V0 modem interlock.
export function packetPreparationMode(enabled,packetChannelId){return enabled?.includes(packetChannelId)?'scan':'direct';}
export function canExpeditePacket({request,manualRequestId,txSuspended,ptt,connections,radioState,users,radioPorts=null,lastPtt=0,now=Date.now()}){
const attached=[...(users||'').matchAll(/(?:TNC Uplink Port|Attached to Port)\s+(\d+)\//g)].some(m=>!radioPorts||radioPorts.includes(Number(m[1])));
return Boolean(request&&request.id!==manualRequestId&&!txSuspended&&!ptt&&!connections&&now-lastPtt>=1000&&!/^(?:connecting|connected|calling|interlocked)\b/i.test(radioState||'')&&!attached);
}
export function shouldAdvancePacketScan({frequency,packetFrequencyMHz,lastFrequency,lastAdvance=0,now=Date.now()}){
return Number.isFinite(frequency)&&Number.isFinite(packetFrequencyMHz)&&Math.abs(frequency-packetFrequencyMHz)>0.0001&&(frequency!==lastFrequency||now-lastAdvance>=1500);
}
export function canRecoverIdleScan({phase,scanning,txSuspended,ptt,request,manualRequestId,radioState,users,radioPorts=null,lastPtt=0,idleSince=0,now=Date.now()}){
return Boolean(['hf','waiting'].includes(phase)&&!scanning&&!request&&!manualRequestId&&idleSince&&now-idleSince>=8000&&canExpeditePacket({request:{id:'scan-recovery'},manualRequestId,txSuspended,ptt,connections:0,radioState,users,radioPorts,lastPtt,now}));
}
+19
View File
@@ -0,0 +1,19 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {canExpeditePacket,shouldAdvancePacketScan,packetPreparationMode} from './packet-preparation.mjs';
test('manual packet preparation is independent of listening channel selection',()=>{
const selected=['7050000-USB','14122000-USB'];assert.equal(packetPreparationMode(selected,'144950000-DATA-FM'),'direct');assert.equal(packetPreparationMode([...selected,'144950000-DATA-FM'],'144950000-DATA-FM'),'scan');assert.deepEqual(selected,['7050000-USB','14122000-USB']);
});
test('a manual packet request may advance the scanner from either HF band while idle',()=>{
const idle={request:{id:'new'},manualRequestId:null,ptt:false,connections:0,radioState:'Free',users:'',lastPtt:0,now:100000};
assert.equal(canExpeditePacket(idle),true);assert.equal(canExpeditePacket({...idle,radioPorts:[4,7],users:'Attached to Port 2/1'}),true);assert.equal(canExpeditePacket({...idle,radioPorts:[4,7],users:'Attached to Port 7/1'}),false);
for(const busy of [{txSuspended:true},{ptt:true},{connections:1},{radioState:'Connecting to remote'},{radioState:'Connected'},{radioState:'Interlocked'},{users:'Attached to Port 1/1'},{users:'TNC Uplink Port 3/1'},{lastPtt:99500},{manualRequestId:'new'},{request:null}])assert.equal(canExpeditePacket({...idle,...busy}),false,JSON.stringify(busy));
for(const frequency of [7.050,14.122])assert.equal(shouldAdvancePacketScan({packetFrequencyMHz:144.950,frequency,now:100000}),true);
assert.equal(shouldAdvancePacketScan({packetFrequencyMHz:144.950,frequency:144.950,now:100000}),false);
assert.equal(shouldAdvancePacketScan({packetFrequencyMHz:144.950,frequency:NaN,now:100000}),false);
});
test('native scan commands wait for a frequency change or a bounded retry interval',()=>{
assert.equal(shouldAdvancePacketScan({packetFrequencyMHz:144.950,frequency:7.050,lastFrequency:7.050,lastAdvance:10000,now:10500}),false);
assert.equal(shouldAdvancePacketScan({packetFrequencyMHz:144.950,frequency:14.122,lastFrequency:7.050,lastAdvance:10000,now:10500}),true);
assert.equal(shouldAdvancePacketScan({packetFrequencyMHz:144.950,frequency:7.050,lastFrequency:7.050,lastAdvance:10000,now:11500}),true);
});
+20
View File
@@ -0,0 +1,20 @@
// Return the native message list immediately; enrich optional fields serially.
export class ProgressiveMetadata {
constructor(load){this.load=load;this.values=new Map();this.pending=new Map();this.running=false;this.generation=new Map();}
enrich(items){
const result=items.map(item=>({...item,...this.values.get(item.id)}));
for(const item of items)if(!this.values.has(item.id)&&!this.pending.has(item.id))this.pending.set(item.id,{item,generation:this.generation.get(item.id)||0});
if(!this.running&&this.pending.size){this.running=true;setImmediate(()=>this.drain());}
return result;
}
invalidate(id){this.values.delete(id);this.pending.delete(id);this.generation.set(id,(this.generation.get(id)||0)+1);}
async drain(){
while(this.pending.size){
const [id,job]=this.pending.entries().next().value;
try{const fields=await this.load(job.item);if((this.generation.get(id)||0)===job.generation)this.values.set(id,fields);}catch{/* A later refresh retries unavailable metadata. */}
if(this.pending.get(id)===job)this.pending.delete(id);
await new Promise(resolve=>setImmediate(resolve));
}
this.running=false;
}
}
+18
View File
@@ -0,0 +1,18 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {ProgressiveMetadata} from './progressive-metadata.mjs';
const turn=()=>new Promise(resolve=>setImmediate(resolve));
test('message rows are available while optional metadata is blocked, without duplicate work',async()=>{
let release;const gate=new Promise(resolve=>release=resolve),calls=[];
const reader=new ProgressiveMetadata(async item=>{calls.push(item.id);await gate;return {receivedAt:'2026-10-17T07:00:00Z'};});
const rows=[{id:1,subject:'Bulletin'},{id:2,subject:'Mail'}];
assert.deepEqual(reader.enrich(rows),rows);await turn();assert.deepEqual(calls,[1]);
assert.deepEqual(reader.enrich(rows),rows);release();for(let i=0;i<5;i++)await turn();
assert.deepEqual(calls,[1,2]);assert.equal(reader.enrich(rows)[0].receivedAt,'2026-10-17T07:00:00Z');
assert.equal(rows[0].receivedAt,undefined);
});
test('failed metadata can retry and deleted messages cannot repopulate the cache',async()=>{
let attempts=0;const reader=new ProgressiveMetadata(async()=>{if(!attempts++)throw Error('BPQ starting');return {createdAt:'ready'};});
reader.enrich([{id:3}]);for(let i=0;i<3;i++)await turn();reader.enrich([{id:3}]);for(let i=0;i<3;i++)await turn();assert.equal(reader.enrich([{id:3}])[0].createdAt,'ready');
let release;const other=new ProgressiveMetadata(()=>new Promise(resolve=>release=resolve));other.enrich([{id:4}]);await turn();other.invalidate(4);release({createdAt:'stale'});for(let i=0;i<3;i++)await turn();assert.equal(other.values.has(4),false);
});
+3
View File
@@ -0,0 +1,3 @@
Natural Earth, 1:110m land polygons. Public domain.
Source: https://github.com/nvkelso/natural-earth-vector/blob/master/geojson/ne_110m_land.geojson
Terms: https://www.naturalearthdata.com/about/terms-of-use/
+30 -24
View File
@@ -1,13 +1,14 @@
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 station={call:'',alias:'',features:{},apps:[]};
const deletedMessageIds=new Set();
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=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])); const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[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 {busy=true,...request}=options;const finish=(busy&&window.BPQBusy?.start())||(()=>{});try{const r=await fetch('/api'+url,{...request,headers:{...(options.body instanceof FormData?{}:{'Content-Type':'application/json'}),...(options.method==='POST'?{'X-CSRF-Token':csrf}:{}),...options.headers}});const data=await r.json();if(!r.ok){if(r.status===401&&url!=='/login')showLogin();throw new Error(data.error||'Richiesta fallita')}return data;}finally{finish();}}
function toast(text){$('#toast').textContent=text;$('#toast').hidden=false;clearTimeout(toast.timer);toast.timer=setTimeout(()=>$('#toast').hidden=true,6500);} function 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(){document.dispatchEvent(new Event('bpq-detach-auth-lost'));document.title='BPQ Console';$('#shell').hidden=true;$('#login').hidden=false;csrf='';}
function showShell(user){station=user.config;applyStation(user);csrf=user.csrf;$('#login').hidden=true;$('#shell').hidden=false;loadDashboard();if(station.features.bbs)loadMessages();} function showShell(user){deletedMessageIds.clear();station=user.config;applyStation(user);csrf=user.csrf;$('#login').hidden=true;$('#shell').hidden=false;if(!window.BPQDetached?.view){loadDashboard();if(station.features.bbs)loadMessages();}document.dispatchEvent(new Event('station-ready'));}
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(BPQI18n.locale(),{hour:'2-digit',minute:'2-digit'});}
function categoryLabel(m){return m.type==='P'?'PERSONALE':m.to||'BOLLETTINO'} function categoryLabel(m){return m.type==='P'?BPQI18n.t('PERSONALE'):m.to||BPQI18n.t('BOLLETTINO')}
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 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'}
@@ -15,39 +16,40 @@ function navigate(next){page=next;$$('.page').forEach(p=>p.hidden=p.id!==next);$
$$('[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?(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 loadDashboard(background=false){if(window.BPQDetached?.view)return;try{const d=await api('/dashboard',{busy:!background});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(BPQI18n.locale(),{hour:'2-digit',minute:'2-digit'});$('#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(){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)}} async function loadMessages(background=false){if(!station.features.bbs)return;try{allMessages=(await api('/messages',{busy:!background})).filter(m=>!deletedMessageIds.has(m.id));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(BPQI18n.locale(),{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'});}
function mailTimezone(){const minutes=-new Date().getTimezoneOffset();return 'UTC'+(minutes>=0?'+':'-')+String(Math.floor(Math.abs(minutes)/60)).padStart(2,'0')+':'+String(Math.abs(minutes)%60).padStart(2,'0');} function 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(BPQI18n.locale(),{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.read&&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)')}${m.attachmentCount?'<span class="mail-paperclip" aria-label="Allegati" title="'+m.attachmentCount+' '+BPQI18n.t('Allegati')+'">📎 '+m.attachmentCount+'</span>':''}</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.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)));} function renderMessages(){const q=$('#search').value.toLowerCase(),cat=$('#category').value;const list=allMessages.filter(m=>(filter==='all'||m.type===filter||filter==='sent'&&m.from.replace(/-\d+$/,'')===station.call.replace(/-\d+$/,''))&&(!cat||m.to===cat)&&(!q||`${m.subject} ${m.from} ${m.to} ${m.id}`.toLowerCase().includes(q)));$('#list-count').textContent=list.length+' messaggi';$('#message-list').innerHTML=list.map(m=>mailRow(m,selected,'data-id',{category:categoryLabel(m),status:m.status==='F'?'Inoltrato':m.status==='N'?(m.read?'Letto':'Nuovo'):m.status==='Y'?'Letto':m.status==='H'?'Trattenuto':m.status})).join('')||'<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>`}} function replyDraft(message,comment=false){const bulletin=comment&&message.type==='B',destination=String((bulletin?message.to:message.from)||'').trim().replace(/\s*@\s*/g,'@'),via=String(message.via||'').trim();return {to:bulletin&&via&&!destination.includes('@')?destination+'@'+via:destination,type:bulletin?'B':'P',subject:(/^Re:/i.test(message.subject)?message.subject:'Re: '+message.subject).slice(0,80),text:'\n\n--- '+message.from+' ---\n'+message.text.split('\n').map(line=>'> '+line).join('\n')};}
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><div class="reader-reply-actions">${m.type==='B'?'<button class="secondary" id="comment" title="Pubblica un commento come bollettino">▤ Commenta</button>':''}<button class="secondary" id="reply" title="Rispondi all’autore con un messaggio personale">↩ Rispondi</button></div></footer>`;markMessageRead(id).catch(error=>toast(error.message));$('#reply').onclick=()=>openCompose(replyDraft(m));if(m.type==='B')$('#comment').onclick=()=>openCompose(replyDraft(m,true));}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||window.bpqComposeAttachments?.count())&&!bpqConfirm('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…';window.bpqComposeAttachments?.busy(true);$('#compose-error').textContent='';try{const data=Object.fromEntries(new FormData(e.target));const payload=winlinkMode&&window.bpqComposeAttachments?.count()?window.bpqComposeAttachments.form(data):JSON.stringify(data);const created=await api('/messages',{method:'POST',body:payload});$('#compose').close();toast('Messaggio #'+created.id+' salvato nella BBS. L’inoltro sarà gestito da BPQ.');if(winlinkMode){wlFolder='queue';navigate('winlink');await wlLoad(true);wlRender();wlRead(created.id);}else{navigate('bbs');await loadMessages();readMessage(created.id);}loadDashboard();}catch(err){$('#compose-error').textContent=err.message}finally{window.bpqComposeAttachments?.busy(false);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};
setInterval(()=>{if(csrf&&!document.hidden)loadDashboard()},20000);setInterval(()=>{$('#clock').textContent=new Date().toLocaleTimeString('it-IT',{hour:'2-digit',minute:'2-digit'})+' · '+mailTimezone()},1000); setInterval(()=>{if(csrf&&!document.hidden)loadDashboard(true)},20000);setInterval(()=>{$('#clock').textContent=new Date().toLocaleTimeString(BPQI18n.locale(),{hour:'2-digit',minute:'2-digit'})+' · '+mailTimezone()},1000);
api('/session').then(showShell).catch(()=>showLogin()); function restoreSession(){api('/session').then(showShell).catch(()=>showLogin());}
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',restoreSession,{once:true});else restoreSession();
function applyStation(user){ function applyStation(user){
document.title='BPQ Console · '+station.nodeCall; document.title='BPQ Console · '+station.nodeCall;
$('.side-station').textContent=[station.nodeCall,station.alias,station.locator].filter(Boolean).join(' · '); $('.side-station').textContent=[station.nodeCall,station.alias,station.locator].filter(Boolean).join(' · ');
$('.profile .avatar').textContent=station.call.slice(0,2); $('.profile .avatar').textContent=station.call.slice(0,2);
$('.profile > div:nth-child(2)').textContent=user.name+' · '+station.call; $('.profile > div:nth-child(2)').textContent=user.name+' · '+user.call;
$('.mission-heading h1').textContent=station.nodeCall+' / '+station.alias; $('.mission-heading h1').textContent=station.nodeCall+' / '+station.alias;
$('.mission-location').textContent=station.locator||'BPQ'; $('.mission-location').textContent=station.locator||'BPQ';
$('.modem-brand').textContent=station.radio?.name||'Nessuna porta modem'; $('.modem-brand').textContent=station.radio?.name||BPQI18n.t('Nessuna porta modem');
$('#home .page-footer').firstChild.textContent='BPQ Console · '+station.nodeCall+' '; $('#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 .eyebrow').textContent=station.call;
$('.compose-help').textContent='Il messaggio sarà salvato nella BBS. L’inoltro segue i profili BPQ.'; $('.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'; $('.wl-account').textContent=station.call.replace(/-\d+$/,'')+'@winlink.org';
$('.chat-empty h2').textContent=station.apps.find(a=>a.command==='CHAT')?.alias||'Chat BPQ'; const chatHeading=$('.chat-empty h2'),chatHint=$('.chat-empty p');
$('.chat-empty p').textContent='Connettiti come '+station.call+' per partecipare alla chat.'; if(chatHeading)chatHeading.textContent=station.apps.find(a=>a.command==='CHAT')?.alias||'Chat BPQ';
if(chatHint)chatHint.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];} 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 .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 .muted').textContent=station.call;
@@ -59,3 +61,7 @@ function applyStation(user){
if(!station.features.bbs){$('#nav-count').hidden=true;$$('.compose-button').forEach(b=>b.disabled=true);} 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'); if(!station.features[page]&&['bbs','chat','winlink','monitor'].includes(page))navigate('home');
} }
document.addEventListener('bpq-languagechange',()=>{if(csrf){if(!station.radio)$('.modem-brand').textContent=BPQI18n.t('Nessuna porta modem');renderMessages();if(typeof wlRender==='function')wlRender();}});
async function markMessageRead(id){const state=await api('/messages/'+id+'/read',{method:'POST',body:'{}'});for(const item of allMessages)if(item.id===id)Object.assign(item,state);if(typeof wlData!=='undefined'&&wlData)for(const item of wlData.messages)if(item.id===id)Object.assign(item,state);renderMessages();if(typeof wlRender==='function')wlRender();}
+49
View File
@@ -0,0 +1,49 @@
.aprs-view-tabs{display:flex;gap:6px;margin:0 0 23px;border-bottom:1px solid #2c3e53}.aprs-view-tabs button{padding:12px 24px;background:transparent;color:#8da7bf;border:0;border-bottom:2px solid transparent;cursor:pointer;font-weight:600;font-size:13px}.aprs-view-tabs button[aria-selected=true]{color:#c4e8dc;border-bottom-color:#8bd2b8;background:#91cdb30a}.aprs-activity-toolbar{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:15px}.aprs-activity-toolbar input,.aprs-activity-toolbar select{padding:9px 12px;background:#121f2e;color:#c3d4e6;border:1px solid #30465c;border-radius:7px;font-size:11px}.aprs-activity-toolbar input{flex:1;min-width:160px}.aprs-activity-toolbar .secondary{font-size:11px}.aprs-activity-kpis{display:grid;grid-template-columns:repeat(5,1fr);gap:12px;margin-bottom:18px}.aprs-activity-kpis article{padding:14px 18px;border:1px solid #2d4258;border-radius:9px;background:linear-gradient(135deg,#17283a,#111d2b)}.aprs-activity-kpis span{display:block;color:#8ca6be;font-size:10px}.aprs-activity-kpis strong{display:block;font:26px Consolas,monospace;color:#d6e7f5;margin-top:7px}.aprs-map-layout{display:grid;grid-template-columns:minmax(0,2.5fr) minmax(230px,1fr);gap:16px;margin-bottom:20px}.aprs-map-card header,.aprs-stations-card header,.aprs-traffic-card>header{padding:16px 20px;display:flex;align-items:center;justify-content:space-between;gap:12px;border-bottom:1px solid #2b4055}.aprs-map-card h2,.aprs-stations-card h2,.aprs-traffic-card h2{font-size:14px;margin:0;color:#d8e6f3}.aprs-map-card header span,.aprs-traffic-card header>span{font-size:10px;color:#8ba6bd}.aprs-map-card header span{display:block;margin-top:5px}.aprs-map-card .secondary{font-size:10px}.aprs-map-card{overflow:hidden}#aprs-station-map{height:390px;z-index:0;background:#111d2b}.aprs-map-card footer{display:flex;gap:14px;flex-wrap:wrap;padding:11px 18px;color:#8ba4bc;font-size:9px}.aprs-map-card footer>span:last-child{margin-left:auto}.aprs-legend:before{content:'';display:inline-block;width:7px;height:7px;border-radius:50%;margin-right:6px;background:#6fd4b1}.aprs-legend.internet:before{background:#81b9f4}.aprs-legend.own:before{background:#efcf89}.aprs-stations-card{display:flex;flex-direction:column;min-width:0;max-height:492px}.aprs-stations-card>div{overflow:auto;flex:1;min-height:0}.aprs-received-station{display:block;width:100%;text-align:left;background:none;border:0;border-bottom:1px solid #2c3f53;padding:14px 17px;cursor:pointer;color:#cadae9}.aprs-received-station:hover,.aprs-received-station.selected{background:#29435644}.aprs-received-station>span{display:flex;justify-content:space-between;align-items:center}.aprs-received-station b{font:13px Consolas,monospace}.aprs-received-station small{display:block;font-size:9px;color:#819ab1;margin-top:5px}.aprs-received-station p{font-size:10px;line-height:1.5;color:#9eb4c7;margin:7px 0 0;overflow:hidden;max-height:3em}.aprs-source-dot{height:6px;width:6px;background:#6fd4b1;border-radius:50%}.aprs-source-dot.internet{background:#81b9f4}.aprs-traffic-scroll{max-height:380px;overflow:auto}.aprs-traffic-table{width:100%;border-collapse:collapse;table-layout:fixed;min-width:740px}.aprs-traffic-table th{position:sticky;top:0;background:#142337;z-index:1;text-align:left;font-size:10px;color:#8ca7c0;padding:12px 15px}.aprs-traffic-table td{padding:12px 15px;border-top:1px solid #2a3d50;vertical-align:top;font-size:11px;color:#b4c9dc}.aprs-traffic-table th:nth-child(1){width:150px}.aprs-traffic-table th:nth-child(2){width:80px}.aprs-traffic-table th:nth-child(3){width:100px}.aprs-traffic-table th:nth-child(4){width:155px}.aprs-traffic-table td small{display:block;font-size:10px;color:#7f9bb2;margin-top:4px}.aprs-traffic-table tr[data-aprs-event]{cursor:pointer}.aprs-traffic-table tr[data-aprs-event]:hover{background:#233e5244}.aprs-packet-direction{font:11px Consolas,monospace;padding:3px 7px;border-radius:4px;background:#26384b}.aprs-packet-direction.rx{color:#9edcbe}.aprs-packet-direction.tx{color:#9ac9f3}.aprs-packet-type{display:block;color:#789bb6;font-size:9px;margin-bottom:5px}.aprs-packet-preview{display:block;font:10px/1.5 Consolas,monospace;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.aprs-packet-detail pre{white-space:pre-wrap;overflow-wrap:anywhere;margin:0;color:#c4dfed;font:11px/1.7 Consolas,monospace}.aprs-traffic-card>footer,.aprs-activity-status{padding:12px 18px;font-size:10px;line-height:1.6;color:#819cb3}.aprs-map-popup{display:grid;gap:5px;min-width:160px;max-width:280px;color:#c6dce9}.aprs-map-popup b{font:17px Consolas,monospace;color:#d5ecf6}.aprs-map-popup span,.aprs-map-popup small{font-size:10px;color:#9bb9cd}.aprs-map-popup p{margin:5px 0;overflow-wrap:anywhere;font-size:11px;line-height:1.5}.aprs-map-card .leaflet-popup-content-wrapper,.aprs-map-card .leaflet-popup-tip{background:#162738;box-shadow:0 6px 24px #0006}.aprs-map-card .leaflet-control-zoom a{background:#172a3b;color:#d8e9f5;border-color:#3e5369}.aprLine truncated
.aprs-view-tabs{margin-bottom:20px}
.aprs-map-layout{grid-template-columns:minmax(0,1fr) 300px;gap:16px;align-items:stretch}
#aprs-station-map{height:clamp(340px,calc(100dvh - 415px),500px)}
.aprs-stations-card{height:calc(clamp(340px,calc(100dvh - 415px),500px) + 112px);max-height:none}
.aprs-map-card header,.aprs-stations-card header,.aprs-traffic-card>header{padding:16px 18px;min-height:64px}
.aprs-map-card h2,.aprs-stations-card h2,.aprs-traffic-card h2{font-size:15px}
.aprs-map-card header span,.aprs-traffic-card header>span{font-size:12px}
.aprs-map-card footer{padding:12px 18px;font-size:11px}
.aprs-map-card footer>span:last-child{margin-left:0}
.aprs-received-station b{font-size:15px}
.aprs-received-station small,.aprs-received-station p{font-size:12px;line-height:1.5}
.aprs-traffic-table th,.aprs-packet-preview,.aprs-packet-type{font-size:11px}
.aprs-traffic-table td{font-size:12px}
.aprs-traffic-table th:nth-child(1){width:160px}
.aprs-traffic-card>footer,.aprs-activity-status{font-size:11px;padding:12px 18px}
.aprs-activity-status{padding-left:0}
.aprs-map-popup span,.aprs-map-popup small{font-size:12px}
.aprs-map-popup p{font-size:13px}
.aprs-map-card .leaflet-container{font-family:'Segoe UI',sans-serif}
@media(max-width:1050px){.aprs-map-layout{grid-template-columns:1fr}.aprs-stations-card{height:250px}.aprs-stations-card>div{display:block}.aprs-received-station{padding:12px 16px}}
@media(max-width:650px){#aprs-station-map{height:330px}.aprs-activity-toolbar input{order:1;flex-basis:100%}.aprs-map-card header{flex-wrap:wrap}.aprs-map-card footer{gap:12px}.aprs-stations-card{height:230px}}
.aprs-traffic-card>footer summary{cursor:pointer;width:fit-content;color:#a9bfd6;font-size:12px}.aprs-traffic-card>footer p{margin-top:8px;line-height:1.65}
.aprs-map-card .leaflet-tile-pane{filter:invert(1) hue-rotate(180deg) saturate(.4) brightness(.9) contrast(.85)}
/* APRS icons use local high-resolution sprites; transport remains a separate rim. */
.aprs-station-icon{display:grid;place-items:center;background:#edf1ed;border:2px solid #6fd4b1;border-radius:8px;box-shadow:0 2px 7px #0008}
.aprs-station-icon.internet{border-color:#81b9f4}
.aprs-symbol-image{position:relative;display:inline-block;width:24px;height:24px;flex:0 0 24px;background-size:384px 144px;background-repeat:no-repeat;vertical-align:middle}
.aprs-symbol-image.aprs-symbol-primary{background-image:url('/vendor/aprs-symbols/primary.png')}
.aprs-symbol-image.aprs-symbol-alternate{background-image:url('/vendor/aprs-symbols/alternate.png')}
.aprs-symbol-overlay{position:absolute;inset:0;display:grid;place-items:center;font:900 15px/1 Arial,sans-serif;color:#111;text-shadow:1px 0 #fff,-1px 0 #fff,0 1px #fff,0 -1px #fff}
.aprs-symbol-unknown{display:inline-grid;place-items:center;width:24px;height:24px;color:#647373;font:700 17px/1 sans-serif}
.aprs-list-symbol{display:inline-grid;place-items:center;background:#edf1ed;border-radius:5px;flex:0 0 28px;height:28px;margin-right:7px}
.aprs-symbol-detail{font-size:11px;color:var(--muted,#99aaa5);line-height:1.5}
.aprs-symbol-detail code{color:inherit;font-size:11px}
.aprs-received-station>span{justify-content:flex-start;gap:7px}.aprs-received-station>span>b{flex:1}.aprs-list-symbol{margin-right:0}.aprs-station-icon.own{border-color:#efcf89;box-shadow:0 0 0 3px #efcf8930,0 2px 7px #0008}
.aprs-symbol-col-0{background-position-x:0px}.aprs-symbol-col-1{background-position-x:-24px}.aprs-symbol-col-2{background-position-x:-48px}.aprs-symbol-col-3{background-position-x:-72px}.aprs-symbol-col-4{background-position-x:-96px}.aprs-symbol-col-5{background-position-x:-120px}.aprs-symbol-col-6{background-position-x:-144px}.aprs-symbol-col-7{background-position-x:-168px}.aprs-symbol-col-8{background-position-x:-192px}.aprs-symbol-col-9{background-position-x:-216px}.aprs-symbol-col-10{background-position-x:-240px}.aprs-symbol-col-11{background-position-x:-264px}.aprs-symbol-col-12{background-position-x:-288px}.aprs-symbol-col-13{background-position-x:-312px}.aprs-symbol-col-14{background-position-x:-336px}.aprs-symbol-col-15{background-position-x:-360px}
.aprs-symbol-row-0{background-position-y:0px}.aprs-symbol-row-1{background-position-y:-24px}.aprs-symbol-row-2{background-position-y:-48px}.aprs-symbol-row-3{background-position-y:-72px}.aprs-symbol-row-4{background-position-y:-96px}.aprs-symbol-row-5{background-position-y:-120px}
.aprs-map-actions{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end}.aprs-map-actions .secondary{white-space:nowrap}@media(max-width:650px){.aprs-map-actions{width:100%;justify-content:flex-start}.aprs-map-actions .secondary{flex:1}}
.aprs-map-actions .secondary[aria-pressed=true]{border-color:#88c7b1;background:#8acbb018;color:#c8ebdf}
.aprs-map-popup p{white-space:pre-line}.aprs-raw-packet summary{font-size:11px;color:#a9c4d8;cursor:pointer}.aprs-raw-packet pre{max-height:120px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere;font:11px/1.5 Consolas,monospace;color:#a7becf;margin:6px 0}.aprs-received-station p{white-space:pre-line}
+110
View File
@@ -0,0 +1,110 @@
(()=>{
const section=$('#aprs'),form=$('#aprs-form'),heading=form.querySelector('.page-heading');section.prepend(heading);$('#aprs-save').setAttribute('form','aprs-form');
const tabs=document.createElement('div');tabs.className='aprs-view-tabs';tabs.setAttribute('role','tablist');tabs.setAttribute('aria-label','Viste APRS');tabs.innerHTML='<button role="tab" aria-selected="true" data-aprs-view="activity">Attività</button><button role="tab" aria-selected="false" data-aprs-view="config">Configurazione</button>';heading.after(tabs);
const pane=document.createElement('section');pane.className='aprs-activity-pane';pane.innerHTML='<div class="aprs-activity-toolbar"><span id="aprs-live-state" class="tag">Collegamento…</span><select id="aprs-source" aria-label="Origine APRS"><option value="Radio">Radio</option><option value="">Radio + Internet</option><option value="Internet">Internet</option></select><select id="aprs-direction" aria-label="Direzione APRS"><option value="">RX + TX</option><option value="RX">RX</option><option value="TX">TX</option></select><input id="aprs-search" type="search" placeholder="Cerca nominativo o testo…" aria-label="Cerca APRS"><button class="secondary" id="aprs-activity-pause">Pausa vista</button><button class="secondary" id="aprs-activity-refresh">↻ Aggiorna</button></div><div class="aprs-activity-kpis" id="aprs-activity-kpis"></div><div class="aprs-map-layout"><article class="card aprs-map-card"><header><div><h2>Stazioni ricevute</h2><span id="aprs-map-count"></span></div><div class="aprs-map-actions"><button class="secondary" id="aprs-map-fit" aria-pressed="false" title="Inquadra il gruppo più denso, ignorando le stazioni isolate">Centra stazioni</button><button class="secondary" id="aprs-map-local" aria-pressed="true">Zona locale · 30 km</button></div></header><div id="aprs-station-map" aria-label="Mappa stazioni APRS"></div><footer><span class="aprs-legend radio">Radio</span><span class="aprs-legend internet">Internet</span><span class="aprs-legend own">La tua stazione</span></footer></article><aside class="card aprs-stations-card"><header><h2>Ultime ricezioni</h2></header><div id="aprs-received-stations"></div></aside></div><article class="card aprs-traffic-card"><header><h2>Traffico APRS</h2><span id="aprs-traffic-count"></span></header><div class="aprs-traffic-scroll"><table class="aprs-traffic-table"><thead><tr><th>Data e ora</th><th>Direzione</th><th>Trasporto</th><th>Da → A</th><th>Tipo / pacchetto</th></tr></thead><tbody id="aprs-traffic-rows"></tbody></table></div><footer><details><summary>Dettagli del registro</summary><p id="aprs-traffic-scope"></p></details></footer></article><div class="aprs-activity-status" id="aprs-activity-status" role="status"></div>';
tabs.after(pane);let view='activity',data=null,loading=false,starting=false,paused=false,map=null,layers=null,markers=new Map(),ownMarker=null,fitted=false,selected=null,selectedEvent=null;
const snapshots=new WeakMap();
function markup(selector,html){const el=$(selector);if(snapshots.get(el)===html)return;snapshots.set(el,html);el.innerHTML=html;}
const time=t=>t?new Date(t).toLocaleString(BPQI18n.locale(),{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit',second:'2-digit'}):'—';
const type=t=>({position:'Posizione',message:'Messaggio',status:'Stato',object:'Oggetto APRS',weather:'Meteo',telemetry:'Telemetria','third-party':'Messaggio inoltrato',query:'Richiesta'}[t]||t);
const source=()=>$('#aprs-source').value,query=()=>$('#aprs-search').value.trim().toUpperCase();
const stations=()=>data?.stations.filter(s=>(!source()||s.transport===source()||source()==='Radio'&&s.heardRadio)&&(!query()||(s.call+' '+s.status+' '+s.lastBody).toUpperCase().includes(query())))||[];
function setView(next){view=next;form.hidden=next!=='config';pane.hidden=next!=='activity';$('#aprs-save').hidden=next!=='config';tabs.querySelectorAll('button').forEach(b=>b.setAttribute('aria-selected',String(b.dataset.aprsView===next)));if(next==='activity'&&page==='aprs'){start();requestAnimationFrame(()=>map?.invalidateSize({pan:false}));}}
tabs.onclick=e=>{const next=e.target.closest('[data-aprs-view]')?.dataset.aprsView;if(next)setView(next);};
function symbolIcon(position,transport='Radio'){
const info=window.BPQAprsSymbols.decode(position),html=window.BPQAprsSymbols.html(position);
return L.divIcon({className:'aprs-station-icon '+(transport==='Own'?'own':transport==='Radio'?'radio':'internet'),html,iconSize:[32,32],iconAnchor:[16,16],popupAnchor:[0,-17]});
}
const symbolKey=(s)=>JSON.stringify([s.position?.symset,s.position?.symbol,s.transport]);
function symbolDetail(position){const info=window.BPQAprsSymbols.decode(position);return info?esc(info.name)+' · <code>'+esc(info.code)+'</code>'+(info.overlay?' · '+BPQI18n.t('Sovrapposizione')+' '+esc(info.overlay):''):BPQI18n.t('Simbolo non disponibile');}
function stationDescription(s){
const packet=window.BPQAprsPacket.decode(s.lastBody||''),parts=[];
if(packet.format)parts.push(packet.format==='APRS'?BPQI18n.t('Posizione APRS'):packet.format);
if(packet.speedKmh!==null)parts.push(packet.speedKmh+' km/h');
if(packet.course!==null)parts.push(packet.course+'°');
if(packet.altitudeM!==null)parts.push(BPQI18n.t('Quota')+' '+packet.altitudeM+' m');
if(packet.device)parts.push(packet.device);
const status=window.BPQAprsPacket.decode(s.status||'').comment;
return [parts.join(' · '),status||packet.comment].filter(Boolean).join('\n');
}
function rawPacket(s){return s.lastBody?'<details class="aprs-raw-packet"><summary>'+BPQI18n.t('Pacchetto originale')+'</summary><pre>'+esc(s.lastBody.replace(/[\x00-\x1f\x7f-\x9f]/g,c=>String.fromCharCode(92)+'x'+c.charCodeAt(0).toString(16).padStart(2,'0')))+'</pre></details>':'';}
function popup(s){return '<div class="aprs-map-popup"><b>'+esc(s.call)+'</b><span class="aprs-symbol-detail">'+symbolDetail(s.position)+'</span><span>'+esc(s.transport)+(s.port?' · Port '+s.port:'')+'</span><span>'+esc(time(s.lastAt))+'</span><span>'+s.position.lat.toFixed(5)+', '+s.position.lon.toFixed(5)+'</span><p>'+esc(stationDescription(s))+'</p>'+rawPacket(s)+'<small>'+esc(s.path||'')+'</small></div>';}
function initMap(){if(map||!window.L)return;map=L.map('aprs-station-map',{zoomControl:true,scrollWheelZoom:true}).setView([25,0],2);L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png',{maxZoom:19,referrerPolicy:'origin',attribution:'&copy; <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener">OpenStreetMap</a> contributors · <a href="/vendor/aprs-symbols/README.md" target="_blank" rel="noopener">APRS symbols © OH7LZB</a>'}).addTo(map);layers=L.layerGroup().addTo(map);if(typeof ResizeObserver!=='undefined')new ResizeObserver(()=>{if(page==='aprs'&&view==='activity')map.invalidateSize({pan:false});}).observe($('#aprs-station-map'));}
const validPosition=p=>p&&Number.isFinite(p.lat)&&Number.isFinite(p.lon)&&Math.abs(p.lat)<=90&&Math.abs(p.lon)<=180;
function distanceKm(a,b){
const rad=Math.PI/180,lat=(b.lat-a.lat)*rad,lon=(b.lon-a.lon)*rad;
const h=Math.sin(lat/2)**2+Math.cos(a.lat*rad)*Math.cos(b.lat*rad)*Math.sin(lon/2)**2;
return 12742*Math.asin(Math.sqrt(Math.min(1,h)));
}
function densePositions(points,own){
// A fixed neighbourhood prevents chains of scattered stations from expanding the fit.
points=points.filter(validPosition);let best=[],center=null,tie=Infinity;
for(const candidate of points){
const nearby=points.filter(p=>distanceKm(candidate,p)<=100);
const rank=validPosition(own)?distanceKm(candidate,own):nearby.reduce((n,p)=>n+distanceKm(candidate,p),0);
if(nearby.length>best.length||nearby.length===best.length&&rank<tie){best=nearby;center=candidate;tie=rank;}
}
if(validPosition(own)&&(!center||distanceKm(center,own)<=100))best.push(own);
return best;
}
function localBounds(position,radiusKm=30){
const latDelta=radiusKm/6371*180/Math.PI,lat=position.lat;
const lonDelta=Math.abs(lat)+latDelta>=90?180:Math.asin(Math.sin(radiusKm/6371)/Math.cos(lat*Math.PI/180))*180/Math.PI;
return [[Math.max(-90,lat-latDelta),position.lon-lonDelta],[Math.min(90,lat+latDelta),position.lon+lonDelta]];
}
function mapPreset(local){$('#aprs-map-local').setAttribute('aria-pressed',String(local));$('#aprs-map-fit').setAttribute('aria-pressed',String(!local));}
function fit(){
if(!map)return;
const positions=densePositions(stations().map(s=>s.position),data?.own.position);
if(positions.length){map.fitBounds(L.latLngBounds(positions.map(p=>[p.lat,p.lon])),{padding:[38,38],maxZoom:13});mapPreset(false);}
}
function fitLocal(){
if(!map||!validPosition(data?.own.position))return;
map.fitBounds(L.latLngBounds(localBounds(data.own.position)),{padding:[20,20]});mapPreset(true);fitted=true;
}
function renderMap(){
if(page!=='aprs'||view!=='activity')return;
initMap();if(!map)return;$('#aprs-map-local').disabled=!validPosition(data?.own.position);$('#aprs-map-local').title=BPQI18n.t(validPosition(data?.own.position)?'Inquadra un raggio di 30 km dalla tua stazione':'Posizione della tua stazione non disponibile');
const list=stations(),visible=new Set();
for(const s of list){
if(!s.position)continue;
visible.add(s.call);
const point=[s.position.lat,s.position.lon],html=popup(s);
let marker=markers.get(s.call);
if(!marker){
marker=L.marker(point,{title:s.call,alt:s.call,icon:symbolIcon(s.position,s.transport)})
.bindTooltip(esc(s.call),{direction:'top',offset:[0,-6]})
.bindPopup(html,{autoPan:false});
marker.on('click',()=>{selected=s.call;renderStations();});
marker.symbolKey=symbolKey(s);marker.addTo(layers);markers.set(s.call,marker);
}else{
const current=marker.getLatLng();
if(current.lat!==point[0]||current.lng!==point[1])marker.setLatLng(point);
if(marker.symbolKey!==symbolKey(s)){marker.setIcon(symbolIcon(s.position,s.transport));marker.symbolKey=symbolKey(s);}
if(marker.getPopup().getContent()!==html)marker.setPopupContent(html);
}
}
for(const [call,marker]of markers)if(!visible.has(call)){layers.removeLayer(marker);markers.delete(call);}
const own=data?.own;
if(own?.position){
const point=[own.position.lat,own.position.lon],label=esc(own.call)+' · '+BPQI18n.t('La tua stazione');
if(!ownMarker){ownMarker=L.marker(point,{title:own.call,alt:own.call,icon:symbolIcon(own.position,'Own')}).bindTooltip(label).addTo(layers);ownMarker.symbolKey=symbolKey(own);}
else{if(ownMarker.symbolKey!==symbolKey(own)){ownMarker.setIcon(symbolIcon(own.position,'Own'));ownMarker.symbolKey=symbolKey(own);}const current=ownMarker.getLatLng();if(current.lat!==point[0]||current.lng!==point[1])ownMarker.setLatLng(point);if(ownMarker.getTooltip().getContent()!==label)ownMarker.setTooltipContent(label);}
}else if(ownMarker){layers.removeLayer(ownMarker);ownMarker=null;}
$('#aprs-map-count').textContent=visible.size+' '+BPQI18n.t('sulla mappa')+' · '+(list.length-visible.size)+' '+BPQI18n.t('senza posizione');
if(!fitted&&(visible.size||own?.position)){if(validPosition(own?.position))fitLocal();else fit();fitted=true;}
}
function renderStations(){const list=stations();markup('#aprs-received-stations',list.map(s=>'<button data-aprs-station="'+esc(s.call)+'" class="aprs-received-station '+(s.call===selected?'selected':'')+'"><span><span class="aprs-list-symbol">'+window.BPQAprsSymbols.html(s.position)+'</span><b>'+esc(s.call)+'</b><i class="aprs-source-dot '+s.transport.toLowerCase()+'"></i></span><small>'+esc(s.transport)+(s.port?' · Port '+s.port:'')+' · '+esc(time(s.lastAt))+'</small><small class="aprs-symbol-detail">'+symbolDetail(s.position)+'</small><p>'+esc((stationDescription(s)||'—').slice(0,170))+'</p>'+(!s.position?'<small>Senza posizione</small>':'')+'</button>').join('')||'<p class="empty">Nessuna stazione ricevuta con questi filtri.</p>');}
function render(){if(!data)return;const events=data.events.filter(e=>(!source()||e.transport===source())&&(!$('#aprs-direction').value||e.direction===$('#aprs-direction').value)&&(!query()||(e.packet+' '+e.from).toUpperCase().includes(query()))).slice().reverse();
$('#aprs-live-state').textContent=paused?'Vista in pausa':data.monitor==='online'?'● APRS in tempo reale':'Monitor '+data.monitor;
markup('#aprs-activity-kpis',[['Radio RX',data.counts?.radioRx??events.filter(e=>e.transport==='Radio'&&e.direction==='RX').length],['Radio TX · BPQ',data.counts?.radioTx??events.filter(e=>e.transport==='Radio'&&e.direction==='TX').length],['Internet RX',data.counts?.internetRx??events.filter(e=>e.transport==='Internet'&&e.direction==='RX').length],['Internet TX',data.counts?.internetTx??events.filter(e=>e.transport==='Internet'&&e.direction==='TX').length],['Stazioni ricevute',stations().length]].map(([k,v])=>'<article><span>'+esc(k)+'</span><strong>'+v+'</strong></article>').join(''));
$('#aprs-traffic-count').textContent=events.length+' '+BPQI18n.t('pacchetti nel registro');markup('#aprs-traffic-rows',events.slice(0,400).map(e=>'<tr data-aprs-event="'+e.id+'" tabindex="0" aria-expanded="'+(selectedEvent===e.id)+'"><td>'+esc(time(e.at))+'</td><td><span class="aprs-packet-direction '+e.direction.toLowerCase()+'">'+e.direction+'</span></td><td>'+esc(e.transport)+(e.port?'<small>Port '+e.port+'</small>':'')+'</td><td><b>'+esc(e.from)+'</b><small>→ '+esc(e.to)+'</small></td><td><span class="aprs-packet-type">'+esc(type(e.type))+'</span><span class="aprs-packet-preview">'+esc(e.body.slice(0,180))+'</span></td></tr>'+(selectedEvent===e.id?'<tr class="aprs-packet-detail"><td colspan="5"><pre>'+esc(e.packet)+'</pre><small>'+esc(e.evidence)+'</small></td></tr>':'')).join('')||'<tr><td colspan="5" class="empty">In attesa di pacchetti APRS ricevuti o inviati.</td></tr>');
$('#aprs-traffic-scope').textContent=BPQI18n.t('Ultimi 2000 pacchetti · TX radio = richieste registrate da BPQ.');$('#aprs-activity-status').textContent=[...data.errors,...(!data.loggingInternet?[BPQI18n.t('Log Internet non disponibile')]:[]),BPQI18n.t('Aggiornato')+' '+time(data.updatedAt)].join(' · ');renderStations();renderMap();
}
async function start(){if(!csrf||window.BPQDetached&&!window.BPQDetached.shouldPoll('aprs'))return;if(starting||data?.started){if(data)render();return;}starting=true;try{data=await api('/aprs/activity/start',{method:'POST',body:'{}'});render();}catch(e){$('#aprs-activity-status').textContent=e.message;}finally{starting=false;}}
async function poll(background=true){if(!csrf||loading||paused||document.hidden||window.BPQDetached&&!window.BPQDetached.shouldPoll('aprs')||page!=='aprs'||view!=='activity')return;loading=true;try{const next=await api('/aprs/activity',{busy:!background});data=next;render();if(!data.started)start();}catch(e){$('#aprs-activity-status').textContent=e.message;}finally{loading=false;}}
$('#aprs-map-fit').onclick=fit;$('#aprs-map-local').onclick=fitLocal;$('#aprs-activity-refresh').onclick=()=>{if(paused){render();return;}poll(false);};$('#aprs-activity-pause').onclick=()=>{paused=!paused;$('#aprs-activity-pause').textContent=paused?'Riprendi vista':'Pausa vista';if(!paused)poll();else render();};for(const id of ['aprs-source','aprs-direction','aprs-search'])$('#'+id).addEventListener(id==='aprs-search'?'input':'change',()=>{render();});
$('#aprs-received-stations').onclick=e=>{const call=e.target.closest('[data-aprs-station]')?.dataset.aprsStation;if(!call)return;selected=call;const marker=markers.get(call);if(marker){map.setView(marker.getLatLng(),Math.max(map.getZoom(),13));marker.openPopup();}renderStations();};
$('#aprs-traffic-rows').onclick=e=>{const row=e.target.closest('[data-aprs-event]');if(row){const id=Number(row.dataset.aprsEvent);selectedEvent=selectedEvent===id?null:id;render();}};$('#aprs-traffic-rows').onkeydown=e=>{if(['Enter',' '].includes(e.key)&&e.target.matches('[data-aprs-event]')){e.preventDefault();e.target.click();}};
const prior=navigate;navigate=function(next){prior(next);if(next==='aprs'&&view==='activity'){start();requestAnimationFrame(()=>map?.invalidateSize({pan:false}));}};document.addEventListener('station-ready',()=>{if(page==='aprs')start();});document.addEventListener('bpq-languagechange',()=>{if(data)render();});setInterval(poll,2000);setView('activity');
})();
+53
View File
@@ -0,0 +1,53 @@
/* APRS descriptions: OH7LZB / aprs-symbol-index, CC BY-SA 4.0. See vendor/aprs-symbols/README.md. */
(()=>{
const names={"/!":"Police station","/#":"Digipeater","/$":"Telephone","/%":"DX cluster","/&":"HF gateway","/'":"Small aircraft","/(":"Mobile satellite station","/)":"Wheelchair, handicapped","/*":"Snowmobile","/+":"Red Cross","/,":"Boy Scouts","/-":"House","/.":"Red X","//":"Red dot","/0":"Numbered circle: 0","/1":"Numbered circle: 1","/2":"Numbered circle: 2","/3":"Numbered circle: 3","/4":"Numbered circle: 4","/5":"Numbered circle: 5","/6":"Numbered circle: 6","/7":"Numbered circle: 7","/8":"Numbered circle: 8","/9":"Numbered circle: 9","/:":"Fire","/;":"Campground, tent","/<":"Motorcycle","/=":"Railroad engine","/>":"Car","/?":"File server","/@":"Hurricane predicted path","/A":"Aid station","/B":"BBS","/C":"Canoe","/E":"Eyeball","/F":"Farm vehicle, tractor","/G":"Grid square, 3 by 3","/H":"Hotel","/I":"TCP/IP network station","/K":"School","/L":"PC user","/M":"Mac apple","/N":"NTS station","/O":"Balloon","/P":"Police car","/R":"Recreational vehicle","/S":"Space Shuttle","/T":"SSTV","/U":"Bus","/V":"ATV, Amateur Television","/W":"Weather service site","/X":"Helicopter","/Y":"Sailboat","/Z":"Windows flag","/[":"Human","/\\":"DF triangle","/]":"Mailbox, post office","/^":"Large aircraft","/_":"Weather station","/`":"Satellite dish antenna","/a":"Ambulance","/b":"Bicycle","/c":"Incident command post","/d":"Fire station","/e":"Horse, equestrian","/f":"Fire truck","/g":"Glider","/h":"Hospital","/i":"IOTA, islands on the air","/j":"Jeep","/k":"Truck","/l":"Laptop","/m":"Mic-E repeater","/n":"Node, black bulls-eye","/o":"Emergency operations center","/p":"Dog","/q":"Grid square, 2 by 2","/r":"Repeater tower","/s":"Ship, power boat","/t":"Truck stop","/u":"Semi-trailer truck, 18-wheeler","/v":"Van","/w":"Water station","/x":"X / Unix","/y":"House, yagi antenna","/z":"Shelter","\\!":"Emergency","\\#":"Digipeater, green star","\\$":"Bank or ATM","\\&":"Gateway station","\\'":"Crash / incident site","\\(":"Cloudy","\\)":"Firenet MEO, MODIS Earth Observation","\\*":"Snow","\\+":"Church","\\,":"Girl Scouts","\\-":"House, HF antenna","\\.":"Ambiguous, question mark inside circle","\\/":"Waypoint destination","\\0":"Circle, IRLP / Echolink/WIRES","\\8":"802.11 WiFi or other network node","\\9":"Gas station","\\:":"Hail","\\;":"Park, picnic area","\\<":"Advisory, single red flag","\\>":"Red car","\\?":"Info kiosk","\\@":"Hurricane, Tropical storm","\\A":"White box","\\B":"Blowing snow","\\C":"Coast Guard","\\D":"Drizzling rain","\\E":"Smoke, Chimney","\\F":"Freezing rain","\\G":"Snow shower","\\H":"Haze","\\I":"Rain shower","\\J":"Lightning","\\K":"Kenwood HT","\\L":"Lighthouse","\\N":"Navigation buoy","\\O":"Rocket","\\P":"Parking","\\Q":"Earthquake","\\R":"Restaurant","\\S":"Satellite","\\T":"Thunderstorm","\\U":"Sunny","\\V":"VORTAC, Navigational aid","\\W":"NWS site","\\X":"Pharmacy","\\[":"Wall Cloud","\\^":"Aircraft","\\_":"Weather site","\\`":"Rain","\\a":"Red diamond","\\b":"Blowing dust, sand","\\c":"CD triangle, RACES, CERTS, SATERN","\\d":"DX spot","\\e":"Sleet","\\f":"Funnel cloud","\\g":"Gale, two red flags","\\h":"Store","\\i":"Black box, point of interest","\\j":"Work zone, excavating machine","\\k":"SUV, ATV","\\m":"Value sign, 3 digit display","\\n":"Red triangle","\\o":"Small circle","\\p":"Partly cloudy","\\r":"Restrooms","\\s":"Ship, boat","\\t":"Tornado","\\u":"Truck","\\v":"Van","\\w":"Flooding","\\y":"Skywarn","\\z":"Shelter","\\{":"Fog"};
function decode(position){
const {symbol,symset}=position||{};
if(typeof symbol!=='string'||symbol.length!==1||symbol<'!'||symbol>'~'||!/^[/\\A-Z0-9]$/.test(symset||''))return null;
const table=symset==='/'?'primary':'alternate',overlay=/^[A-Z0-9]$/.test(symset)?symset:null;
const index=symbol.charCodeAt(0)-33;
return {symbol,symset,table,overlay,index,name:names[(table==='primary'?'/':'\\')+symbol]||'APRS',code:symset+symbol};
}
function html(position){
const info=decode(position);if(!info)return '<span class="aprs-symbol-unknown" aria-hidden="true">?</span>';
const col=info.index%16,row=Math.floor(info.index/16);
return '<span class="aprs-symbol-image aprs-symbol-'+info.table+' aprs-symbol-col-'+col+' aprs-symbol-row-'+row+'" aria-hidden="true">'+(info.overlay?'<span class="aprs-symbol-overlay">'+info.overlay+'</span>':'')+'</span>';
}
// APRS101 chapter 10 and aprs.org/aprs12/mic-e-types.txt.
function packetDetails(body=''){
body=String(body);const result={format:null,comment:body,speedKmh:null,course:null,altitudeM:null,device:null};
if(/^[`']/.test(body)){
result.format='Mic-E';result.comment='';
if(body.length<9||!decode({symset:body[8],symbol:body[7]}))return result;
const [sp,dc,se]=[4,5,6].map(i=>body.charCodeAt(i)-28);
if(sp>=0&&sp<=99&&dc>=0&&dc<=99&&se>=0&&se<=99){
let speed=sp*10+Math.floor(dc/10),course=(dc%10)*100+se;
if(speed>=800)speed-=800;if(course>=400)course-=400;
if(speed>=0&&speed<=799&&course>=0&&course<=360){result.speedKmh=Math.round(speed*1.852);result.course=course||null;}
}
let tail=body.slice(9),prefix=tail[0];
if(prefix==='>'||prefix===']'){
result.device=prefix==='>'?'Kenwood TH-D7':'Kenwood TM-D700';tail=tail.slice(1);
if(tail.endsWith('=')){result.device=prefix==='>'?'Kenwood TH-D72':'Kenwood TM-D710';tail=tail.slice(0,-1);}
else if(prefix==='>'&&tail.endsWith('^')){result.device='Kenwood TH-D74';tail=tail.slice(0,-1);}
}else if(prefix==='`'||prefix==="'"){
tail=tail.slice(1);
const devices={'_ ':'Yaesu VX-8','_"':'Yaesu FTM-350','_#':'Yaesu VX-8G','_$':'Yaesu FT1D','_%':'Yaesu FTM-400DR','_)':'Yaesu FTM-100D','_(':'Yaesu FT2D','_0':'Yaesu FT3D','_3':'Yaesu FT5D','_1':'Yaesu FTM-300D','(5':'AnyTone D578UV','(8':'AnyTone D878UV','|3':'Byonics TinyTrak3','|4':'Byonics TinyTrak4',':4':'SCS DR-7400',':8':'SCS DR-7800'};
const device=devices[tail.slice(-2)];if(device){result.device=device;tail=tail.slice(0,-2);}
}else if(prefix===' ')tail=tail.slice(1);
const altitude=tail.match(/^([!-{]{3})\}/);
if(altitude){result.altitudeM=[...altitude[1]].reduce((n,c)=>n*91+c.charCodeAt(0)-33,0)-10000;tail=tail.slice(4);}
result.comment=tail;
}else if(/^[!=/@]/.test(body)){
result.format='APRS';const payload=body.slice(body[0]==='@'||body[0]==='/'?8:1);
if(/^\d{4}\.\d{2}[NS].\d{5}\.\d{2}[EW]./.test(payload))result.comment=payload.slice(19);
else if(/^[/\A-Z0-9][!-{]{8}[!-~][!-{]{3}/.test(payload))result.comment=payload.slice(13);
else result.comment='';
}else if(body.startsWith('>'))result.comment=body.slice(1).replace(/^\d{6}[zh/]/,'');
// Control bytes belong to the encoded frame, never the operator's description.
result.comment=result.comment.replace(/[\x00-\x1f\x7f-\x9f]/g,' ').trim();return result;
}
window.BPQAprsPacket={decode:packetDetails};
window.BPQAprsSymbols={decode,html};
})();
+2
View File
@@ -0,0 +1,2 @@
.aprs-settings-grid{display:grid;grid-template-columns:1fr 1fr;gap:18px;margin-bottom:18px}.aprs-settings-card{padding:24px}.aprs-settings-card h2{font-size:16px;margin:0 0 20px;color:#dbe8f5}.aprs-card-title{display:flex;align-items:baseline;justify-content:space-between;gap:15px}.aprs-fields{display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:17px}.aprs-settings-card label{display:grid;gap:8px;color:#94abc2;font-size:11px}.aprs-settings-card input:not([type=checkbox]),.aprs-settings-card textarea{width:100%;min-width:0;padding:11px 12px;background:#101b29;border:1px solid #304359;border-radius:7px;color:#d6e4f2;font-size:13px}.aprs-settings-card textarea{resize:vertical}.aprs-check{display:flex!important;align-items:center;gap:9px!important}.aprs-check input{width:16px;height:16px;accent-color:#8ccdb3}.aprs-help{color:#8199af;font-size:11px;line-height:1.65;margin-top:16px}.aprs-table-wrap{overflow:auto}.aprs-table{width:100%;border-collapse:collapse;min-width:760px}.aprs-table th{text-align:center;font-size:10px;line-height:1.5;color:#8ea7be;padding:12px;border-bottom:1px solid #2e4258;max-width:125px}.aprs-table th:first-child{text-align:left;width:280px}.aprs-table td{padding:20px 12px;border-bottom:1px solid #293a4c;text-align:center;vertical-align:top}.aprs-table td:first-child{text-align:left}.aprs-table strong{font-size:13px;color:#dbe7f5}.aprs-table small{display:block;font-size:10px;color:#809aaf;margin-top:5px}.aprs-frequency{display:flex!important;align-items:center;margin-top:15px}.aprs-frequency input{max-width:145px;font-family:Consolas,monospace}.aprs-frequency span{font-size:10px;white-space:nowrap}.aprs-path{margin-top:12px}.aprs-path input{max-width:230px;font-family:Consolas,monospace;font-size:11px!important}.aprs-switch{display:inline-flex!important;position:relative;cursor:pointer;align-items:center;margin-top:5px}.aprs-switch input{position:absolute;opacity:0;width:38px;height:22px}.aprs-switch span{width:38px;height:22px;border-radius:20px;background:#26374a;border:1px solid #3d5269;transition:.15s}.aprs-switch span:after{content:'';display:block;width:14px;height:14px;border-radius:50%;background:#94a8bc;margin:3px;transition:.15s}.aprs-switch input:checked+span{background:#285347;border-color:#5d9c83}.aprs-switch input:checked+span:after{transform:translateX(16px);background:#c4ecdb}.aprs-switch input:focus-visible+span{outline:2px solid #a9d8c9;outline-offset:3px}@media(max-width:850px){.aprs-settings-grid{grid-template-columns:1fr}.aprs-settings-card{padding:18px}}@media(max-width:500px){.aprs-fields{grid-template-columns:1fr}.aprs-card-title{align-items:flex-start}}
.aprs-table{table-layout:fixed;min-width:900px}.aprs-table th:first-child,.aprs-table td:first-child{width:26%}.aprs-table td:first-child{padding-right:22px}.aprs-frequency input{flex:0 1 145px;min-width:105px}.aprs-frequency{gap:8px!important}.aprs-table small{line-height:1.5}.aprs-table th{overflow-wrap:break-word}
+18
View File
@@ -0,0 +1,18 @@
(()=>{
let data=null,busy=false,dirty=false;
const nav=document.createElement('button');nav.dataset.page='aprs';nav.innerHTML='<span>⌖</span> APRS';nav.onclick=()=>navigate('aprs');$('nav [data-page="monitor"]').before(nav);
const pageElement=document.createElement('section');pageElement.id='aprs';pageElement.className='page';pageElement.hidden=true;
pageElement.innerHTML='<form id="aprs-form"><div class="page-heading"><div><span class="eyebrow">APRS / IGATE</span><h1>APRS</h1><p>Ascolto e inoltro, porta per porta.</p></div><button type="submit" class="primary" id="aprs-save">Salva e applica</button></div><div id="aprs-feedback" class="notice" role="status" hidden></div><div class="aprs-settings-grid"><article class="card aprs-settings-card"><h2>Stazione</h2><div class="aprs-fields"><label>Nominativo APRS<input name="call" required maxlength="10"></label><label>Beacon · minuti<input name="beaconMinutes" type="number" min="5" max="120" required></label><label>Latitudine APRS<input name="latitude" required placeholder="4534.18N"></label><label>Longitudine APRS<input name="longitude" required placeholder="00907.89E"></label><label>Simbolo<input name="symbol" maxlength="1" required></label><label>Tabella simboli<input name="symset" maxlength="1" required></label></div><label>Messaggio di stato<textarea name="status" rows="3" maxlength="180"></textarea></label></article><article class="card aprs-settings-card"><div class="aprs-card-title"><h2>Internet / APRS-IS</h2><label class="aprs-check"><input name="internetEnabled" type="checkbox">Abilitato</label></div><div class="aprs-fields"><label>Server<input name="host" required></label><label>Porta TCP<input name="port" type="number" min="1" max="65535" required></label><label>Passcode APRS-IS<input name="passcode" type="password" autocomplete="new-password" placeholder="Non configurato"></label><label>Filtro APRS-IS<input name="filter" placeholder="m/50"></label></div><label class="aprs-check"><input name="beaconInternet" type="checkbox">Pubblica il beacon su Internet</label><p id="aprs-passcode-state" class="aprs-help"></p><p class="aprs-help">I messaggi da Internet alla radio sono un flusso separato dalla ripetizione dei pacchetti radio.</p></article></div><article class="card aprs-settings-card aprs-port-card"><h2>Porte APRS</h2><div class="aprs-table-wrap"><table class="aprs-table"><thead><tr><th>Porta / frequenza</th><th>Ascolto</th><th>Radio → Internet</th><th>Ripeti via radio</th><th>Messaggi Internet → radio</th><th>Beacon radio</th></tr></thead><tbody id="aprs-ports"></tbody></table></div><p class="aprs-help">La frequenza APRS selezionata diventa la frequenza di ascolto della porta. I sync manuali mantengono la priorità e al termine ripristinano l’ascolto.</p><p class="aprs-help">Le ritrasmissioni radio seguono il percorso APRS e la soppressione dei duplicati gestiti da BPQ.</p></article></form>';$('main').append(pageElement);
const form=$('#aprs-form'),feedback=$('#aprs-feedback');
const prior=navigate;navigate=function(next){prior(next);if(next==='aprs'){$('#breadcrumb').textContent='Stazione / APRS';if(!dirty)load();}};
const check=(r,k)=>'<label class="aprs-switch"><input type="checkbox" data-aprs-option="'+k+'" aria-label="'+esc(k)+' Port '+r.port+'" '+(r[k]?'checked':'')+'><span></span></label>';
function render(){for(const key of ['call','status','latitude','longitude','symbol','symset','beaconMinutes','host','port','filter'])form.elements[key].value=data[key];for(const key of ['internetEnabled','beaconInternet'])form.elements[key].checked=data[key];form.elements.passcode.value='';form.elements.passcode.placeholder=data.passcodeConfigured?'Configurato · lascia vuoto per mantenerlo':'Non configurato';$('#aprs-passcode-state').textContent=data.passcodeConfigured?'Passcode salvato in BPQ':'Per inoltrare i pacchetti ricevuti a Internet serve il passcode APRS-IS.';
$('#aprs-ports').innerHTML=data.ports.map(r=>'<tr data-aprs-port="'+r.port+'"><td><strong>Port '+r.port+' · '+esc(r.driver)+'</strong><small>'+esc(r.name)+'</small><label class="aprs-frequency"><input data-frequency type="number" step="0.000001" min="144" max="440" value="'+r.frequencyMHz+'" aria-label="Frequenza APRS Port '+r.port+'"><span>MHz FM</span></label><label class="aprs-path">Percorso<input data-path value="'+esc(r.path)+'" aria-label="Percorso APRS Port '+r.port+'"></label></td>'+['enabled','radioToInternet','radioRepeat','internetToRadio','beaconRadio'].map(k=>'<td>'+check(r,k)+'</td>').join('')+'</tr>').join('')||'<tr><td colspan="6">Nessuna porta packet con controllo di frequenza disponibile.</td></tr>';
}
async function load(){if(!csrf||busy)return;try{data=await api('/aprs/settings');render();dirty=false;}catch(e){feedback.hidden=false;feedback.textContent=e.message;}}
form.oninput=()=>{dirty=true;};form.onsubmit=async e=>{e.preventDefault();if(busy||!data)return;busy=true;$('#aprs-save').disabled=true;feedback.hidden=true;toast('Applicazione della configurazione APRS…');
try{const next={...data};for(const key of ['call','status','latitude','longitude','symbol','symset','host','filter'])next[key]=form.elements[key].value.trim();for(const key of ['beaconMinutes','port'])next[key]=Number(form.elements[key].value);for(const key of ['internetEnabled','beaconInternet'])next[key]=form.elements[key].checked;next.passcode=form.elements.passcode.value;next.ports=data.ports.map(r=>{const row=form.querySelector('[data-aprs-port="'+r.port+'"]');return {...r,frequencyMHz:Number(row.querySelector('[data-frequency]').value),path:row.querySelector('[data-path]').value.trim().toUpperCase(),...Object.fromEntries(['enabled','radioToInternet','radioRepeat','internetToRadio','beaconRadio'].map(k=>[k,row.querySelector('[data-aprs-option="'+k+'"]').checked]))};});next.call=next.call.toUpperCase();data=await api('/aprs/settings',{method:'POST',body:JSON.stringify(next)});dirty=false;render();feedback.hidden=true;toast('Configurazione APRS applicata · backup salvato');}
catch(e){feedback.hidden=true;toast(e.message);}finally{busy=false;$('#aprs-save').disabled=false;}
};
document.addEventListener('station-ready',()=>{if(location.hash==='#aprs')navigate('aprs');else if(page==='aprs')load();});
})();
+3 -1
View File
@@ -2,6 +2,8 @@ let attachmentGeneration=0,attachmentPdf=null;
const attachmentDialog=document.createElement('dialog');attachmentDialog.className='attachment-dialog';attachmentDialog.innerHTML='<div class="dialog-heading"><h2 id="attachment-title">Allegato</h2><button id="attachment-close" class="icon-button" aria-label="Chiudi anteprima">×</button></div><div id="attachment-preview"></div><footer><a id="attachment-download" class="primary" download>Scarica file ↓</a></footer>';document.body.append(attachmentDialog);$('#attachment-close').onclick=()=>attachmentDialog.close();attachmentDialog.addEventListener('close',()=>{attachmentGeneration++;attachmentPdf?.destroy().catch(()=>{});attachmentPdf=null;$('#attachment-preview').replaceChildren();}); const attachmentDialog=document.createElement('dialog');attachmentDialog.className='attachment-dialog';attachmentDialog.innerHTML='<div class="dialog-heading"><h2 id="attachment-title">Allegato</h2><button id="attachment-close" class="icon-button" aria-label="Chiudi anteprima">×</button></div><div id="attachment-preview"></div><footer><a id="attachment-download" class="primary" download>Scarica file ↓</a></footer>';document.body.append(attachmentDialog);$('#attachment-close').onclick=()=>attachmentDialog.close();attachmentDialog.addEventListener('close',()=>{attachmentGeneration++;attachmentPdf?.destroy().catch(()=>{});attachmentPdf=null;$('#attachment-preview').replaceChildren();});
async function renderPdf(url,generation){const pdfjs=await import('/vendor/pdfjs/pdf.min.mjs');pdfjs.GlobalWorkerOptions.workerSrc='/vendor/pdfjs/pdf.worker.min.mjs';const documentPdf=await pdfjs.getDocument({url,withCredentials:true,isEvalSupported:false,enableXfa:false,disableFontFace:true,useSystemFonts:true,standardFontDataUrl:'/vendor/pdfjs/standard_fonts/',cMapUrl:'/vendor/pdfjs/cmaps/',cMapPacked:true}).promise;if(generation!==attachmentGeneration){await documentPdf.destroy();return;}attachmentPdf=documentPdf;const preview=$('#attachment-preview');preview.innerHTML='<div class="pdf-controls"><button id="pdf-previous" class="secondary">←</button><span id="pdf-page"></span><button id="pdf-next" class="secondary">→</button></div><canvas id="pdf-canvas" aria-label="Anteprima pagina PDF"></canvas>';let page=1,busy=false;async function draw(){if(busy||generation!==attachmentGeneration)return;busy=true;try{const p=await documentPdf.getPage(page);const v=p.getViewport({scale:1});const scale=Math.min(2,Math.max(1,(preview.clientWidth-30)/v.width));const viewport=p.getViewport({scale});const canvas=$('#pdf-canvas');if(!canvas||generation!==attachmentGeneration)return;canvas.width=viewport.width;canvas.height=viewport.height;await p.render({canvasContext:canvas.getContext('2d'),viewport}).promise;$('#pdf-page').textContent=page+' / '+documentPdf.numPages;$('#pdf-previous').disabled=page===1;$('#pdf-next').disabled=page===documentPdf.numPages;}finally{busy=false}}$('#pdf-previous').onclick=()=>{if(page>1&&!busy){page--;draw()}};$('#pdf-next').onclick=()=>{if(page<documentPdf.numPages&&!busy){page++;draw()}};await draw();} async function renderPdf(url,generation){const pdfjs=await import('/vendor/pdfjs/pdf.min.mjs');pdfjs.GlobalWorkerOptions.workerSrc='/vendor/pdfjs/pdf.worker.min.mjs';const documentPdf=await pdfjs.getDocument({url,withCredentials:true,isEvalSupported:false,enableXfa:false,disableFontFace:true,useSystemFonts:true,standardFontDataUrl:'/vendor/pdfjs/standard_fonts/',cMapUrl:'/vendor/pdfjs/cmaps/',cMapPacked:true}).promise;if(generation!==attachmentGeneration){await documentPdf.destroy();return;}attachmentPdf=documentPdf;const preview=$('#attachment-preview');preview.innerHTML='<div class="pdf-controls"><button id="pdf-previous" class="secondary">←</button><span id="pdf-page"></span><button id="pdf-next" class="secondary">→</button></div><canvas id="pdf-canvas" aria-label="Anteprima pagina PDF"></canvas>';let page=1,busy=false;async function draw(){if(busy||generation!==attachmentGeneration)return;busy=true;try{const p=await documentPdf.getPage(page);const v=p.getViewport({scale:1});const scale=Math.min(2,Math.max(1,(preview.clientWidth-30)/v.width));const viewport=p.getViewport({scale});const canvas=$('#pdf-canvas');if(!canvas||generation!==attachmentGeneration)return;canvas.width=viewport.width;canvas.height=viewport.height;await p.render({canvasContext:canvas.getContext('2d'),viewport}).promise;$('#pdf-page').textContent=page+' / '+documentPdf.numPages;$('#pdf-previous').disabled=page===1;$('#pdf-next').disabled=page===documentPdf.numPages;}finally{busy=false}}$('#pdf-previous').onclick=()=>{if(page>1&&!busy){page--;draw()}};$('#pdf-next').onclick=()=>{if(page<documentPdf.numPages&&!busy){page++;draw()}};await draw();}
async function openAttachment(id,file){const generation=++attachmentGeneration;$('#attachment-title').textContent=file.name;const url='/api/messages/'+id+'/attachments/'+file.index;$('#attachment-download').href=url;$('#attachment-preview').innerHTML='<p class="empty">Caricamento anteprima…</p>';attachmentDialog.showModal();if(file.mime.startsWith('image/')){const image=document.createElement('img');image.alt=file.name;image.src=url+'?preview=1';image.onerror=()=>$('#attachment-preview').innerHTML='<p class="empty">Anteprima non disponibile. Puoi scaricare il file.</p>';$('#attachment-preview').replaceChildren(image);}else if(file.mime==='application/pdf'){try{await renderPdf(url+'?preview=1',generation)}catch{if(generation===attachmentGeneration)$('#attachment-preview').innerHTML='<p class="empty">Anteprima PDF non disponibile. Puoi scaricare il file.</p>';}}else if(file.mime==='text/plain'){try{const data=await api('/messages/'+id+'/attachments/'+file.index+'?text=1');if(generation!==attachmentGeneration)return;const pre=document.createElement('pre');pre.textContent=data.text;$('#attachment-preview').replaceChildren(pre);if(data.truncated){const hint=document.createElement('p');hint.className='muted';hint.textContent='Anteprima limitata ai primi 128 KB. Il download contiene il file completo.';$('#attachment-preview').append(hint)}}catch(e){$('#attachment-preview').textContent=e.message}}else{$('#attachment-preview').innerHTML='<p class="empty">Anteprima non disponibile per questo formato. Puoi scaricare il file.</p>';}} async function openAttachment(id,file){const generation=++attachmentGeneration;$('#attachment-title').textContent=file.name;const url='/api/messages/'+id+'/attachments/'+file.index;$('#attachment-download').href=url;$('#attachment-preview').innerHTML='<p class="empty">Caricamento anteprima…</p>';attachmentDialog.showModal();if(file.mime.startsWith('image/')){const image=document.createElement('img');image.alt=file.name;image.src=url+'?preview=1';image.onerror=()=>$('#attachment-preview').innerHTML='<p class="empty">Anteprima non disponibile. Puoi scaricare il file.</p>';$('#attachment-preview').replaceChildren(image);}else if(file.mime==='application/pdf'){try{await renderPdf(url+'?preview=1',generation)}catch{if(generation===attachmentGeneration)$('#attachment-preview').innerHTML='<p class="empty">Anteprima PDF non disponibile. Puoi scaricare il file.</p>';}}else if(file.mime==='text/plain'){try{const data=await api('/messages/'+id+'/attachments/'+file.index+'?text=1');if(generation!==attachmentGeneration)return;const pre=document.createElement('pre');pre.textContent=data.text;$('#attachment-preview').replaceChildren(pre);if(data.truncated){const hint=document.createElement('p');hint.className='muted';hint.textContent='Anteprima limitata ai primi 128 KB. Il download contiene il file completo.';$('#attachment-preview').append(hint)}}catch(e){$('#attachment-preview').textContent=e.message}}else{$('#attachment-preview').innerHTML='<p class="empty">Anteprima non disponibile per questo formato. Puoi scaricare il file.</p>';}}
async function showAttachments(id,reader){const section=document.createElement('section');section.className='message-attachments';section.innerHTML='<span class="muted">Controllo allegati…</span>';reader.querySelector('.reader-footer')?.before(section);try{const data=await api('/messages/'+id+'/attachments');if(!section.isConnected)return;if(!data.files.length&&!data.encoded){section.remove();return;}section.replaceChildren();if(data.files.length){const heading=document.createElement('h3');heading.textContent='Allegati · '+data.files.length;section.append(heading);for(const file of data.files){const row=document.createElement('div');row.className='attachment-row';row.innerHTML=`<span class="attachment-icon">${file.mime.startsWith('image/')?'▧':file.mime==='application/pdf'?'PDF':'▤'}</span><div><b>${esc(file.name)}</b><small>${size(file.size)}</small></div><button class="secondary attachment-open">Anteprima</button><a class="secondary" href="/api/messages/${id}/attachments/${file.index}" download>Scarica ↓</a>`;row.querySelector('button').onclick=()=>openAttachment(id,file);if(file.mime==='application/octet-stream')row.querySelector('button').hidden=true;section.append(row);}}if(data.encoded){const box=document.createElement('div');box.className='encoded-attachment';box.innerHTML=`<b>7plus · ${esc(data.encoded.name)}</b><p>Parte ${data.encoded.part}/${data.encoded.total}. L’anteprima dell’immagine richiede il file ricostruito dalle parti complete.</p><a class="text-button" href="/api/messages/${id}/source" download>Scarica testo originale della parte ↓</a>`;section.append(box);}}catch(e){section.innerHTML=`<span class="muted">${esc(e.message)}</span>`;}} async function showAttachments(id,reader){const section=document.createElement('section');section.className='message-attachments';section.innerHTML='<span class="muted">Controllo allegati…</span>';reader.querySelector('.reader-footer')?.before(section);try{const data=await api('/messages/'+id+'/attachments');if(!section.isConnected)return;if(!data.files.length&&!data.encoded){section.remove();return;}section.replaceChildren();reader.querySelector('.reader-attachment-count')?.remove();if(data.files.length){const count=document.createElement('span');count.className='reader-attachment-count';count.textContent='📎 '+data.files.length;count.title='Allegati';reader.querySelector('.reader-header .tag')?.after(count);}if(data.files.length){const heading=document.createElement('h3');heading.textContent='Allegati · '+data.files.length;section.append(heading);for(const file of data.files){const row=document.createElement('div');row.className='attachment-row';row.innerHTML=`<span class="attachment-icon">${file.mime.startsWith('image/')?'▧':file.mime==='application/pdf'?'PDF':'▤'}</span><div><b>${esc(file.name)}</b><small>${size(file.size)}${file.reconstructed?' · Ricostruito da '+file.parts+' parti · CRC verificati':''}</small></div><button class="secondary attachment-open">Anteprima</button><a class="secondary" href="/api/messages/${id}/attachments/${file.index}" download>Scarica ↓</a>`;row.querySelector('button').onclick=()=>openAttachment(id,file);if(file.mime==='application/octet-stream')row.querySelector('button').hidden=true;section.append(row);}}if(data.encoded?.state==='complete'){const imageFile=data.files.find(f=>f.reconstructed&&f.mime.startsWith('image/')),body=reader.querySelector('.reader-body');if(imageFile&&body){const original=document.createElement('details');original.className='sevenplus-original';const summary=document.createElement('summary');summary.textContent='Mostra messaggio originale e dati 7plus';original.append(summary,...body.childNodes);const preview=document.createElement('div');preview.className='sevenplus-inline';const img=document.createElement('img');img.src='/api/messages/'+id+'/attachments/'+imageFile.index+'?preview=1';img.alt=imageFile.name;img.loading='lazy';img.onclick=()=>openAttachment(id,imageFile);const caption=document.createElement('p');caption.dataset.fileName=imageFile.name;caption.dataset.parts=imageFile.parts;caption.textContent=imageFile.name+' · '+BPQI18n.t(imageFile.parts+' parti ricostruite · CRC verificati');preview.append(img,caption);body.replaceChildren(preview,original);}}if(data.encoded){const box=document.createElement('div');box.className='encoded-attachment';box.innerHTML=`<b>7plus · ${esc(data.encoded.name)}</b><p>${data.encoded.state==='complete'?'Ricostruzione completa · '+data.encoded.total+'/'+data.encoded.total+' parti verificate. Anteprima e download disponibili negli allegati.':data.encoded.state==='incomplete'?'Ricevute '+data.encoded.availableParts.length+'/'+data.encoded.total+' parti. Mancano: '+data.encoded.missingParts.join(', ')+'.'+(data.encoded.damagedParts.length?' Parti danneggiate: '+data.encoded.damagedParts.join(', ')+'.':''):data.encoded.state==='damaged'?'Ricostruzione sospesa: dati incompleti o CRC non validi nelle parti '+data.encoded.damagedParts.join(', ')+'.':'Parte '+data.encoded.part+'/'+data.encoded.total+'. Nessun blocco 7plus riconoscibile nel messaggio.'}</p>${data.encoded.issues?.length?'<p>'+esc(data.encoded.issues.join(' · '))+'</p>':''}${data.encoded.messageIds?.length?'<div class="sevenplus-parts">'+data.encoded.messageIds.map(mid=>'<button class="text-button" data-seven-message="'+mid+'">#'+mid+'</button>').join('')+'</div>':''}<a class="text-button" href="/api/messages/${id}/source" download>Scarica testo originale della parte ↓</a>`;section.append(box);box.querySelectorAll('[data-seven-message]').forEach(b=>b.onclick=()=>{navigate('bbs');readMessage(Number(b.dataset.sevenMessage));});}}catch(e){section.innerHTML=`<span class="muted">${esc(e.message)}</span>`;}}
const attachmentRead=readMessage;readMessage=async function(id){await attachmentRead(id);if(selected===id&&$('#reader .reader-footer'))showAttachments(id,$('#reader'));}; const attachmentRead=readMessage;readMessage=async function(id){await attachmentRead(id);if(selected===id&&$('#reader .reader-footer'))showAttachments(id,$('#reader'));};
const attachmentWlRead=wlRead;wlRead=async function(id){await attachmentWlRead(id);if(wlSelected===id&&$('#wl-reader .reader-footer'))showAttachments(id,$('#wl-reader'));}; const attachmentWlRead=wlRead;wlRead=async function(id){await attachmentWlRead(id);if(wlSelected===id&&$('#wl-reader .reader-footer'))showAttachments(id,$('#wl-reader'));};
document.addEventListener('bpq-languagechange',()=>{$$('.sevenplus-inline p[data-parts]').forEach(caption=>{caption.textContent=caption.dataset.fileName+' · '+BPQI18n.t(caption.dataset.parts+' parti ricostruite · CRC verificati');});});
+10
View File
@@ -0,0 +1,10 @@
.bpq-busy{position:fixed;left:254px;bottom:24px;z-index:900;display:flex;align-items:center;gap:12px;padding:13px 18px;border:1px solid #91bce537;border-radius:16px;background:linear-gradient(135deg,#1a2838ed,#101923f5);box-shadow:0 12px 38px #0005,0 0 24px #8bb8e00a;backdrop-filter:blur(18px);color:#d8e7f6;font-size:12px;font-weight:500;letter-spacing:.025em;pointer-events:none;animation:busy-enter .2s ease-out}
.bpq-busy[hidden]{display:none}
.busy-orbit{display:inline-block;flex:none;width:20px;height:20px;border:2px solid #93bce32b;border-top-color:#b2d8ff;border-right-color:#7ea8cf;border-radius:50%;animation:busy-spin .95s linear infinite}
.busy-dots{display:flex;gap:4px;margin-left:4px}.busy-dots i{width:3px;height:3px;border-radius:50%;background:#9ebfdf;animation:busy-dot 1.4s ease-in-out infinite}.busy-dots i:nth-child(2){animation-delay:.18s}.busy-dots i:nth-child(3){animation-delay:.36s}
.bpq-working:before{content:'';position:fixed;top:0;left:0;width:35%;height:2px;z-index:2000;background:linear-gradient(90deg,transparent,#b4d8fb,transparent);animation:busy-track 1.8s ease-in-out infinite;pointer-events:none}
.forward-loading{padding:24px;border:1px solid #8baac41c;border-radius:14px;background:#121c27;overflow:hidden}.forward-loading-head{display:flex;align-items:center;gap:12px;margin-bottom:24px;color:#a9bfd3;font-size:12px}.forward-skeleton{display:grid;grid-template-columns:1.2fr 1fr .5fr 1.3fr .6fr 1fr;gap:24px;padding:21px 0;border-top:1px solid #91a8be13}.forward-skeleton span{height:10px;border-radius:6px;background:linear-gradient(100deg,#233140 25%,#354b60 45%,#233140 65%);background-size:260% 100%;animation:busy-shimmer 2s ease-in-out infinite}.forward-skeleton span:nth-child(2n){width:70%}
#forwarding[aria-busy=true] #forward-refresh{opacity:.65}#forwarding[aria-busy=true] #forward-refresh:before{content:'';display:inline-block;width:11px;height:11px;border:1.5px solid #9ebfdf40;border-top-color:#c3e0fb;border-radius:50%;margin-right:8px;animation:busy-spin .95s linear infinite}
@keyframes busy-spin{to{transform:rotate(360deg)}}@keyframes busy-dot{0%,80%,100%{opacity:.25}40%{opacity:1}}@keyframes busy-track{from{transform:translateX(-110%)}to{transform:translateX(390%)}}@keyframes busy-shimmer{to{background-position:-160% 0}}@keyframes busy-enter{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:translateY(0)}}
@media(prefers-reduced-motion:reduce){.bpq-busy,.busy-orbit,.busy-dots i,.bpq-working:before,.forward-skeleton span,#forwarding[aria-busy=true] #forward-refresh:before{animation:none}}
@media(max-width:650px){.bpq-busy{left:16px;bottom:16px}.forward-skeleton{gap:12px;grid-template-columns:1fr 1fr 1fr}.forward-skeleton span:nth-child(n+4){display:none}}
+23
View File
@@ -0,0 +1,23 @@
(() => {
let pending=0,showTimer,hideTimer,shownAt=0,indicator;
function mount(){
if(indicator)return;
indicator=document.createElement('div');indicator.className='bpq-busy';indicator.hidden=true;
indicator.setAttribute('role','status');indicator.setAttribute('aria-live','polite');
indicator.innerHTML='<span class="busy-orbit" aria-hidden="true"></span><span>Elaborazione BPQ</span><span class="busy-dots" aria-hidden="true"><i></i><i></i><i></i></span>';
document.body.append(indicator);
}
window.BPQBusy={
start(){
pending++;clearTimeout(hideTimer);
if(pending===1){showTimer=setTimeout(()=>{if(!pending)return;mount();shownAt=Date.now();indicator.hidden=false;document.documentElement.classList.add('bpq-working');},300);}
let finished=false;
return ()=>{
if(finished)return;finished=true;pending=Math.max(0,pending-1);
if(pending)return;
clearTimeout(showTimer);
hideTimer=setTimeout(()=>{if(pending)return;if(indicator)indicator.hidden=true;document.documentElement.classList.remove('bpq-working');},Math.max(0,650-(Date.now()-shownAt)));
};
}
};
})();
+32
View File
@@ -0,0 +1,32 @@
#compose{max-height:94dvh;overflow:hidden;padding:0}
#compose-form{display:flex;flex-direction:column;max-height:calc(94dvh - 2px)}
#compose .dialog-heading{flex:none;margin:0;padding:22px 30px 16px;border-bottom:1px solid #2b3a4d}
#compose .compose-scroll-body{min-height:0;overflow:auto;padding:20px 30px;overscroll-behavior:contain}
#compose footer{flex:none;margin:0;padding:15px 30px;border-top:1px solid #2b3a4d;background:#151d28}
.compose-attachments{border:1px dashed #3d5268;border-radius:10px;padding:14px 16px;margin:18px 0;background:#101b29;transition:border-color .15s,background .15s}
.compose-attachments[hidden]{display:none}
.compose-attachments.dragging{border-color:#a6c8ea;background:#1a3045}
.compose-attachments-heading{display:flex;justify-content:space-between;align-items:center;gap:12px}
.compose-attachments-heading>div{display:flex;gap:12px;align-items:center;font-size:12px}
.compose-attachments-heading small{color:#8ca2b6;font-size:10px;font-weight:400}
.compose-attachments-heading button{min-height:34px;padding:7px 12px;font-size:11px}
.compose-file-list{display:grid;gap:7px;margin-top:10px;max-height:170px;overflow:auto}
.compose-file-list:empty{display:none}
.compose-file{display:flex;align-items:center;gap:11px;padding:8px 10px;background:#172638;border:1px solid #2b4157;border-radius:7px;min-width:0}
.compose-file-icon{display:grid;place-items:center;width:36px;height:36px;flex:none;font-size:20px;color:#9fbdd9}
.compose-file-icon img{max-width:36px;max-height:36px;border-radius:4px;object-fit:contain}
.compose-file>div{min-width:0;flex:1}.compose-file b{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px;color:#e0eaf4}
.compose-file small{display:block;font-size:10px;color:#8ca2b6;margin-top:4px}
.compose-file-remove{border:0;background:transparent;color:#b2c4d4;width:32px;height:32px;border-radius:6px;font-size:20px;cursor:pointer}
.compose-file-remove:hover{background:#48313b;color:#ffb7bd}.compose-file-remove:focus-visible{outline:2px solid #a6c8ea}
#compose .compose-file-help{font-size:10px;line-height:1.5;color:#8ca2b6;margin:10px 0 0}
.mail-paperclip{display:inline-flex;gap:3px;align-items:center;margin-left:9px;color:#9ebfdf;font-size:10px;vertical-align:middle;white-space:nowrap}
.reader-attachment-count{display:inline-flex;align-items:center;gap:4px;border-radius:5px;background:#263b50;color:#c3d8ec;padding:4px 8px;font-size:10px;margin-left:8px}
@media(max-width:600px){.compose-attachments{padding:12px}.compose-attachments-heading>div{gap:6px;flex-wrap:wrap}.compose-file-list{max-height:130px}}
#compose:has(.compose-attachments:not([hidden])) textarea{height:120px;min-height:90px}
#compose:has(.compose-attachments:not([hidden])) .compose-row{grid-template-columns:1fr}
@media(max-width:600px){#compose .dialog-heading{padding:18px 20px 14px}#compose .compose-scroll-body{padding:16px 20px}#compose footer{padding:12px 20px}}
+28
View File
@@ -0,0 +1,28 @@
(() => {
const form=document.querySelector('#compose-form'),panel=document.createElement('section');panel.className='compose-attachments';panel.hidden=true;
panel.innerHTML='<div class="compose-attachments-heading"><div><b>Allegati</b><small id="compose-file-total">0 / 64 KB</small></div><button type="button" class="secondary" id="compose-file-add">+ Allega file</button></div><input id="compose-files" type="file" multiple hidden aria-label="Seleziona allegati"><div id="compose-file-list" class="compose-file-list"></div><p class="compose-file-help">Trascina qui i file oppure selezionali. Massimo 10 file e 64 KB complessivi. Via radio, i file piccoli riducono il tempo di collegamento.</p><p id="compose-file-error" class="error" role="alert"></p>';
form.querySelector('.compose-help').before(panel);
const scrollBody=document.createElement('div');scrollBody.className='compose-scroll-body';const heading=form.querySelector('.dialog-heading'),footer=form.querySelector('footer');
while(heading.nextSibling&&heading.nextSibling!==footer)scrollBody.append(heading.nextSibling);heading.after(scrollBody);
const input=panel.querySelector('input'),list=panel.querySelector('#compose-file-list');let files=[],sending=false;
const total=()=>files.reduce((sum,item)=>sum+item.file.size,0);
function render(){
panel.hidden=!wlCompose;panel.querySelector('#compose-file-total').textContent=files.length+' / 10 · '+size(total())+' / 64 KB';panel.querySelector('#compose-file-add').disabled=sending||files.length>=10;input.disabled=sending;
list.innerHTML=files.map((item,i)=>'<div class="compose-file"><span class="compose-file-icon">'+(item.url?'<img src="'+item.url+'" alt="">':'📎')+'</span><div><b data-no-i18n>'+esc(item.file.name)+'</b><small>'+size(item.file.size)+'</small></div><button type="button" class="compose-file-remove" data-remove-file="'+i+'" aria-label="Rimuovi allegato" '+(sending?'disabled':'')+'>×</button></div>').join('');
}
function add(incoming){
if(sending)return;const candidate=[...incoming],error=panel.querySelector('#compose-file-error');error.textContent='';
if(files.length+candidate.length>10){error.textContent='Massimo 10 allegati per messaggio';return;}
if(total()+candidate.reduce((sum,file)=>sum+file.size,0)>64*1024){error.textContent='Allegati troppo grandi: massimo 64 KB complessivi';return;}
const names=new Set(files.map(item=>item.file.name.toLowerCase()));
for(const file of candidate){if(names.has(file.name.toLowerCase())){error.textContent='Nomi allegati duplicati: rinomina i file';return;}names.add(file.name.toLowerCase());}
files.push(...candidate.map(file=>({file,url:/^image\/(png|jpeg|gif|webp)$/.test(file.type)?URL.createObjectURL(file):null})));render();
}
panel.querySelector('#compose-file-add').onclick=()=>input.click();input.onchange=()=>{add(input.files);input.value='';};
list.onclick=e=>{const button=e.target.closest('[data-remove-file]');if(!button||sending)return;const [removed]=files.splice(Number(button.dataset.removeFile),1);if(removed.url)URL.revokeObjectURL(removed.url);panel.querySelector('#compose-file-error').textContent='';render();};
for(const name of ['dragenter','dragover'])panel.addEventListener(name,e=>{e.preventDefault();if(!sending)panel.classList.add('dragging');});
panel.addEventListener('dragleave',e=>{if(!panel.contains(e.relatedTarget))panel.classList.remove('dragging');});panel.addEventListener('drop',e=>{e.preventDefault();panel.classList.remove('dragging');add(e.dataTransfer.files);});
window.bpqComposeAttachments={count:()=>files.length,reset(){files.forEach(item=>{if(item.url)URL.revokeObjectURL(item.url);});files=[];sending=false;input.value='';panel.querySelector('#compose-file-error').textContent='';render();},form(data){const textBytes=new TextEncoder().encode(String(data.text||'').replace(/\r?\n/g,'\r\n')).length;if(textBytes+total()>80*1024)throw new Error(BPQI18n.t('Testo e allegati superano 80 KB complessivi'));const payload=new FormData();for(const [key,value]of Object.entries(data))payload.set(key,value);for(const item of files)payload.append('files',item.file,item.file.name);return payload;},busy(value){sending=value;render();}};
document.querySelector('#compose').addEventListener('cancel',e=>{if((form.elements.text.value||form.elements.subject.value||files.length)&&!bpqConfirm('Chiudere e scartare questa bozza?'))e.preventDefault();});
document.addEventListener('bpq-languagechange',render);
})();
+46 -1
View File
@@ -1,4 +1,4 @@
:root{color-scheme:dark;--bg:#0b0e13;--ink:#e4e8f0;--muted:#8a94a5;--green:#91b8df;--line:#252b36;--white:#151a23;--lime:#b6cdea}body{background:var(--bg)}.sidebar{background:#10141c;border-right:1px solid #232936;color:#e0e8f4}.sidebar .brand{font-weight:600;letter-spacing:1px}.side-label{color:#69788d}.side-station,.profile{border-color:#262e3b}.side-station small,.profile small{color:#8493a8}.side-frequency span{color:#a9bbd2}.avatar{background:#263c55;color:#b7d4ee}.dot{background:#7baaac}nav button{color:#94a2b7}nav button.active{background:#202e41;color:#b6d4ef}nav button:hover{background:#1a2433}nav b{background:#324a65;color:#c5e0f6}.card,.metrics article,.service,.secondary,.icon-button,input,select,textarea{background:#151a23;border-color:var(--line);color:var(--ink)}.card-header{border-color:var(--line)}.metrics strong{font-weight:500}.metrics i{color:#7088a5}.metrics article{box-shadow:0 4px 20px #0001}.primary{background:#adc9e5;color:#122133}.primary:hover{background:#c5dcf0}.secondary:hover,button.service:hover,.recent-item:hover{background:#1c2431}.tag,.live-badge{background:#233348;color:#aac8e5}.service{border-top-color:var(--line)}.service-icon{background:#242f3d;color:#a2bdd9}.service-call{color:#8c9aaf}.radio-card{background:linear-gradient(130deg,#1c2a3b,#152031);border:1px solid #30445c;color:#e1eaf5}.radio-card .eyebrow{color:#89a8c9}.radio-card .tag{background:#304862;color:#bdd7ef}.radio-details span,.radio-frequency small{color:#8b9fb8}.radio-card footer{border-color:#34465a;color:#a0b8d3}.waveform{background:repeating-linear-gradient(90deg,transparent 0 6px,#6e9bbf 6px 8px,transparent 8px 12px)}.recent-item{border-color:var(--line)}.category-chip{border-color:#304155;background:#202c3b;color:#a6bed6}.activity{border-color:#334255}.activity:before{background:#7c9abd}.tabs{background:#161e2b;border:1px solid #2a3445}.tabs button{color:#8696ad}.tabs button.active{background:#2a3c53;color:#bed8ed;box-shadow:none}.mail-list-heading,.message-item,.reader-header,.reader-footer{border-color:var(--line)}.message-item{background:#151a23;color:var(--ink)}.message-item:hover{background:#1c2635}.message-item.selected{background:#233349;border-color:#96bada}.message-bottom span:first-child{color:#9bbbd9}.reader-empty{color:#7f8ca0}.reader-empty>span,.reader-empty h2{color:#819bb8}.reader-body{color:#c5cfde}.routing-trace{border-color:#2c3a4d;background:#111822;color:#8397b0}.node{background:#19212e;border-color:#2b3544}th{background:#111722;color:#94a2b8}td,th{border-color:var(--line)}dialog{background:#161c26;border-color:#344056;color:var(--ink)}dialog::backdrop{background:#05080cbd}.notice{background:#2c241a;border-color:#61502e;color:#d9bf8e}.error{color:#e29a91}#toast{background:#223447;color:#dfedfa}.login-art{background:linear-gradient(135deg,#152338,#10161f)}.login-art .eyebrow{color:#7ea2c8}.login-art em{color:#afcbe7}.login-art p{color:#8396b0}.signal-art i{border-color:#304a68}.signal-art b{color:#a8c5e4}.topbar{background:#0d1118}.page-heading h1{font-size:29px;letter-spacing:-.7px}.page-heading .eyebrow,.page-heading>div>p{display:none}.page-heading{margin-bottom:25px}.page-footer{color:#58667a}.brand>span{color:#748ba9}.text-button{color:#9bbbd9}.reader-header h2{font-weight:500}.notification-stack{position:fixed;bottom:23px;right:24px;display:flex;flex-direction:column;gap:10px;z-index:30;width:min(360px,calc(100vw - 36px))}.arrival-toast{display:flex;gap:13px;align-items:center;padding:17px 18px;background:#1c293b;border:1px solid #3d5877;border-radius:11px;box-shadow:0 12px 35px #0005;animation:slide-in .3s ease;color:#e1edf8;cursor:pointer}.arrival-toast>span{display:grid;place-items:center;width:35px;height:35px;border-radius:9px;background:#314861;color:#b7d5f0;font-size:19px}.arrival-toast strong{font-size:12px;display:block;font-weight:600}.arrival-toast small{font-size:11px;display:block;margin-top:5px;color:#9eb3ca}.arrival-toast button{border:0;background:none;color:#8397b0;margin-left:auto;font-size:18px}.arrival-toast.mail{border-color:#536451}.arrival-toast.mail>span{background:#364d3b;color:#b7d5bc}@keyframes slide-in{from{opacity:0;transform:translateY(15px)}to{opacity:1;transform:translateY(0)}}.sound-toggle{font-size:15px}.sound-toggle.enabled{background:#243f51;border-color:#4b748c;color:#c4e1ef}.chat-heading{display:flex;align-items:center;justify-content:space-between;margin-bottom:22px;gap:14px}.chat-heading h1{font-size:29px;font-weight:500}.chat-heading .chat-actions{display:flex;gap:10px;align-items:center}.chat-layout{display:grid;grid-template-columns:190px minmax(0,1fr) 235px;height:calc(100vh - 200px);min-height:500px;max-height:1000px;border:1px solid #2a3442;border-radius:12px;overflow:hidden;background:#121923}.chat-rooms{background:#111721;border-right:1px solid #273240;padding:20px 14px}.chat-label{display:flex;justify-content:space-between;align-items:center;color:#70839d;font-size:10px;letter-spacing:1.3px;font-weight:600;margin-bottom:13px}.cLine truncated :root{color-scheme:dark;--bg:#0b0e13;--ink:#e4e8f0;--muted:#8a94a5;--green:#91b8df;--line:#252b36;--white:#151a23;--lime:#b6cdea}body{background:var(--bg)}.sidebar{background:#10141c;border-right:1px solid #232936;color:#e0e8f4}.sidebar .brand{font-weight:600;letter-spacing:1px}.side-label{color:#69788d}.side-station,.profile{border-color:#262e3b}.side-station small,.profile small{color:#8493a8}.side-frequency span{color:#a9bbd2}.avatar{background:#263c55;color:#b7d4ee}.dot{background:#7baaac}nav button{color:#94a2b7}nav button.active{background:#202e41;color:#b6d4ef}nav button:hover{background:#1a2433}nav b{background:#324a65;color:#c5e0f6}.card,.metrics article,.service,.secondary,.icon-button,input,select,textarea{background:#151a23;border-color:var(--line);color:var(--ink)}.card-header{border-color:var(--line)}.metrics strong{font-weight:500}.metrics i{color:#7088a5}.metrics article{box-shadow:0 4px 20px #0001}.primary{background:#adc9e5;color:#122133}.primary:hover{background:#c5dcf0}.secondary:hover,button.service:hover,.recent-item:hover{background:#1c2431}.tag,.live-badge{background:#233348;color:#aac8e5}.service{border-top-color:var(--line)}.service-icon{background:#242f3d;color:#a2bdd9}.service-call{color:#8c9aaf}.radio-card{background:linear-gradient(130deg,#1c2a3b,#152031);border:1px solid #30445c;color:#e1eaf5}.radio-card .eyebrow{color:#89a8c9}.radio-card .tag{background:#304862;color:#bdd7ef}.radio-details span,.radio-frequency small{color:#8b9fb8}.radio-card footer{border-color:#34465a;color:#a0b8d3}.waveform{background:repeating-linear-gradient(90deg,transparent 0 6px,#6e9bbf 6px 8px,transparent 8px 12px)}.recent-item{border-color:var(--line)}.category-chip{border-color:#304155;background:#202c3b;color:#a6bed6}.activity{border-color:#334255}.activity:before{background:#7c9abd}.tabs{background:#161e2b;border:1px solid #2a3445}.tabs button{color:#8696ad}.tabs button.active{background:#2a3c53;color:#bed8ed;box-shadow:none}.mail-list-heading,.message-item,.reader-header,.reader-footer{border-color:var(--line)}.message-item{background:#151a23;color:var(--ink)}.message-item:hover{background:#1c2635}.message-item.selected{background:#233349;border-color:#96bada}.message-bottom span:first-child{color:#9bbbd9}.reader-empty{color:#7f8ca0}.reader-empty>span,.reader-empty h2{color:#819bb8}.reader-body{color:#c5cfde}.routing-trace{border-color:#2c3a4d;background:#111822;color:#8397b0}.node{background:#19212e;border-color:#2b3544}th{background:#111722;color:#94a2b8}td,th{border-color:var(--line)}dialog{background:#161c26;border-color:#344056;color:var(--ink)}dialog::backdrop{background:#05080cbd}.notice{background:#2c241a;border-color:#61502e;color:#d9bf8e}.error{color:#e29a91}#toast{background:#223447;color:#dfedfa}.login-art{background:linear-gradient(135deg,#152338,#10161f)}.login-art .eyebrow{color:#7ea2c8}.login-art em{color:#afcbe7}.login-art p{color:#8396b0}.topbar{background:#0d1118}.page-heading h1{font-size:29px;letter-spacing:-.7px}.page-heading .eyebrow,.page-heading>div>p{display:none}.page-heading{margin-bottom:25px}.page-footer{color:#58667a}.brand>span{color:#748ba9}.text-button{color:#9bbbd9}.reader-header h2{font-weight:500}.notification-stack{position:fixed;bottom:23px;right:24px;display:flex;flex-direction:column;gap:10px;z-index:30;width:min(360px,calc(100vw - 36px))}.arrival-toast{display:flex;gap:13px;align-items:center;padding:17px 18px;background:#1c293b;border:1px solid #3d5877;border-radius:11px;box-shadow:0 12px 35px #0005;animation:slide-in .3s ease;color:#e1edf8;cursor:pointer}.arrival-toast>span{display:grid;place-items:center;width:35px;height:35px;border-radius:9px;background:#314861;color:#b7d5f0;font-size:19px}.arrival-toast strong{font-size:12px;display:block;font-weight:600}.arrival-toast small{font-size:11px;display:block;margin-top:5px;color:#9eb3ca}.arrival-toast button{border:0;background:none;color:#8397b0;margin-left:auto;font-size:18px}.arrival-toast.mail{border-color:#536451}.arrival-toast.mail>span{background:#364d3b;color:#b7d5bc}@keyframes slide-in{from{opacity:0;transform:translateY(15px)}to{opacity:1;transform:translateY(0)}}.sound-toggle{font-size:15px}.sound-toggle.enabled{background:#243f51;border-color:#4b748c;color:#c4e1ef}.chat-heading{display:flex;align-items:center;justify-content:space-between;margin-bottom:22px;gap:14px}.chat-heading h1{font-size:29px;font-weight:500}.chat-heading .chat-actions{display:flex;gap:10px;align-items:center}.chat-layout{display:grid;grid-template-columns:190px minmax(0,1fr) 235px;height:calc(100vh - 200px);min-height:500px;max-height:1000px;border:1px solid #2a3442;border-radius:12px;overflow:hidden;background:#121923}.chat-rooms{background:#111721;border-right:1px solid #273240;padding:20px 14px}.chat-label{display:flex;justify-content:space-between;align-items:center;color:#70839d;font-size:10px;letter-spacing:1.3px;font-weight:600;margin-bottom:13px}.chat-label button{background:none;border:0;color:#8fabc8;font-siLine truncated
.mobile-presence{display:none}.chat-layout{position:relative}@media(max-width:900px){.mobile-presence{display:inline-flex}.chat-layout.users-open .chat-users{display:block;position:absolute;right:0;top:0;bottom:0;width:235px;z-index:5;box-shadow:-15px 0 30px #0004}} .mobile-presence{display:none}.chat-layout{position:relative}@media(max-width:900px){.mobile-presence{display:inline-flex}.chat-layout.users-open .chat-users{display:block;position:absolute;right:0;top:0;bottom:0;width:235px;z-index:5;box-shadow:-15px 0 30px #0004}}
.wl-account{color:#8095af;font:12px Consolas,monospace;margin-top:8px}.wl-status{display:flex;gap:18px;padding:13px 18px;border:1px solid #29394b;background:#121d2a;border-radius:9px;font-size:11px;color:#8195ae;margin-bottom:22px}.wl-status>span:last-child{margin-left:auto}.wl-state.complete{color:#a0c4ae}.wl-state.running{color:#b6cce5}.wl-state.error{color:#d3948a}.danger{border:1px solid #6a4241;background:#322121;color:#e8afaa;border-radius:7px;padding:10px 15px;cursor:pointer;font-size:12px}.danger:hover{background:#4a2a2a}.delete-subject{margin-top:18px;color:#c2cddd}.delete-note{font-size:12px;color:#8191a6;margin-top:15px}@media(max-width:600px){.wl-status{flex-wrap:wrap;gap:10px}.wl-status>span:last-child{margin-left:0}} .wl-account{color:#8095af;font:12px Consolas,monospace;margin-top:8px}.wl-status{display:flex;gap:18px;padding:13px 18px;border:1px solid #29394b;background:#121d2a;border-radius:9px;font-size:11px;color:#8195ae;margin-bottom:22px}.wl-status>span:last-child{margin-left:auto}.wl-state.complete{color:#a0c4ae}.wl-state.running{color:#b6cce5}.wl-state.error{color:#d3948a}.danger{border:1px solid #6a4241;background:#322121;color:#e8afaa;border-radius:7px;padding:10px 15px;cursor:pointer;font-size:12px}.danger:hover{background:#4a2a2a}.delete-subject{margin-top:18px;color:#c2cddd}.delete-note{font-size:12px;color:#8191a6;margin-top:15px}@media(max-width:600px){.wl-status{flex-wrap:wrap;gap:10px}.wl-status>span:last-child{margin-left:0}}
.message-attachments{padding:20px 25px;border-top:1px solid #283647}.message-attachments h3{font-size:12px;color:#a5bdd5;margin:0 0 14px}.attachment-row{display:flex;align-items:center;gap:12px;border:1px solid #31445b;border-radius:8px;padding:12px;margin-top:9px;background:#142031}.attachment-icon{font-size:14px;color:#88accd}.attachment-row>div{flex:1;min-width:0}.attachment-row b{display:block;font-size:11px;overflow-wrap:anywhere}.attachment-row small{display:block;font-size:10px;color:#7890aa;margin-top:5px}.attachment-row .secondary{font-size:10px;padding:8px 10px;text-decoration:none}.encoded-attachment{padding:16px;background:#1c2532;border:1px solid #354357;border-radius:8px;font-size:11px}.encoded-attachment p{font-size:11px;color:#8fa3bd;margin:8px 0 12px}.encoded-attachment a{text-decoration:none}.attachment-dialog{width:min(1000px,94vw);max-height:92vh}.attachment-dialog .dialog-heading{margin-bottom:15px}.attachment-dialog h2{font-size:17px;overflow-wrap:anywhere}#attachment-preview{max-height:68vh;overflow:auto;min-height:80px;text-align:center}#attachment-preview img{max-width:100%;max-height:65vh;object-fit:contain;border-radius:8px}#attachment-preview iframe{width:100%;height:65vh;border:1px solid #354357;border-radius:7px;background:#fff}#attachment-preview pre{white-space:pre-wrap;overflow-wrap:anywhere;text-align:left;font:12px/1.8 Consolas,monospace;color:#c4d2e2}.attachment-dialog .primary{text-decoration:none}@media(max-width:600px){.attachment-row{flex-wrap:wrap}.attachment-row>div{min-width:70%}.attachment-row .secondary{flex:1}} .message-attachments{padding:20px 25px;border-top:1px solid #283647}.message-attachments h3{font-size:12px;color:#a5bdd5;margin:0 0 14px}.attachment-row{display:flex;align-items:center;gap:12px;border:1px solid #31445b;border-radius:8px;padding:12px;margin-top:9px;background:#142031}.attachment-icon{font-size:14px;color:#88accd}.attachment-row>div{flex:1;min-width:0}.attachment-row b{display:block;font-size:11px;overflow-wrap:anywhere}.attachment-row small{display:block;font-size:10px;color:#7890aa;margin-top:5px}.attachment-row .secondary{font-size:10px;padding:8px 10px;text-decoration:none}.encoded-attachment{padding:16px;background:#1c2532;border:1px solid #354357;border-radius:8px;font-size:11px}.encoded-attachment p{font-size:11px;color:#8fa3bd;margin:8px 0 12px}.encoded-attachment a{text-decoration:none}.attachment-dialog{width:min(1000px,94vw);max-height:92vh}.attachment-dialog .dialog-heading{margin-bottom:15px}.attachment-dialog h2{font-size:17px;overflow-wrap:anywhere}#attachment-preview{max-height:68vh;overflow:auto;min-height:80px;text-align:center}#attachment-preview img{max-width:100%;max-height:65vh;object-fit:contain;border-radius:8px}#attachment-preview iframe{width:100%;height:65vh;border:1px solid #354357;border-radius:7px;background:#fff}#attachment-preview pre{white-space:pre-wrap;overflow-wrap:anywhere;text-align:left;font:12px/1.8 Consolas,monospace;color:#c4d2e2}.attachment-dialog .primary{text-decoration:none}@media(max-width:600px){.attachment-row{flex-wrap:wrap}.attachment-row>div{min-width:70%}.attachment-row .secondary{flex:1}}
@@ -72,3 +72,48 @@ body:has(#chat:not([hidden])) .topbar{height:64px}
@media(max-width:600px){#bbs,#winlink{height:auto;min-height:calc(100dvh - 175px);padding:20px 14px}#winlink .chat-heading{flex-wrap:wrap;gap:12px}#winlink .chat-actions{display:flex;gap:8px}.mail-toolbar .tabs{width:100%;flex-wrap:nowrap}.mail-layout .mail-list{max-height:none}#bbs .mail-layout,#winlink .mail-layout{flex:none;grid-template-rows:260px minmax(330px,auto);gap:12px}.mail-columns{display:none}.message-item.mail-row{grid-template-columns:12px minmax(0,1fr) 110px;grid-template-rows:auto auto;gap:4px 9px;padding:11px 12px;min-height:62px}.message-item.mail-row.selected{padding-left:12px}.mail-indicator{grid-column:1;grid-row:1 / 3;align-self:start;margin-top:3px}.mail-from{grid-column:2;grid-row:1}.mail-date{grid-column:3;grid-row:1;font-size:9px;text-align:right}.mail-subject{grid-column:2 / 4;grid-row:2;font-size:12px}.mail-layout .reader-header{padding:14px 16px}.mail-layout .reader-header h2{font-size:17px}.mail-layout .reader-body{flex:none;min-height:150px;max-height:50dvh;padding:16px;font-size:12px}.mail-layout .reader-footer{padding:9px 16px}.mail-layout .reader-meta{gap:7px 14px;font-size:10px}.mail-layout .message-attachments{padding:12px 16px;max-height:170px}} @media(max-width:600px){#bbs,#winlink{height:auto;min-height:calc(100dvh - 175px);padding:20px 14px}#winlink .chat-heading{flex-wrap:wrap;gap:12px}#winlink .chat-actions{display:flex;gap:8px}.mail-toolbar .tabs{width:100%;flex-wrap:nowrap}.mail-layout .mail-list{max-height:none}#bbs .mail-layout,#winlink .mail-layout{flex:none;grid-template-rows:260px minmax(330px,auto);gap:12px}.mail-columns{display:none}.message-item.mail-row{grid-template-columns:12px minmax(0,1fr) 110px;grid-template-rows:auto auto;gap:4px 9px;padding:11px 12px;min-height:62px}.message-item.mail-row.selected{padding-left:12px}.mail-indicator{grid-column:1;grid-row:1 / 3;align-self:start;margin-top:3px}.mail-from{grid-column:2;grid-row:1}.mail-date{grid-column:3;grid-row:1;font-size:9px;text-align:right}.mail-subject{grid-column:2 / 4;grid-row:2;font-size:12px}.mail-layout .reader-header{padding:14px 16px}.mail-layout .reader-header h2{font-size:17px}.mail-layout .reader-body{flex:none;min-height:150px;max-height:50dvh;padding:16px;font-size:12px}.mail-layout .reader-footer{padding:9px 16px}.mail-layout .reader-meta{gap:7px 14px;font-size:10px}.mail-layout .message-attachments{padding:12px 16px;max-height:170px}}
.mail-layout .mail-list-heading{gap:16px}.mail-layout .mail-list-heading>span{white-space:nowrap}.mail-layout .mail-list-heading .mail-timezone{margin-left:auto} .mail-layout .mail-list-heading{gap:16px}.mail-layout .mail-list-heading>span{white-space:nowrap}.mail-layout .mail-list-heading .mail-timezone{margin-left:auto}
.notification-stack{right:24px;bottom:24px;width:460px;max-width:calc(100vw - 32px);gap:14px;max-height:calc(100dvh - 40px);overflow-y:auto}
.arrival-toast{width:100%;padding:20px;gap:16px;min-height:100px;box-sizing:border-box;border-radius:15px;box-shadow:0 16px 48px #0008;border:1px solid #496481}
.arrival-toast>span{font-size:28px;align-self:center}
.arrival-toast>div{min-width:0;flex:1}.arrival-toast strong{font-size:16px;line-height:1.4}.arrival-toast small{font-size:14px;line-height:1.55;margin-top:6px;overflow-wrap:anywhere}
.arrival-toast>button{width:32px;height:32px;min-width:32px;font-size:24px;align-self:flex-start}
@media(max-width:600px){.notification-stack{right:16px;bottom:16px}.arrival-toast{padding:16px;gap:12px}.arrival-toast strong{font-size:15px}.arrival-toast small{font-size:13px}}
.sevenplus-inline{white-space:normal;text-align:center;padding:16px;border:1px solid #38546b;border-radius:12px;background:#102335;margin-bottom:14px}.sevenplus-inline img{display:block;max-width:100%;width:auto;max-height:280px;object-fit:contain;margin:auto;cursor:zoom-in}.sevenplus-inline p{font-size:11px;color:#97b5cc;margin:12px 0 0}.sevenplus-original>summary{cursor:pointer;color:#88a8c4;font-size:11px;white-space:normal;padding:10px 0}.sevenplus-parts{display:flex;flex-wrap:wrap;gap:5px;margin:10px 0}.sevenplus-parts button{font-size:10px;padding:4px 7px}
.reader:has(.sevenplus-inline){display:block;overflow:auto}.reader:has(.sevenplus-inline) .reader-body{overflow:visible;max-height:none}.reader:has(.sevenplus-inline) .message-attachments{max-height:none;overflow:visible}
/* Shared rhythm for operational pages. */
:root{--panel-gap:16px;--control-height:40px;--panel-radius:12px;--text-secondary:#9bacbf}
html{scrollbar-gutter:stable}
#shell .sidebar{padding:24px 18px 20px}
#shell .sidebar .brand{margin-bottom:26px;font-size:21px;letter-spacing:.3px}
#shell .side-label{margin-bottom:12px;letter-spacing:1.5px}
#shell nav button{min-height:42px;padding:10px 12px;margin-bottom:3px;font-size:13px;line-height:1.35;gap:10px}
#shell .side-station{padding:16px 10px;font-size:12px;line-height:1.6}
#shell .profile{padding-top:16px}
#shell .topbar{padding-inline:28px}
#shell .page:not(#home){padding:24px 28px;max-width:none}
#shell .page :is(.page-heading,.journal-heading,.forward-heading,.chat-heading,.monitor-heading,.terminal-heading){gap:16px;margin:0 0 20px;min-height:40px;align-items:center}
#shell .page :is(.page-heading,.journal-heading,.forward-heading,.chat-heading,.monitor-heading,.terminal-heading) h1{font:600 26px/1.25 'Segoe UI',sans-serif;letter-spacing:-.5px;margin:0}
#shell :is(.journal-heading,.forward-heading,.terminal-heading) p{font-size:12px;line-height:1.6;margin:6px 0 0;color:var(--text-secondary)}
#shell .page:not(#home) :is(.primary,.secondary){min-height:var(--control-height);padding:9px 14px;border-radius:8px;font-size:12px;line-height:1.5}
#shell .page :is(.mail-toolbar,.journal-filters,.map-toolbar,.aprs-activity-toolbar) :is(input,select){height:var(--control-height);border-radius:8px;font-size:12px;padding:8px 12px}
#shell :is(input,select,textarea):focus-visible{border-color:#8fb8de;box-shadow:0 0 0 3px #8fb8de20}
#shell :is(button,a,summary):focus-visible{outline:2px solid #a1c9ec;outline-offset:3px}
#shell .page :is(.journal-kpis,.forward-summary,.aprs-activity-kpis){gap:var(--panel-gap);margin-bottom:20px}
#shell .page :is(.journal-kpis article,.forward-summary>div,.aprs-activity-kpis article){padding:16px 18px;border-radius:var(--panel-radius);background:linear-gradient(135deg,#192433,#121923);border:1px solid #293c52;min-width:0}
#shell .page :is(.journal-kpis,.forward-summary,.aprs-activity-kpis) span{font-size:12px;color:var(--text-secondary)}
#shell .page :is(.journal-kpis,.forward-summary,.aprs-activity-kpis) strong{display:block;font:500 26px/1.25 Consolas,monospace;font-variant-numeric:tabular-nums;color:#d5e5f4;margin-top:8px;overflow-wrap:anywhere}
.data-notes{margin:16px 0 0;padding:12px 16px;border:1px solid #29384a;border-radius:9px;background:#111923;color:var(--text-secondary);font:12px/1.65 'Segoe UI',sans-serif;overflow-wrap:anywhere}
.data-notes>summary{cursor:pointer;width:fit-content;color:#a9bfd6;font-size:12px;user-select:none}
.data-notes[open]>summary{margin-bottom:10px}
.data-notes p,.data-notes .journal-source,.data-notes .forward-note{font-size:12px;margin:8px 0 0;line-height:1.7;color:var(--text-secondary)}
.data-notes>div{white-space:pre-line}
.journal-table-scroll,.journal-detail,.map-info,#aprs-received-stations,.aprs-traffic-scroll,.reader-body{scrollbar-gutter:stable;overscroll-behavior:contain}
@media(min-width:601px) and (max-height:760px){#shell .sidebar{padding-top:20px}#shell .sidebar .brand{margin-bottom:18px}#shell nav button{min-height:38px;padding-block:8px}#shell .side-station{padding-block:12px}}
@media(max-width:700px){#shell .page:not(#home){padding:20px 16px}#shell .topbar{padding-inline:16px}#shell .page :is(.page-heading,.journal-heading,.forward-heading,.chat-heading,.monitor-heading,.terminal-heading){flex-wrap:wrap;gap:12px}#shell .page :is(.page-heading,.journal-heading,.forward-heading,.chat-heading,.monitor-heading,.terminal-heading) h1{font-size:23px}#shell .page :is(.journal-kpis,.forward-summary,.aprs-activity-kpis){gap:10px}#shell .page :is(.journal-kpis article,.forward-summary>div,.aprs-activity-kpis article){padding:14px}}
@media(max-width:600px){#shell .sidebar{padding:16px}#shell .sidebar .brand{margin:0}#shell nav button{margin:0;min-height:38px;font-size:12px;padding:8px 10px}}
@media(prefers-reduced-motion:reduce){.arrival-toast{animation:none}.chat-messages{scroll-behavior:auto}}
.reader-reply-actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.reader-footer:has(.reader-reply-actions){gap:12px;flex-wrap:wrap}.reader-footer .reader-reply-actions button{white-space:nowrap}@media(max-width:600px){.reader-footer .reader-reply-actions{flex:1}.reader-footer .reader-reply-actions button{flex:1}}
+6
View File
@@ -0,0 +1,6 @@
.section-detached-away>.detached-placeholder{display:flex;flex:1;min-height:360px;align-items:center;justify-content:center;flex-direction:column;text-align:center;padding:48px 24px;gap:18px;border:1px dashed #3d5368;border-radius:16px;background:radial-gradient(ellipse at top,#233b4c50,transparent 65%)}
.section-detached-away>:not(.detached-placeholder){display:none!important}.section-detached-away>.detached-placeholder[hidden]{display:none!important}.detached-placeholder-icon{display:grid;place-items:center;width:62px;height:62px;background:#8fb5cf10;border:1px solid #8fb5cf35;border-radius:18px;font-size:30px;color:#9fc9e4}.detached-placeholder h2{font-size:24px;letter-spacing:-.4px}.detached-placeholder p{color:#8fa7ba;max-width:420px;line-height:1.7}.detached-placeholder>div{display:flex;gap:10px;flex-wrap:wrap;justify-content:center;margin-top:6px}.detach-button{white-space:nowrap}
html[data-detached-view] #shell>.sidebar,html[data-detached-view] .topbar,html[data-detached-view] #notice{display:none!important}html[data-detached-view] #shell>main{margin:0;padding:0;width:100%;max-width:none}html[data-detached-view] #shell .page{height:100dvh;max-width:none;min-height:0;padding:20px}html[data-detached-view=chat] #chat{height:100dvh}html[data-detached-view=monitor] #monitor{height:100dvh}html[data-detached-view=aprs] #aprs{height:auto;min-height:100dvh;padding:20px}html[data-detached-view=aprs] #aprs-station-map{height:clamp(340px,calc(100dvh - 330px),680px)}html[data-detached-view=aprs] .aprs-stations-card{height:calc(clamp(340px,calc(100dvh - 330px),680px) + 112px)}
@media(max-width:650px){html[data-detached-view] #shell .page{padding:12px}.detached-placeholder>div{width:100%}.detached-placeholder>div button{flex:1}.chat-actions,.monitor-heading>div{flex-wrap:wrap}}
.detached-returned-note{min-height:100dvh;display:flex;align-items:center;justify-content:center;flex-direction:column;gap:20px;text-align:center;padding:30px;color:#cedce8}.detached-returned-note p{color:#8fa7ba}
+96
View File
@@ -0,0 +1,96 @@
/* Window ownership is UI metadata only; authentication stays in the HttpOnly cookie. */
(()=>{
const labels={terminal:'Terminale',aprs:'APRS',monitor:'Monitor',chat:'Chat'},params=new URLSearchParams(location.search);
const requested=location.pathname==='/terminal-window'?'terminal':params.get('detached');
const view=Object.hasOwn(labels,requested)?requested:null;
const uuid=()=>globalThis.crypto?.randomUUID?.()||'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,c=>{const n=Math.floor(Math.random()*16);return(c==='x'?n:(n&3)|8).toString(16);});
const mounted=new WeakSet();
const owner=params.get('window')||uuid(),refs=new Map(),ready=new Set(),ttl=120000;
const key=id=>'bpq-detached:'+id,commandKey='bpq-detached-command';
const target=id=>'bpq-console-'+id;
const read=id=>{try{const value=JSON.parse(localStorage.getItem(key(id)));return value&&typeof value.owner==='string'&&Number.isFinite(value.at)?value:null;}catch{return null;}};
const write=(id,value)=>{try{value?localStorage.setItem(key(id),JSON.stringify(value)):localStorage.removeItem(key(id));}catch{}};
let initialized=false,authenticated=false,released=false,domReady=document.readyState==='complete';
if(view){document.documentElement.dataset.detachedView=view;window.name=target(view);}
function isAway(id){
if(view===id)return false;
const ref=refs.get(id);
if(ref){if(ref.closed){refs.delete(id);ready.delete(id);write(id,null);return false;}if(ready.has(id))return true;}
const record=read(id);return !!record&&Date.now()-record.at<ttl;
}
function shouldPoll(id){return (!view||!released&&view===id)&&!isAway(id);}
function release(){if(!view)return;released=true;const record=read(view);if(record?.owner===owner)write(view,null);}
function claim(){if(!view||!authenticated||released)return;write(view,{owner,at:Date.now()});}
function tell(id,action){try{localStorage.setItem(commandKey,JSON.stringify({id,action,at:Date.now(),nonce:uuid()}));}catch{}}
function focus(id){const ref=refs.get(id);if(ref&&!ref.closed){ref.focus();return;}tell(id,'focus');const popup=window.open('',target(id),'popup=yes,width=1180,height=820,resizable=yes,scrollbars=yes');if(popup)popup.focus();}
function closeView(){
release();const main=document.querySelector('main');if(main)main.hidden=true;
const note=document.createElement('section');note.className='detached-returned-note';
note.innerHTML='<span class="detached-placeholder-icon" aria-hidden="true">↙</span><h2>Sezione riportata nel pannello</h2><p>Puoi chiudere questa finestra.</p>';
document.body.append(note);window.close();
}
function dock(id){
if(view===id){
try{if(window.opener&&!window.opener.closed){window.opener.location.hash='#'+id;window.opener.focus();}}catch{}
closeView();return;
}
tell(id,'dock');const ref=refs.get(id);if(ref&&!ref.closed)ref.close();refs.delete(id);ready.delete(id);write(id,null);refresh();
if(typeof navigate==='function')navigate(id);
}
function open(id){
if(!Object.hasOwn(labels,id))return;
if(isAway(id)){focus(id);return;}
const nonce=uuid(),url=id==='terminal'?'/terminal-window?window='+nonce:'/?detached='+id+'&window='+nonce+'#'+id;
const popup=window.open(url,target(id),'popup=yes,width=1180,height=820,resizable=yes,scrollbars=yes');
if(!popup){if(typeof toast==='function')toast(BPQI18n.t('Consenti le finestre popup per aprire la sezione separata.'));return;}
refs.set(id,popup);popup.focus();
}
function refresh(){
if(!initialized)return;
for(const id of Object.keys(labels)){
const section=document.getElementById(id);if(!section)continue;
const away=isAway(id);section.classList.toggle('section-detached-away',away);
const placeholder=section.querySelector('.detached-placeholder');if(placeholder)placeholder.hidden=!away;
if(read(id)&&refs.has(id))ready.add(id);
}
}
function setup(){
if(!domReady)return;const first=!initialized;initialized=true;
for(const [id,label]of Object.entries(labels)){
const section=document.getElementById(id);if(!section||mounted.has(section))continue;
const heading=section.querySelector('.terminal-actions,.monitor-heading>div,.chat-actions,.page-heading');
if(!heading)continue;mounted.add(section);
if(view===id&&heading){
const fullscreen=document.createElement('button');fullscreen.type='button';fullscreen.className='secondary detach-button';
const update=()=>{const active=!!document.fullscreenElement;fullscreen.textContent=(active?'⊡ ':'⛶ ')+BPQI18n.t(active?'Torna alla finestra':'Schermo intero');fullscreen.setAttribute('aria-pressed',String(active));};
fullscreen.onclick=async()=>{try{if(document.fullscreenElement)await document.exitFullscreen();else await document.documentElement.requestFullscreen();}catch{if(typeof toast==='function')toast(BPQI18n.t('Schermo intero non disponibile in questo browser. Prova F11.'));}};
document.addEventListener('fullscreenchange',update);update();heading.append(fullscreen);
}
if(id!=='terminal'&&heading){
const button=document.createElement('button');button.type='button';button.className='secondary detach-button';button.dataset.detach=id;
button.textContent=view===id?'↙ Torna al pannello':'↗ Stacca';button.onclick=()=>view===id?dock(id):open(id);heading.append(button);
}
if(!view){
const placeholder=document.createElement('div');placeholder.className='detached-placeholder';placeholder.hidden=true;
placeholder.innerHTML='<span class="detached-placeholder-icon" aria-hidden="true">↗</span><h2></h2><p>Questa sezione è aperta in una finestra separata.</p><div><button type="button" class="primary">Mostra finestra</button><button type="button" class="secondary">Riporta qui</button></div>';
placeholder.querySelector('h2').textContent=label;const buttons=placeholder.querySelectorAll('button');buttons[0].onclick=()=>focus(id);buttons[1].onclick=()=>dock(id);section.append(placeholder);
}
}
if(first&&view&&location.pathname!=='/terminal-window'){
const previous=navigate;navigate=function(){previous(view);};navigate(view);
document.title='BPQ Console · '+labels[view];
}
refresh();
}
window.BPQDetached={view,open,dock,isAway,shouldPoll};
document.addEventListener('DOMContentLoaded',()=>{domReady=true;setup();});
document.addEventListener('station-ready',()=>{authenticated=true;released=false;setup();claim();refresh();if(view){document.title='BPQ Console · '+labels[view];if(location.pathname!=='/terminal-window')navigate(view);}});
document.addEventListener('bpq-detach-auth-lost',()=>{authenticated=false;release();});
window.addEventListener('storage',event=>{
if(event.key===commandKey&&view){try{const cmd=JSON.parse(event.newValue);if(cmd.id===view&&Date.now()-cmd.at<5000){if(cmd.action==='focus')window.focus();else if(cmd.action==='dock')closeView();}}catch{}}
if(event.key?.startsWith('bpq-detached:'))refresh();
});
window.addEventListener('pagehide',release);window.addEventListener('beforeunload',release);
window.addEventListener('pageshow',()=>{if(view&&authenticated){released=false;claim();}});
setInterval(()=>{setup();claim();refresh();},2000);
})();
+11 -9
View File
@@ -2,15 +2,17 @@ import {incoming} from '/notifications.js';
let soundOn=localStorage.getItem('alnode-sound')!=='no',audio=null,chatLastId=0,chatState='offline',chatPollBusy=false; let soundOn=localStorage.getItem('alnode-sound')!=='no',audio=null,chatLastId=0,chatState='offline',chatPollBusy=false;
const soundButton=document.createElement('button');soundButton.id='sound-toggle';soundButton.className='icon-button sound-toggle';soundButton.setAttribute('aria-label','Attiva o disattiva suoni');$('#refresh').before(soundButton); const soundButton=document.createElement('button');soundButton.id='sound-toggle';soundButton.className='icon-button sound-toggle';soundButton.setAttribute('aria-label','Attiva o disattiva suoni');$('#refresh').before(soundButton);
function soundLabel(){soundButton.textContent=soundOn?'♪':'♩';soundButton.classList.toggle('enabled',soundOn);soundButton.title=soundOn?'Suono attivo':'Attiva suono notifiche';soundButton.setAttribute('aria-pressed',String(soundOn))}soundLabel(); function soundLabel(){soundButton.textContent=soundOn?'♪':'♩';soundButton.classList.toggle('enabled',soundOn);soundButton.title=soundOn?'Suono attivo':'Attiva suono notifiche';soundButton.setAttribute('aria-pressed',String(soundOn))}soundLabel();
function prepareAudio(){try{audio??=new (window.AudioContext||window.webkitAudioContext)();audio.resume();}catch{}} async function prepareAudio(){try{audio??=new (window.AudioContext||window.webkitAudioContext)();if(audio.state!=='running')await audio.resume();return audio.state==='running';}catch{return false}}
function chime(){if(!soundOn||!audio||audio.state!=='running')return;const t=audio.currentTime;for(const [offset,freq]of [[0,659.25],[.17,987.77]]){const o=audio.createOscillator(),g=audio.createGain();o.type='sine';o.frequency.value=freq;g.gain.setValueAtTime(0,t+offset);g.gain.linearRampToValueAtTime(.045,t+offset+.025);g.gain.exponentialRampToValueAtTime(.0001,t+offset+.65);o.connect(g);g.connect(audio.destination);o.start(t+offset);o.stop(t+offset+.7)}} async function chime(force=false){if(!soundOn&&!force)return;if(!await prepareAudio()){soundButton.title='Clicca per attivare l’audio';return;}const t=audio.currentTime+.025;const compressor=audio.createDynamicsCompressor();compressor.threshold.value=-8;compressor.knee.value=10;compressor.ratio.value=3;compressor.connect(audio.destination);for(const [offset,freq]of [[0,659.25],[.23,830.61],[.46,987.77]]){const o=audio.createOscillator(),g=audio.createGain();o.type='triangle';o.frequency.value=freq;g.gain.setValueAtTime(0,t+offset);g.gain.linearRampToValueAtTime(.24,t+offset+.02);g.gain.exponentialRampToValueAtTime(.0001,t+offset+.75);o.connect(g);g.connect(compressor);o.start(t+offset);o.stop(t+offset+.8);}setTimeout(()=>compressor.disconnect(),1700)}
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=async()=>{soundOn=!soundOn;localStorage.setItem('alnode-sound',soundOn?'yes':'no');soundLabel();if(soundOn)await chime();};
for(const event of ['pointerdown','keydown'])document.addEventListener(event,()=>{if(soundOn&&audio?.state!=='running')prepareAudio()},{passive:true});
const soundTest=document.createElement('button');soundTest.id='notification-test';soundTest.className='icon-button';soundTest.textContent='♬';soundTest.title='Prova notifica e suono';soundTest.setAttribute('aria-label','Prova notifica e suono');soundButton.after(soundTest);soundTest.onclick=async()=>{soundOn=true;localStorage.setItem('alnode-sound','yes');soundLabel();arrival('mail','Notifica di prova','Audio attivato · avviso per nuova posta o bollettini');await chime(true);soundTest.dataset.audioState=audio?.state||'unavailable';if(audio?.state!=='running')toast('Audio non attivato dal browser: verifica i permessi audio del sito.');};
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 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} 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;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();}}; loadMessages=async function(...args){await oldLoadMessages(...args);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('bpq-message-ids-'+station.call,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&&!document.hidden&&!window.BPQDetached?.view)loadMessages(true)},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>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 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);
@@ -33,17 +35,17 @@ function renderChat(data){
$$('.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-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'}">${esc(({open:'Attivo',idle:'In attesa',connecting:'Connessione…','connect failed':'Connessione fallita',closed:'Chiuso'})[l.state.toLowerCase()]||l.state)}</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===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);} 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(BPQI18n.locale(),{}))}">${new Date(event.at).toLocaleTimeString(BPQI18n.locale(),{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===station.call&&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();}
} }
} }
async function pollChat(){if(!csrf||chatPollBusy)return;chatPollBusy=true;try{renderChat(await api('/chat'))}catch(e){if(page==='chat')toast(e.message)}finally{chatPollBusy=false}} async function pollChat(){if(!csrf||chatPollBusy||window.BPQDetached&&!window.BPQDetached.shouldPoll('chat'))return;chatPollBusy=true;try{renderChat(await api('/chat',{busy:false}))}catch(e){if(page==='chat')toast(e.message)}finally{chatPollBusy=false}}
$('#chat-connect').onclick=async()=>{try{chatLastId=0;chatFollowing=true;chatUnread=0;$('#chat-messages').innerHTML='';renderChat(await api('/chat/connect',{method:'POST',body:'{}'}))}catch(e){toast(e.message)}};$('#chat-disconnect').onclick=async()=>{try{await api('/chat/disconnect',{method:'POST',body:'{}'});pollChat()}catch(e){toast(e.message)}}; $('#chat-connect').onclick=async()=>{try{chatLastId=0;chatFollowing=true;chatUnread=0;$('#chat-messages').innerHTML='';renderChat(await api('/chat/connect',{method:'POST',body:'{}'}))}catch(e){toast(e.message)}};$('#chat-disconnect').onclick=async()=>{try{await api('/chat/disconnect',{method:'POST',body:'{}'});pollChat()}catch(e){toast(e.message)}};
$('#chat-form').onsubmit=async e=>{e.preventDefault();const input=$('#chat-input'),button=$('#chat-send'),text=input.value.trim();if(!text)return;button.disabled=true;try{await api('/chat/send',{method:'POST',body:JSON.stringify({text,to:$('#chat-recipient').value})});input.value='';await pollChat()}catch(err){toast(err.message)}finally{button.disabled=chatState!=='online';input.focus()}}; $('#chat-form').onsubmit=async e=>{e.preventDefault();const input=$('#chat-input'),button=$('#chat-send'),text=input.value.trim();if(!text)return;button.disabled=true;try{await api('/chat/send',{method:'POST',body:JSON.stringify({text,to:$('#chat-recipient').value})});input.value='';await pollChat()}catch(err){toast(err.message)}finally{button.disabled=chatState!=='online';input.focus()}};
$('#new-topic').onclick=()=>topicDialog.showModal();$('#topic-cancel').onclick=()=>topicDialog.close();$('#topic-form').onsubmit=async e=>{e.preventDefault();try{await api('/chat/topic',{method:'POST',body:JSON.stringify({topic:$('#topic-name').value})});topicDialog.close();pollChat()}catch(err){toast(err.message)}}; $('#new-topic').onclick=()=>topicDialog.showModal();$('#topic-cancel').onclick=()=>topicDialog.close();$('#topic-form').onsubmit=async e=>{e.preventDefault();try{await api('/chat/topic',{method:'POST',body:JSON.stringify({topic:$('#topic-name').value})});topicDialog.close();pollChat()}catch(err){toast(err.message)}};
@@ -56,5 +58,5 @@ if(location.hash==='#chat')navigate('chat');
window.addEventListener('DOMContentLoaded',()=>{for(const target of ['#bbs .mail-list-heading','#winlink .mail-list-heading']){const heading=$(target);if(heading){const tag=document.createElement('small');tag.className='mail-timezone';tag.textContent='Timezone: '+mailTimezone();heading.append(tag);}}}); window.addEventListener('DOMContentLoaded',()=>{for(const target of ['#bbs .mail-list-heading','#winlink .mail-list-heading']){const heading=$(target);if(heading){const tag=document.createElement('small');tag.className='mail-timezone';tag.textContent='Timezone: '+mailTimezone();heading.append(tag);}}});
function restoreMailPage(){const target=location.hash.slice(1);if(['home','bbs','winlink','chat','network','monitor'].includes(target)&&page!==target&&document.getElementById(target))navigate(target);} function restoreMailPage(){const target=location.hash.slice(1);if(['home','bbs','winlink','chat','network','monitor','journal','map'].includes(target)&&page!==target&&document.getElementById(target))navigate(target);}
window.addEventListener('DOMContentLoaded',restoreMailPage);window.addEventListener('hashchange',restoreMailPage); window.addEventListener('DOMContentLoaded',restoreMailPage);window.addEventListener('hashchange',restoreMailPage);
+1
View File
@@ -0,0 +1 @@
.forward-heading{display:flex;align-items:center;justify-content:space-between;gap:20px;margin-bottom:24px}.forward-heading h1{font-size:29px;letter-spacing:-.7px;margin:0 0 8px}.forward-heading p,.forward-note{color:var(--muted);font-size:12px;line-height:1.7}.forward-summary{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:24px}.forward-summary>div{border:1px solid var(--line);background:var(--white);border-radius:10px;padding:15px 20px}.forward-summary span{display:block;color:var(--muted);font-size:11px}.forward-summary strong{display:block;font-size:26px;font-weight:500;margin-top:6px}.forward-table-wrap{overflow:auto}.forward-table{width:100%;min-width:900px;border-collapse:collapse;text-align:left}.forward-table>thead>tr>th{padding:14px 10px;font-size:10px;font-weight:500;color:#899bb2;letter-spacing:.35px;white-space:nowrap;background:#111822}.forward-row{cursor:pointer;background:#151c27;transition:background .15s}.forward-row:hover{background:#1b2838}.forward-row.expanded{background:#203249}.forward-row>td{padding:16px 10px;font-size:11px;vertical-align:middle;border-bottom:1px solid #293444;white-space:nowrap}.forward-row>td>small,.forward-toggle small,.forward-feedback{display:block;color:var(--muted);font-size:10px;line-height:1.5;margin-top:5px}.forward-toggle{display:flex;align-items:center;gap:12px;padding:0;border:0;background:none;color:var(--ink);text-align:left;cursor:pointer}.forward-toggle b{font-size:14px;font-weight:600;letter-spacing:.3px}.forward-toggle small{margin-top:4px;font-weight:400}.forward-chevron{font-size:23px;color:#8eabc8;line-height:1;transition:transform .15s}.expanded .forward-chevron{transform:rotate(90deg)}.forward-status{display:inline-block;background:#243346;border:1px solid #34485f;color:#b6cfea;padding:5px 8px;border-radius:5px;font-size:10px;white-space:nowrap}.forward-status.live{background:#153c36;color:#a8e1c7;border-color:#2c6355}.forward-row>.forward-queue{font-size:18px;font-weight:500;font-variant-numeric:tabular-nums}.forward-row .forward-outcome{color:#a2c2bc}.forward-row .forward-outcome.failed{color:#e2a198}.forward-sync-cell>button{font-size:10px;padding:9px 10px;white-space:nowrap}.forward-feedback{white-space:normal;max-width:180px}.forward-detail-row>td{padding:0;border-bottom:1px solid #34465d;background:#101823}.forward-details{padding:24px 28px 28px;border-left:3px solid #7899bc}.forward-detail-grid{display:grid;grid-template-columns:1fr .85fr 1.25fr;gap:30px;white-space:normal}.forward-detail-grid>section{min-width:0}.forward-details h3{font-size:12px;margin:0 0 14px;font-weight:600;color:#c1d4e7}.forward-details dl{font-size:11px;display:grid;gap:5px;margin:0}.forward-details dt{color:var(--muted);margin-top:12px}.forward-details dt:first-child{margin-top:0}.forward-details dd{margin:0;line-height:1.7;overflow-wrap:anywhere}.forward-details code{display:inline-block;background:#253044;color:#b4cde6;padding:0 5px;border-radius:3px;font-size:10px}.forward-details code:empty{display:none}.forward-details p{font-size:11px;line-height:1.7;overflow-wrap:anywhere}.forward-details pre{margin:0 0 24px;padding:14px;background:#0b121c;border:1px solid var(--line);border-radius:6px;color:#9cb2c9;font-size:11px;line-height:1.8;overflow:auto}.forward-table-scroll{overflow:auto}.forward-history table{width:100%;font-size:10px;white-space:nowrap}.forward-history th,.forward-history td{padding:9px 8px}.forward-history small{display:block;margin-top:10px;font-size:10px;color:var(--muted)}#forwarding>.forward-note{margin-top:20px}#forward-error{margin:0 0 20px}@media(max-width:1400px){.forward-detail-grid{grid-template-columns:1fr 1fr}.forward-history{grid-column:1/-1}}@media(max-width:650px){.forward-summary{grid-template-columns:repeat(2,1fr);gap:10px}.forward-summary>div{padding:14px}.forward-heading{align-items:start}.forward-heading h1{font-size:25px}.forward-details{padding:20px}.forward-detail-grid{gap:22px}}
+31
View File
@@ -0,0 +1,31 @@
(() => {
let data=null,loading=false,pending=new Map(),expanded=null;
const nav=document.createElement('button');nav.dataset.page='forwarding';nav.innerHTML='<span>⇄</span> Forwarding';nav.onclick=()=>navigate('forwarding');$('nav [data-page="network"]').before(nav);
const panel=document.createElement('section');panel.id='forwarding';panel.className='page';panel.hidden=true;panel.innerHTML='<div class="forward-heading"><div><h1>Forwarding</h1><p id="forward-updated">Partner e scambi della BBS</p></div><button id="forward-restore" class="secondary" hidden>Ripristina percorso originale</button><button id="forward-refresh" class="secondary">↻ Aggiorna</button></div><div id="forward-summary" class="forward-summary"></div><div id="forward-error" class="notice" hidden></div><div id="forward-partners" class="forward-partners"><div class="forward-loading" role="status"><div class="forward-loading-head"><span class="busy-orbit" aria-hidden="true"></span><span>Connessione a BPQ</span></div><div class="forward-skeleton" aria-hidden="true"><span></span><span></span><span></span><span></span><span></span><span></span></div><div class="forward-skeleton" aria-hidden="true"><span></span><span></span><span></span><span></span><span></span><span></span></div><div class="forward-skeleton" aria-hidden="true"><span></span><span></span><span></span><span></span><span></span><span></span></div><div class="forward-skeleton" aria-hidden="true"><span></span><span></span><span></span><span></span><span></span><span></span></div></div></div><details class="data-notes"><summary>Informazioni sulla programmazione</summary><p class="forward-note">Le fasce mostrano il fuso configurato in BPQ. Il prossimo tentativo è una stima: timer, disponibilità del modem e condizioni di connessione sono gestiti da BPQ. Le regole si modificano nella configurazione BPQ.</p></details>';$('main').append(panel);
const prevNavigate=navigate;navigate=function(next){prevNavigate(next);if(next==='forwarding'){$('#breadcrumb').textContent='Stazione / Forwarding';load();}};
const time=t=>t?new Date(t).toLocaleString(BPQI18n.locale(),{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit',second:'2-digit'}):'Non rilevato';
const interval=n=>!n?'Non impostato':n%3600===0?n/3600+' h':n%60===0?n/60+' min':n+' s';
const state=s=>({complete:'Completato',calling:'Chiamata in corso',connected:'Collegato',failed:'Non riuscito',incomplete:'Sessione interrotta',unknown:'Esito non registrato'}[s]||'In attesa');
const rules=(values,kind)=>!values.length?'Nessuna regola esplicita':values.includes('WW')?(kind==='bulletins'?'Tutte le aree geografiche':'Destinazioni geografiche tramite questo partner'):values.join(', ');
const bands=p=>p.times.length?p.times.map(t=>t.replace(/^(\d{2})(\d{2})-(\d{2})(\d{2})$/,'$1:$2–$3:$4')).join(' · '):'00:00–23:59';
function render(){if(!data)return;$('#forward-restore').hidden=!(data.manualSession?.restoring&&data.manualSession?.error);const focused=document.activeElement,focusPeer=focused.closest?.('[data-forward-row]')?.dataset.forwardRow,focusKind=focused.matches?.('[data-forward-start]')?'[data-forward-start]':focused.matches?.('.forward-toggle')?'.forward-toggle':null;const profiles=[...data.profiles].sort((a,b)=>Number(b.enabled&&b.configured)-Number(a.enabled&&a.configured)||Number(b.transport==='Radio')-Number(a.transport==='Radio')||a.call.localeCompare(b.call)),total=profiles.reduce((a,p)=>a+((p.manualOnly||p.scheduled)?0:p.queued||0),0);$('#forward-summary').innerHTML=[['Percorsi',profiles.length],['Automatici',profiles.filter(p=>p.enabled&&p.configured).length],['Messaggi in coda',total+(profiles.some(p=>p.queued===null)?' + ?':'')],['Sessioni attive',profiles.filter(p=>p.active).length]].map(([label,n])=>'<div><span>'+label+'</span><strong>'+n+'</strong></div>').join('');const errors=[...data.errors,...(data.manualSession?.restoring&&data.manualSession?.error?[data.manualSession.error]:[])];$('#forward-error').hidden=!errors.length;$('#forward-error').textContent=errors.join(' · ');$('#forward-updated').textContent='Aggiornato '+time(data.updatedAt)+' · '+mailTimezone();
$('#forward-partners').innerHTML='<div class="card forward-table-wrap"><table class="forward-table"><thead><tr><th>Partner / percorso</th><th>Stato</th><th>Coda</th><th>Ultimo scambio</th><th>TX / RX</th><th>Programmazione</th><th>Prossimo · stima</th><th>Azioni</th></tr></thead><tbody>'+profiles.map(p=>{
const requested=pending.get(p.call),requestWaiting=requested&&Date.now()-requested<30000,radioReason=p.transport!=='Radio'?'':(data.radio?.txSuspended||data.radio?.portsPaused?.[p.port]||!p.independentRadio&&data.radio?.portSuspended)?'Trasmissioni sospese':!p.independentRadio&&(data.radio?.active||data.radio?.connecting)?'Modem impegnato':'',blocked=p.reservedBy||p.active||requestWaiting||radioReason,last=p.last;
const status=p.reservedBy?'Riservato al percorso VHF':p.active?(p.preparing?'Preparazione radio':state(last?.status)):requestWaiting?'Richiesta inviata':!p.configured?'Non configurato':p.scheduled?'Automatico':p.manualOnly?'Solo manuale':p.enabled?'Automatico':'Disattivato';
const next=p.reservedBy?'Attende fine percorso VHF':p.active?'Sessione in corso':p.scheduled?time(p.nextEstimated):p.manualOnly?'Solo su richiesta':!p.enabled?'Automatico disattivo':!p.configured?'Script assente':p.nextEstimated?time(p.nextEstimated):!p.reverse&&p.queued===0?'In attesa di messaggi':'Timer non disponibile';
const isOpen=expanded===p.call;
return `<tr class="forward-row ${isOpen?'expanded':''}" data-forward-row="${esc(p.call)}" tabindex="0" aria-expanded="${isOpen}"><td><button class="forward-toggle" aria-expanded="${isOpen}" aria-controls="forward-detail-${esc(p.call)}" aria-label="Dettagli ${esc(p.call)}"><span class="forward-chevron" aria-hidden="true">›</span><span><b>${esc(p.label||p.call)}</b><small>${esc(p.transport)}${p.driver?' · '+esc(p.driver):''}</small></span></button></td><td><span class="forward-status ${p.active?'live':!p.configured?'muted':''}">${esc(status)}</span></td><td class="forward-queue">${p.queued??'—'}</td><td>${esc(time(last?.startedAt).replace(/:\d{2}$/,''))}<small class="forward-outcome ${last?.status==='failed'?'failed':''}">${esc(last?state(last.status):'Nessuna sessione recente')}</small></td><td>${last?last.sent+' / '+last.received:'—'}</td><td>${p.manualOnly&&!p.scheduled?'Solo manuale':esc(interval(p.interval))}<small>${(p.manualOnly||p.scheduled)?esc(p.frequency.join(' MHz ')):esc(bands(p))+' · '+(p.timesLocal?'locale BPQ':'UTC')}</small></td><td>${esc(next)}<small>${p.nextEstimated?esc(mailTimezone()):''}</small></td><td class="forward-sync-cell"><button class="secondary" data-forward-start="${esc(p.call)}" ${!p.configured||blocked?'disabled':''}>${p.active?'In corso':requestWaiting?'Richiesta inviata…':p.manualOnly?'Avvia manualmente':'↻ Sincronizza ora'}</button>${radioReason&&!p.active?'<small>'+esc(radioReason)+'</small>':''}<span class="forward-feedback" role="status" data-feedback="${esc(p.call)}"></span></td></tr><tr class="forward-detail-row" ${isOpen?'':'hidden'}><td colspan="8"><div id="forward-detail-${esc(p.call)}" role="region" aria-label="Dettagli ${esc(p.call)}" class="forward-details">${isOpen?details(p):''}</div></td></tr>`;
}).join('')+'</tbody></table>'+(!profiles.length?'<p class="empty">Nessun partner di forwarding configurato in BPQ.</p>':'')+'</div>';
if(focusPeer){const row=$$('#forward-partners [data-forward-row]').find(r=>r.dataset.forwardRow===focusPeer);(focusKind?row?.querySelector(focusKind):row)?.focus({preventScroll:true});}
}
function details(p){return `<div class="forward-detail-grid"><section><h3>Regole di inoltro</h3><dl><dt>Bollettini</dt><dd>${p.personalOnly?'Esclusi: solo posta personale':esc(rules(p.bulletins,'bulletins'))} <code>${esc(p.bulletins.join(', '))}</code></dd><dt>Posta personale e bollettini diretti</dt><dd>${esc(rules(p.personal,'personal'))} <code>${esc(p.personal.join(', '))}</code></dd><dt>Destinatari espliciti · TO</dt><dd>${esc(p.to.join(', ')||'Nessuno')}</dd><dt>Distribuzioni esplicite · AT</dt><dd>${esc(p.at.join(', ')||'Nessuna')}</dd><dt>Richiesta messaggi al partner</dt><dd>${p.reverse?'Attiva · intervallo '+esc(interval(p.reverseInterval)):'Disattiva'}</dd><dt>Invio immediato nuovi messaggi</dt><dd>${p.immediate?'Attivo':'Disattivo'}</dd></dl><p class="forward-note">${(p.manualOnly||p.scheduled)?'Stessa coda e stesse regole del partner '+esc(p.peer)+(p.scheduled?'. Sync automatico gestito dalla console. ':'. Nessun timer automatico per questo percorso. '):''}Le regole geografiche dipendono dagli indirizzi gerarchici e dalle altre rotte BPQ. I messaggi locali e quelli già ricevuti dal partner seguono le regole di esclusione di BPQ.</p></section><section><h3>Percorso di connessione${p.port?' · porta '+p.port:''}</h3><pre>${esc(p.script.join('\n')||'Nessuno script configurato')}</pre><h3>Indirizzo gerarchico</h3><p>${esc(p.ha||'Non impostato')}</p>${p.frequency?'<p>Dial: '+esc(p.frequency.join(' MHz '))+'</p>':''}</section><section class="forward-history">${data.manualSession?.channel?.id===p.call&&!data.manualSession.restoring&&data.manualSession.error?'<p class="forward-note">'+esc(time(data.manualSession.endedAt||data.manualSession.startedAt))+' \u00b7 '+esc(BPQI18n.t(data.manualSession.error))+'</p>':''}<h3>Ultimi scambi · ${esc(mailTimezone())}</h3><div class="forward-table-scroll"><table><thead><tr><th>Data e ora</th><th>Direzione</th><th>TX / RX</th><th>Esito</th></tr></thead><tbody>${p.history.map(s=>'<tr><td>'+esc(time(s.startedAt))+'</td><td>'+(s.direction==='incoming'?'Ingresso':'Uscita')+'</td><td>'+s.sent+' / '+s.received+'</td><td title="'+esc(s.error||'')+'">'+esc(state(s.status))+'</td></tr>').join('')||'<tr><td colspan="4">Nessuno scambio nei sette file di log più recenti.</td></tr>'}</tbody></table></div><small>TX / RX: messaggi registrati nei log della sessione, non byte.</small></section></div>`;}
async function load(background=false){if(!csrf||!station.features.bbs||loading)return;loading=true;panel.setAttribute('aria-busy','true');$('#forward-refresh').disabled=true;try{data=await api('/forwarding',{busy:!background});render();}catch(e){$('#forward-error').hidden=false;$('#forward-error').textContent=e.message;if(!data)$('#forward-partners').innerHTML='';}finally{loading=false;panel.setAttribute('aria-busy','false');$('#forward-refresh').disabled=false;}}
$('#forward-refresh').onclick=()=>load();
$('#forward-restore').onclick=async()=>{try{await api('/forwarding/manual/restore',{method:'POST',body:'{}'});toast('Percorso originale ripristinato');await load();}catch(e){toast(e.message);}};
panel.addEventListener('keydown',e=>{if(e.target.matches('[data-forward-row]')&&['Enter',' '].includes(e.key)){e.preventDefault();e.target.click();}});
panel.addEventListener('click',async e=>{const b=e.target.closest('[data-forward-start]');if(!b){const row=e.target.closest('[data-forward-row]');if(row){expanded=expanded===row.dataset.forwardRow?null:row.dataset.forwardRow;render();}return;}if(b.disabled)return;const peer=b.dataset.forwardStart;b.disabled=true;b.textContent='Richiesta…';try{await window.bpqSync.start({kind:'forwarding',peer});pending.set(peer,Date.now());await load();}catch(err){toast(err.message);const feedback=[...panel.querySelectorAll('[data-feedback]')].find(n=>n.dataset.feedback===peer);if(feedback)feedback.textContent=err.message;b.disabled=false;b.textContent='↻ Sincronizza ora';}});
document.addEventListener('bpq-languagechange',()=>{if(data)render();});
document.addEventListener('station-ready',()=>{data=null;pending.clear();expanded=null;nav.hidden=!station.features.bbs;if(page==='forwarding'){if(station.features.bbs)load();else navigate('home');}});
document.addEventListener('DOMContentLoaded',()=>{if(location.hash==='#forwarding')navigate('forwarding');});
setInterval(()=>{if(csrf&&!document.hidden&&page==='forwarding')load(true);},6000);
})();
+16
View File
@@ -0,0 +1,16 @@
.language-switch{position:relative;display:inline-flex;align-items:center;isolation:isolate;flex:none;width:116px;height:36px;padding:3px;border:1px solid #34434e;border-radius:20px;background:#0c141c;color:#82939f;cursor:pointer;box-shadow:inset 0 1px 5px #0003;vertical-align:middle}
.language-switch .language-thumb{position:absolute;z-index:-1;left:3px;top:3px;bottom:3px;width:53px;border-radius:16px;background:linear-gradient(145deg,#334c60,#253d50);box-shadow:0 1px 4px #0005,inset 0 1px #ffffff12;transition:transform .2s ease}
.language-switch[aria-checked="true"] .language-thumb{transform:translateX(55px)}
.language-choice{width:50%;display:inline-flex;align-items:center;justify-content:center;gap:6px;font:600 10px/1 system-ui,sans-serif;letter-spacing:.04em;opacity:.55;transition:opacity .2s ease,color .2s ease}
.language-switch[aria-checked="false"] .language-choice:nth-child(2),.language-switch[aria-checked="true"] .language-choice:nth-child(3){opacity:1;color:#f0f6fc}
.language-flag{width:20px;height:14px;display:block;border-radius:2px;overflow:hidden;box-shadow:0 0 0 1px #ffffff20}
.language-switch:hover{border-color:#647e90}
.language-switch:focus-visible{outline:2px solid #9acac4;outline-offset:4px}
.language-login{display:flex;margin:24px auto 0}
.language-toolbar{margin-right:4px}
.login-byline{font:500 12px/1.5 system-ui,sans-serif;letter-spacing:.12em;color:#899eae}
.login-art .login-byline{margin-top:12px;font-size:14px;color:#a6b9c9}
.login-card .login-brand{margin-bottom:40px}
.login-card .login-brand .brand{margin-bottom:5px}
@media(prefers-reduced-motion:reduce){.language-switch .language-thumb,.language-choice{transition:none}}
@media(max-width:700px){.language-toolbar{width:100px;margin-right:0}.language-toolbar .language-thumb{width:45px}.language-toolbar[aria-checked="true"] .language-thumb{transform:translateX(47px)}.language-choice{gap:4px}.language-flag{width:18px;height:12px}.topbar>div{gap:6px}}
+920
View File
@@ -0,0 +1,920 @@
/* UI translations only. Message bodies, subjects, terminal and radio traffic stay original. */
(() => {
'use strict';
const entries=`
Dal|Since
Dettagli del registro|Log details
Zona locale · 30 km|Local area · 30 km
Inquadra il gruppo più denso, ignorando le stazioni isolate|Fit the densest group, excluding isolated stations
Inquadra un raggio di 30 km dalla tua stazione|Show a 30 km radius around your station
Posizione della tua stazione non disponibile|Your station position is unavailable
Questa sezione è aperta in una finestra separata.|This section is open in a separate window.
Sezione riportata nel pannello|Section returned to the dashboard
Puoi chiudere questa finestra.|You can close this window.
Mostra finestra|Show window
Riporta qui|Bring back here
Consenti le finestre popup per aprire la sezione separata.|Allow popups to open the detached section.
Fosfori|Phosphor
Stile del terminale|Terminal theme
Stacca|Detach
Torna al pannello|Back to dashboard
Apri il pannello|Open dashboard
Apri il terminale in una finestra separata|Open the terminal in a separate window
Consenti le finestre popup per aprire il terminale separato.|Allow popups to open the detached terminal.
Sessione scaduta. Accedi nuovamente dal pannello.|Session expired. Sign in again from the dashboard.
Terminale non configurato in BPQ.|Terminal is not configured in BPQ.
Quota|Altitude
Posizione APRS|APRS position
Pacchetto originale|Original packet
Simbolo non disponibile|Symbol unavailable
Sovrapposizione|Overlay
Commenta|Comment
Pubblica un commento come bollettino|Post a comment as a bulletin
Rispondi all’autore con un messaggio personale|Reply privately to the author
Seleziona un messaggio|Select a message
Mappa delle stazioni|Station map
Seleziona un collegamento|Select a connection
Traffico, servizio ed eventi della sessione.|Session traffic, service and events.
Seleziona una stazione|Select a station
Copertura parziale dei dati|Partial data coverage
Informazioni sulla mappa|About this map
Informazioni sulla programmazione|About scheduling
Dettagli dei dati|Data details
Fonti|Sources
La tua stazione, in un unico pannello.|Your station, in one dashboard.
Benvenuto in stazione.|Welcome to your station.
Accedi con l’utente e la password Telnet del tuo BPQ.|Sign in with your BPQ Telnet username and password.
Utente|Username
Il tuo utente BPQ|Your BPQ username
Entra nel pannello|Open dashboard
LA TUA STAZIONE|YOUR STATION
Panoramica|Overview
Rete & nodi|Network & nodes
Rete|Network
Stazione BPQ|BPQ station
STAZIONE BPQ|BPQ STATION
STAZIONE|STATION
Stazione|Station
Esci|Sign out
Esci dal pannello|Sign out of dashboard
Collegamento…|Connecting…
Aggiorna dati|Refresh data
IL TUO PUNTO SULLA RETE|YOUR PLACE ON THE NETWORK
Radio, messaggi e collegamenti. Tutto nello stesso posto.|Radio, messages and connections. All in one place.
Nuovo messaggio|New message
Messaggi nella BBS|BBS messages
In attesa di BPQ|Waiting for BPQ
Nodi conosciuti|Known nodes
Destinazioni NET/ROM|NET/ROM destinations
Collegamenti attivi|Active links
Vicini sulla rete BPQ|Neighbours on the BPQ network
Ultimo sync BBS|Last BBS sync
Nessuno rilevato oggi|None detected today
PORTA RADIO|RADIO PORT
Canale|Channel
S/N ultima sessione|Last session S/N
Stato BPQ|BPQ status
Servizi della stazione|Station services
BBS & bollettini|BBS & bulletins
Leggi, scrivi e condividi via radio|Read, write and share over radio
Chat di rete|Network chat
Accesso dal nodo con CHAT|Access from the node using CHAT
Posta radio verso il CMS|Radio mail to the CMS
Nodo interattivo|Interactive node
Servizi configurati nel nodo|Services configured on the node
NODO|NODE
Bollettini dalla rete e messaggi personali, finalmente leggibili.|Network bulletins and personal messages, clearly presented.
Tutti|All
Tutte|All
Bollettini|Bulletins
Personali|Personal
Inviati|Sent
Inviate|Sent
Cerca oggetto, nominativo o categoria…|Search subject, callsign or category…
Cerca messaggi|Search messages
Categoria|Category
Tutte le categorie|All categories
Più recenti prima|Newest first
Da|From
A|To
Da / A|From / To
Oggetto|Subject
Ricevuto · data e ora|Received · date and time
Dimensione|Size
Stato|Status
Una finestra sulla rete.|A window onto the network.
Scegli un messaggio per leggerlo qui.|Select a message to read it here.
Collegamenti Internet e destinazioni annunciate al tuo nodo.|Internet links and destinations advertised to your node.
Rotte verso i vicini|Routes to neighbours
DATI BPQ|BPQ DATA
Nodo|Node
Porta|Port
Qualità|Quality
Destinazioni|Destinations
Destinazioni conosciute|Known destinations
Rotte e destinazioni rilevate da BPQ.|Routes and destinations reported by BPQ.
Chiudi|Close
Destinatario|Recipient
Tipo|Type
Nominativo oppure indirizzo email|Callsign or email address
Messaggio personale|Personal message
Bollettino|Bulletin
Di cosa vuoi parlare?|What is your message about?
Messaggio|Message
Scrivi il tuo messaggio…|Write your message…
Il messaggio sarà salvato nella BBS. L’inoltro segue i profili BPQ.|The message will be saved in the BBS. Forwarding follows the BPQ profiles.
Annulla|Cancel
Salva e metti in coda|Save and queue
Richiesta fallita|Request failed
Percorso del messaggio nella rete|Message route through the network
PERSONALE|PERSONAL
BOLLETTINO|BULLETIN
MESSAGGIO PERSONALE|PERSONAL MESSAGE
Dati parziali|Partial data
BPQ connesso|BPQ connected
NON DISPONIBILE|UNAVAILABLE
Non disponibile|Unavailable
Non collegato|Disconnected
Occupato|Busy
Libero|Free
Scansione attiva|Scanning
Scansione non rilevata|Scan not detected
ATTIVO|ACTIVE
INATTIVO|INACTIVE
Nessuna rotta disponibile|No routes available
Connessione assente|No connection
Inviato|Sent
Ricevuto|Received
Non letto|Unread
Elaborazione BPQ|BPQ processing
Connessione a BPQ|Connecting to BPQ
Letto|Read
(Senza oggetto)|(No subject)
Inoltrato|Forwarded
Nuovo|New
Trattenuto|Held
Nessun messaggio corrisponde ai filtri.|No messages match the filters.
Caricamento messaggio…|Loading message…
Rispondi|Reply
Messaggio non disponibile|Message unavailable
Chiudere e scartare questa bozza?|Close and discard this draft?
Salvataggio in BPQ…|Saving to BPQ…
Nessuna porta modem|No modem port
Non configurato|Not configured
Attiva o disattiva suoni|Toggle sounds
Suono attivo|Sound enabled
Attiva suono notifiche|Enable notification sound
Clicca per attivare l’audio|Click to enable audio
Prova notifica e suono|Test notification and sound
Notifica di prova|Test notification
Audio attivato · avviso per nuova posta o bollettini|Audio enabled · new mail or bulletin alert
Audio non attivato dal browser: verifica i permessi audio del sito.|Audio was not enabled by the browser: check the site's audio permissions.
Chiudi notifica|Dismiss notification
Nuovo bollettino scaricato|New bulletin downloaded
Nuova mail ricevuta|New mail received
Disponibili nella BBS|Available in the BBS
Disponibili nella posta personale|Available in personal mail
Disconnesso|Disconnected
Connetti|Connect
STANZE|ROOMS
Crea stanza|Create room
COLLEGAMENTI|LINKS
PRESENTI|ONLINE
Connettiti con il tuo account per partecipare alla chat.|Connect with your account to join the chat.
Tutta la stanza|Everyone in the room
Messaggio chat|Chat message
Invia|Send
Non connesso|Not connected
Crea o apri una stanza|Create or join a room
Nome stanza|Room name
Entra|Join
Conversazione chat|Chat conversation
Vai agli ultimi messaggi|Jump to latest messages
Ultimi messaggi|Latest messages
Connessione…|Connecting…
Connessione interrotta|Connection interrupted
Scrivi alla stanza…|Write to the room…
Connettiti per scrivere…|Connect to write…
Inattivo|Inactive
Attivo|Active
Nessun utente rilevato|No users detected
Connettiti per vedere chi è presente.|Connect to see who is online.
Privato|Private
privato|private
In attesa|Idle
Connessione fallita|Connection failed
Chiuso|Closed
Utenti|Users
Posta della stazione|Station mail
Aggiorna mail|Refresh mail
Nuova email|New email
Ricevute|Inbox
In coda|Queued
Cerca email|Search email
Cerca email…|Search email…
Data e ora|Date and time
Seleziona una email|Select an email
Consegnata al CMS|Delivered to CMS
Trattenuta|Held
Nuova|New
Ricevuta|Received
Nessuna email in questa cartella.|No email in this folder.
Caricamento…|Loading…
Email non disponibile|Email unavailable
Elimina|Delete
Elimina messaggio|Delete message
Elimina email|Delete email
Eliminazione…|Deleting…
Scrivi una email|Write an email
Indirizzo email oppure nominativo Winlink|Email address or Winlink callsign
Invia email|Send email
STAZIONE IN ASCOLTO|STATION LISTENING
NODO LOCALE|LOCAL NODE
Porta radio BPQ|BPQ radio port
TRAFFICO BPQ|BPQ TRAFFIC
Velocità del modem|Modem speed
Campioni durante le connessioni|Samples during connections
Processo modem · ogni 5 s|Modem process · every 5 s
CPU SISTEMA|SYSTEM CPU
Carico totale del PC|Total PC load
SNR ultima sessione|Last session SNR
Nessun campione disponibile|No samples available
TX SOSPESO|TX SUSPENDED
LINK ATTIVO|LINK ACTIVE
IN ASCOLTO|LISTENING
PORTE RADIO IN PAUSA|RADIO PORTS PAUSED
CHIAMATA IN CORSO|CALLING
CONNESSIONE RADIO|RADIO CONNECTION
CHIAMANTE|CALLER
CHIAMATO|CALLED
Attendo risposta|Waiting for response
Chiamata in uscita|Outgoing call
Chiamata in ingresso|Incoming call
Nessuna porta modem configurata|No modem port configured
Frequenza bloccata|Frequency locked
Canale occupato|Channel busy
Canale libero|Channel clear
Modem non disponibile|Modem unavailable
SNR esposto da BPQ|SNR reported by BPQ
In attesa della prossima connessione|Waiting for the next connection
Schermo intero|Full screen
Schermo intero non disponibile in questo browser. Prova F11.|Full screen is unavailable in this browser. Try F11.
Torna alla finestra|Exit full screen
Allegato|Attachment
Chiudi anteprima|Close preview
Scarica file|Download file
Anteprima pagina PDF|PDF page preview
Caricamento anteprima…|Loading preview…
Anteprima non disponibile. Puoi scaricare il file.|Preview unavailable. You can download the file.
Anteprima PDF non disponibile. Puoi scaricare il file.|PDF preview unavailable. You can download the file.
Anteprima non disponibile per questo formato. Puoi scaricare il file.|Preview unavailable for this format. You can download the file.
Anteprima limitata ai primi 128 KB. Il download contiene il file completo.|Preview limited to the first 128 KB. The download contains the complete file.
Controllo allegati…|Checking attachments…
Anteprima|Preview
Scarica|Download
Mostra messaggio originale e dati 7plus|Show original message and 7plus data
Scarica testo originale della parte|Download original part text
Avvia monitor|Start monitor
Ferma|Stop
Direzione|Direction
Tutte le porte|All ports
Cerca nominativo o testo…|Search callsign or text…
Cerca nel traffico|Search traffic
Pausa|Pause
Riprendi|Resume
Pulisci|Clear
Scarica registro|Download log
Traffico BPQ|BPQ traffic
Avvia il monitor per seguire il traffico BPQ.|Start the monitor to follow BPQ traffic.
Monitor BPQ · sola lettura · orari originali BPQ|BPQ monitor · read only · original BPQ timestamps
Scorrimento automatico|Auto scroll
In ascolto. Nessun traffico corrispondente ai filtri.|Listening. No traffic matches the filters.
In ascolto|Listening
Nessun frame da scaricare|No frames to download
Diario|Logbook
Mappa|Map
Diario dei collegamenti|Connection logbook
Esporta CSV|Export CSV
Cerca nominativo, servizio, frequenza…|Search callsign, service or frequency…
Cerca nel diario|Search logbook
Periodo diario|Logbook period
Servizio diario|Logbook service
Direzione diario|Logbook direction
Esito diario|Logbook result
Tutti i servizi|All services
Tutte le direzioni|All directions
In ingresso|Incoming
In uscita|Outgoing
Non rilevata|Not detected
Tutti gli esiti|All results
Scambio concluso|Exchange completed
Collegato|Connected
Non riuscito|Failed
Esito non registrato|Result not recorded
Sessioni|Sessions
Stazione / servizio|Station / service
Collegamento|Connection
Durata|Duration
Messaggi|Messages
Esito|Result
Ogni collegamento ha una storia.|Every connection has a story.
Seleziona una sessione per vedere traffico, servizio e sequenza degli eventi.|Select a session to see traffic, service and event history.
La rete, sulla mappa.|The network, on a map.
Mostra collegamenti|Show links
Servizio mappa|Map service
Periodo mappa|Map period
24 ore|24 hours
7 giorni|7 days
30 giorni|30 days
Ingrandisci mappa|Zoom in
Riduci mappa|Zoom out
Inquadra rete|Fit network
Mappa interattiva delle stazioni collegate|Interactive map of connected stations
Internet / rete|Internet / network
Mezzo non archiviato|Transport not recorded
Stazione locale|Local station
Natural Earth · pubblico dominio|Natural Earth · public domain
Stazioni nel periodo|Stations in this period
Collegamenti stabiliti|Connections established
Traffico registrato|Recorded traffic
Sono mostrate le 5000 sessioni più recenti.|Showing the 5,000 most recent sessions.
Nessuna sessione corrisponde ai filtri.|No sessions match the filters.
Inizio|Start
Connessione|Connection
Fine|End
Durata collegamento|Connection duration
Trasporto|Transport
Non registrato|Not recorded
Non registrata|Not recorded
Porta BPQ|BPQ port
Frequenza|Frequency
SNR medio|Average SNR
Tentativi|Attempts
Picco TX / RX|Peak TX / RX
Messaggi inviati / ricevuti|Messages sent / received
Contatori di traffico non presenti nel log.|Traffic counters are not available in the log.
Le statistiche disponibili dipendono dal servizio e dal modem; i trattini indicano dati non registrati.|Available statistics depend on the service and modem; dashes indicate unrecorded data.
Mostra stazione sulla mappa|Show station on map
Sequenza degli eventi|Event history
Messaggi trasferiti|Transferred messages
Aggiungi locator|Add locator
Nessun collegamento stabilito nel periodo selezionato.|No connections established in the selected period.
Scegli una stazione.|Choose a station.
Clicca un punto, una traccia o un nominativo nell’elenco.|Click a point, a track or a callsign in the list.
Il LOCATOR della stazione locale non è presente in BPQ: le tracce non possono essere disegnate.|The local station's LOCATOR is missing in BPQ: tracks cannot be drawn.
Stazioni nello stesso punto|Stations at the same point
Il locator individua un’area: le posizioni effettive possono essere diverse.|A locator identifies an area: actual positions may differ.
STAZIONE COLLEGATA|CONNECTED STATION
Distanza non disponibile|Distance unavailable
Stesso locator del nodo|Same locator as the node
Posizione non disponibile|Position unavailable
Ultimo collegamento nel periodo|Last connection in this period
Salva posizione|Save position
Inserisci il locator comunicato dalla stazione.|Enter the locator provided by the station.
Es. IO91AA|e.g. IO91AA
Aggiorna|Refresh
Partner e scambi della BBS|BBS partners and exchanges
Ripristina percorso originale|Restore original route
Caricamento profili BPQ…|Loading BPQ profiles…
Le fasce mostrano il fuso configurato in BPQ. Il prossimo tentativo è una stima: timer, disponibilità del modem e condizioni di connessione sono gestiti da BPQ. Le regole si modificano nella configurazione BPQ.|Time windows use the timezone configured in BPQ. The next attempt is an estimate: BPQ manages timers, modem availability and connection conditions. Edit rules in the BPQ configuration.
Non rilevato|Not detected
Non impostato|Not set
Completato|Completed
Chiamata in corso|Calling
Sessione interrotta|Session interrupted
Nessuna regola esplicita|No explicit rules
Tutte le aree geografiche|All geographical areas
Destinazioni geografiche tramite questo partner|Geographical destinations via this partner
Percorsi|Routes
Automatici|Automatic
Messaggi in coda|Queued messages
Sessioni attive|Active sessions
Partner / percorso|Partner / route
Coda|Queue
Ultimo scambio|Last exchange
Programmazione|Schedule
Prossimo · stima|Next · estimate
Azioni|Actions
Riservato al percorso VHF|Reserved for the VHF route
Preparazione radio|Preparing radio
Richiesta inviata|Request sent
Solo manuale|Manual only
Automatico|Automatic
Disattivato|Disabled
Attende fine percorso VHF|Waiting for the VHF route to finish
Sessione in corso|Session in progress
Solo su richiesta|On request only
Automatico disattivo|Automatic disabled
Script assente|Script missing
In attesa di messaggi|Waiting for messages
Timer non disponibile|Timer unavailable
Nessuna sessione recente|No recent sessions
locale BPQ|BPQ local time
In corso|In progress
Richiesta inviata…|Request sent…
Avvia manualmente|Start manually
Sincronizza ora|Sync now
Modem impegnato|Modem busy
Trasmissioni sospese|Transmissions paused
Nessun partner di forwarding configurato in BPQ.|No forwarding partners configured in BPQ.
Regole di inoltro|Forwarding rules
Esclusi: solo posta personale|Excluded: personal mail only
Posta personale e bollettini diretti|Personal mail and direct bulletins
Destinatari espliciti · TO|Explicit recipients · TO
Distribuzioni esplicite · AT|Explicit distributions · AT
Nessuno|None
Nessuna|None
Richiesta messaggi al partner|Request messages from partner
Disattiva|Disabled
Invio immediato nuovi messaggi|Send new messages immediately
Disattivo|Disabled
Le regole geografiche dipendono dagli indirizzi gerarchici e dalle altre rotte BPQ. I messaggi locali e quelli già ricevuti dal partner seguono le regole di esclusione di BPQ.|Geographical rules depend on hierarchical addresses and other BPQ routes. Local messages and those already received from the partner follow BPQ's exclusion rules.
Percorso di connessione|Connection route
Nessuno script configurato|No script configured
Indirizzo gerarchico|Hierarchical address
Ultimi scambi|Recent exchanges
Ingresso|Incoming
Uscita|Outgoing
Nessuno scambio nei sette file di log più recenti.|No exchanges in the seven most recent log files.
TX / RX: messaggi registrati nei log della sessione, non byte.|TX / RX: messages recorded in the session logs, not bytes.
Percorso originale ripristinato|Original route restored
Richiesta…|Requesting…
FREQUENZE DI ASCOLTO|LISTENING FREQUENCIES
Sospendi TX|Suspend TX
Caricamento frequenze…|Loading frequencies…
Nessuna scansione configurata|No scan configured
Riprendi radio|Resume radio
Controllo remoto non disponibile|Remote control unavailable
Applicazione richiesta in corso…|Applying request…
TX sospeso · porte e connessioni radio ferme|TX suspended · radio ports and connections stopped
La pausa TX chiude le connessioni radio; Internet resta disponibile.|Pausing TX closes radio connections; Internet remains available.
Mantieni almeno una frequenza di ascolto|Keep at least one listening frequency
Scegli un gateway|Choose a gateway
Directory ufficiale · canali PUBLIC|Official directory · PUBLIC channels
Aggiorna elenco|Refresh list
Cerca gateway Winlink|Search Winlink gateways
Nominativo, locator o località…|Callsign, locator or location…
Banda gateway|Gateway band
40 e 20 metri|40 and 20 metres
40 metri|40 metres
20 metri|20 metres
VHF · 2 metri|VHF · 2 metres
UHF · 70 centimetri|UHF · 70 centimetres
VHF e UHF|VHF and UHF
Tutte le bande HF|All HF bands
HF, VHF e UHF|HF, VHF and UHF
In orario e report recente|Within hours and recently reported
Ordina gateway|Sort gateways
Distanza crescente|Nearest first
Nominativo|Callsign
Frequenze sul display · USB / FM · orari UTC|Dial frequencies · USB / FM · UTC hours
Frequenza / modo|Frequency / mode
Modo / banda|Mode / band
Locator / distanza|Locator / distance
Orari UTC|UTC hours
Ultimo report|Last report
Nessun gateway selezionato|No gateway selected
Seleziona un canale nell’elenco.|Select a channel from the list.
Connetti e sincronizza|Connect and sync
La distanza non indica la qualità del collegamento. Il report conferma la pubblicazione del gateway, non che il canale radio sia libero. La frequenza centrale è disponibile nel dettaglio del canale selezionato.|Distance does not indicate link quality. A report confirms the gateway is listed, not that the radio channel is clear. The centre frequency is available in the selected channel's details.
Verifica configurazione radio…|Checking radio configuration…
Sync radio non configurato: verifica modem e controllo CAT.|Radio sync not configured: check modem and CAT control.
Sync radio non configurato: serve un modem supportato e il controllo CAT abilitato.|Radio sync not configured: a supported modem and CAT control are required.
Elenco non aggiornato: aggiorna prima di collegarti.|The list is out of date: refresh before connecting.
Non dichiarati|Not specified
In orario|Within operating hours
Fuori orario|Outside operating hours
Orari non riconosciuti|Unrecognised operating hours
Recente|Recent
Report scaduto / assente|Report expired / missing
Nessun canale corrisponde ai filtri.|No channels match the filters.
Sessione in corso…|Session in progress…
Elenco non disponibile|List unavailable
Preparazione modem packet e frequenza|Preparing packet modem and frequency
Richiesta inviata a BPQ|Request sent to BPQ
Chiamata radio in corso|Radio call in progress
Collegato · scambio posta|Connected · exchanging mail
Sync radio completato|Radio sync completed
Profilo Internet ripristinato|Internet profile restored
Collegamento non riuscito|Connection failed
Errore nella richiesta|Request error
Ripristino da verificare|Recovery needs checking
Ripristina profilo Internet|Restore Internet profile
Terminale|Terminal
Salva testo|Save text
Collega|Connect
Disconnetti|Disconnect
Terminale Telnet BPQ|BPQ Telnet terminal
Comando Telnet|Telnet command
Collega il terminale per iniziare|Connect the terminal to begin
Invia comando|Send command
INVIO|ENTER
TELNET · BPQ LOCALE|TELNET · LOCAL BPQ
↑ ↓ cronologia · Invio per inviare|↑ ↓ history · Enter to send
Torna al fondo|Jump to bottom
COLLEGAMENTO…|CONNECTING…
ERRORE|ERROR
Scrivi un comando…|Type a command…
Il terminale è vuoto|The terminal is empty
SESSIONE BPQ|BPQ SESSION
Sincronizzazione|Synchronisation
Riduci finestra|Minimise window
Preparazione…|Preparing…
Preparazione|Preparation
Chiamata|Calling
Scambio messaggi|Exchanging messages
Ripristino|Restoring
Interruzione in corso|Cancelling
Interrotto|Cancelled
Scambio|Exchange
Conclusione|Completion
Messaggi inviati|Messages sent
Messaggi ricevuti|Messages received
Avanzamento della sessione|Session progress
Aggiornamento automatico|Automatic refresh
Interrompi sync|Cancel sync
Mostra avanzamento sincronizzazione|Show sync progress
Richiesta di sincronizzazione|Synchronisation request
Interruzione…|Cancelling…
Riprova interruzione|Retry cancellation
Aggiornamento ogni 1,5 secondi|Updates every 1.5 seconds
Sessione terminata|Session ended
Invio della richiesta a BPQ|Sending request to BPQ
Sessione del pannello non più attiva. Stato BPQ ricaricato.|Dashboard session no longer active. BPQ status reloaded.
Eliminare il messaggio?|Delete this message?
Verrà rimosso dalla BBS locale di BPQ. Una email già inviata non può essere richiamata.|It will be removed from the local BPQ BBS. An email that has already been sent cannot be recalled.
Messaggio eliminato|Message deleted
Email eliminata|Email deleted
Nominativo Winlink oppure [email protected]|Winlink callsign or [email protected]
Inserisci un nominativo Winlink o un indirizzo email valido|Enter a valid Winlink callsign or email address
Sincronizzazione richiesta…|Synchronisation requested…
Nessuna sessione rilevata oggi|No sessions detected today
Sincronizzazione completata|Synchronisation completed
Errore nella sessione CMS|CMS session error
Sessione CMS conclusa|CMS session ended
Sincronizzazione in corso|Synchronisation in progress
Una sincronizzazione è già in corso|A synchronisation is already in progress
Verifica della sessione CMS e della coda|Checking the CMS session and queue
Verifica radio e preparazione del percorso|Checking radio and preparing the route
Richiesta accettata da BPQ · attendo il collegamento|Request accepted by BPQ · waiting for connection
Sincronizzazione non trovata|Synchronisation not found
Ripristino del percorso e della scansione|Restoring route and scanning
Collegamento terminato senza completare lo scambio|Connection ended before the exchange completed
Collegamento stabilito · scambio messaggi|Connection established · exchanging messages
Chiamata in corso · attendo la risposta del nodo|Calling · waiting for the node's response
BPQ non ha registrato l’avvio della sessione|BPQ did not record the session starting
Interruzione richiesta · attendo la conferma di BPQ|Cancellation requested · waiting for BPQ confirmation
Comando di disconnessione BPQ non disponibile|BPQ disconnect command unavailable
BPQ non ha ancora confermato la disconnessione: riprova|BPQ has not confirmed disconnection yet: retry
Sincronizzazione interrotta · percorso ripristinato|Synchronisation cancelled · route restored
Locale / Telnet|Local / Telnet
Nodo BPQ|BPQ node
Porta non archiviata|Port not recorded
Lettura dei log BPQ…|Reading BPQ logs…
Cerca nominativo, servizio o frequenza…|Search callsign, service or frequency…
Ultime 24 ore|Last 24 hours
Ultimi 7 giorni|Last 7 days
Ultimi 30 giorni|Last 30 days
Le tracce uniscono le posizioni delle stazioni: non rappresentano il percorso fisico del segnale. Il punto è il centro del locator, non una posizione GPS esatta. Stazioni con lo stesso centro del locator condividono il punto: selezionale dal riquadro dettagli o dall’elenco. I nominativi senza locator restano nel diario e nell’elenco.|Tracks connect station positions: they do not represent the physical signal path. Each point is the locator centre, not an exact GPS position. Stations sharing a locator centre share a point: select them in the details panel or list. Callsigns without a locator remain in the logbook and list.
Operazioni radio|Radio operations
Diario di stazione|Station logbook
Stazioni collegate|Connected stations
in ascolto|listening
profilo Internet sospeso|Internet profile suspended
dati BPQ|BPQ data
CPU sistema|System CPU
traffico BPQ TX RX|BPQ TX RX traffic
cronologia|history
Invio per inviare|Enter to send
Account sysop configurato non trovato|Configured sysop account not found
Timeout BPQ|BPQ timeout
WebMail BPQ non disponibile|BPQ WebMail unavailable
Lista messaggi BPQ non disponibile|BPQ message list unavailable
Messaggio troppo grande|Message too large
BBS non configurata|BBS not configured
Metadati BBS non disponibili|BBS metadata unavailable
Metadati BBS non ancora disponibili|BBS metadata not available yet
Messaggio non presente|Message not found
BPQ non ha confermato la cancellazione|BPQ did not confirm deletion
Messaggio troppo grande per il download web (32 MB)|Message too large for web download (32 MB)
Controlla destinatario, oggetto (max 80 caratteri) e testo (max 32 KB)|Check recipient, subject (max 80 characters) and text (max 32 KB)
BPQ non ha confermato il salvataggio. Controlla la lista prima di riprovare.|BPQ did not confirm saving. Check the list before trying again.
Host non autorizzato|Host not authorised
Origine non autorizzata|Origin not authorised
Troppi tentativi. Riprova tra 15 minuti.|Too many attempts. Try again in 15 minutes.
Credenziali BPQ non valide per il pannello sysop|Invalid BPQ credentials for the sysop dashboard
Accedi con le credenziali BPQ|Sign in with your BPQ credentials
Servizio non configurato in BPQ|Service not configured in BPQ
Sessione non valida. Ricarica la pagina.|Invalid session. Reload the page.
Porta Telnet BPQ non configurata|BPQ Telnet port not configured
Cursore non valido|Invalid cursor
Cursore monitor non valido|Invalid monitor cursor
Percorso di forwarding non configurato|Forwarding route not configured
Tipo di sincronizzazione non disponibile|Synchronisation type unavailable
Allegato non disponibile|Attachment unavailable
Questo file non ha anteprima testuale|This file has no text preview
Sincronizzazione già richiesta. Attendi qualche secondo.|Synchronisation already requested. Wait a few seconds.
Operazione non disponibile|Operation unavailable
Metodo non disponibile|Method unavailable
Pagina non trovata|Page not found
Seleziona almeno una frequenza configurata|Select at least one configured frequency
Controller radio non disponibile|Radio controller unavailable
Stato TX non valido|Invalid TX state
Profilo RMS non presente in BPQ|RMS profile missing in BPQ
Stato sessioni BBS non verificabile|BBS session status cannot be verified
Canale radio non valido|Invalid radio channel
Attendi la fine della sessione BBS prima di ripristinare Internet|Wait for the BBS session to end before restoring Internet
Una sessione Winlink radio è già in corso o in ripristino|A Winlink radio session is already running or being restored
Controllo frequenza CAT per Winlink radio non configurato|CAT frequency control for Winlink radio not configured
Modem impegnato: attendi la fine della connessione|Modem busy: wait for the connection to end
Telemetria radio non disponibile: impossibile verificare il modem|Radio telemetry unavailable: cannot check the modem
Sync Winlink già richiesto: attendi|Winlink sync already requested: please wait
Una sessione BBS è attiva: riprova al termine|A BBS session is active: retry when it ends
Il profilo RMS non è impostato per Internet: verifica la configurazione prima del cambio|The RMS profile is not set to Internet: check configuration before switching
Una sessione BBS è iniziata: riprova al termine|A BBS session has started: retry when it ends
Percorso manuale di forwarding non valido|Invalid manual forwarding route
Percorsi del controllo radio non validi|Invalid radio control paths
Percorso manuale non configurato|Manual route not configured
Un inoltro per questo partner è già in corso|Forwarding to this partner is already in progress
Partner BBS non configurato|BBS partner not configured
Radio non disponibile o impegnata|Radio unavailable or busy
Attendi la fine delle sessioni BBS|Wait for BBS sessions to end
Timeout di accesso chat|Chat sign-in timeout
Connettiti alla chat prima di scrivere|Connect to chat before writing
Scrivi un messaggio su una sola riga, massimo 500 caratteri|Write a single-line message, up to 500 characters
Nominativo non valido|Invalid callsign
Chat non connessa|Chat not connected
Nome stanza non valido|Invalid room name
Credenziali Telnet BPQ non disponibili|BPQ Telnet credentials unavailable
Accesso Telnet non confermato|Telnet sign-in not confirmed
Accesso rifiutato|Access denied
Collega prima il terminale|Connect the terminal first
Invia un solo comando, massimo 1000 caratteri|Send one command, up to 1000 characters
`;
const uploadCopy=`Allegati|Attachments
Allega file|Attach files
Seleziona allegati|Choose attachments
Rimuovi allegato|Remove attachment
Trascina qui i file oppure selezionali. Massimo 10 file e 64 KB complessivi. Via radio, i file piccoli riducono il tempo di collegamento.|Drop files here or select them. Up to 10 files and 64 KB total. Small files reduce radio connection time.
Massimo 10 allegati per messaggio|Up to 10 attachments per message
Allegati troppo grandi: massimo 64 KB complessivi|Attachments too large: maximum 64 KB total
Nomi allegati duplicati: rinomina i file|Duplicate attachment names: rename the files
Usa il caricamento file per gli allegati|Use file upload for attachments
Campi del messaggio non validi|Invalid message fields
Campo allegato non valido|Invalid attachment field
Gli allegati in uscita sono disponibili per le email Winlink|Outgoing attachments are available for Winlink emails
BPQ ha salvato il messaggio ma gli allegati non corrispondono. Controlla la coda prima di riprovare.|BPQ saved the message but the attachments do not match. Check the queue before retrying.`;
const sizeCopy='Testo e allegati superano 80 KB complessivi|Message text and attachments exceed 80 KB total\nMessaggio troppo grande per il server HTTP BPQ|Message too large for the BPQ HTTP server';
const deleteCopy='Sessione amministrativa BPQ non disponibile|BPQ admin session unavailable\nBPQ non ha confermato il messaggio da cancellare|BPQ did not confirm the message selected for deletion\nMetadati BPQ non verificabili: cancellazione interrotta|BPQ metadata could not be verified: deletion stopped\nMessaggio non valido|Invalid message\nBPQ non autorizza la cancellazione: verifica i permessi sysop della BBS|BPQ denied deletion: check the BBS sysop permissions\nBPQ non ha risposto in tempo. Aggiorna l’elenco prima di riprovare.|BPQ did not respond in time. Refresh the list before retrying.';
const portCopy=`PORTE RADIO|RADIO PORTS
Porte radio|Radio ports
Sospendi tutte le TX|Pause all TX
Riprendi tutte le TX|Resume all TX
Ferma porta|Stop port
Avvia porta|Start port
PORTA FERMA|PORT STOPPED
Frequenze|Frequencies
Frequenze di ascolto|Listening frequencies
+ Frequenza|+ Frequency
Frequenza MHz|Frequency MHz
Secondi|Seconds
In scansione|Scan enabled
Rimuovi frequenza|Remove frequency
Tutte le trasmissioni sono sospese|All transmissions are paused
Porta ferma|Port stopped
Trasmissioni della porta sospese|Port transmissions paused
Ascolto sulla frequenza selezionata|Listening on the selected frequency
Controllo porta non disponibile|Port control unavailable
Statistiche frame BPQ|BPQ frame statistics
FRAME AX.25|AX.25 FRAMES
TX / RX · contatori BPQ|TX / RX · BPQ counters
Contatore BPQ|BPQ counter
TIMEOUT L2|L2 TIMEOUTS
CPU MODEM|MODEM CPU
● Frequenza fissa|● Fixed frequency
● Porta ferma|● Port stopped
Configura da 1 a 12 frequenze|Configure 1 to 12 frequencies
Frequenza, intervallo o selezione non validi|Invalid frequency, dwell or selection
Stato porta non valido|Invalid port state
Mantieni almeno una frequenza selezionata|Keep at least one frequency selected`;
const aprsCopy=`Ascolto e inoltro, porta per porta.|Listening and forwarding, port by port.
Salva e applica|Save and apply
Stazione|Station
Nominativo APRS|APRS callsign
Beacon · minuti|Beacon · minutes
Latitudine APRS|APRS latitude
Longitudine APRS|APRS longitude
Simbolo|Symbol
Tabella simboli|Symbol table
Messaggio di stato|Status message
Abilitato|Enabled
Server|Server
Porta TCP|TCP port
Passcode APRS-IS|APRS-IS passcode
Filtro APRS-IS|APRS-IS filter
Pubblica il beacon su Internet|Publish beacon to the Internet
Passcode salvato in BPQ|Passcode saved in BPQ
Per inoltrare i pacchetti ricevuti a Internet serve il passcode APRS-IS.|An APRS-IS passcode is required to forward received packets to the Internet.
I messaggi da Internet alla radio sono un flusso separato dalla ripetizione dei pacchetti radio.|Internet-to-radio messages are separate from radio packet repeating.
Porte APRS|APRS ports
Porta / frequenza|Port / frequency
Ascolto|Listen
Radio → Internet|Radio → Internet
Ripeti via radio|Repeat over radio
Messaggi Internet → radio|Internet → radio messages
Beacon radio|Radio beacon
Percorso|Path
La frequenza APRS selezionata diventa la frequenza di ascolto della porta. I sync manuali mantengono la priorità e al termine ripristinano l’ascolto.|The selected APRS frequency becomes the port listening frequency. Manual syncs take priority and restore listening afterward.
Le ritrasmissioni radio seguono il percorso APRS e la soppressione dei duplicati gestiti da BPQ.|Radio retransmissions follow the APRS path and BPQ duplicate suppression.
Nessuna porta packet con controllo di frequenza disponibile.|No packet port with frequency control is available.
Applicazione della configurazione APRS…|Applying APRS configuration…
Configurazione APRS applicata · backup salvato|APRS configuration applied · backup saved
Configurazione APRS applicata|APRS configuration applied
Configurato · lascia vuoto per mantenerlo|Configured · leave blank to keep it
Non configurato|Not configured
Stazione / APRS|Station / APRS`;
const liveCopy=`Attività|Activity
Configurazione|Configuration
Viste APRS|APRS views
Origine APRS|APRS source
Direzione APRS|APRS direction
Cerca APRS|Search APRS
Mappa stazioni APRS|APRS station map
Pausa vista|Pause display
Riprendi vista|Resume display
Vista in pausa|Display paused
APRS in tempo reale|Live APRS
Stazioni ricevute|Heard stations
Centra stazioni|Fit stations
La tua stazione|Your station
Ultime ricezioni|Recently heard
Traffico APRS|APRS traffic
Da → A|From → To
Tipo / pacchetto|Type / packet
Senza posizione|No position
senza posizione|without position
sulla mappa|on map
Nessuna stazione ricevuta con questi filtri.|No stations match these filters.
In attesa di pacchetti APRS ricevuti o inviati.|Waiting for received or transmitted APRS packets.
Posizione|Position
Oggetto APRS|APRS object
Meteo|Weather
Telemetria|Telemetry
Messaggio inoltrato|Forwarded message
Richiesta|Request
pacchetti nel registro|packets in the log
Ultimi 2000 pacchetti · TX radio = richieste registrate da BPQ.|Last 2000 packets · Radio TX = requests logged by BPQ.
Log Internet non disponibile|Internet log unavailable
Aggiornato|Updated
Salva|Save
BBS & messaggi|BBS & messages
messaggi|messages
messaggio ricevuto|message received
messaggi ricevuti|messages received
destinazioni|destinations
stazioni|stations
stazione locale|local station
in ascolto|listening
— messaggi|— messages
— presenti|— online
Scrivi un messaggio…|Write a message…
BBS / STAZIONE|BBS / STATION
Il messaggio sarà salvato nella BBS come STAZIONE. L’inoltro segue le rotte configurate in BPQ.|The message will be saved in the station BBS. BPQ handles forwarding using its configured routes.
Chiamata radio verso il nodo remoto avviata|Radio call to the remote node started
il nodo remoto si è collegato alla nostra BBS|the remote node connected to our BBS
Ricevuto e salvato un nuovo bollettino|New bulletin received and saved
Servizio|Service
Connessione UTC|Connection UTC
Messaggi TX|Messages TX
Messaggi RX|Messages RX
CRC verificati|CRCs verified
Sync automatico gestito dalla console.|Automatic sync managed by the console.`;
const dictionary=new Map((entries+'\n'+uploadCopy+'\n'+sizeCopy+'\n'+deleteCopy+'\n'+portCopy+'\n'+aprsCopy+'\n'+liveCopy).split(/\r?\n/).map(line=>line.split('|')).filter(([source,target])=>source?.trim()&&typeof target==='string'&&target.trim()));
function resolveLanguage(preference=null,languages=[]){
if(preference==='it'||preference==='en')return preference;
// The first browser language is the user's preferred UI language; English is the fallback.
return /^it(?:-|$)/i.test(languages[0]||'')?'it':'en';
}
let preference=null,language='it';
const patterns=[
[/^Stazione \/ (.+)$/,m=>'Station / '+translate(m[1])],
[/^(\d+) bollettini · (\d+) personali$/,m=>m[1]+' bulletins · '+m[2]+' personal'],
[/^(\d+) (messaggi|messaggio ricevuto|messaggi ricevuti|destinazioni|sessioni|stazioni|nuovo messaggio|nuovi messaggi|nuovi bollettini scaricati|nuove mail ricevute|nella stanza|presenti|collegamenti nel periodo)$/,m=>m[1]+' '+({'messaggi':'messages','messaggio ricevuto':'message received','messaggi ricevuti':'messages received','destinazioni':'destinations','sessioni':'sessions','stazioni':'stations','nuovo messaggio':'new message','nuovi messaggi':'new messages','nuovi bollettini scaricati':'new bulletins downloaded','nuove mail ricevute':'new mail messages received','nella stanza':'in the room','presenti':'online','collegamenti nel periodo':'connections in this period'})[m[2]]],
[/^Aggiornato (.+)$/,m=>'Updated '+m[1]],
[/^(.+) · aggiornato (.+)$/,m=>m[1]+' · updated '+m[2]],
[/^Connettiti come (\S+) per partecipare alla chat\.$/,m=>'Connect as '+m[1]+' to join the chat.'],
[/^Connesso alla chat come (\S+)$/,m=>'Connected to chat as '+m[1]],
[/^Disconnesso dalla chat$/,()=> 'Disconnected from chat'],
[/^Connesso · (\S+)$/,m=>'Connected · '+m[1]],
[/^Messaggio privato a (.+)$/,m=>'Private message to '+m[1]],
[/^Privato · (.+)$/,m=>'Private · '+m[1]],
[/^(Dettagli|Dettagli stazione|Seleziona|Grafico) (.+)$/,m=>({'Dettagli':'Details','Dettagli stazione':'Station details','Seleziona':'Select','Grafico':'Chart'})[m[1]]+' '+m[2]],
[/^(Allegati) · (\d+)$/,m=>'Attachments · '+m[2]],
[/^Percorso di connessione · porta (\d+)$/,m=>'Connection route · port '+m[1]],
[/^Attiva · intervallo (.+)$/,m=>'Enabled · interval '+m[1]],
[/^Porta (\d+)$/,m=>'Port '+m[1]],
[/^Posizioni dai locator · orari (.+)$/,m=>'Positions from locators · times '+m[1]],
[/^Posizioni dai locator · (.+)$/,m=>'Positions from locators · '+m[1]],
[/^Log disponibili dal (.+) · massimo 30 giorni · (.+)$/,m=>'Logs available since '+m[1]+' · up to 30 days · '+m[2]],
[/^(\d+) sulla mappa · (\d+) senza locator$/,m=>m[1]+' on map · '+m[2]+' without locator'],
[/^(\d+) sulla mappa · (\d+) senza posizione$/,m=>m[1]+' on map · '+m[2]+' without position'],
[/^(\d+) pacchetti nel registro$/,m=>m[1]+' packets in the log'],
[/^Dal (.+)$/,m=>'Since '+m[1]],
[/^Frequenza APRS Port (\d+)$/,m=>'APRS frequency port '+m[1]],
[/^Frequenza FM: (.+)$/,m=>'FM frequency: '+m[1]],
[/^(.+) · ultimo collegamento (.+)$/,m=>m[1]+' · last connection '+m[2]],
[/^Sync automatico gestito dalla console\. (.+)$/,m=>'Automatic sync managed by the console. '+translate(m[1])],
[/^Stessa coda e stesse regole del partner (\S+)\. Sync automatico gestito dalla console\. (.+)$/,m=>'Same queue and rules as partner '+m[1]+'. Automatic sync managed by the console. '+translate(m[2])],
[/^(\d+) parti ricostruite$/,m=>m[1]+' reconstructed parts'],
[/^Ricostruito da (\d+) parti$/,m=>'Rebuilt from '+m[1]+' parts'],
[/^Ricostruzione completa · (\d+)\/(\d+) parti verificate\. Anteprima e download disponibili negli allegati\.$/,m=>'Reconstruction complete · '+m[1]+'/'+m[2]+' verified parts. Preview and download available in attachments.'],
[/^Ricevute (\d+)\/(\d+) parti\. Mancano: ([\d, ]+)\.(?: Parti danneggiate: ([\d, ]+)\.)?$/,m=>'Received '+m[1]+'/'+m[2]+' parts. Missing: '+m[3]+'.'+(m[4]?' Damaged parts: '+m[4]+'.':'')],
[/^Ricostruzione sospesa: dati incompleti o CRC non validi nelle parti ([\d, ]+)\.$/,m=>'Reconstruction suspended: incomplete data or invalid CRCs in parts '+m[1]+'.'],
[/^Parte (\d+)\/(\d+)\. Nessun blocco 7plus riconoscibile nel messaggio\.$/,m=>'Part '+m[1]+'/'+m[2]+'. No recognisable 7plus block in the message.'],
[/^(\d+) km dal nodo$/,m=>m[1]+' km from node'],
[/^Locator salvato per (\S+)$/,m=>'Locator saved for '+m[1]],
[/^(\d+) canali? · (\d+) gateway$/,m=>m[1]+' '+(m[1]==='1'?'channel':'channels')+' · '+m[2]+' gateways'],
[/^(\d+) frame · (\d+) in memoria( · visualizzazione in pausa)?$/,m=>m[1]+' frames · '+m[2]+' in memory'+(m[3]?' · display paused':'')],
[/^Messaggio #(\d+) salvato nella BBS\. L’inoltro sarà gestito da BPQ\.$/,m=>'Message #'+m[1]+' saved in the BBS. BPQ will handle forwarding.'],
[/^Messaggio #(\d+) eliminato da BPQ$/,m=>'Message #'+m[1]+' deleted from BPQ'],
[/^(Aggiornamento BPQ in attesa|Ripristino del percorso dopo errore|Diario non disponibile): (.+)$/,m=>({'Aggiornamento BPQ in attesa':'BPQ update pending','Ripristino del percorso dopo errore':'Restoring route after error','Diario non disponibile':'Logbook unavailable'})[m[1]]+': '+translate(m[2])],
[/^Stessa coda e stesse regole del partner (\S+)\. Nessun timer automatico per questo percorso\. (.+)$/,m=>'Same queue and rules as partner '+m[1]+'. No automatic timer for this route. '+translate(m[2])],
];
function translate(text){
if(!text.trim())return text;
if(dictionary.has(text))return dictionary.get(text);
for(const [pattern,render]of patterns){const match=text.match(pattern);if(match)return render(match);}
if(text.includes(' · '))return text.split(' · ').map(translate).join(' · ');
return text;
}
function t(value){
const text=String(value??'');if(language!=='en')return text;
const whole=text.match(/^(\s*)(.*?)(\s*)$/s);if(whole&&dictionary.has(whole[2]))return whole[1]+dictionary.get(whole[2])+whole[3];
// Preserve indentation and decorative icons, which often live in the same text node.
const match=text.match(/^(\s*(?:(?:▸_|[\p{S}\uFE0E\uFE0F])\s*)*)(.*?)(\s*(?:[\p{S}\uFE0E\uFE0F]\s*)*)$/su);
return match?match[1]+translate(match[2])+match[3]:translate(text);
}
const api={t,resolveLanguage,get language(){return language},get preference(){return preference},locale:()=>language==='it'?'it-IT':'en-GB'};
globalThis.BPQI18n=api;
if(typeof document==='undefined')return;
try{const saved=localStorage.getItem('bpq-language');if(['it','en'].includes(saved))preference=saved;}catch{}
const browserLanguages=()=>navigator.languages?.length?navigator.languages:[navigator.language];
language=resolveLanguage(preference||globalThis.BPQ_DEFAULT_LANGUAGE,browserLanguages());preference=language;try{localStorage.setItem('bpq-language',language);}catch{}document.documentElement.lang=language;
const originals=new WeakMap(),attributes=new WeakMap();
// These are user/protocol data, never interface copy. Do not translate their labels or contents.
const protectedContent='script,style,textarea,pre,code,[contenteditable],[data-no-i18n],.reader-body,.mail-subject,.mail-from,.mail-category,.reader-header h2,.reader-meta b,.chat-message-content p,.chat-message-meta strong,.chat-user-name,.chat-user b,.chat-user small,.room-button,#chat-room-name,.attachment-row b,#attachment-title,#delete-subject,.arrival-toast small,.side-station,.profile>div,.mission-heading h1,.mission-location,.modem-brand,#caller-call,#called-call,.service-call,#nodes,.wl-account,#wl-gateway-rows td:nth-child(2),#category option:not([value]),#terminal-output,.monitor-frame,.aprs-packet-preview,.aprs-received-station p,.aprs-map-popup p,.aprs-map-popup b,.aprs-map-popup small';
function excluded(el){if(!el)return true;if(el.matches('.routing-trace>summary,.sevenplus-original>summary'))return false;return !!el.closest(protectedContent);}
function textNode(node){
if(excluded(node.parentElement))return;
let entry=originals.get(node);
if(!entry||node.nodeValue!==entry.rendered)entry={source:node.nodeValue,rendered:null};
const rendered=t(entry.source);entry.rendered=rendered;originals.set(node,entry);
if(node.nodeValue!==rendered)node.nodeValue=rendered;
}
function element(el){
if(excluded(el))return;
for(const name of ['title','placeholder','aria-label']){
if(name==='title'&&el.matches('.mail-row,.chat-user'))continue;
if(!el.hasAttribute(name))continue;
const stored=attributes.get(el)||{};let entry=stored[name],value=el.getAttribute(name);
if(!entry||value!==entry.rendered)entry={source:value,rendered:null};
const rendered=t(entry.source);entry.rendered=rendered;stored[name]=entry;attributes.set(el,stored);
if(value!==rendered)el.setAttribute(name,rendered);
}
}
function apply(root=document.body){
if(!root)return;
if(root.nodeType===3){textNode(root);return;}
if(root.nodeType!==1)return;
element(root);const walker=document.createTreeWalker(root,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT);
let node;while((node=walker.nextNode())){if(node.nodeType===3)textNode(node);else element(node);}
}
let observer;
function observe(){observer.observe(document.body,{subtree:true,childList:true,characterData:true,attributes:true,attributeFilter:['title','placeholder','aria-label']});}
function syncControls(){document.querySelectorAll('[data-language-switch]').forEach(control=>{control.setAttribute('aria-checked',String(language==='en'));control.setAttribute('title',language==='en'?'Switch to Italian':'Passa all’inglese');});}
api.setLanguage=value=>{
if(!['it','en'].includes(value))return;
preference=value;try{localStorage.setItem('bpq-language',value);}catch{}
language=resolveLanguage(value,browserLanguages());document.documentElement.lang=language;
observer?.disconnect();apply();syncControls();if(observer)observe();
document.dispatchEvent(new CustomEvent('bpq-languagechange',{detail:{language,preference}}));
};
globalThis.bpqConfirm=message=>globalThis.confirm(t(message));
globalThis.bpqPrompt=(message,defaultValue='')=>globalThis.prompt(t(message),defaultValue);
function mount(){
const picker=place=>{
const control=document.createElement('button');control.type='button';control.className='language-switch '+place;control.dataset.languageSwitch='';control.setAttribute('role','switch');control.setAttribute('aria-label','English / Italiano');
control.innerHTML='<span class="language-thumb" aria-hidden="true"></span><span class="language-choice" aria-hidden="true"><svg class="language-flag" viewBox="0 0 60 40"><rect width="60" height="40" fill="#fff"/><path d="M0 0h20v40H0z" fill="#009246"/><path d="M40 0h20v40H40z" fill="#ce2b37"/></svg><span>IT</span></span><span class="language-choice" aria-hidden="true"><svg class="language-flag" viewBox="0 0 60 40"><rect width="60" height="40" fill="#193775"/><path d="m0 0 60 40M60 0 0 40" stroke="#fff" stroke-width="9"/><path d="m0 0 60 40M60 0 0 40" stroke="#c73545" stroke-width="3"/><path d="M30 0v40M0 20h60" stroke="#fff" stroke-width="13"/><path d="M30 0v40M0 20h60" stroke="#c73545" stroke-width="7"/></svg><span>EN</span></span>';
control.onclick=()=>api.setLanguage(language==='it'?'en':'it');control.onkeydown=e=>{if(e.key==='ArrowLeft'||e.key==='ArrowRight'){e.preventDefault();api.setLanguage(e.key==='ArrowRight'?'en':'it');}};return control;
};
document.querySelector('.login-card')?.append(picker('language-login'));
document.querySelector('.topbar > div')?.prepend(picker('language-toolbar'));
syncControls();apply();observer=new MutationObserver(records=>{
observer.disconnect();const roots=new Set();
for(const r of records){if(r.type==='childList')for(const child of r.addedNodes)roots.add(child);else roots.add(r.target);}
for(const root of roots)if(root.isConnected)apply(root);observe();
});observe();
}
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',mount,{once:true});else mount();
})();
+5 -7
View File
@@ -1,19 +1,17 @@
<!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>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> <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 Console</title><link rel="stylesheet" href="/i18n.css"><script src="/ui-config.js"></script><script defer src="/detach.js?v=20261029-lan"></script><link rel="stylesheet" href="/detach.css?v=20261019-multi"><script src="/i18n.js?v=20261019-label-audit"></script><link rel="stylesheet" href="/style.css"><link rel="stylesheet" href="/dark.css"><link rel="stylesheet" href="/mission.css"><link rel="stylesheet" href="/busy.css"><script defer src="/busy.js"></script><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="/compose-attachments.css"><script defer src="/compose-attachments.js"></script><link rel="stylesheet" href="/monitor.css"><script defer src="/monitor.js"></script><link rel="stylesheet" href="/journal.css"><script defer src="/journal.js"></script><link rel="stylesheet" href="/forwarding.css"><script defer src="/forwarding.js?v=20261017-hourly-2"></script><link rel="stylesheet" href="/winlink-radio.css"><script defer src="/winlink-radio.js"></script><link rel="stylesheet" href="/terminal.css?v=20261019-themes"><script defer src="/terminal.js?v=20261019-themes"></script><link rel="stylesheet" href="/radio-control.css"><link rel="stylesheet" href="/radio-ports.css"><script defer src="/radio-ports.js"></script><link rel="stylesheet" href="/aprs.css"><script defer src="/aprs.js"></script><link rel="stylesheet" href="/vendor/leaflet/leaflet.css"><script defer src="/vendor/leaflet/leaflet.js"></script><link rel="stylesheet" href="/aprs-activity.css?v=20261019-packet-text"><script defer src="/aprs-symbols.js"></script><script defer src="/aprs-activity.js?v=20261019-packet-text"></script><link rel="stylesheet" href="/sync-progress.css"><script type="module" src="/sync-progress.js"></script></head>
<body> <body>
<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> <section id="login" class="login-screen"><div class="login-art"><h1>BPQ Console</h1><div class="login-byline" data-no-i18n>by IU2EUG</div><p>La tua stazione, in un unico pannello.</p></div><form id="login-form" class="login-card"><div class="login-brand"><span class="brand">BPQ Console</span><div class="login-byline" data-no-i18n>by IU2EUG</div></div><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></form></section>
<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> <div id="shell" hidden><aside class="sidebar"><a class="brand" href="#home">BPQ Console</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 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="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">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> <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">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> <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 nodo remoto</button></article></div>
<footer class="page-footer">BPQ Console · <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">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="bbs" class="page" hidden><div class="page-heading"><div><h1>BBS</h1></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>Seleziona un messaggio</h2></div></article></div></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> <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></section>
</main></div> </main></div>
<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="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 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>
+36
View File
@@ -0,0 +1,36 @@
#journal,#map{max-width:none;padding:28px} .journal-heading{display:flex;justify-content:space-between;align-items:center;gap:20px;margin-bottom:22px}.journal-heading h1{font-size:29px;font-weight:500;margin:8px 0}.journal-heading p{color:#8b9eb6;font-size:12px}.journal-heading>div:last-child{display:flex;gap:10px}.journal-heading>div:first-child{display:block}.journal-kpis{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:14px;margin-bottom:18px}.journal-kpis article{padding:18px 20px;border:1px solid #2c4056;border-radius:13px;background:linear-gradient(130deg,#18283a,#111b29)}.journal-kpis span{font-size:11px;color:#91a5bc}.journal-kpis strong{display:block;font:24px Consolas,monospace;margin-top:10px;color:#d5e7f7}.journal-filters,.map-toolbar{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:18px}.journal-filters input{flex:1;min-width:200px}.journal-filters input,.journal-filters select,.map-toolbar select{height:42px;border-radius:9px;padding:0 13px;font-size:12px}.journal-layout{display:grid;grid-template-columns:minmax(0,1fr) 340px;gap:18px;align-items:start}.journal-table-card{min-width:0}.journal-table-card .card-header{padding:18px 20px}.journal-table-card h2{font-size:15px}.journal-table-card .card-header>span{font-size:11px;color:#8fa5bd}.journal-table-scroll{max-height:calc(100dvh - 360px);min-height:300px;overflow:auto}.journal-table{width:100%;font-size:11px;border-collapse:collapse;white-space:nowrap}.journal-table th{position:sticky;top:0;background:#172334;color:#a9bfd6;z-index:1;font-size:10px;padding:14px 12px;text-align:left}.journal-table td{padding:14px 12px;border-bottom:1px solid #26384b;vertical-align:middle}.journal-table tbody tr{cursor:pointer}.journal-table tbody tr:hover{background:#1b2c40}.journal-table tr.selected{background:#243c55}.journal-table td b{font:14px Consolas,monospace;color:#d7e9f7}.journal-table td small{display:block;color:#839bb4;margin-top:6px;font-size:10px}.journal-open{background:none;border:0;color:#bfd7ed;padding:0;font:inherit;text-align:left}.journal-badge{padding:4px 7px;background:#253851;border-radius:5px;color:#adc6e5;font-size:10px}.journal-badge.radio{background:#243f3a;color:#a8dac6}.journal-result{font-size:10px;color:#92a7bc;line-height:1.5}.journal-result.complete,.journal-result.connected{color:#a6d8bc}.journal-result.failed{color:#dba6a6}.journal-detail{max-height:calc(100dvh - 350px);min-height:400px;overflow:auto;padding:22px}.journal-detail header h2{font:28px Consolas,monospace;margin:10px 0}.journal-detail h3,.map-info h3{font-size:12px;margin:22px 0 14px;color:#b1c4d9}.journal-facts{display:grid;grid-template-columns:1fr 1fr;gap:16px 12px;margin-top:22px}.journal-facts span{font-size:10px;color:#7e98b3;display:block;margin-bottom:5px}.journal-facts b{font-size:11px;font-weight:500;overflow-wrap:anywhere}.journal-source,.journal-footnote{font-size:10px;color:#8196ac;line-height:1.7;margin:18px 0}.journal-timeline{padding:0;list-style:none;border-left:1px solid #3b546b;margin-left:4px}.journal-timeline li{position:relative;padding:0 0 18px 16px}.journal-timeline li:before{content:'';position:absolute;left:-4px;top:4px;width:7px;height:7px;background:#7ca7c7;border-radius:50%}.journal-timeline time{display:block;color:#7b96b0;font-size:9px;margin-bottom:5px}.journal-timeline span{font-size:11px;line-height:1.6}.journal-transfers>div{display:flex;justify-content:space-between;gap:10px;padding:8px 0;border-bottom:1px solid #28394b;font-size:10px}.journal-warning{padding:12px 16px;margin-bottom:15px;border:1px solid #665940;border-radius:9px;color:#d4c59f;font-size:11px}.map-toolbar{font-size:12px;color:#a2b9d0}.map-toolbar label{display:flex;align-items:center;gap:8px}.map-toolbar input[type=checkbox]{width:16px;height:16px}.map-toolbar #map-summary{margin-left:auto;font-size:11px}.map-layout{display:grid;grid-template-columns:minmax(0,1fr) 320px;gap:18px;align-items:stretch}.map-card{position:relative;min-height:520px;background:#0d1b2b;overflow:hidden}.map-card svg{display:block;width:100%;height:100%;min-height:520px;touch-action:none;cursor:grab}.map-card svg:active{cursor:grabbing}.map-land{fill:#203b4d;stroke:#456171;stroke-width:.7;vector-effect:non-scaling-stroke;fill-rule:evenodd}.map-gridline{stroke:#7496b0;stroke-width:.4;opacity:.15;vector-effect:non-scaling-stroke;fill:none}.map-track{fill:none;stroke-width:2;opacity:.7;vector-effect:non-scaling-stroke;cursor:pointer;stroke-dasharray:5 5}.map-track:hover,.map-track.selected{opacity:1;stroke-width:3;stroke-dasharray:none}.map-point{cursor:pointer;outline:none}.map-point text,.map-local text{font-family:Consolas,monospace;paint-order:stroke;stroke:#0b1824;stroke-width:.6px;stroke-linejoin:round}.map-point:hover circle:first-child,.map-point.selected circle:first-child,.map-point:focus circle:first-child{opacity:.6}.map-controls{position:absolute;top:16px;left:16px;display:flex;gap:5px;z-index:2}.map-controls button{height:35px;min-width:35px;Line truncated
.map-local{pointer-events:none}.map-shared{margin-top:18px;padding:14px;border:1px solid #426177;border-radius:9px;background:#172b3b}.map-shared>b{display:block;font-size:12px;color:#b8d4e8}.map-shared p{margin:10px 0}.map-shared button{margin:9px 6px 4px 0;font-size:12px;padding:7px 12px}.map-shared small{display:block;font-size:10px;line-height:1.6;color:#8ea7bd;margin-top:8px}
.legend-unknown{color:#d3c394}
.journal-layout{gap:16px;grid-template-columns:minmax(0,1fr) 330px}
.journal-table-scroll{max-height:clamp(280px,calc(100dvh - 500px),680px)}
.journal-table{font-size:12px}
.journal-table th,.journal-table td{padding:13px 12px}
.journal-table th,.journal-table td small,.journal-badge,.journal-result{font-size:11px}
.journal-table td b{font-size:14px}
.journal-detail{padding:20px;min-height:320px;max-height:clamp(336px,calc(100dvh - 442px),738px)}
.journal-detail .reader-empty{min-height:280px;gap:8px}
.journal-detail .reader-empty h2{font-size:17px}
.journal-detail .reader-empty p{max-width:240px;line-height:1.6}
.journal-facts span,.journal-facts b,.journal-timeline span{font-size:12px}
.journal-timeline time{font-size:11px}
.journal-layout .data-notes{padding:10px 12px}
.map-layout{gap:16px;grid-template-columns:minmax(0,1fr) 300px;height:clamp(380px,calc(100dvh - 270px),640px)}
.map-card{height:100%;min-height:0;background:#0b1624}
.map-card svg{height:100%;min-height:0}
.map-info{padding:20px;max-height:none;min-height:0;overflow:auto}
.map-info-empty{display:flex;flex-direction:column;justify-content:center;align-items:center;min-height:100%;padding:24px 0;gap:14px}
.map-info-empty h2{font-size:17px;margin:0}
.map-info-empty p{max-width:230px;margin:0;font-size:12px}
.map-info p,.map-info form label,.map-info form small,.map-last span,.map-last small,.map-recent small,.map-shared small{font-size:12px}
.map-info header h2{font-size:27px}
.map-legend{gap:12px;flex-wrap:wrap;max-width:calc(100% - 32px);font-size:11px;left:16px;bottom:23px;border:1px solid #344b60}
.map-attribution{font-size:10px;bottom:6px}
.map-toolbar #map-summary{font-size:12px}
.map-station small{font-size:11px;color:#9bacbf}
.map-station{min-width:160px}
@media(max-width:1400px){.journal-layout{grid-template-columns:1fr}.journal-detail:has(.reader-empty){display:none}.journal-detail{max-height:560px}.map-layout{grid-template-columns:minmax(0,1fr) 280px}}
@media(max-width:950px){.map-layout{grid-template-columns:1fr;height:auto}.map-card{height:420px}.map-info{max-height:440px}.map-info:has(.map-info-empty){display:none}}
@media(max-width:600px){.map-card{height:360px}.map-legend{font-size:10px;gap:8px}.journal-table-scroll{min-height:260px}.journal-detail{padding:16px}}
+25
View File
@@ -0,0 +1,25 @@
(() => {
let data=null,loading=false,selected=null;
const snapshots=new WeakMap();
function markup(el,html){if(snapshots.get(el)===html)return false;const open=[...el.querySelectorAll('details[open][id]')].map(d=>d.id);snapshots.set(el,html);el.innerHTML=html;for(const id of open){const item=document.getElementById(id);if(item)item.open=true;}return true;}
const time=t=>t?new Date(t).toLocaleString(BPQI18n.locale(),{day:'2-digit',month:'2-digit',year:'numeric',hour:'2-digit',minute:'2-digit',second:'2-digit'}):'—';
const bytes=n=>n==null?'—':size(n);
const state=s=>({complete:'Scambio concluso',connected:'Collegato',failed:'Non riuscito',incomplete:'Esito non registrato'}[s]||s);
const direction=d=>({incoming:'In ingresso',outgoing:'In uscita',unknown:'Non rilevata'}[d]);
const transport=t=>({Radio:'Radio',Internet:'Internet','NET/ROM':'NET/ROM',Local:'Locale / Telnet',CMS:'Gateway Winlink',BPQ:'Nodo BPQ',Unknown:'Porta non archiviata'}[t]||t);
const duration=s=>s==null?'—':s>=3600?Math.floor(s/3600)+' h '+Math.floor(s%3600/60)+' min':s>=60?Math.floor(s/60)+' min '+s%60+' s':s+' s';
for(const [id,title,icon]of [['journal','Diario','◷']]){const b=document.createElement('button');b.dataset.page=id;b.innerHTML='<span>'+icon+'</span> '+title;b.onclick=()=>navigate(id);$('nav').append(b);}
const journal=document.createElement('section');journal.id='journal';journal.className='page';journal.hidden=true;journal.innerHTML=`<div class="journal-heading"><div><h1>Diario dei collegamenti</h1><p id="journal-coverage">Lettura dei log BPQ…</p></div><div><button class="secondary" id="journal-export">↓ CSV</button><button class="primary" id="journal-refresh">↻ Aggiorna</button></div></div><div class="journal-kpis" id="journal-kpis"></div><div class="journal-filters"><input id="journal-search" type="search" placeholder="Cerca nominativo, servizio o frequenza…" aria-label="Cerca nel diario"><select id="journal-period" aria-label="Periodo diario"><option value="1">Ultime 24 ore</option><option value="7" selected>Ultimi 7 giorni</option><option value="30">Ultimi 30 giorni</option></select><select id="journal-service" aria-label="Servizio diario"><option value="">Tutti i servizi</option><option>BBS</option><option>Winlink</option><option>Chat</option><option>Radio</option></select><select id="journal-direction" aria-label="Direzione diario"><option value="">Tutte le direzioni</option><option value="incoming">In ingresso</option><option value="outgoing">In uscita</option><option value="unknown">Non rilevata</option></select><select id="journal-result" aria-label="Esito diario"><option value="">Tutti gli esiti</option><option value="complete">Scambio concluso</option><option value="connected">Collegato</option><option value="failed">Non riuscito</option><option value="incomplete">Esito non registrato</option></select></div><div class="journal-layout"><div class="card journal-table-card"><div class="card-header"><h2>Sessioni</h2><span id="journal-count"></span></div><div class="journal-table-scroll"><table class="journal-table"><thead><tr><th>Data e ora</th><th>Stazione / servizio</th><th>Collegamento</th><th>Durata</th><th>TX / RX</th><th>Messaggi</th><th>Esito</th></tr></thead><tbody id="journal-rows"></tbody></table></div></div><aside class="card journal-detail" id="journal-detail"><div class="reader-empty"><span>◷</span><h2>Seleziona un collegamento</h2><p>Traffico, servizio ed eventi della sessione.</p></div></aside></div><details id="journal-warning" class="data-notes" hidden><summary>Copertura parziale dei dati</summary><div id="journal-warning-detail" data-no-i18n></div></details>`;$('main').append(journal);
const previousNavigate=navigate;navigate=function(next){if(next==='map')next='journal';previousNavigate(next);if(next==='journal'){$('#breadcrumb').textContent='Stazione / Diario';load();}};
async function load(force=false,background=false){if(!csrf||loading)return;if(data&&!force){render();return;}loading=true;try{data=await api('/journal',{busy:!background});render();}catch(e){toast(e.message);$('#journal-coverage').textContent='Diario non disponibile: '+e.message;}finally{loading=false;}}
function filtered(){const q=$('#journal-search').value.toUpperCase(),days=Number($('#journal-period').value),svc=$('#journal-service').value,dir=$('#journal-direction').value,result=$('#journal-result').value;return (data?.sessions||[]).filter(s=>Date.parse(s.startedAt)>=Date.now()-days*86400000&&(!svc||s.service===svc)&&(!dir||s.direction===dir)&&(!result||s.status===result)&&(!q||[s.call,s.localCall,s.service,s.frequency,s.transport].join(' ').toUpperCase().includes(q)));}
function render(){if(!data)return;const list=filtered();$('#journal-coverage').textContent=BPQI18n.t('Dal')+' '+(data.since||'—')+' · '+mailTimezone();$('#journal-count').textContent=list.length+' sessioni';const connected=list.filter(s=>s.connectedAt||s.status==='complete');const peers=new Set(list.map(s=>s.call));const tx=list.reduce((a,s)=>a+(s.txBytes||0),0),rx=list.reduce((a,s)=>a+(s.rxBytes||0),0);markup($('#journal-kpis'),[['Sessioni',list.length],['Collegamenti stabiliti',connected.length],['Destinazioni',peers.size],['Traffico registrato',bytes(tx)+' / '+bytes(rx)]].map(([title,value])=>`<article><span>${esc(title)}</span><strong>${esc(value)}</strong></article>`).join(''));$('#journal-warning').hidden=!data.warnings.length&&!data.limited;$('#journal-warning-detail').textContent=[...data.warnings,data.limited?'Sono mostrate le 5000 sessioni più recenti.':''].filter(Boolean).join(' · ');markup($('#journal-rows'),list.map(s=>`<tr class="${selected===s.id?'selected':''}"><td><button class="journal-open" data-session="${esc(s.id)}">${esc(time(s.startedAt))}</button><small>${esc(direction(s.direction))}</small></td><td><b>${esc(s.call)}</b><small>${esc(s.service)}</small></td><td><span title="${esc(s.transportEvidence||'')}" class="journal-badge ${s.transport==='Radio'?'radio':''}">${esc(transport(s.transport))}</span><small>${s.frequency?esc(s.frequency)+' MHz':s.port?'Porta '+s.port:'—'}</small></td><td>${esc(duration(s.duration))}</td><td><span class="tx-key">↑ ${esc(bytes(s.txBytes))}</span><small class="rx-key">↓ ${esc(bytes(s.rxBytes))}</small></td><td>${s.sentMessages||0} ↑ / ${s.receivedMessages||0} ↓</td><td><span class="journal-result ${esc(s.status)}">${esc(state(s.status))}</span></td></tr>`).join('')||'<tr><td colspan="7" class="empty">Nessuna sessione corrisponde ai filtri.</td></tr>');$$('#journal-rows tr').forEach(row=>{const b=row.querySelector('[data-session]');if(b)row.onclick=()=>detail(b.dataset.session);});if(selected)detail(selected,false);}
function detail(id,refresh=true){const s=data.sessions.find(s=>s.id===id);if(!s)return;selected=id;markup($('#journal-detail'),`<header><span class="eyebrow">${esc(s.service)} · ${esc(direction(s.direction))}</span><h2>${esc(s.call)}</h2><span class="journal-result ${esc(s.status)}">${esc(state(s.status))}</span></header><div class="journal-facts">${[['Inizio',time(s.startedAt)],['Connessione',time(s.connectedAt)],['Fine',time(s.endedAt)],['Durata collegamento',duration(s.duration)],['Trasporto',transport(s.transport)],['Modem',s.mode||'Non registrato'],['Porta BPQ',s.port||'—'],['Frequenza',s.frequency?s.frequency+' MHz':'Non registrata'],['SNR medio',s.snr==null?'—':s.snr+' dB'],['Tentativi',s.attempts?s.attempts+' / '+s.maxAttempts:'—'],['TX',bytes(s.txBytes)],['RX',bytes(s.rxBytes)],['Picco TX / RX',s.peakTxBps==null?'—':s.peakTxBps+' / '+s.peakRxBps+' bit/s'],['Messaggi inviati / ricevuti',s.sentMessages+' / '+s.receivedMessages]].map(([k,v])=>`<div><span>${esc(k)}</span><b>${esc(v)}</b></div>`).join('')}</div><details id="journal-evidence" class="data-notes"><summary>Dettagli dei dati</summary><p class="journal-source">${esc(s.transportEvidence||'')}<br>${esc(s.trafficScope||'Contatori di traffico non presenti nel log.')}<br>Le statistiche disponibili dipendono dal servizio e dal modem; i trattini indicano dati non registrati.</p>${s.cmsTraffic?`<p class="journal-source">Connessione CMS: TX ${esc(bytes(s.cmsTraffic.txBytes))} / RX ${esc(bytes(s.cmsTraffic.rxBytes))}</p>`:''}</details><h3>Sequenza degli eventi</h3><ol class="journal-timeline">${s.events.map(e=>`<li><time>${esc(time(e.at))}</time><span>${esc(e.text)}</span></li>`).join('')}</ol>${s.messages.length?`<h3>Messaggi trasferiti</h3><div class="journal-transfers">${s.messages.map(m=>`<div><b>${esc(m.direction)} ${m.id?'#'+m.id:''}</b><span>${esc(bytes(m.bytes))} · compressi ${esc(bytes(m.compressedBytes))}</span></div>`).join('')}</div>`:''}<details id="journal-sources" class="data-notes"><summary>Fonti</summary><p class="journal-source" data-no-i18n>${esc([...new Set(s.sources)].join(', '))}</p></details>`);if(refresh)$$('#journal-rows tr').forEach(row=>row.classList.toggle('selected',row.querySelector('[data-session]')?.dataset.session===id));}
for(const id of ['journal-search','journal-period','journal-service','journal-direction','journal-result'])$('#'+id).oninput=render;
$('#journal-refresh').onclick=()=>load(true);
$('#journal-export').onclick=()=>{const quote=v=>'"'+String(v??'').replaceAll('"','""')+'"';const rows=[['Stazione','Servizio','Trasporto','Direzione','Inizio UTC','Connessione UTC','Fine UTC','Durata s','Frequenza MHz','TX byte','RX byte','Messaggi TX','Messaggi RX','Esito'],...filtered().map(s=>[s.call,s.service,s.transport,s.direction,s.startedAt,s.connectedAt,s.endedAt,s.duration,s.frequency,s.txBytes,s.rxBytes,s.sentMessages,s.receivedMessages,s.status])];const url=URL.createObjectURL(new Blob(['\ufeff'+rows.map(row=>row.map(quote).join(';')).join('\r\n')],{type:'text/csv;charset=utf-8'})),a=document.createElement('a');a.href=url;a.download='BPQ-diario-'+new Date().toISOString().slice(0,10)+'.csv';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
setInterval(()=>{if(csrf&&!document.hidden&&page==='journal')load(true,true)},30000);
document.addEventListener('bpq-languagechange',()=>{if(data)render();});
document.addEventListener('station-ready',()=>{if(page==='journal')load();});
document.addEventListener('DOMContentLoaded',()=>{const hash=location.hash.slice(1);if(['journal','map'].includes(hash))navigate(hash)});
})();
+27 -1
View File
@@ -2,7 +2,7 @@
.callsign-pair>div{display:flex;flex-direction:column;gap:11px}.callsign-pair>div:last-child{text-align:right}.callsign-pair small{font-size:8px;letter-spacing:1.5px;color:#617d9b}.modem-session.idle .callsign-pair>div:first-child b{color:#deedfa}.modem-session.connected .callsign-pair small{color:#7daa9b} .callsign-pair>div{display:flex;flex-direction:column;gap:11px}.callsign-pair>div:last-child{text-align:right}.callsign-pair small{font-size:8px;letter-spacing:1.5px;color:#617d9b}.modem-session.idle .callsign-pair>div:first-child b{color:#deedfa}.modem-session.connected .callsign-pair small{color:#7daa9b}
@media(min-width:1200px) and (min-height:820px){ @media(min-width:1200px) and (min-height:820px){
body:has(#home:not([hidden])) .topbar{height:64px} body:has(#home:not([hidden])) .topbar{height:64px}
#home{height:calc(100dvh - 64px);max-width:none;display:grid;grid-template-rows:56px 100px minmax(380px,1fr) minmax(100px,.42fr) 14px;gap:14px;padding:18px 28px 14px} #home{height:calc(100dvh - 64px);max-width:none;display:grid;grid-template-rows:56px 100px minmax(380px,1fr) 14px;gap:14px;padding:18px 28px 14px}
#home .mission-heading,#home .metrics,#home .overview-grid,#home .page-footer{margin:0} #home .mission-heading,#home .metrics,#home .overview-grid,#home .page-footer{margin:0}
#home .mission-heading h1{font-size:28px;margin-top:6px} #home .mission-heading h1{font-size:28px;margin-top:6px}
#home .metrics article{min-height:0;padding:15px 20px} #home .metrics article{min-height:0;padding:15px 20px}
@@ -31,3 +31,29 @@
#home .bottom-grid .full{padding:8px;width:calc(100% - 36px);margin:7px 18px 10px;flex-shrink:0} #home .bottom-grid .full{padding:8px;width:calc(100% - 36px);margin:7px 18px 10px;flex-shrink:0}
#home .page-footer{font-size:8px;align-items:center} #home .page-footer{font-size:8px;align-items:center}
} }
/* Compact connection header; reserve the modem card for telemetry. */
#home .overview-grid{grid-template-columns:minmax(0,1.9fr) minmax(280px,1fr)}
#home .modem-session{padding:9px 18px;display:grid;grid-template-columns:125px minmax(0,1fr);column-gap:16px;align-items:center}
#home .session-label{font-size:8px;line-height:1.5;letter-spacing:1.4px}
#home .callsign-pair{margin:0;gap:14px}
#home .callsign-pair>div{gap:3px}
#home .callsign-pair b{font-size:21px;line-height:1.25}
#home .callsign-pair small{font-size:7px;letter-spacing:1px}
#home .callsign-pair>span{font-size:18px}
#home #session-detail{grid-column:2;margin-top:3px;font-size:9px}
#home .telemetry-chart{height:112px;margin-top:8px}
#home .telemetry-grid header>span{font-size:10px;letter-spacing:.7px}
#home .telemetry-grid header b{font-size:19px}
#home .telemetry-grid article footer{font-size:9px}
@media(min-width:1200px) and (min-height:820px){
#home .telemetry-chart{height:auto;flex:1;min-height:45px}
#home .telemetry-grid article{padding:11px 17px 0}
}
@media(max-width:1150px){#home .overview-grid{grid-template-columns:1fr}}
@media(max-width:600px){
#home .modem-session{grid-template-columns:1fr;padding:10px 14px;gap:7px}
#home .session-label{font-size:8px}#home #session-detail{grid-column:1}
#home .callsign-pair b{font-size:19px}#home .telemetry-chart{height:100px}
#home .telemetry-grid header>span{font-size:8px}#home .telemetry-grid header b{font-size:16px}
}
+4 -4
View File
@@ -1,11 +1,11 @@
let modemTelemetry=null,modemPolling=false; let modemTelemetry=null,modemPolling=false;
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>TRAFFICO BPQ</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 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>TRAFFICO BPQ</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>STAZIONE<span> / BPQ</span></h1></div><div class="mission-location"><span class="dot"></span> STAZIONE BPQ <small></small></div>'; const missionHead=document.createElement('div');missionHead.className='mission-heading';missionHead.innerHTML='<div><span class="mission-kicker">Operazioni radio</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||'—':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.available?Math.round((c.txBps||0)+(c.rxBps||0)).toLocaleString('it-IT'):'—';$('#bps-caption').textContent='TX '+Math.round(c.txBps||0).toLocaleString('it-IT')+' / RX '+Math.round(c.rxBps||0).toLocaleString('it-IT')+' bit/s · dati BPQ';$('#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,['txBps','rxBps'],'traffico BPQ 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=window.bpqRadioControl?.txSuspended?'TX SOSPESO':!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=window.bpqRadioControl?.txSuspended?'PORTE RADIO IN PAUSA':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.available?Math.round((c.txBps||0)+(c.rxBps||0)).toLocaleString(BPQI18n.locale()):'—';$('#bps-caption').textContent='TX '+Math.round(c.txBps||0).toLocaleString(BPQI18n.locale())+' / RX '+Math.round(c.rxBps||0).toLocaleString(BPQI18n.locale())+' bit/s · dati BPQ';$('#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,['txBps','rxBps'],'traffico BPQ 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',{busy:false}))}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(...args){await missionDashboard(...args);if(modemTelemetry)renderTelemetry(modemTelemetry);pollTelemetry();};setInterval(()=>{if(csrf&&!document.hidden&&!window.BPQDetached?.view)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);
fullscreenButton.onclick=async()=>{try{if(document.fullscreenElement)await document.exitFullscreen();else await document.documentElement.requestFullscreen();}catch{toast('Schermo intero non disponibile in questo browser. Prova F11.');}}; fullscreenButton.onclick=async()=>{try{if(document.fullscreenElement)await document.exitFullscreen();else await document.documentElement.requestFullscreen();}catch{toast('Schermo intero non disponibile in questo browser. Prova F11.');}};
document.addEventListener('fullscreenchange',()=>{const active=!!document.fullscreenElement;fullscreenButton.textContent=active?'⊡':'⛶';fullscreenButton.title=active?'Torna alla finestra':'Schermo intero';fullscreenButton.setAttribute('aria-label',fullscreenButton.title);fullscreenButton.setAttribute('aria-pressed',String(active));}); document.addEventListener('fullscreenchange',()=>{const active=!!document.fullscreenElement;fullscreenButton.textContent=active?'⊡':'⛶';fullscreenButton.title=active?'Torna alla finestra':'Schermo intero';fullscreenButton.setAttribute('aria-label',fullscreenButton.title);fullscreenButton.setAttribute('aria-pressed',String(active));});
+1 -1
View File
@@ -6,7 +6,7 @@ const originalNavigate=navigate;navigate=function(next){originalNavigate(next);i
function filtered(){const port=$('#monitor-port').value,dir=$('#monitor-direction').value,q=$('#monitor-search').value.toLowerCase();return events.filter(e=>(!port||String(e.port)===port)&&(!dir||e.direction===dir)&&(!q||e.text.toLowerCase().includes(q)));} function filtered(){const port=$('#monitor-port').value,dir=$('#monitor-direction').value,q=$('#monitor-search').value.toLowerCase();return events.filter(e=>(!port||String(e.port)===port)&&(!dir||e.direction===dir)&&(!q||e.text.toLowerCase().includes(q)));}
function render(){const list=filtered(),area=$('#monitor-console');area.innerHTML=list.map(e=>`<article class="monitor-frame ${e.direction.toLowerCase()}"><div><span class="monitor-direction">${esc(e.direction)}</span><span class="monitor-port">${e.port?'P'+e.port:'BPQ'}</span></div><pre>${esc(e.text)}</pre></article>`).join('')||'<p class="monitor-empty">'+(state==='online'?'In ascolto. Nessun traffico corrispondente ai filtri.':'Avvia il monitor per seguire il traffico BPQ.')+'</p>';$('#monitor-count').textContent=list.length+' frame · '+events.length+' in memoria'+(paused?' · visualizzazione in pausa':'');if($('#monitor-follow').checked)area.scrollTop=area.scrollHeight;displayedCursor=cursor;} function render(){const list=filtered(),area=$('#monitor-console');area.innerHTML=list.map(e=>`<article class="monitor-frame ${e.direction.toLowerCase()}"><div><span class="monitor-direction">${esc(e.direction)}</span><span class="monitor-port">${e.port?'P'+e.port:'BPQ'}</span></div><pre>${esc(e.text)}</pre></article>`).join('')||'<p class="monitor-empty">'+(state==='online'?'In ascolto. Nessun traffico corrispondente ai filtri.':'Avvia il monitor per seguire il traffico BPQ.')+'</p>';$('#monitor-count').textContent=list.length+' frame · '+events.length+' in memoria'+(paused?' · visualizzazione in pausa':'');if($('#monitor-follow').checked)area.scrollTop=area.scrollHeight;displayedCursor=cursor;}
function status(data){state=data.state;$('#monitor-state').className='chat-status '+state;$('#monitor-state').textContent=data.error||({online:'● In ascolto',connecting:'Connessione…',offline:'Disconnesso',error:'Non disponibile'}[state]);$('#monitor-connect').hidden=state==='online';$('#monitor-connect').disabled=state==='connecting';$('#monitor-stop').hidden=!['online','connecting'].includes(state);const current=$('#monitor-port').value;$('#monitor-port').innerHTML='<option value="">Tutte le porte</option>'+data.ports.map(p=>`<option value="${p.id}">${p.id} · ${esc(p.name)}</option>`).join('');$('#monitor-port').value=current;} function status(data){state=data.state;$('#monitor-state').className='chat-status '+state;$('#monitor-state').textContent=data.error||({online:'● In ascolto',connecting:'Connessione…',offline:'Disconnesso',error:'Non disponibile'}[state]);$('#monitor-connect').hidden=state==='online';$('#monitor-connect').disabled=state==='connecting';$('#monitor-stop').hidden=!['online','connecting'].includes(state);const current=$('#monitor-port').value;$('#monitor-port').innerHTML='<option value="">Tutte le porte</option>'+data.ports.map(p=>`<option value="${p.id}">${p.id} · ${esc(p.name)}</option>`).join('');$('#monitor-port').value=current;}
async function poll(){if(!csrf||busy)return;busy=true;try{let data=await api('/monitor?after='+cursor);if(data.latest<cursor){cursor=0;events=[];data=await api('/monitor?after=0');}status(data);events.push(...data.events);events=events.slice(-1000);cursor=data.latest;if(!paused&&(cursor!==displayedCursor||!events.length))render();}catch(e){if(page==='monitor')toast(e.message)}finally{busy=false;}} async function poll(){if(!csrf||busy||window.BPQDetached&&!window.BPQDetached.shouldPoll('monitor'))return;busy=true;try{let data=await api('/monitor?after='+cursor,{busy:false});if(data.latest<cursor){cursor=0;events=[];data=await api('/monitor?after=0');}status(data);events.push(...data.events);events=events.slice(-1000);cursor=data.latest;if(!paused&&(cursor!==displayedCursor||!events.length))render();}catch(e){if(page==='monitor')toast(e.message)}finally{busy=false;}}
$('#monitor-connect').onclick=async()=>{try{status(await api('/monitor/connect',{method:'POST',body:'{}'}));await poll();}catch(e){toast(e.message)}}; $('#monitor-connect').onclick=async()=>{try{status(await api('/monitor/connect',{method:'POST',body:'{}'}));await poll();}catch(e){toast(e.message)}};
$('#monitor-stop').onclick=async()=>{try{await api('/monitor/disconnect',{method:'POST',body:'{}'});await poll()}catch(e){toast(e.message)}}; $('#monitor-stop').onclick=async()=>{try{await api('/monitor/disconnect',{method:'POST',body:'{}'});await poll()}catch(e){toast(e.message)}};
$('#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';};
+1
View File
@@ -0,0 +1 @@
.radio-control{padding:10px 17px;border-block:1px solid #293544;background:#101a26}.radio-control-head{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:9px}.radio-control-head>span{font-size:9px;letter-spacing:1.2px;color:#91a8c0}.radio-control-head button{font-size:10px;padding:6px 10px}.radio-control-head .tx-paused{background:#493422;border-color:#bc8b53;color:#f0ca97}.radio-listen-channels{display:flex;gap:8px;flex-wrap:wrap}.listen-channel{flex:1;display:flex;gap:8px;align-items:center;padding:8px 10px;border:1px solid #2d3a4b;border-radius:8px;color:#8595aa;cursor:pointer;min-width:140px;transition:background .15s}.listen-channel.enabled{color:#d1deed;background:#172333}.listen-channel.listening{border-color:#698e96;box-shadow:inset 0 0 0 1px #698e9633}.listen-channel input[type=checkbox]{width:15px;height:15px;flex:none;margin:0;accent-color:#8bb7b2}.listen-channel b{display:block;font-size:12px;font-weight:500;font-variant-numeric:tabular-nums}.listen-channel small{display:block;font-size:9px;color:#91a6bc;margin-top:3px}.listen-channel:has(input:disabled){cursor:default}#radio-control-state{font-size:9px;color:#90a3b9;margin-top:7px;line-height:1.4}@media(max-width:600px){.listen-channel{min-width:120px}.radio-control{padding-inline:12px}}
+11
View File
@@ -0,0 +1,11 @@
(()=>{
const panel=document.createElement('section');panel.className='radio-control';panel.innerHTML='<div class="radio-control-head"><span>FREQUENZE DI ASCOLTO</span><button id="radio-tx-toggle" class="secondary" disabled>Sospendi TX</button></div><div id="radio-listen-channels" class="radio-listen-channels"></div><div id="radio-control-state" role="status">Caricamento frequenze…</div>';
document.querySelector('.modem-frequency').after(panel);let data=null,busy=false,loading=false;
const text=r=>r.frequencyMHz.toLocaleString(BPQI18n.locale(),{minimumFractionDigits:3,maximumFractionDigits:3,useGrouping:false})+' MHz';
function render(){if(!data)return;window.bpqRadioControl=data;const active=document.activeElement?.dataset?.scanChannel;document.querySelector('#radio-listen-channels').innerHTML=data.channels.map(r=>'<label class="listen-channel '+(r.enabled?'enabled ':'')+(r.current?'listening':'')+'"><input type="checkbox" data-scan-channel="'+esc(r.id)+'" '+(r.enabled?'checked ':'')+(!data.supported||data.pending||busy?'disabled':'')+'><span><b>'+text(r)+'</b><small>'+esc(r.mode)+' · '+r.dwellSeconds+' s'+(r.current&&r.enabled&&!data.txSuspended?' · in ascolto':'')+'</small></span></label>').join('')||'<span>Nessuna scansione configurata</span>';const tx=document.querySelector('#radio-tx-toggle');tx.textContent=data.txSuspended?'Riprendi radio':'Sospendi TX';tx.classList.toggle('tx-paused',data.txSuspended);tx.setAttribute('aria-pressed',String(data.txSuspended));tx.disabled=!data.supported||data.pending||busy;document.querySelector('#radio-control-state').textContent=data.error||(!data.supported?'Controllo remoto non disponibile':data.pending?'Applicazione richiesta in corso…':data.txSuspended?'TX sospeso · porte e connessioni radio ferme':'La pausa TX chiude le connessioni radio; Internet resta disponibile.');if(active)document.querySelector('[data-scan-channel="'+active+'"]')?.focus({preventScroll:true});}
async function load(){if(!csrf||loading)return;loading=true;try{data=await api('/radio/control');render();}catch(e){document.querySelector('#radio-control-state').textContent=e.message;}finally{loading=false;}}
async function apply(enabled,txSuspended){if(busy)return;if(!enabled.length){toast('Mantieni almeno una frequenza di ascolto');render();return;}busy=true;render();try{data=await api('/radio/control',{method:'POST',body:JSON.stringify({enabled,txSuspended})});}catch(e){toast(e.message);}finally{busy=false;render();}}
panel.addEventListener('change',e=>{if(e.target.matches('[data-scan-channel]')){const enabled=data.channels.filter(r=>r.id===e.target.dataset.scanChannel?e.target.checked:r.enabled).map(r=>r.id);apply(enabled,data.txSuspended);}});
document.querySelector('#radio-tx-toggle').onclick=()=>apply(data.channels.filter(r=>r.enabled).map(r=>r.id),!data.txSuspended);
document.addEventListener('bpq-languagechange',render);document.addEventListener('station-ready',load);setInterval(()=>{if(!document.hidden&&page==='home')load();},2000);load();
})();
+1
View File
@@ -0,0 +1 @@
.port-tabs{display:flex;gap:8px;padding:9px 16px;border-bottom:1px solid #2a3b4f;overflow-x:auto;flex-shrink:0}.port-tab{flex:1;min-width:150px;text-align:left;background:#101b29;border:1px solid #2c4056;border-radius:9px;padding:9px 12px;color:#b7c9dc;cursor:pointer}.port-tab.selected{border-color:#73adc9;background:linear-gradient(120deg,#1d354b,#172739)}.port-tab-title{display:flex;gap:7px;align-items:center;font-size:10px;letter-spacing:.7px}.port-tab-title small{margin-left:auto;color:#8ca6bb}.port-dot{height:6px;width:6px;border-radius:50%;background:#7dcba5;box-shadow:0 0 9px #7dcba544}.port-dot.offline{background:#687587}.port-dot.paused{background:#dfbc79}.port-dot.live{background:#90e3c0;box-shadow:0 0 10px #90e3c0}.port-tab-frequency{display:block;font:20px/1.4 Consolas,monospace;color:#d8e8f7;margin-top:3px}.port-tab-frequency small{font-size:9px;color:#8aa4be}.port-tab-stats{display:block;font:9px Consolas,monospace;color:#8aa4be}.global-tx{margin-left:12px;font-size:10px!important}.modem-brand{margin-right:auto}.radio-port-actions{display:flex;gap:7px;align-items:center;flex-wrap:wrap}.radio-port-actions>span{margin-right:auto;font:9px Consolas,monospace;color:#8ca6bc}.radio-port-actions button{font-size:10px;padding:5px 8px}.radio-listen-channels{margin-top:8px}.port-channel{display:inline-flex;gap:7px;align-items:center;padding:4px 7px;border:1px solid #2b3d51;border-radius:5px;font:11px Consolas,monospace;color:#6c8296}.port-channel.enabled{color:#c0d5e7}.port-channel.listening.enabled{border-color:#6caa97;color:#a8dec6}.port-channel small{font-size:8px;color:#819aaf}.port-frequency-dialog{width:min(570px,95vw);background:#121e2d;color:#d8e5f2;border:1px solid #3d536b;border-radius:14px;padding:25px}.port-frequency-dialog::backdrop{background:#040911aa;backdrop-filter:blur(5px)}.port-frequency-rows{display:grid;gap:9px;margin:20px 0}.port-frequency-row{display:grid!important;grid-template-columns:18px minmax(100px,1fr) 45px 60px 12px 28px;gap:9px;align-items:center}.port-frequency-row input[type=checkbox]{width:16px;height:16px;accent-color:#9bcebd}.port-frequency-row input[type=number]{width:100%;min-width:0;margin:0;padding:9px;background:#0c1622;color:#d8e5f2;border:1px solid #34495e;border-radius:6px;font:13px Consolas,monospace}.port-frequency-row span,.port-frequency-row small{font-size:10px;color:#91a9be}.port-frequency-dialog footer{display:flex;justify-content:flex-end;gap:10px;margin-top:22px}.port-frequency-dialog .error{font-size:12px}.port-tab:focus-visible{outline:2px solid #addbc9;outline-offset:2px}#home .modem-top{padding:10px 17px}#home .radio-control{padding:8px 17px}#home #radio-control-state{margin-top:6px;font-size:9px}@media(max-width:600px){.port-tabs{padding:8px}.modem-brand{font-size:12px}.global-tx{font-size:8px!important}.port-frequency-dialog{padding:15px}.port-frequency-row{gap:5px;grid-template-columns:16px minmax(90px,1fr) 30px 45px 10px 22px}}
+33
View File
@@ -0,0 +1,33 @@
(()=>{
let data=null,selected=null,busy=false,loading=false;
const tabs=document.createElement('div');tabs.className='port-tabs';tabs.setAttribute('role','tablist');tabs.setAttribute('aria-label','Porte radio');document.querySelector('.modem-top').after(tabs);
const all=document.createElement('button');all.id='radio-tx-toggle';all.className='secondary global-tx';document.querySelector('.modem-top').append(all);
const panel=document.createElement('section');panel.className='radio-control';panel.innerHTML='<div class="radio-port-actions"><span id="port-control-title"></span><button class="secondary" data-action="listen"></button><button class="secondary" data-action="tx"></button><button class="secondary" data-action="frequencies">Frequenze</button></div><div class="radio-listen-channels" id="radio-listen-channels"></div><div id="radio-control-state" role="status"></div>';document.querySelector('.modem-frequency').after(panel);
const modal=document.createElement('dialog');modal.className='port-frequency-dialog';modal.innerHTML='<form><div class="dialog-heading"><h2>Frequenze di ascolto</h2><button type="button" class="icon-button" data-close aria-label="Chiudi">×</button></div><div class="port-frequency-rows"></div><button type="button" class="secondary" data-add>+ Frequenza</button><p class="error" role="alert"></p><footer><button type="button" class="secondary" data-close>Annulla</button><button class="primary" type="submit">Salva</button></footer></form>';document.body.append(modal);
const port=()=>data?.ports.find(p=>p.id===selected),hz=v=>Number.isFinite(Number(v))?Number(v).toLocaleString(BPQI18n.locale(),{minimumFractionDigits:3,maximumFractionDigits:3,useGrouping:false}):'—',rate=v=>v==null?'—':Math.round(v).toLocaleString(BPQI18n.locale());
function render(){if(!data)return;if(!data.ports.some(p=>p.id===selected))selected=data.ports[0]?.id;const p=port();if(!p)return;const focus=document.activeElement?.dataset?.portTab;
tabs.innerHTML=data.ports.map(r=>{const c=r.current,paused=data.global.txSuspended||r.control.txSuspended||!r.control.listening;return '<button role="tab" aria-selected="'+(r.id===selected)+'" data-port-tab="'+r.id+'" class="port-tab '+(r.id===selected?'selected':'')+'"><span class="port-tab-title"><i class="port-dot '+(!c.available?'offline':paused?'paused':c.active?'live':'')+'"></i><b>Port '+r.id+'</b><small>'+esc(r.driver)+'</small></span><span class="port-tab-frequency">'+hz(c.frequency)+' <small>MHz</small></span><span class="port-tab-stats">TX '+rate(c.txBps)+' · RX '+rate(c.rxBps)+' bit/s</span></button>';}).join('');if(focus)tabs.querySelector('[data-port-tab="'+focus+'"]')?.focus({preventScroll:true});
all.textContent=data.global.txSuspended?'Riprendi tutte le TX':'Sospendi tutte le TX';all.disabled=busy||!data.global.supported||data.global.pending;all.setAttribute('aria-pressed',String(data.global.txSuspended));
$('#port-control-title').textContent='PORT '+p.id+' · '+p.driver;const listen=panel.querySelector('[data-action="listen"]'),tx=panel.querySelector('[data-action="tx"]');listen.textContent=p.control.listening?'Ferma porta':'Avvia porta';tx.textContent=p.control.txSuspended?'Riprendi TX':'Sospendi TX';listen.setAttribute('aria-pressed',String(!p.control.listening));tx.setAttribute('aria-pressed',String(p.control.txSuspended));panel.querySelectorAll('button').forEach(b=>b.disabled=busy||!p.supported||p.control.pending);
$('#radio-listen-channels').innerHTML=p.channels.map(r=>'<span class="port-channel '+(r.enabled?'enabled':'')+' '+(r.current?'listening':'')+'">'+hz(r.frequencyMHz)+' <small>'+esc(r.mode)+' · '+r.dwellSeconds+' s</small></span>').join('');
$('#radio-control-state').textContent=p.error||(p.control.pending?'Applicazione richiesta in corso…':!p.supported?'Controllo porta non disponibile':data.global.txSuspended?'Tutte le trasmissioni sono sospese':!p.control.listening?'Porta ferma':p.control.txSuspended?'Trasmissioni della porta sospese':p.current.scan?'Scansione attiva':'Ascolto sulla frequenza selezionata');renderSelected();
}
const legacyRender=renderTelemetry;
function renderSelected(){const p=port();if(!p)return;const originalRadio=station.radio,originalControl=window.bpqRadioControl;station.radio={id:p.id,name:p.name,driver:p.driver};window.bpqRadioControl={txSuspended:data.global.txSuspended||p.control.txSuspended||!p.control.listening};
try{legacyRender({current:p.current,history:p.history});$('#radio-status').textContent=!p.control.listening?'PORTA FERMA':window.bpqRadioControl.txSuspended?'TX SOSPESO':!p.current.available?'OFFLINE':p.current.ptt?'TX':p.current.active?'LINK ATTIVO':'IN ASCOLTO';$('#session-detail').textContent=p.name;$('#modem-traffic').textContent=p.current.sent!=null?'TX '+size(p.current.sent)+' / RX '+size(p.current.received||0):'TX '+rate(p.current.txFrames)+' / RX '+rate(p.current.rxFrames)+' frame';$('#bps-value').textContent=p.current.txBps==null&&p.current.rxBps==null?'—':rate((p.current.txBps||0)+(p.current.rxBps||0));$('#bps-caption').textContent=p.current.txBps==null?'Statistiche frame BPQ':'TX '+rate(p.current.txBps)+' / RX '+rate(p.current.rxBps)+' bit/s';$('#radio-scan').textContent=p.current.scan?'● Scansione attiva':p.control.listening?'● Frequenza fissa':'● Porta ferma';$('#radio-modem').textContent='PORT '+p.id+' · '+p.driver;}
finally{station.radio=originalRadio;window.bpqRadioControl=originalControl;}
document.querySelector('.modem-brand').textContent=BPQI18n.t('PORTE RADIO');
const packet=/KISS|AX25|AX\.25/i.test(p.driver),cards=document.querySelectorAll('.telemetry-grid article');cards[1].querySelector('header>span').textContent=packet?'FRAME AX.25':'SNR / BPQ';cards[2].querySelector('header>span').textContent=packet?'TIMEOUT L2':/VARA/i.test(p.driver)?'CPU VARA':'CPU MODEM';cards[2].querySelector('footer').textContent=packet?'Contatore BPQ':'Processo modem · ogni 5 s';
if(packet){$('#snr-value').textContent=rate(p.current.txFrames)+' / '+rate(p.current.rxFrames);$('#snr-chart').innerHTML=graph(p.history,['txFrames','rxFrames'],'frame AX25',10);$('#snr-caption').textContent='TX / RX · contatori BPQ';$('#vara-cpu-value').textContent=rate(p.current.timeouts);$('#vara-cpu-chart').innerHTML=graph(p.history,['timeouts'],'timeout L2',5);}
}
renderTelemetry=function(){renderSelected();};
async function load(){if(!csrf||loading)return;loading=true;try{data=await api('/radio/ports',{busy:!data});render();}catch(e){$('#radio-control-state').textContent=e.message;}finally{loading=false;}}pollTelemetry=load;
async function apply(changes){const p=port();if(!p||busy)return;busy=true;render();try{data=await api('/radio/ports/'+p.id,{method:'POST',body:JSON.stringify({listening:p.control.listening,txSuspended:p.control.txSuspended,channels:p.channels,...changes})});return true;}catch(e){toast(e.message);modal.querySelector('.error').textContent=e.message;return false;}finally{busy=false;render();}}
tabs.onclick=e=>{const b=e.target.closest('[data-port-tab]');if(b){selected=Number(b.dataset.portTab);render();}};tabs.onkeydown=e=>{if(!['ArrowLeft','ArrowRight'].includes(e.key))return;e.preventDefault();const i=data.ports.findIndex(p=>p.id===selected);selected=data.ports[(i+(e.key==='ArrowRight'?1:data.ports.length-1))%data.ports.length].id;render();tabs.querySelector('[aria-selected="true"]')?.focus();};
all.onclick=async()=>{if(busy)return;busy=true;render();try{await api('/radio/control',{method:'POST',body:JSON.stringify({enabled:data.global.channels.filter(r=>r.enabled).map(r=>r.id),txSuspended:!data.global.txSuspended})});}catch(e){toast(e.message);}finally{busy=false;await load();}};
function frequencyRow(r,editable){return '<label class="port-frequency-row"><input type="checkbox" '+(r.enabled?'checked':'')+' aria-label="In scansione"><input type="number" step="0.000001" value="'+r.frequencyMHz+'" '+(!editable?'readonly':'')+' aria-label="Frequenza MHz"><span>'+esc(r.mode)+'</span><input type="number" min="5" max="300" value="'+r.dwellSeconds+'" '+(!editable?'readonly':'')+' aria-label="Secondi"><small>s</small><button type="button" class="icon-button" data-remove '+(!editable?'disabled':'')+' aria-label="Rimuovi frequenza">×</button></label>';}
panel.onclick=e=>{const action=e.target.closest('[data-action]')?.dataset.action,p=port();if(!p)return;if(action==='listen')apply({listening:!p.control.listening});if(action==='tx')apply({txSuspended:!p.control.txSuspended});if(action==='frequencies'){modal.dataset.port=String(p.id);modal.querySelector('.port-frequency-rows').innerHTML=p.channels.map(r=>frequencyRow(r,p.editableChannels)).join('');modal.querySelector('[data-add]').hidden=!p.editableChannels;modal.querySelector('.error').textContent='';modal.showModal();}};
modal.onclick=e=>{if(e.target.closest('[data-close]'))modal.close();if(e.target.closest('[data-remove]'))e.target.closest('.port-frequency-row').remove();if(e.target.closest('[data-add]'))modal.querySelector('.port-frequency-rows').insertAdjacentHTML('beforeend',frequencyRow({frequencyMHz:144.95,mode:'FM',dwellSeconds:15,enabled:false},true));};
modal.querySelector('form').onsubmit=async e=>{e.preventDefault();if(Number(modal.dataset.port)!==selected)return;const p=port(),rows=[...modal.querySelectorAll('.port-frequency-row')].map((r,i)=>{const inputs=r.querySelectorAll('input');return {...p.channels[i],id:p.editableChannels?Math.round(Number(inputs[1].value)*1e6)+'-FM':p.channels[i].id,frequencyMHz:Number(inputs[1].value),mode:p.editableChannels?'FM':p.channels[i].mode,dwellSeconds:Number(inputs[2].value),enabled:inputs[0].checked};});if(await apply({channels:rows}))modal.close();};
document.addEventListener('station-ready',load);document.addEventListener('bpq-languagechange',render);setInterval(()=>{if(!document.hidden&&page==='home')load();},2500);load();
})();
+1 -1
View File
@@ -1,3 +1,3 @@
@import url('data:text/css,'); @import url('data:text/css,');
:root{--bg:#f5f6f1;--ink:#192b23;--muted:#77817a;--green:#2d6249;--line:#e4e8df;--white:#fff;--lime:#c8eaa6}*{box-sizing:border-box}body{margin:0;font:14px 'Segoe UI',Arial,sans-serif;background:var(--bg);color:var(--ink)}button,input,select,textarea{font:inherit}button,a,input,select,textarea{-webkit-tap-highlight-color:transparent}button{cursor:pointer}button:disabled{opacity:.55;cursor:wait}button:focus-visible,a:focus-visible{outline:3px solid #80b862;outline-offset:3px}[hidden]{display:none!important}h1,h2,p{margin:0}h1{font-size:32px;line-height:1.25;letter-spacing:-1.1px;font-weight:600}h2{font-size:17px;font-weight:600}p{line-height:1.7}.eyebrow{font-size:10px;font-weight:700;letter-spacing:2px;color:var(--green)}.muted{color:var(--muted);font-size:12px}.primary,.secondary{border-radius:8px;padding:12px 18px;font-weight:600;display:inline-flex;align-items:center;justify-content:center;gap:10px;border:1px solid transparent}.primary{background:var(--green);color:#fff}.primary:hover{background:#204b37}.secondary{background:#fff;border-color:var(--line);color:var(--ink)}.secondary:hover{background:#f0f4ed}.text-button{background:none;border:0;color:var(--green);font-size:12px;font-weight:600}.icon-button{border:1px solid var(--line);background:#fff;border-radius:7px;width:34px;height:34px;font-size:21px;color:var(--ink)}.full{width:100%}.brand{font-size:23px;font-weight:700;letter-spacing:-1px;text-decoration:none;color:inherit}.brand>span{display:block;font-size:9px;font-weight:500;letter-spacing:3px;margin:7px 0 0 31px}.sidebar{width:230px;position:fixed;inset:0 auto 0 0;background:#11241b;color:#e7eddf;padding:32px 23px;display:flex;flex-direction:column;z-index:4}.sidebar .brand{margin-bottom:45px}.side-label{font-size:9px;letter-spacing:2px;color:#82998a;margin:0 10px 14px}nav button{display:flex;align-items:center;gap:12px;width:100%;border:0;background:none;color:#aec1b3;padding:14px 12px;text-align:left;border-radius:8px;margin-bottom:6px}nav button span{font-size:18px;width:18px}nav button.active{background:#294532;color:#e2f5c9}nav button:hover{background:#223e2d}nav b{font-size:10px;background:#466143;border-radius:4px;padding:2px 6px;margin-left:auto}.side-station{margin-top:auto;padding:24px 10px;color:#d5e6d5;font-weight:600;border-top:1px solid #304333}.dot{display:inline-block;width:7px;height:7px;border-radius:50%;background:var(--lime);margin-right:8px}.side-station small{display:block;color:#94aa99;font-size:11px;font-weight:400;line-height:1.8;margin-top:7px}.side-frequency{font-size:11px;line-height:2.2;margin:18px 0}.side-frequency span{float:right;font-family:Consolas,monospace;color:#cadcbe}.profile{display:flex;gap:10px;align-items:center;border-top:1px solid #304333;padding-top:20px;font-size:12px}.profile small{display:block;color:#92a696;font-size:10px;margin-top:4px}.profile button{margin-left:auto;background:none;border:0;color:#aec1b3;font-size:22px}.avatar{background:#c5dea8;color:#23452e;width:32px;height:32px;border-radius:50%;display:grid;place-items:center;font-size:11px;font-weight:700}main{margin-left:230px}.topbar{height:76px;padding:0 40px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line);font-size:11px;color:var(--muted)}.topbar>div{display:flex;align-items:center;gap:18px}.live-badge{color:var(--green);background:#e9f0e1;padding:7px 10px;border-radius:20px;font-size:10px;font-weight:600}#clock{font-family:Consolas,monospace}.page{padding:35px 40px 20px;max-width:1600px;margin:auto}.page-heading{display:flex;align-items:center;justify-content:space-between;gap:20px;margin-bottom:28px}.page-heading .eyebrow{display:block;margin-bottom:10px}.page-heading p{color:var(--muted);margin-top:10px;font-size:13px}.metrics{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:22px}.metrics article{position:relative;background:#fff;border:1px solid var(--line);border-radius:12px;padding:20px;min-height:137px}.metrics article>span{font-size:11px;color:var(--muted)}.metrics strong{display:block;font-size:32px;font-weight:600;letter-spacing:-1px;margin:10px 0 5px}.metrics small{font-size:10px;color:var(--muted)}.metrics i{position:absolute;right:18px;top:16px;font-style:normal;color:#9ab18d;font-size:19px}.overview-grid{display:grid;grid-template-columns:1fr 1.15fr;gap:22px;margin-bottom:22px}.card{background:#fff;border:1px solid var(--line);border-radius:12px;overflow:hidden}.card-header{display:flex;align-items:center;justify-content:space-between;padding:20px 22px;gap:10px}.tag{font-size:9px;letter-spacing:1px;background:#eff3ea;padding:5px 8px;border-radius:4px;color:var(--green);white-space:nowrap}.radio-card{border-radius:12px;background:#203e2d;color:#eaf1e0;overflow:hidden;position:relative}.radio-card .eyebrow{color:#c1dba7}.radio-card .tag{background:#3c5d40;color:#d2eab8}.radio-frequency{display:flex;align-items:baseline;gap:15px;margin:8px 25px 0}.radio-frequency>span{font:54px Consolas,monospace;leLine truncated :root{--bg:#f5f6f1;--ink:#192b23;--muted:#77817a;--green:#2d6249;--line:#e4e8df;--white:#fff;--lime:#c8eaa6}*{box-sizing:border-box}body{margin:0;font:14px 'Segoe UI',Arial,sans-serif;background:var(--bg);color:var(--ink)}button,input,select,textarea{font:inherit}button,a,input,select,textarea{-webkit-tap-highlight-color:transparent}button{cursor:pointer}button:disabled{opacity:.55;cursor:wait}button:focus-visible,a:focus-visible{outline:3px solid #80b862;outline-offset:3px}[hidden]{display:none!important}h1,h2,p{margin:0}h1{font-size:32px;line-height:1.25;letter-spacing:-1.1px;font-weight:600}h2{font-size:17px;font-weight:600}p{line-height:1.7}.eyebrow{font-size:10px;font-weight:700;letter-spacing:2px;color:var(--green)}.muted{color:var(--muted);font-size:12px}.primary,.secondary{border-radius:8px;padding:12px 18px;font-weight:600;display:inline-flex;align-items:center;justify-content:center;gap:10px;border:1px solid transparent}.primary{background:var(--green);color:#fff}.primary:hover{background:#204b37}.secondary{background:#fff;border-color:var(--line);color:var(--ink)}.secondary:hover{background:#f0f4ed}.text-button{background:none;border:0;color:var(--green);font-size:12px;font-weight:600}.icon-button{border:1px solid var(--line);background:#fff;border-radius:7px;width:34px;height:34px;font-size:21px;color:var(--ink)}.full{width:100%}.brand{font-size:23px;font-weight:700;letter-spacing:-1px;text-decoration:none;color:inherit}.brand>span{display:block;font-size:9px;font-weight:500;letter-spacing:3px;margin:7px 0 0 31px}.sidebar{width:230px;position:fixed;inset:0 auto 0 0;background:#11241b;color:#e7eddf;padding:32px 23px;display:flex;flex-direction:column;z-index:4}.sidebar .brand{margin-bottom:45px}.side-label{font-size:9px;letter-spacing:2px;color:#82998a;margin:0 10px 14px}nav button{display:flex;align-items:center;gap:12px;width:100%;border:0;background:none;color:#aec1b3;padding:14px 12px;text-align:left;border-radius:8px;margin-bottom:6px}nav button span{font-size:18px;width:18px}nav button.active{background:#294532;color:#e2f5c9}nav button:hover{background:#223e2d}nav b{font-size:10px;background:#466143;border-radius:4px;padding:2px 6px;margin-left:auto}.side-station{margin-top:auto;padding:24px 10px;color:#d5e6d5;font-weight:600;border-top:1px solid #304333}.dot{display:inline-block;width:7px;height:7px;border-radius:50%;background:var(--lime);margin-right:8px}.side-station small{display:block;color:#94aa99;font-size:11px;font-weight:400;line-height:1.8;margin-top:7px}.side-frequency{font-size:11px;line-height:2.2;margin:18px 0}.side-frequency span{float:right;font-family:Consolas,monospace;color:#cadcbe}.profile{display:flex;gap:10px;align-items:center;border-top:1px solid #304333;padding-top:20px;font-size:12px}.profile small{display:block;color:#92a696;font-size:10px;margin-top:4px}.profile button{margin-left:auto;background:none;border:0;color:#aec1b3;font-size:22px}.avatar{background:#c5dea8;color:#23452e;width:32px;height:32px;border-radius:50%;display:grid;place-items:center;font-size:11px;font-weight:700}main{margin-left:230px}.topbar{height:76px;padding:0 40px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line);font-size:11px;color:var(--muted)}.topbar>div{display:flex;align-items:center;gap:18px}.live-badge{color:var(--green);background:#e9f0e1;padding:7px 10px;border-radius:20px;font-size:10px;font-weight:600}#clock{font-family:Consolas,monospace}.page{padding:35px 40px 20px;max-width:1600px;margin:auto}.page-heading{display:flex;align-items:center;justify-content:space-between;gap:20px;margin-bottom:28px}.page-heading .eyebrow{display:block;margin-bottom:10px}.page-heading p{color:var(--muted);margin-top:10px;font-size:13px}.metrics{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:22px}.metrics article{position:relative;background:#fff;border:1px solid var(--line);border-radius:12px;padding:20px;min-height:137px}.metrics article>span{font-size:11px;color:var(--muted)}.metrics strong{display:block;font-size:32px;font-weight:600;letter-spacing:-1px;margin:10px 0 5px}.metrics small{font-size:10px;color:var(--muted)}.metrics i{position:absolute;right:18px;top:16px;font-style:normal;color:#9ab18d;font-size:19px}.overview-grid{display:grid;grid-template-columns:1fr 1.15fr;gap:22px;margin-bottom:22px}.card{background:#fff;border:1px solid var(--line);border-radius:12px;overflow:hidden}.card-header{display:flex;align-items:center;justify-content:space-between;padding:20px 22px;gap:10px}.tag{font-size:9px;letter-spacing:1px;background:#eff3ea;padding:5px 8px;border-radius:4px;color:var(--green);white-space:nowrap}.radio-card{border-radius:12px;background:#203e2d;color:#eaf1e0;overflow:hidden;position:relative}.radio-card .eyebrow{color:#c1dba7}.radio-card .tag{background:#3c5d40;color:#d2eab8}.radio-frequency{display:flex;align-items:baseline;gap:15px;margin:8px 25px 0}.radio-frequency>span{font:54px Consolas,monospace;leLine truncated
.routing-trace{font:11px/1.7 Consolas,monospace;border:1px solid #e1e8d9;background:#f7faf3;border-radius:7px;padding:10px 13px;margin:0 0 22px;color:#76866a;white-space:normal}.routing-trace summary{cursor:pointer;font:11px Segoe UI,Arial,sans-serif}.routing-trace pre{white-space:pre-wrap;overflow-wrap:anywhere;margin:12px 0 0} .routing-trace{font:11px/1.7 Consolas,monospace;border:1px solid #e1e8d9;background:#f7faf3;border-radius:7px;padding:10px 13px;margin:0 0 22px;color:#76866a;white-space:normal}.routing-trace summary{cursor:pointer;font:11px Segoe UI,Arial,sans-serif}.routing-trace pre{white-space:pre-wrap;overflow-wrap:anywhere;margin:12px 0 0}
+2
View File
@@ -0,0 +1,2 @@
.mail-table-scroll{flex:1;min-height:0;overflow:auto;scrollbar-gutter:stable;scrollbar-width:thin;scrollbar-color:#405673 transparent;overscroll-behavior:contain}.mail-table-scroll .mail-rows{overflow:visible;flex:none}.mail-table-scroll .mail-columns{position:sticky;top:0;z-index:2}.mail-table-scroll .mail-row,.mail-table-scroll .mail-columns{width:100%;box-sizing:border-box}.mail-table-scroll .mail-columns>span{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.mail-table-scroll .mail-columns>span:nth-child(6),.mail-table-scroll .mail-size{text-align:right}.mail-table-scroll .mail-row{margin:0}.mail-table-scroll .mail-list-heading{font-variant-numeric:tabular-nums}
.sync-dialog{width:min(600px,calc(100vw - 32px));max-height:calc(100dvh - 40px);padding:0;border:1px solid #3b4b60;border-radius:17px;background:#121b28;color:#dce8f5;box-shadow:0 30px 100px #0009;overflow:auto}.sync-dialog::backdrop{background:#040912b8;backdrop-filter:blur(6px)}.sync-dialog header{display:flex;align-items:center;justify-content:space-between;padding:24px 27px 20px;border-bottom:1px solid #29384a}.sync-eyebrow{font-size:9px;letter-spacing:2px;color:#7e9cba}.sync-dialog h2{font-size:21px;margin-top:7px;font-weight:600}.sync-dialog .icon-button{font-size:22px;background:#1a293b;border-color:#34475d;color:#b6cce1}.sync-destination{display:flex;align-items:center;gap:14px;padding:24px 27px 18px}.sync-symbol{display:grid;place-items:center;width:48px;height:48px;border:1px solid #3c5977;border-radius:13px;background:#20364d;font-size:27px;color:#abd1f3}.sync-destination>div{min-width:0}.sync-destination strong{display:block;font-size:18px;overflow-wrap:anywhere;font-weight:600}.sync-destination small{display:block;font-size:9px;letter-spacing:1.2px;color:#7c96af;margin-top:7px}.sync-duration{margin-left:auto;white-space:nowrap;font:18px Consolas,monospace;color:#a8bed5}.sync-stage{display:flex;align-items:flex-start;gap:12px;margin:0 27px;padding:17px;background:#1b2c40;border:1px solid #334b67;border-radius:11px}.sync-stage strong{font-size:14px;font-weight:600}.sync-stage p{font-size:12px;line-height:1.6;margin-top:5px;color:#a7bdd3}.sync-pulse{flex:0 0 8px;height:8px;margin-top:6px;border-radius:50%;background:#a2cbed;box-shadow:0 0 0 5px #80b8e21c;animation:sync-breathe 1.8s ease-in-out infinite}.sync-steps{display:grid;grid-template-columns:repeat(4,1fr);list-style:none;margin:22px 27px;padding:0;gap:7px}.sync-steps li{font-size:10px;color:#758ca5;border-top:3px solid #2b3b4e;padding-top:9px}.sync-steps li.done{border-color:#6bada4;color:#a5c9c3}.sync-steps li.current{border-color:#94bfe6;color:#d0e7fc}.sync-counts{display:flex;margin:0 27px 20px;gap:14px}.sync-counts>div{flex:1;padding:13px 16px;background:#0f1824;border:1px solid #2a3b4e;border-radius:9px;display:flex;align-items:center;justify-content:space-between}.sync-counts span{font-size:11px;color:#8fa7be}.sync-counts strong{font-size:22px;font-weight:500;font-variant-numeric:tabular-nums}.sync-events{margin:0 27px 22px;padding:0;list-style:none;max-height:150px;overflow:auto;scrollbar-width:thin}.sync-events li{display:flex;align-items:baseline;gap:14px;padding:8px 0;border-bottom:1px solid #223145;font-size:11px;line-height:1.5}.sync-events time{color:#7591aa;font:10px Consolas,monospace;white-space:nowrap}.sync-events span{color:#b6c8da}.sync-dialog footer{display:flex;align-items:center;justify-content:flex-end;gap:12px;padding:17px 27px;border-top:1px solid #2c3b4d;background:#101925}.sync-dialog footer>span{margin-right:auto;font-size:10px;color:#8199b1}.sync-dialog footer button{padding:10px 16px;font-size:12px}.sync-error{margin:15px 27px;color:#f0b7ac;font-size:12px}.sync-dialog[data-state=complete] .sync-stage{border-color:#49796f;background:#192f2e}.sync-dialog[data-state=complete] .sync-pulse{background:#90cbb8;animation:none}.sync-dialog[data-state=failed] .sync-stage{border-color:#7e504d;background:#322528}.sync-dialog[data-state=failed] .sync-pulse{background:#dca79a;animation:none}.sync-dialog[data-state=cancelled] .sync-pulse{background:#b4a88c;animation:none}.sync-chip{position:fixed;bottom:24px;left:250px;z-index:35;background:#203a54;color:#d9eafa;border:1px solid #527597;border-radius:10px;padding:13px 18px;box-shadow:0 8px 30px #0006;font-size:12px;max-width:calc(100vw - 280px);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}@keyframes sync-breathe{50%{opacity:.45;box-shadow:0 0 0 7px #80b8e20a}}@media(prefers-reduced-motion:reduce){.sync-pulse{animation:none}}@media(max-width:700px){.sync-dialog header,.sync-destination,.sync-dialog footer{padding:18px}.sync-stage,.sync-steps,.sync-counts,.sync-events{margin-left:18px;margin-right:18px}.sync-destination strong{font-size:15px}.sync-counts>div{padding:11px;gap:8px}.sync-chip{left:16px;max-width:calc(100vw - 32px)}.sync-dialog footer>span{max-width:150px}.sync-steps li{font-size:9px}}
+22
View File
@@ -0,0 +1,22 @@
import {mergeSyncSnapshot} from './sync-state.js';
(() => {
const labels={preparing:'Preparazione',calling:'Chiamata',connected:'Scambio messaggi',restoring:'Ripristino',complete:'Completato',failed:'Non riuscito',cancelling:'Interruzione in corso',cancelled:'Interrotto'};
const dialog=document.createElement('dialog');dialog.className='sync-dialog';dialog.setAttribute('aria-labelledby','sync-title');
dialog.innerHTML='<header><div><span class="sync-eyebrow">SESSIONE BPQ</span><h2 id="sync-title">Sincronizzazione</h2></div><button class="icon-button" id="sync-minimize" aria-label="Riduci finestra">−</button></header><div class="sync-destination"><span class="sync-symbol" aria-hidden="true">⇄</span><div><strong id="sync-destination">Preparazione…</strong><small id="sync-transport"></small></div><span class="sync-duration" id="sync-duration">00:00</span></div><div class="sync-stage" role="status" aria-live="polite"><span class="sync-pulse"></span><div><strong id="sync-state"></strong><p id="sync-detail"></p></div></div><ol class="sync-steps"><li>Preparazione</li><li>Collegamento</li><li>Scambio</li><li>Conclusione</li></ol><div class="sync-counts"><div><span>Messaggi inviati</span><strong id="sync-sent">0</strong></div><div><span>Messaggi ricevuti</span><strong id="sync-received">0</strong></div></div><ol class="sync-events" aria-label="Avanzamento della sessione"></ol><p class="sync-error" role="alert" hidden></p><footer><span id="sync-footnote">Aggiornamento automatico</span><button class="danger" id="sync-abort">Interrompi sync</button><button class="primary" id="sync-close" hidden>Chiudi</button></footer>';
document.body.append(dialog);
const chip=document.createElement('button');chip.className='sync-chip';chip.hidden=true;chip.setAttribute('aria-label','Mostra avanzamento sincronizzazione');document.body.append(chip);
let job=null,timer=null,loading=false,origin=null,creating=false,aborting=false,requestEpoch=0;
const find=s=>dialog.querySelector(s),clock=at=>new Date(at).toLocaleTimeString(BPQI18n.locale(),{hour:'2-digit',minute:'2-digit',second:'2-digit'});
function show(){chip.hidden=true;if(!dialog.open)dialog.showModal();}
function hide(){dialog.close();chip.hidden=!job?.active;if(!job?.active)origin?.focus?.();}
function render(){if(!job)return;dialog.dataset.state=job.state;find('#sync-destination').textContent=job.label||job.peer||'BPQ';find('#sync-transport').textContent=job.kind==='winlink-internet'?'WINLINK · INTERNET':job.kind==='winlink-radio'?'WINLINK · RADIO':'BBS · FORWARDING';if(job.frequency)find('#sync-transport').textContent+=' · '+Number(job.frequency).toLocaleString(BPQI18n.locale(),{minimumFractionDigits:3,maximumFractionDigits:3})+' MHz · '+(job.mode||'');find('#sync-state').textContent=labels[job.state]||'In attesa';find('#sync-detail').textContent=job.detail||'Richiesta di sincronizzazione';const seconds=Math.max(0,Math.floor(((job.endedAt?Date.parse(job.endedAt):Date.now())-Date.parse(job.startedAt))/1000));find('#sync-duration').textContent=String(Math.floor(seconds/60)).padStart(2,'0')+':'+String(seconds%60).padStart(2,'0');find('#sync-sent').textContent=job.sent??0;find('#sync-received').textContent=job.received??0;
const stage={preparing:0,calling:1,connected:2,restoring:3,complete:4}[job.state]??-1;dialog.querySelectorAll('.sync-steps li').forEach((el,i)=>{el.classList.toggle('done',i<stage);el.classList.toggle('current',i===stage);});find('.sync-events').innerHTML=(job.events||[]).map(e=>'<li><time>'+esc(clock(e.at))+'</time><span>'+esc(e.detail)+'</span></li>').join('');find('#sync-abort').hidden=!job.active;find('#sync-abort').disabled=aborting||creating;find('#sync-abort').textContent=aborting?'Interruzione…':job.state==='cancelling'?'Riprova interruzione':'Interrompi sync';find('#sync-close').hidden=!!job.active;find('#sync-footnote').textContent=job.active?'Aggiornamento ogni 1,5 secondi':'Sessione terminata · '+mailTimezone();chip.textContent='⇄ '+(job.label||'BPQ')+' · '+(labels[job.state]||'In attesa');
}
function watch(){clearInterval(timer);timer=setInterval(async()=>{render();if(!job?.id||!job.active||loading||aborting)return;const epoch=requestEpoch,id=job.id;loading=true;try{const fresh=await api('/sync/jobs/'+id,{signal:AbortSignal.timeout(8000)});if(epoch!==requestEpoch||job?.id!==id)return;const wasActive=job.active;job=mergeSyncSnapshot(job,fresh);find('.sync-error').hidden=true;render();if(wasActive&&!job.active){clearInterval(timer);chip.hidden=true;loadMessages();loadDashboard();if(typeof wlLoad==='function')wlLoad();document.dispatchEvent(new Event('sync-finished'));}}catch(e){if(epoch===requestEpoch){find('.sync-error').hidden=false;find('.sync-error').textContent=e.message;}}finally{if(epoch===requestEpoch)loading=false;}},1500);}
window.bpqSync={async start(spec){if(creating||job?.active){show();return job;}origin=document.activeElement;const epoch=++requestEpoch;clearInterval(timer);loading=false;creating=true;job={...spec,label:spec.peer||'Winlink',active:true,state:'preparing',startedAt:new Date().toISOString(),detail:'Invio della richiesta a BPQ',events:[]};render();show();find('.sync-error').hidden=true;try{const created=await api('/sync/jobs',{method:'POST',body:JSON.stringify(spec)});if(epoch!==requestEpoch)return job;job=created;watch();return job;}catch(e){job={...job,active:false,state:'failed',detail:e.message,endedAt:new Date().toISOString()};throw e;}finally{creating=false;render();}}};
find('#sync-abort').onclick=async()=>{if(!job?.id||aborting)return;const epoch=++requestEpoch,id=job.id;loading=false;aborting=true;find('.sync-error').hidden=true;render();try{const stopped=await api('/sync/jobs/'+id+'/abort',{method:'POST',body:'{}'});if(epoch!==requestEpoch||job?.id!==id)return;job=mergeSyncSnapshot(job,stopped);render();if(!job.active){clearInterval(timer);document.dispatchEvent(new Event('sync-finished'));loadDashboard();}}catch(e){find('.sync-error').hidden=false;find('.sync-error').textContent=e.message;}finally{aborting=false;render();}};
find('#sync-minimize').onclick=hide;find('#sync-close').onclick=hide;chip.onclick=show;dialog.addEventListener('cancel',e=>{e.preventDefault();hide();});
document.addEventListener('bpq-languagechange',render);
document.addEventListener('station-ready',async()=>{const epoch=++requestEpoch;loading=false;try{const active=await api('/sync/jobs');if(epoch!==requestEpoch)return;if(active[0]){job=active[0];render();chip.hidden=false;watch();}else if(job?.active){job={...job,active:false,state:'failed',endedAt:new Date().toISOString(),detail:'Sessione del pannello non più attiva. Stato BPQ ricaricato.'};clearInterval(timer);chip.hidden=true;render();}}catch{}});
document.addEventListener('DOMContentLoaded',()=>{document.querySelectorAll('.mail-list').forEach(list=>{const head=list.querySelector('.mail-columns'),rows=list.querySelector('.mail-rows');if(!head||!rows)return;const scroll=document.createElement('div');scroll.className='mail-table-scroll';head.before(scroll);scroll.append(head,rows);});});
})();
+7
View File
@@ -0,0 +1,7 @@
// A delayed poll must never revive an ended operation or replace a newer one.
export function mergeSyncSnapshot(current,incoming){
if(!current||!incoming||current.id!==incoming.id)return current;
if(current.active===false&&incoming.active!==false)return current;
if(Number.isFinite(current.revision)&&Number.isFinite(incoming.revision)&&incoming.revision<current.revision)return current;
return incoming;
}
+16
View File
@@ -0,0 +1,16 @@
<!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="#11110e"><title>BPQ Console · Terminal</title>
<script src="/ui-config.js"></script><script src="/i18n.js?v=20261019-terminal-window"></script>
<link rel="stylesheet" href="/style.css"><link rel="stylesheet" href="/dark.css"><link rel="stylesheet" href="/terminal.css?v=20261019-themes">
<link rel="stylesheet" href="/detach.css?v=20261019-multi"><script defer src="/detach.js?v=20261019-multi"></script><script defer src="/terminal-window.js"></script><script defer src="/terminal.js?v=20261019-themes"></script>
</head>
<body class="terminal-detached">
<nav hidden></nav><span id="breadcrumb" hidden></span><button id="logout" hidden></button>
<main></main>
<section id="terminal-window-error" hidden role="status"><h1>Terminale</h1><p id="terminal-window-error-text"></p><a class="secondary" href="/#terminal">Apri il pannello</a></section>
<div id="toast" hidden role="status"></div>
</body>
</html>
+22
View File
@@ -0,0 +1,22 @@
// A detached view shares the authenticated browser session and its existing Telnet socket.
const $=selector=>document.querySelector(selector);
let station={features:{}},csrf='',page='terminal';
function navigate(){page='terminal';$('#terminal').hidden=false;}
function toast(text){$('#toast').textContent=text;$('#toast').hidden=false;clearTimeout(toast.timer);toast.timer=setTimeout(()=>$('#toast').hidden=true,6500);}
function terminalWindowError(text){document.dispatchEvent(new Event('bpq-detach-auth-lost'));csrf='';station={features:{}};$('#terminal').hidden=true;$('#terminal-window-error').hidden=false;$('#terminal-window-error-text').textContent=BPQI18n.t(text);}
async function api(url,options={}){
const {busy,...request}=options;
const response=await fetch('/api'+url,{...request,headers:{'Content-Type':'application/json',...(request.method==='POST'?{'X-CSRF-Token':csrf}:{}),...request.headers}});
const data=await response.json();
if(!response.ok){if(response.status===401)terminalWindowError('Sessione scaduta. Accedi nuovamente dal pannello.');throw new Error(data.error||'Richiesta fallita');}
return data;
}
$('#logout').onclick=async()=>{};
document.addEventListener('DOMContentLoaded',async()=>{
try{
const user=await api('/session');station=user.config;csrf=user.csrf;
if(!station.features.terminal){terminalWindowError('Terminale non configurato in BPQ.');return;}
document.title='BPQ Console · '+station.call+' · Terminal';
document.dispatchEvent(new Event('station-ready'));
}catch(error){if(csrf||!$('#terminal-window-error-text').textContent)terminalWindowError(error.message);}
});
+27
View File
@@ -0,0 +1,27 @@
#terminal{height:calc(100dvh - 76px);display:flex;flex-direction:column;min-height:560px;padding:24px 28px}.terminal-heading{display:flex;align-items:center;justify-content:space-between;gap:18px;margin-bottom:20px;flex-shrink:0}.terminal-heading h1{font-size:28px;font-weight:500}.terminal-heading p{font-size:11px;color:var(--muted);margin-top:5px}.terminal-actions{display:flex;gap:9px}.terminal-actions button{font-size:11px}.phosphor-case{flex:1;min-height:0;display:flex;flex-direction:column;border-radius:16px;border:1px solid #51452b;background:#11110e;padding:7px;box-shadow:0 16px 45px #0005,inset 0 1px #8e774822;overflow:hidden}.phosphor-top,.phosphor-bottom{display:flex;justify-content:space-between;align-items:center;gap:18px;color:#9e844d;font:10px Consolas,'Courier New',monospace;letter-spacing:1px;flex-shrink:0;padding:14px 19px}.phosphor-top{border-bottom:1px solid #4a3a1c}.phosphor-top>span:first-child{display:flex;align-items:center;gap:10px}.phosphor-top i{display:inline-block;width:6px;height:6px;background:#5d5033;border-radius:50%}.phosphor-top i.online{background:#ffd477;box-shadow:0 0 9px #ffbd4d}.phosphor-screen{flex:1;min-height:0;overflow:auto;padding:24px 26px;color:#ffd376;background:radial-gradient(ellipse at center,#241d0d 0%,#131106 70%,#0b0b06 100%);box-shadow:inset 0 0 55px #000a;scrollbar-color:#72572a #151207;position:relative;isolation:isolate}.phosphor-screen:before{content:'';position:absolute;inset:0;min-height:100%;pointer-events:none;background:repeating-linear-gradient(0deg,transparent 0 2px,#0002 2px 3px);z-index:1}.phosphor-screen pre{font:14px/1.55 Consolas,'Courier New',monospace;white-space:pre-wrap;overflow-wrap:anywhere;tab-size:8;letter-spacing:.2px;text-shadow:0 0 5px #ffc14b66;margin:0;position:relative;z-index:2;user-select:text}.phosphor-screen pre::selection{background:#94702f;color:#fff2c4}.phosphor-cursor{display:inline-block;color:#ffda84;font:16px Consolas,monospace;animation:phosphor-blink 1.1s steps(1) infinite;text-shadow:0 0 8px #ffc354}#terminal-form{display:flex;align-items:center;gap:12px;margin:0;padding:12px 20px;border-top:1px solid #4a3a1c;background:#1c180e;color:#ffd376;flex-shrink:0}#terminal-form label{font:18px Consolas,monospace}#terminal-input{flex:1;width:0;min-width:0;background:transparent;border:0;border-radius:0;box-shadow:none;color:#ffda8a;font:14px Consolas,'Courier New',monospace;padding:10px 0;caret-color:#ffe2a2}#terminal-input::placeholder{color:#82704b}#terminal-input:focus-visible{outline:0;box-shadow:0 1px #c09c4a}#terminal-send{background:#30250f;border:1px solid #665126;color:#e9c779;font:11px Consolas,monospace;padding:10px 13px;border-radius:5px}.phosphor-bottom{font-size:9px;padding:12px 18px;letter-spacing:.5px;flex-wrap:wrap}.phosphor-bottom button{background:transparent;border:0;color:#ffda84;font:inherit;padding:0}@keyframes phosphor-blink{50%{opacity:0}}@media(prefers-reduced-motion:reduce){.phosphor-cursor{animation:none}}@media(max-width:850px){.terminal-heading{align-items:flex-start;flex-direction:column}.terminal-actions{flex-wrap:wrap}.phosphor-screen{padding:16px}.phosphor-screen pre{font-size:12px}.phosphor-top{font-size:9px;letter-spacing:.3px}}@media(max-width:600px){#terminal{padding:20px 14px;height:calc(100dvh - 175px);min-height:510px}.terminal-heading h1{font-size:25px}.terminal-actions button{padding:8px 10px}.phosphor-top{padding:12px 10px}#terminal-form{padding:10px 12px}.phosphor-bottom>span:nth-child(2){display:none}nav{flex-wrap:wrap}}
@media(min-width:601px){.sidebar:has([data-page=terminal]) nav{min-height:100px;overflow-y:auto;flex-shrink:1;scrollbar-width:thin}.sidebar:has([data-page=terminal])>.brand,.sidebar:has([data-page=terminal])>.side-label,.sidebar:has([data-page=terminal])>.profile{flex-shrink:0}.sidebar:has([data-page=terminal])>.side-station{padding-block:14px;flex-shrink:0}}
/* Coordinated phosphor palettes shared by embedded and detached terminal views. */
#terminal{--phosphor:#ffd376;--phosphor-rgb:255,193,75;--phosphor-muted:#a78c57;--phosphor-bg:#100e08;--phosphor-surface:#1c180e}
#terminal[data-theme=green]{--phosphor:#9cf7ad;--phosphor-rgb:109,244,139;--phosphor-muted:#71a781;--phosphor-bg:#070f0a;--phosphor-surface:#101c14}
#terminal[data-theme=ice]{--phosphor:#b3edff;--phosphor-rgb:113,212,255;--phosphor-muted:#779eaf;--phosphor-bg:#080f15;--phosphor-surface:#101c26}
#terminal[data-theme=violet]{--phosphor:#ddbcff;--phosphor-rgb:186,132,255;--phosphor-muted:#a38bb6;--phosphor-bg:#100a16;--phosphor-surface:#1b1325}
#terminal[data-theme=white]{--phosphor:#e8eee9;--phosphor-rgb:216,230,222;--phosphor-muted:#91a29a;--phosphor-bg:#0c100f;--phosphor-surface:#171e1b}
#terminal .phosphor-case{border-color:rgba(var(--phosphor-rgb),.28);background:var(--phosphor-bg);box-shadow:0 16px 45px #0005,inset 0 1px rgba(var(--phosphor-rgb),.12)}
#terminal .phosphor-top,#terminal .phosphor-bottom{color:var(--phosphor-muted);border-color:rgba(var(--phosphor-rgb),.2)}
#terminal .phosphor-top i.online{background:var(--phosphor);box-shadow:0 0 9px rgba(var(--phosphor-rgb),.8)}
#terminal .phosphor-screen{color:var(--phosphor);background:radial-gradient(ellipse at center,rgba(var(--phosphor-rgb),.075),transparent 80%),var(--phosphor-bg);scrollbar-color:var(--phosphor-muted) var(--phosphor-bg)}
#terminal .phosphor-screen pre{color:var(--phosphor);text-shadow:0 0 5px rgba(var(--phosphor-rgb),.32)}
#terminal .phosphor-screen pre::selection{background:rgba(var(--phosphor-rgb),.35);color:var(--phosphor)}
#terminal .phosphor-cursor{color:var(--phosphor);text-shadow:0 0 8px rgba(var(--phosphor-rgb),.65)}
#terminal-form{background:var(--phosphor-surface);color:var(--phosphor);border-color:rgba(var(--phosphor-rgb),.22)}
#terminal-input{color:var(--phosphor);caret-color:var(--phosphor)}#terminal-input::placeholder{color:var(--phosphor-muted)}#terminal-input:focus-visible{box-shadow:0 1px var(--phosphor-muted)}
#terminal-send{color:var(--phosphor);background:rgba(var(--phosphor-rgb),.08);border-color:rgba(var(--phosphor-rgb),.3)}#terminal .phosphor-bottom button{color:var(--phosphor)}
.terminal-actions{flex-wrap:wrap;justify-content:flex-end}.terminal-theme-bar{display:flex;align-items:center;gap:18px;margin:-5px 0 14px;flex-shrink:0}.terminal-theme-bar>span{color:#8396a6;font-size:10px;letter-spacing:1.5px;text-transform:uppercase}.terminal-theme-bar>div{display:flex;gap:5px;flex-wrap:wrap}
.terminal-theme-bar button{display:inline-flex;align-items:center;gap:7px;padding:6px 10px;border:1px solid transparent;border-radius:6px;background:transparent;color:#899dad;font-size:11px;line-height:1.3}.terminal-theme-bar button::before{content:'';width:7px;height:7px;border-radius:50%;background:var(--theme-dot)}
[data-terminal-theme=amber]{--theme-dot:#ffd376}[data-terminal-theme=green]{--theme-dot:#9cf7ad}[data-terminal-theme=ice]{--theme-dot:#b3edff}[data-terminal-theme=violet]{--theme-dot:#ddbcff}[data-terminal-theme=white]{--theme-dot:#e8eee9}
.terminal-theme-bar button:hover{background:#abc4d40a;color:#cddde8}.terminal-theme-bar button[aria-pressed=true]{color:var(--theme-dot);border-color:#8ba6bc35;background:#abc4d40c}
body.terminal-detached{background:#0d141c;color:#d7e3ec;overflow:hidden}.terminal-detached main{margin:0;padding:0;max-width:none;width:100%;height:100dvh}.terminal-detached #terminal{height:100dvh;min-height:0;padding:20px}.terminal-detached .terminal-heading{margin-bottom:15px}.terminal-detached .terminal-heading h1{font-size:23px}.terminal-detached .phosphor-screen{padding:20px 23px}
#terminal-window-error{margin:10vh auto;max-width:460px;padding:28px;border:1px solid #354656;border-radius:14px;background:#172330}#terminal-window-error p{margin:15px 0 22px;color:#a5bbcc}#terminal-window-error a{text-decoration:none}
@media(max-width:650px){.terminal-detached #terminal{padding:12px}.terminal-theme-bar{gap:10px;align-items:flex-start}.terminal-theme-bar button{padding:6px 7px}.terminal-actions{justify-content:flex-start}.terminal-detached .phosphor-screen{padding:15px}.terminal-theme-bar>span{padding-top:6px}}
+32
View File
@@ -0,0 +1,32 @@
(() => {
const detached=document.body.classList.contains('terminal-detached');
const nav=document.createElement('button');nav.dataset.page='terminal';nav.innerHTML='<span>▸_</span> Terminale';nav.onclick=()=>navigate('terminal');$('nav').append(nav);
const section=document.createElement('section');section.id='terminal';section.className='page';section.hidden=true;section.innerHTML=`<div class="terminal-heading"><div><h1>Terminale</h1><p>BPQ · Telnet</p></div><div class="terminal-actions"><button id="terminal-detach" class="secondary" title="Apri il terminale in una finestra separata">↗ Stacca</button><button id="terminal-dock" class="secondary" hidden>↙ Torna al pannello</button><button id="terminal-clear" class="secondary">Pulisci</button><button id="terminal-export" class="secondary">Salva testo</button><button id="terminal-connect" class="primary">Collega</button><button id="terminal-stop" class="secondary" hidden>Disconnetti</button></div></div><div class="terminal-theme-bar"><span>Fosfori</span><div role="group" aria-label="Stile del terminale"><button type="button" data-terminal-theme="amber" aria-pressed="true">Amber</button><button type="button" data-terminal-theme="green" aria-pressed="false">Green</button><button type="button" data-terminal-theme="ice" aria-pressed="false">Ice</button><button type="button" data-terminal-theme="violet" aria-pressed="false">Violet</button><button type="button" data-terminal-theme="white" aria-pressed="false">White</button></div></div><div class="phosphor-case"><div class="phosphor-top"><span><i id="terminal-led"></i> BPQ / REMOTE TERMINAL</span><span id="terminal-state" role="status">OFFLINE</span></div><div class="phosphor-screen" id="terminal-screen" tabindex="0" aria-label="Terminale Telnet BPQ"><pre id="terminal-output" aria-live="off"></pre><span class="phosphor-cursor" aria-hidden="true">▌</span></div><form id="terminal-form" autocomplete="off"><label for="terminal-input">&gt;</label><input id="terminal-input" aria-label="Comando Telnet" placeholder="Collega il terminale per iniziare" spellcheck="false" autocapitalize="off" maxlength="1000" disabled><button type="submit" id="terminal-send" disabled aria-label="Invia comando">INVIO ↵</button></form><div class="phosphor-bottom"><span id="terminal-endpoint">TELNET · BPQ LOCALE</span><span>↑ ↓ cronologia · Invio per inviare</span><button type="button" id="terminal-follow" hidden>↓ Torna al fondo</button></div></div>`;$('main').append(section);if(detached)section.hidden=false;
const themes=['amber','green','ice','violet','white'];
function applyTheme(value){const theme=themes.includes(value)?value:'amber';section.dataset.theme=theme;section.querySelectorAll('[data-terminal-theme]').forEach(button=>button.setAttribute('aria-pressed',String(button.dataset.terminalTheme===theme)));}
function savedTheme(){try{return localStorage.getItem('bpq-terminal-theme');}catch{return 'amber';}}
applyTheme(savedTheme());
section.querySelector('.terminal-theme-bar').onclick=event=>{const theme=event.target.closest('[data-terminal-theme]')?.dataset.terminalTheme;if(!themes.includes(theme))return;applyTheme(theme);try{localStorage.setItem('bpq-terminal-theme',theme);}catch{}};
window.addEventListener('storage',event=>{if(event.key==='bpq-terminal-theme')applyTheme(event.newValue);});
$('#terminal-detach').hidden=detached;$('#terminal-dock').hidden=!detached;
$('#terminal-detach').onclick=()=>{if(window.BPQDetached){window.BPQDetached.open('terminal');return;}const popup=window.open('/terminal-window','bpq-console-terminal','popup=yes,width=1120,height=780,resizable=yes,scrollbars=yes');if(popup)popup.focus();else toast(BPQI18n.t('Consenti le finestre popup per aprire il terminale separato.'));};
$('#terminal-dock').onclick=()=>{if(window.BPQDetached){window.BPQDetached.dock('terminal');return;}try{if(window.opener&&!window.opener.closed){window.opener.location.hash='#terminal';window.opener.focus();window.close();return;}}catch{}window.location.assign('/#terminal');};
let cursor=0,busy=false,state='offline',buffer='',following=true,history=[],historyIndex=0,draft='',sending=false,generation=0;
const area=$('#terminal-screen'),output=$('#terminal-output'),input=$('#terminal-input');
const previousNavigate=navigate;navigate=function(next){previousNavigate(next);if(next==='terminal'){$('#breadcrumb').textContent='Stazione / Terminale';poll();}};
function bottom(){area.scrollTop=area.scrollHeight;following=true;$('#terminal-follow').hidden=true;}
function append(text){buffer=(buffer+text).slice(-200000);output.textContent=buffer;if(following)bottom();}
function status(data){const wasOnline=state==='online';state=data.state;const online=state==='online',connecting=state==='connecting';$('#terminal-state').textContent=data.error||({online:'ONLINE',connecting:'COLLEGAMENTO…',offline:'OFFLINE',error:'ERRORE'}[state]||state);$('#terminal-led').classList.toggle('online',online);$('#terminal-connect').hidden=online||connecting;$('#terminal-stop').hidden=!online&&!connecting;input.disabled=!online;$('#terminal-send').disabled=!online||sending;input.placeholder=online?'Scrivi un comando…':'Collega il terminale per iniziare';$('#terminal-endpoint').textContent='TELNET · 127.0.0.1:'+data.port;if(online&&!wasOnline&&page==='terminal')input.focus();}
async function poll(){if(!csrf||busy||!station.features.terminal||window.BPQDetached&&!window.BPQDetached.shouldPoll('terminal'))return;busy=true;const current=generation;try{const d=await api('/terminal?after='+cursor,{busy:false});if(current!==generation)return;if(d.latest<cursor){cursor=0;buffer='';}status(d);for(const e of d.events)append(e.text);cursor=d.latest;}catch(e){if(page==='terminal')$('#terminal-state').textContent=e.message;}finally{busy=false;}}
$('#terminal-connect').onclick=async()=>{const button=$('#terminal-connect');button.disabled=true;try{const d=await api('/terminal/connect',{method:'POST',body:'{}'});buffer='';output.textContent='';following=true;cursor=0;status(d);await poll();}catch(e){toast(e.message);}finally{button.disabled=false;}};
$('#terminal-stop').onclick=async()=>{try{status(await api('/terminal/disconnect',{method:'POST',body:'{}'}));await poll();}catch(e){toast(e.message);}};
$('#terminal-form').onsubmit=async e=>{e.preventDefault();if(sending||state!=='online')return;const text=input.value;sending=true;$('#terminal-send').disabled=true;try{await api('/terminal/send',{method:'POST',body:JSON.stringify({text})});if(text&&history.at(-1)!==text)history.push(text);history=history.slice(-100);historyIndex=history.length;draft='';input.value='';await poll();}catch(e){toast(e.message);}finally{sending=false;$('#terminal-send').disabled=state!=='online';if(state==='online')input.focus();}};
input.addEventListener('keydown',e=>{if(e.key==='ArrowUp'){e.preventDefault();if(historyIndex===history.length)draft=input.value;if(historyIndex>0)input.value=history[--historyIndex];}else if(e.key==='ArrowDown'){e.preventDefault();if(historyIndex<history.length)historyIndex++;input.value=historyIndex===history.length?draft:history[historyIndex];}});
area.addEventListener('scroll',()=>{following=area.scrollHeight-area.scrollTop-area.clientHeight<40;$('#terminal-follow').hidden=following;});$('#terminal-follow').onclick=bottom;
$('#terminal-clear').onclick=()=>{buffer='';output.textContent='';bottom();input.focus();};
$('#terminal-export').onclick=()=>{if(!buffer){toast('Il terminale è vuoto');return;}const url=URL.createObjectURL(new Blob([buffer],{type:'text/plain;charset=utf-8'})),a=document.createElement('a');a.href=url;a.download='BPQ-terminal-'+new Date().toISOString().replace(/[:.]/g,'-')+'.txt';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
document.addEventListener('station-ready',()=>{generation++;cursor=0;buffer='';output.textContent='';history=[];historyIndex=0;nav.hidden=!station.features.terminal;if(page==='terminal')poll();});
const logout=$('#logout').onclick;$('#logout').onclick=async()=>{generation++;buffer='';output.textContent='';history=[];input.value='';await logout();};
setInterval(()=>{if(csrf&&page==='terminal')poll();},700);
window.addEventListener('hashchange',()=>{if(location.hash==='#terminal'&&page!=='terminal')navigate('terminal');});if(location.hash==='#terminal')navigate('terminal');
})();
+423
View File
@@ -0,0 +1,423 @@
Copyright and licensing information
======================================
This is a collection of vectorized symbols for use on the APRS system.
The copyright status of this collection is a bit complicated, since the
symbols come from various sources, each having different copyright owners.
Most of the vectorized symbols are loosely based on the low-resolution
"standard" bitmap symbol set as distributed by Stephen Smith, WA8LMF. That
set is used by most APRS software around the world. The low resolution of
those symbols does not allow direct vector conversion, so I've drawn new
symbols in a similar layout. The vector versions try to mimic the original
appearance and colours, with the intention of keeping the set recognizable
and familiar to existing users. In some cases the vector versions are
probably similar enough to the originals, so that they cannot be considered
"original work" by myself. In some of these cases, the originals are
probably also mimicking someone else's design.
The original symbols do not come with any information on their licensing.
They've been distributed with a lot of APRS software over time, but I don't
know who designed which symbol originally. Most likely all of them are
drawn by one of:
* Roger Barker, G4IDE, "original set provided with UI-View" (SK)
* Steve Dimse, KH4G, "U.S. customary set"
* Stephen Smith, WA8LMF
The Adobe Illustrator (.ai) file contains a copy of the original bitmaps
as a hidden layer, just for reference.
Some symbols I obtained from other sources, such as Wikipedia. In those
cases I picked SVG versions which allow commercial reuse (source known, and
the work is placed on public domain, or with a CC license which allows
adaptation and commercial reuse).
Some symbols are vectorized versions of product or brand logos. The
copyright of those is owned by the respective companies (Apple, Microsoft,
Kenwood), and each of those may have some opinions on how the logos are
used. Please check for yourself if you can use them or not.
In the list below I try to summarize the licensing status for each symbol.
Shorthand notation for common licensing status
-------------------------------------------------
* *VEC-OH7LZB* - Vectorized by OH7LZB, based on original APRS symbol set
* Source of original bitmap: http://wa8lmf.net/aprs/APRS_symbols.htm
* Original designer of individual symbol unknown at this time, but one of:
* Roger Barker, G4IDE
* Steve Dimse, KH4G
* Stephen Smith, WA8LMF
* Vectorized versions are designed to look similar
* Licensing: Unknown
* *OH7LZB* - Original vector design by Heikki Hannikainen, OH7LZB
* Different enough (by author's opinion) to make it a new original work,
instead of a copy of the old symbol
* License: CC BY-SA 2.0
* https://creativecommons.org/licenses/by-sa/2.0/
Primary table
----------------
* /! - Police station
* VEC-OH7LZB
* /# - Digipeater / Green star with D in middle
* VEC-OH7LZB
* /$ - Telephone
* VEC-OH7LZB
* /% - DX cluster
* VEC-OH7LZB
* /& - HF gateway
* VEC-OH7LZB
* /' - Small aircraft
* https://openclipart.org/detail/27182/topdown-airplane-view
* Author: Wirelizard (Brian Burger)
* With color and some other small tuning added by OH7LZB
* PD: https://openclipart.org/share
* /( - Mobile satellite station
* OH7LZB
* /) - Wheelchair, handicapped
* PD wheelchair symbol
* Vectorized from bitmap by OH7LZB
* /* - Snowmobile
* https://openclipart.org/detail/15849/snowmobile
* Author: Mystica (https://openclipart.org/user-detail/mystica)
* PD: https://openclipart.org/share
* /+ - Red Cross
* VEC-OH7LZB
* /, - Boy Scouts
* VEC-OH7LZB
* /- - House
* VEC-OH7LZB
* /. - Red X
* VEC-OH7LZB
* // - Red dot
* VEC-OH7LZB
* /0 to /9 - Numbered circles
* VEC-OH7LZB
* Fire
* http://commons.wikimedia.org/wiki/File:FireIcon.svg
* Author: Piotr Jaworski
* PD: I, the copyright holder of this work, release this work into the public domain. This applies worldwide.
* Tent
* https://openclipart.org/detail/174933/green-tent-by-stamps-174933
* Author: stamps
* PD: https://openclipart.org/share
* Motorcycle
* http://commons.wikimedia.org/wiki/File:MUTCD_W8-15P.svg
* This file is in the public domain because it comes from the Manual on
Uniform Traffic Control Devices, sign number W8-15P, which states
specifically on page I-1 that: Any traffic control device design or
application provision contained in this Manual shall be considered to
be in the public domain. Traffic control devices contained in this
Manual shall not be protected by a patent, trademark, or copyright,
except for the Interstate Shield and any other items owned by FHWA.
* Colour version by OH7LZB
* /= - Railroad engine
* http://commons.wikimedia.org/wiki/File:Icon_train.svg
* Author: http://en.wikipedia.org/wiki/User:Richtom80
* CC-BY-SA-2.5,2.0,1.0
* /> - Car
* OH7LZB
* /? - File server
* https://openclipart.org/detail/163717/file-server-by-lyte
* Author: lyte
* PD: https://openclipart.org/share
* /@ - Hurricane predicted path
* VEC-OH7LZB
* /A - Aid station
* VEC-OH7LZB
* Mail (BBS)
* https://openclipart.org/detail/29268/yellow-mail-by-rg1024-29268
* Author: rg1024
* PD: https://openclipart.org/share
* /C - Canoe
* https://openclipart.org/detail/179047/red-canoe-by-rambo-tribble-179047
* https://openclipart.org/detail/179041/canoe-paddle-by-rambo-tribble-179041
* Author: Rambo Tribble
* PD: I, the copyright holder of this work, release this work into the public domain. This applies worldwide.
* /E - Eyeball
* http://commons.wikimedia.org/wiki/File:Blue_eye.svg
* PD: "This file is from the Open Clip Art Library, which released it explicitly into the public domain"
* PD: https://openclipart.org/share
* /F - Tractor
* https://openclipart.org/detail/191654/farm-tractor-by-tmjbeary-191654
* Author: tmjbeary
* PD: https://openclipart.org/share
* /G - Grid square, 3 by 3
* VEC-OH7LZB
* /H - Hotel
* VEC-OH7LZB
* /I - TCP/IP
* VEC-OH7LZB
* /K - School
* OH7LZB
* /L - PC user
* OH7LZB
* /M - Mac apple
* Apple
* /N - NTS
* VEC-OH7LZB
* /O - Hot air balloon
* OH7LZB
* /P - Police
* OH7LZB
* /R - RV
* OH7LZB
* /S - Space Shuttle
* https://openclipart.org/detail/814/space-shuttle-by-johnny_automatic
* PD: Published by the NASA, in "The Brain in Space"
* /T - SSTV
* https://openclipart.org/detail/48997/flat-screen-by-rg1024
* Author: rg1024
* Adjusted by OH7LZB
* PD: https://openclipart.org/share
* /U - Bus
* OH7LZB
* /V - ATV, amateur television
* https://openclipart.org/detail/48997/flat-screen-by-rg1024
* Author: rg1024
* Adjusted by OH7LZB
* PD: https://openclipart.org/share
* /W - Wx, Weather service site
* VEC-OH7LZB
* /X - Helicopter
* OH7LZB
* /Y - Sailboat
* OH7LZB
* /Z - Windows flag
* Microsoft
* /[ - Human
* VEC-OH7LZB
* /\ - DF triangle
* VEC-OH7LZB
* /] - Mailbox, post office, letter
* /^ - Large aircraft
* https://openclipart.org/detail/183204/plane-red-by-sketchartist-183204
* Author: SketchArtist
* PD: https://openclipart.org/share
* /_ - Weather station
* VEC-OH7LZB
* /` - Satellite dish
* OH7LZB
* /a - Ambulance
* OH7LZB
* /b - Bicycle
* http://commons.wikimedia.org/wiki/File:Bicycle_evolution-numbers.svg
* Author: Wikipedia user: Al2
* CC BY 3.0
* /c - Incident command post
* VEC-OH7LZB
* /d - Fire station
* VEC-OH7LZB
* /e - Horse, equestrian
* https://openclipart.org/detail/142627/horse-riding-lesson-by-olku
* Author: OlKu
* PD: https://openclipart.org/share
* /f - Fire truck
* OH7LZB
* /g - Hang glider
* OH7LZB
* /h - Hospital
* VEC-OH7LZB
* /i - IOTA, islands on the air
* http://commons.wikimedia.org/wiki/File:Palm_Island_R.svg
* PI
* /j - Jeep
* OH7LZB
* /k - Truck
* OH7LZB
* /l - Laptop
* OH7LZB
* /m - Mic-E repeater
* VEC-OH7LZB
* /n - Node, black bulls-eye
* VEC-OH7LZB
* /o - Emergency operations center
* VEC-OH7LZB
* /p - Dog(e)
* OH7LZB
* /q - Grid square, 2 by 2
* VEC-OH7LZB
* /r - Repeater tower
* OH7LZB
* /s - Ship, power boat
* OH7LZB
* /t - Truck stop
* VEC-OH7LZB
* /u - Semi-trailer truck, 18-wheeler
* OH7LZB
* /v - Van
* OH7LZB
* /w - Water station
* VEC-OH7LZB
* /x - X / Unix
* https://commons.wikimedia.org/wiki/File:X11.svg
* PD
* /y - House, yagi antenna
* VEC-OH7LZB
* /z - Shelter
* VEC-OH7LZB
Secondary table
------------------
* Emergency
* VEC-OH7LZB
* Numbered digipeater / Green star
* VEC-OH7LZB
* Bank
* VEC-OH7LZB
* Numbered gateway / Black diamond
* VEC-OH7LZB
* Crash site
* OH7LZB
* Cloudy
* OH7LZB
* MEO
* VEC-OH7LZB
* Snowflake
* http://commons.wikimedia.org/wiki/File:Snowflake_01.svg
* Author: Wikipedia user: Amada44
* Public Domain
* Church
* VEC-OH7LZB
* Girl Scout
* VEC-OH7LZB
* Looks slightly like the common USA girl scouts logos. Should be different
enough to not infringe on "Girl Scouts of the USA" copyrights.
* Home (HF antenna)
* VEC-OH7LZB
* Unknown position
* VEC-OH7LZB
* Destination
* VEC-OH7LZB
* Numbered circle
* VEC-OH7LZB
* Petrol Station
* OH7LZB
* Hail
* VEC-OH7LZB
* Park
* VEC-OH7LZB
* Gale Flag
* VEC-OH7LZB
* Red car from above
* OH7LZB
* Info Kiosk
* VEC-OH7LZB
* Hurricane
* OH7LZB
* Numbered white box
* VEC-OH7LZB
* Snow blowing
* VEC-OH7LZB
* Coast Guard
* VEC-OH7LZB
* Drizzle
* VEC-OH7LZB
* Smoke / Chimney
* VEC-OH7LZB
* Freezing rain
* VEC-OH7LZB
* Snow Shwr
* VEC-OH7LZB
* Haze
* VEC-OH7LZB
* Rain Shower
* VEC-OH7LZB
* Lightning
* OH7LZB
* "Kenwood radio"
* Kenwood logo, vectorized
* "Lighthouse"
* CC BY-SA 2.0
* http://wiki.openstreetmap.org/wiki/File:Lighthouse.svg
* Nav Buoy
* OH7LZB
* Rocket
* http://www.clker.com/clipart-gglkuglug.html
* PD according to clker.com license
* Parking
* VEC-OH7LZB
* Earthquake, Restaurant
* VEC-OH7LZB
* Satellite
* OH7LZB
* Thunderstorm
* OH7LZB
* Sunny
* OH7LZB
* VORTAC, Numbered WXS
* VEC-OH7LZB
* Pharmacy Rx
* OH7LZB
* Wall Cloud
* OH7LZB
* Numbered plane
* https://openclipart.org/detail/183204/plane-red-by-sketchartist-183204
* Author: SketchArtist
* PD: https://openclipart.org/share
* Numbered WX Station
* VEC-OH7LZB
* Rain
* Source: http://commons.wikimedia.org/wiki/File:Heavy-rain-shower-transparent.svg
* Author: Wikipedia user: Peepo
* Public Domain
* With modifications by OH7LZB
* Numbered diamond
* VEC-OH7LZB
* Dust blowing
* NA
* Numbered civil defence
* VEC-OH7LZB
* DX spot
* VEC-OH7LZB
* Sleet
* NA
* Funnel Cloud
* NA
* Gale
* VEC-OH7LZB
* Store
* https://openclipart.org/detail/89299/cart-medium-by-martins.bruvelis
* Author: martins.bruvelis
* Public Domain
* Adjustments by OH7LZB
* Numbered black box
* VEC-OH7LZB
* Work zone / Excavator
* Based on http://www.clker.com/clipart-292480.html PNG version
* Vectorized and colors adjusted by OH7LZB
* PD according to clker.com documentation, uploader KURSVEIAL
* SUV
* OH7LZB
* Milepost, Numbered triangle, Circle sm
* VEC-OH7LZB
* Partly cloudy
* OH7LZB
* Restrooms, Numbered boat
* VEC-OH7LZB
* Tornado (also used in Funnel cloud, Skywarn)
* https://openclipart.org/detail/104887/tornado-by-laabadon
* Author: Laabadon
* Public Domain
* Numbered truck
* OH7LZB
* Numbered van
* OH7LZB
* Flooding
* NA
* Sky warn, Numbered shelter, fog
* VEC-OH7LZB
+7
View File
@@ -0,0 +1,7 @@
# APRS symbol assets
Unmodified 48-pixel PNG sprite sheets from [aprs.fi high-resolution symbols](https://github.com/hessu/aprs-symbols), by Heikki Hannikainen, OH7LZB and the individual contributors listed in COPYRIGHT.md. Displayed at 24 CSS pixels. Copyright and licensing vary by symbol; the full upstream notice is preserved in COPYRIGHT.md.
Descriptions in ../../aprs-symbols.js are adapted from [aprs-symbol-index](https://github.com/hessu/aprs-symbol-index), maintained by OH7LZB for aprs.fi, licensed under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/). Blank descriptions are omitted. Symbol overlays are drawn as text on the alternate table.
Mapping: printable APRS symbol codes ! through ~, sixteen columns per row, six rows per table. Unknown symbols use a neutral question mark rather than an invented station type.
Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

+26
View File
@@ -0,0 +1,26 @@
BSD 2-Clause License
Copyright (c) 2010-2023, Volodymyr Agafonkin
Copyright (c) 2010-2011, CloudMade
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+661
View File
@@ -0,0 +1,661 @@
/* required styles */
.leaflet-pane,
.leaflet-tile,
.leaflet-marker-icon,
.leaflet-marker-shadow,
.leaflet-tile-container,
.leaflet-pane > svg,
.leaflet-pane > canvas,
.leaflet-zoom-box,
.leaflet-image-layer,
.leaflet-layer {
position: absolute;
left: 0;
top: 0;
}
.leaflet-container {
overflow: hidden;
}
.leaflet-tile,
.leaflet-marker-icon,
.leaflet-marker-shadow {
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
-webkit-user-drag: none;
}
/* Prevents IE11 from highlighting tiles in blue */
.leaflet-tile::selection {
background: transparent;
}
/* Safari renders non-retina tile on retina better with this, but Chrome is worse */
.leaflet-safari .leaflet-tile {
image-rendering: -webkit-optimize-contrast;
}
/* hack that prevents hw layers "stretching" when loading new tiles */
.leaflet-safari .leaflet-tile-container {
width: 1600px;
height: 1600px;
-webkit-transform-origin: 0 0;
}
.leaflet-marker-icon,
.leaflet-marker-shadow {
display: block;
}
/* .leaflet-container svg: reset svg max-width decleration shipped in Joomla! (joomla.org) 3.x */
/* .leaflet-container img: map is broken in FF if you have max-width: 100% on tiles */
.leaflet-container .leaflet-overlay-pane svg {
max-width: none !important;
max-height: none !important;
}
.leaflet-container .leaflet-marker-pane img,
.leaflet-container .leaflet-shadow-pane img,
.leaflet-container .leaflet-tile-pane img,
.leaflet-container img.leaflet-image-layer,
.leaflet-container .leaflet-tile {
max-width: none !important;
max-height: none !important;
width: auto;
padding: 0;
}
.leaflet-container img.leaflet-tile {
/* See: https://bugs.chromium.org/p/chromium/issues/detail?id=600120 */
mix-blend-mode: plus-lighter;
}
.leaflet-container.leaflet-touch-zoom {
-ms-touch-action: pan-x pan-y;
touch-action: pan-x pan-y;
}
.leaflet-container.leaflet-touch-drag {
-ms-touch-action: pinch-zoom;
/* Fallback for FF which doesn't support pinch-zoom */
touch-action: none;
touch-action: pinch-zoom;
}
.leaflet-container.leaflet-touch-drag.leaflet-touch-zoom {
-ms-touch-action: none;
touch-action: none;
}
.leaflet-container {
-webkit-tap-highlight-color: transparent;
}
.leaflet-container a {
-webkit-tap-highlight-color: rgba(51, 181, 229, 0.4);
}
.leaflet-tile {
filter: inherit;
visibility: hidden;
}
.leaflet-tile-loaded {
visibility: inherit;
}
.leaflet-zoom-box {
width: 0;
height: 0;
-moz-box-sizing: border-box;
box-sizing: border-box;
z-index: 800;
}
/* workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=888319 */
.leaflet-overlay-pane svg {
-moz-user-select: none;
}
.leaflet-pane { z-index: 400; }
.leaflet-tile-pane { z-index: 200; }
.leaflet-overlay-pane { z-index: 400; }
.leaflet-shadow-pane { z-index: 500; }
.leaflet-marker-pane { z-index: 600; }
.leaflet-tooltip-pane { z-index: 650; }
.leaflet-popup-pane { z-index: 700; }
.leaflet-map-pane canvas { z-index: 100; }
.leaflet-map-pane svg { z-index: 200; }
.leaflet-vml-shape {
width: 1px;
height: 1px;
}
.lvml {
behavior: url(#default#VML);
display: inline-block;
position: absolute;
}
/* control positioning */
.leaflet-control {
position: relative;
z-index: 800;
pointer-events: visiblePainted; /* IE 9-10 doesn't have auto */
pointer-events: auto;
}
.leaflet-top,
.leaflet-bottom {
position: absolute;
z-index: 1000;
pointer-events: none;
}
.leaflet-top {
top: 0;
}
.leaflet-right {
right: 0;
}
.leaflet-bottom {
bottom: 0;
}
.leaflet-left {
left: 0;
}
.leaflet-control {
float: left;
clear: both;
}
.leaflet-right .leaflet-control {
float: right;
}
.leaflet-top .leaflet-control {
margin-top: 10px;
}
.leaflet-bottom .leaflet-control {
margin-bottom: 10px;
}
.leaflet-left .leaflet-control {
margin-left: 10px;
}
.leaflet-right .leaflet-control {
margin-right: 10px;
}
/* zoom and fade animations */
.leaflet-fade-anim .leaflet-popup {
opacity: 0;
-webkit-transition: opacity 0.2s linear;
-moz-transition: opacity 0.2s linear;
transition: opacity 0.2s linear;
}
.leaflet-fade-anim .leaflet-map-pane .leaflet-popup {
opacity: 1;
}
.leaflet-zoom-animated {
-webkit-transform-origin: 0 0;
-ms-transform-origin: 0 0;
transform-origin: 0 0;
}
svg.leaflet-zoom-animated {
will-change: transform;
}
.leaflet-zoom-anim .leaflet-zoom-animated {
-webkit-transition: -webkit-transform 0.25s cubic-bezier(0,0,0.25,1);
-moz-transition: -moz-transform 0.25s cubic-bezier(0,0,0.25,1);
transition: transform 0.25s cubic-bezier(0,0,0.25,1);
}
.leaflet-zoom-anim .leaflet-tile,
.leaflet-pan-anim .leaflet-tile {
-webkit-transition: none;
-moz-transition: none;
transition: none;
}
.leaflet-zoom-anim .leaflet-zoom-hide {
visibility: hidden;
}
/* cursors */
.leaflet-interactive {
cursor: pointer;
}
.leaflet-grab {
cursor: -webkit-grab;
cursor: -moz-grab;
cursor: grab;
}
.leaflet-crosshair,
.leaflet-crosshair .leaflet-interactive {
cursor: crosshair;
}
.leaflet-popup-pane,
.leaflet-control {
cursor: auto;
}
.leaflet-dragging .leaflet-grab,
.leaflet-dragging .leaflet-grab .leaflet-interactive,
.leaflet-dragging .leaflet-marker-draggable {
cursor: move;
cursor: -webkit-grabbing;
cursor: -moz-grabbing;
cursor: grabbing;
}
/* marker & overlays interactivity */
.leaflet-marker-icon,
.leaflet-marker-shadow,
.leaflet-image-layer,
.leaflet-pane > svg path,
.leaflet-tile-container {
pointer-events: none;
}
.leaflet-marker-icon.leaflet-interactive,
.leaflet-image-layer.leaflet-interactive,
.leaflet-pane > svg path.leaflet-interactive,
svg.leaflet-image-layer.leaflet-interactive path {
pointer-events: visiblePainted; /* IE 9-10 doesn't have auto */
pointer-events: auto;
}
/* visual tweaks */
.leaflet-container {
background: #ddd;
outline-offset: 1px;
}
.leaflet-container a {
color: #0078A8;
}
.leaflet-zoom-box {
border: 2px dotted #38f;
background: rgba(255,255,255,0.5);
}
/* general typography */
.leaflet-container {
font-family: "Helvetica Neue", Arial, Helvetica, sans-serif;
font-size: 12px;
font-size: 0.75rem;
line-height: 1.5;
}
/* general toolbar styles */
.leaflet-bar {
box-shadow: 0 1px 5px rgba(0,0,0,0.65);
border-radius: 4px;
}
.leaflet-bar a {
background-color: #fff;
border-bottom: 1px solid #ccc;
width: 26px;
height: 26px;
line-height: 26px;
display: block;
text-align: center;
text-decoration: none;
color: black;
}
.leaflet-bar a,
.leaflet-control-layers-toggle {
background-position: 50% 50%;
background-repeat: no-repeat;
display: block;
}
.leaflet-bar a:hover,
.leaflet-bar a:focus {
background-color: #f4f4f4;
}
.leaflet-bar a:first-child {
border-top-left-radius: 4px;
border-top-right-radius: 4px;
}
.leaflet-bar a:last-child {
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
border-bottom: none;
}
.leaflet-bar a.leaflet-disabled {
cursor: default;
background-color: #f4f4f4;
color: #bbb;
}
.leaflet-touch .leaflet-bar a {
width: 30px;
height: 30px;
line-height: 30px;
}
.leaflet-touch .leaflet-bar a:first-child {
border-top-left-radius: 2px;
border-top-right-radius: 2px;
}
.leaflet-touch .leaflet-bar a:last-child {
border-bottom-left-radius: 2px;
border-bottom-right-radius: 2px;
}
/* zoom control */
.leaflet-control-zoom-in,
.leaflet-control-zoom-out {
font: bold 18px 'Lucida Console', Monaco, monospace;
text-indent: 1px;
}
.leaflet-touch .leaflet-control-zoom-in, .leaflet-touch .leaflet-control-zoom-out {
font-size: 22px;
}
/* layers control */
.leaflet-control-layers {
box-shadow: 0 1px 5px rgba(0,0,0,0.4);
background: #fff;
border-radius: 5px;
}
.leaflet-control-layers-toggle {
background-image: url(images/layers.png);
width: 36px;
height: 36px;
}
.leaflet-retina .leaflet-control-layers-toggle {
background-image: url(images/layers-2x.png);
background-size: 26px 26px;
}
.leaflet-touch .leaflet-control-layers-toggle {
width: 44px;
height: 44px;
}
.leaflet-control-layers .leaflet-control-layers-list,
.leaflet-control-layers-expanded .leaflet-control-layers-toggle {
display: none;
}
.leaflet-control-layers-expanded .leaflet-control-layers-list {
display: block;
position: relative;
}
.leaflet-control-layers-expanded {
padding: 6px 10px 6px 6px;
color: #333;
background: #fff;
}
.leaflet-control-layers-scrollbar {
overflow-y: scroll;
overflow-x: hidden;
padding-right: 5px;
}
.leaflet-control-layers-selector {
margin-top: 2px;
position: relative;
top: 1px;
}
.leaflet-control-layers label {
display: block;
font-size: 13px;
font-size: 1.08333em;
}
.leaflet-control-layers-separator {
height: 0;
border-top: 1px solid #ddd;
margin: 5px -10px 5px -6px;
}
/* Default icon URLs */
.leaflet-default-icon-path { /* used only in path-guessing heuristic, see L.Icon.Default */
background-image: url(images/marker-icon.png);
}
/* attribution and scale controls */
.leaflet-container .leaflet-control-attribution {
background: #fff;
background: rgba(255, 255, 255, 0.8);
margin: 0;
}
.leaflet-control-attribution,
.leaflet-control-scale-line {
padding: 0 5px;
color: #333;
line-height: 1.4;
}
.leaflet-control-attribution a {
text-decoration: none;
}
.leaflet-control-attribution a:hover,
.leaflet-control-attribution a:focus {
text-decoration: underline;
}
.leaflet-attribution-flag {
display: inline !important;
vertical-align: baseline !important;
width: 1em;
height: 0.6669em;
}
.leaflet-left .leaflet-control-scale {
margin-left: 5px;
}
.leaflet-bottom .leaflet-control-scale {
margin-bottom: 5px;
}
.leaflet-control-scale-line {
border: 2px solid #777;
border-top: none;
line-height: 1.1;
padding: 2px 5px 1px;
white-space: nowrap;
-moz-box-sizing: border-box;
box-sizing: border-box;
background: rgba(255, 255, 255, 0.8);
text-shadow: 1px 1px #fff;
}
.leaflet-control-scale-line:not(:first-child) {
border-top: 2px solid #777;
border-bottom: none;
margin-top: -2px;
}
.leaflet-control-scale-line:not(:first-child):not(:last-child) {
border-bottom: 2px solid #777;
}
.leaflet-touch .leaflet-control-attribution,
.leaflet-touch .leaflet-control-layers,
.leaflet-touch .leaflet-bar {
box-shadow: none;
}
.leaflet-touch .leaflet-control-layers,
.leaflet-touch .leaflet-bar {
border: 2px solid rgba(0,0,0,0.2);
background-clip: padding-box;
}
/* popup */
.leaflet-popup {
position: absolute;
text-align: center;
margin-bottom: 20px;
}
.leaflet-popup-content-wrapper {
padding: 1px;
text-align: left;
border-radius: 12px;
}
.leaflet-popup-content {
margin: 13px 24px 13px 20px;
line-height: 1.3;
font-size: 13px;
font-size: 1.08333em;
min-height: 1px;
}
.leaflet-popup-content p {
margin: 17px 0;
margin: 1.3em 0;
}
.leaflet-popup-tip-container {
width: 40px;
height: 20px;
position: absolute;
left: 50%;
margin-top: -1px;
margin-left: -20px;
overflow: hidden;
pointer-events: none;
}
.leaflet-popup-tip {
width: 17px;
height: 17px;
padding: 1px;
margin: -10px auto 0;
pointer-events: auto;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
.leaflet-popup-content-wrapper,
.leaflet-popup-tip {
background: white;
color: #333;
box-shadow: 0 3px 14px rgba(0,0,0,0.4);
}
.leaflet-container a.leaflet-popup-close-button {
position: absolute;
top: 0;
right: 0;
border: none;
text-align: center;
width: 24px;
height: 24px;
font: 16px/24px Tahoma, Verdana, sans-serif;
color: #757575;
text-decoration: none;
background: transparent;
}
.leaflet-container a.leaflet-popup-close-button:hover,
.leaflet-container a.leaflet-popup-close-button:focus {
color: #585858;
}
.leaflet-popup-scrolled {
overflow: auto;
}
.leaflet-oldie .leaflet-popup-content-wrapper {
-ms-zoom: 1;
}
.leaflet-oldie .leaflet-popup-tip {
width: 24px;
margin: 0 auto;
-ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678)";
filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678);
}
.leaflet-oldie .leaflet-control-zoom,
.leaflet-oldie .leaflet-control-layers,
.leaflet-oldie .leaflet-popup-content-wrapper,
.leaflet-oldie .leaflet-popup-tip {
border: 1px solid #999;
}
/* div icon */
.leaflet-div-icon {
background: #fff;
border: 1px solid #666;
}
/* Tooltip */
/* Base styles for the element that has a tooltip */
.leaflet-tooltip {
position: absolute;
padding: 6px;
background-color: #fff;
border: 1px solid #fff;
border-radius: 3px;
color: #222;
white-space: nowrap;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
pointer-events: none;
box-shadow: 0 1px 3px rgba(0,0,0,0.4);
}
.leaflet-tooltip.leaflet-interactive {
cursor: pointer;
pointer-events: auto;
}
.leaflet-tooltip-top:before,
.leaflet-tooltip-bottom:before,
.leaflet-tooltip-left:before,
.leaflet-tooltip-right:before {
position: absolute;
pointer-events: none;
border: 6px solid transparent;
background: transparent;
content: "";
}
/* Directions */
.leaflet-tooltip-bottom {
margin-top: 6px;
}
.leaflet-tooltip-top {
margin-top: -6px;
}
.leaflet-tooltip-bottom:before,
.leaflet-tooltip-top:before {
left: 50%;
margin-left: -6px;
}
.leaflet-tooltip-top:before {
bottom: 0;
margin-bottom: -12px;
border-top-color: #fff;
}
.leaflet-tooltip-bottom:before {
top: 0;
margin-top: -12px;
margin-left: -6px;
border-bottom-color: #fff;
}
.leaflet-tooltip-left {
margin-left: -6px;
}
.leaflet-tooltip-right {
margin-left: 6px;
}
.leaflet-tooltip-left:before,
.leaflet-tooltip-right:before {
top: 50%;
margin-top: -6px;
}
.leaflet-tooltip-left:before {
right: 0;
margin-right: -12px;
border-left-color: #fff;
}
.leaflet-tooltip-right:before {
left: 0;
margin-left: -12px;
border-right-color: #fff;
}
/* Printing */
@media print {
/* Prevent printers from removing background-images of controls. */
.leaflet-control {
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
}
+6
View File
@@ -0,0 +1,6 @@
/* @preserve
* Leaflet 1.9.4, a JS library for interactive maps. https://leafletjs.com
* (c) 2010-2023 Vladimir Agafonkin, (c) 2010-2011 CloudMade
*/
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).leaflet={})}(this,function(t){"use strict";function l(t){for(var e,i,n=1,o=arguments.length;n<o;n++)for(e in i=arguments[n])t[e]=i[e];return t}var R=Object.create||function(t){return N.prototype=t,new N};function N(){}function a(t,e){var i,n=Array.prototype.slice;return t.bind?t.bind.apply(t,n.call(arguments,1)):(i=n.call(arguments,2),function(){return t.apply(e,i.length?i.concat(n.call(arguments)):arguments)})}var D=0;function h(t){return"_leaflet_id"in t||(t._leaflet_id=++D),t._leaflet_id}function j(t,e,i){var n,o,s=function(){n=!1,o&&(r.apply(i,o),o=!1)},r=function(){n?o=arguments:(t.apply(i,arguments),setTimeout(s,e),n=!0)};return r}function H(t,e,i){var n=e[1],e=e[0],o=n-e;return t===n&&i?t:((t-e)%o+o)%o+e}function u(){return!1}function i(t,e){return!1===e?t:(e=Math.pow(10,void 0===e?6:e),Math.round(t*e)/e)}function W(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function F(t){return W(t).split(/\s+/)}function c(t,e){for(var i in Object.prototype.hasOwnProperty.call(t,"options")||(t.options=t.options?R(t.options):{}),e)t.options[i]=e[i];return t.options}function U(t,e,i){var n,o=[];for(n in t)o.push(encodeURIComponent(i?n.toUpperCase():n)+"="+encodeURIComponent(t[n]));return(e&&-1!==e.indexOf("?")?"&":"?")+o.join("&")}var V=/\{ *([\w_ -]+) *\}/g;function q(t,i){return t.replace(V,function(t,e){e=i[e];if(void 0===e)throw new Error("No value provided for variable "+t);return e="function"==typeof e?e(i):e})}var d=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)};function G(t,e){for(var i=0;i<t.length;i++)if(t[i]===e)return i;return-1}var K="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=";function Y(t){return window["webkit"+t]||window["moz"+t]||window["ms"+t]}var X=0;function J(t){var e=+new Date,i=Math.max(0,16-(e-X));return X=e+i,window.setTimeout(t,i)}var $=window.requestAnimationFrame||Y("RequestAnimationFrame")||J,Q=window.cancelAnimationFrame||Y("CancelAnimationFrame")||Y("CancelRequestAnimationFrame")||function(t){window.clearTimeout(t)};function x(t,e,i){if(!i||$!==J)return $.call(window,a(t,e));t.call(e)}function r(t){t&&Q.call(window,t)}var tt={__proto__:null,extend:l,create:R,bind:a,get lastId(){return D},stamp:h,throttle:j,wrapNum:H,falseFn:u,formatNum:i,trim:W,splitWords:F,setOptions:c,getParamString:U,template:q,isArray:d,indexOf:G,emptyImageUrl:K,requestFn:$,cancelFn:Q,requestAnimFrame:x,cancelAnimFrame:r};function et(){}et.extend=function(t){function e(){c(this),this.initialize&&this.initialize.apply(this,arguments),this.callInitHooks()}var i,n=e.__super__=this.prototype,o=R(n);for(i in(o.constructor=e).prototype=o,this)Object.prototype.hasOwnProperty.call(this,i)&&"prototype"!==i&&"__super__"!==i&&(e[i]=this[i]);if(t.statics&&l(e,t.statics),t.includes){var s=t.includes;if("undefined"!=typeof L&&L&&L.Mixin){s=d(s)?s:[s];for(var r=0;r<s.length;r++)s[r]===L.Mixin.Events&&console.warn("Deprecated include of L.Mixin.Events: this property will be removed in future releases, please inherit from L.Evented instead.",(new Error).stack)}l.apply(null,[o].concat(t.includes))}return l(o,t),delete o.statics,delete o.includes,o.options&&(o.options=n.options?R(n.options):{},l(o.options,t.options)),o._initHooks=[],o.callInitHooks=function(){if(!this._initHooksCalled){n.callInitHooks&&n.callInitHooks.call(this),this._initHooksCalled=!0;for(var t=0,e=o._initHooks.length;t<e;t++)o._initHooks[t].call(this)}},e},et.include=function(t){var e=this.prototype.options;return l(this.prototype,t),t.options&&(this.prototype.options=e,this.mergeOptions(t.options)),this},et.mergeOptions=function(t){return l(this.prototype.options,t),this},et.addInitHook=function(t){var e=Array.prototype.slice.call(arguments,1),i="function"==typeof t?t:function(){this[t].apply(this,e)};return this.prototype._initHooks=this.prototype._initHooks||[],this.prototype._initHooks.push(i),this};var e={on:function(t,e,i){if("object"==typeof t)for(var n in t)this._on(n,t[n],e);else for(var o=0,s=(t=F(t)).length;o<s;o++)this._on(t[o],e,i);return this},off:function(t,e,i){if(arguments.length)if("object"==typeof t)for(var n in t)this._off(n,t[n],e);else{t=F(t);for(var o=1===arguments.length,s=0,r=t.length;s<r;s++)o?this._off(t[s]):this._off(t[s],e,i)}else delete this._events;return this},_on:function(t,e,i,n){"function"!=typeof e?console.warn("wrong listener type: "+typeof e):!1===this._listens(t,e,i)&&(e={fn:e,ctx:i=i===this?void 0:i},n&&(e.once=!0),this._events=this._events||{},this._events[t]=this._events[t]||[],this._events[t].push(e))},_off:function(t,e,i){var n,o,s;if(this._events&&(n=this._events[t]))if(1===arguments.length){if(this._firingCount)for(o=0,s=n.length;o<s;o++)n[o].fn=u;delete this._events[t]}else"function"!=typeof e?console.warn("wrong listener type: "+typeof e):!1!==(e=this._listens(Line truncated
//# sourceMappingURL=leaflet.js.map
+3
View File
@@ -0,0 +1,3 @@
.wl-radio-panel{margin-bottom:20px;overflow:hidden}.wl-radio-heading{display:flex;justify-content:space-between;align-items:center;gap:16px;padding:22px 24px 17px}.wl-radio-eyebrow{font-size:9px;color:#7e9cbb;letter-spacing:1.5px}.wl-radio-heading h2{margin:7px 0;font-size:21px;font-weight:500}.wl-radio-heading p{font-size:11px;color:var(--muted);margin:0}.wl-radio-heading button{font-size:11px;padding:10px 13px}.wl-radio-toolbar{display:flex;gap:12px;align-items:center;padding:0 24px 18px;flex-wrap:wrap}.wl-radio-toolbar input[type=search]{flex:1;min-width:190px}.wl-radio-toolbar input[type=search],.wl-radio-toolbar select{font-size:11px;padding:10px 12px}.wl-radio-toolbar label{display:flex;align-items:center;gap:7px;font-size:11px;color:var(--muted)}.wl-radio-toolbar input[type=checkbox]{accent-color:#9bbbd9}.wl-gateway-caption{display:flex;justify-content:space-between;gap:15px;padding:11px 24px;border-block:1px solid var(--line);color:#8e9fb5;font-size:10px;background:#111822}.wl-gateway-scroll{max-height:310px;overflow:auto}.wl-gateway-table{width:100%;min-width:870px;border-collapse:collapse}.wl-gateway-table th{position:sticky;top:0;z-index:1;background:#111822;color:#8e9fb5;font-size:10px;font-weight:500;white-space:nowrap;padding:12px 14px}.wl-gateway-table td{padding:13px 14px;font-size:11px;border-color:#252f3f}.wl-gateway-table tr[data-channel]{cursor:pointer}.wl-gateway-table tr[data-channel]:hover{background:#1a293b}.wl-gateway-table tr.selected{background:#233a53}.wl-gateway-table tr.unavailable{opacity:.55;cursor:default}.wl-gateway-table td:first-child{width:30px;padding-right:0}.wl-gateway-table td:nth-child(2){max-width:230px}.wl-gateway-table td:nth-child(2)>b{font-size:12px;letter-spacing:.3px}.wl-gateway-table small{display:block;font-size:9px;color:var(--muted);margin-top:5px;line-height:1.5}.wl-gateway-table input{accent-color:#a5c3e0}.wl-channel-frequency{font-variant-numeric:tabular-nums;font-weight:500;white-space:nowrap;color:#c4d9ee}.wl-gateway-table .fresh{color:#90b9ad}.wl-gateway-table .old{color:#d8ad91}.wl-radio-connect{display:flex;justify-content:space-between;align-items:center;gap:20px;padding:19px 24px;background:#172334;border-top:1px solid #304159}.wl-radio-connect strong{font-size:14px;font-weight:500}.wl-radio-connect p{font-size:10px;color:#91a7be;margin:7px 0 0}.wl-radio-connect button{font-size:12px;white-space:nowrap}.wl-radio-footnote{font-size:10px;color:var(--muted);line-height:1.6;padding:0 24px 14px}.wl-directory-error{padding:12px 24px;background:#342a20;color:#e3c5a2;font-size:12px;line-height:1.6}.wl-radio-progress{padding:14px 24px;font-size:12px;line-height:1.7;border-top:1px solid var(--line);color:#acc0d8}.wl-radio-progress.running{background:#162c3e;color:#b6d7ed}.wl-radio-progress.complete{background:#16302a;color:#b2d9c8}#wl-radio-toggle.active{background:#243c54;border-color:#718fac;color:#c4ddef}@media(max-width:650px){.wl-radio-heading,.wl-radio-connect{align-items:flex-start;flex-direction:column}.wl-radio-toolbar{padding-inline:18px}.wl-radio-toolbar input[type=search]{width:100%}.wl-radio-connect button{width:100%}.wl-gateway-caption>span:last-child{display:none}}
#winlink:has(.wl-radio-panel:not([hidden])){height:auto;min-height:calc(100dvh - 76px)}.wl-radio-panel{flex-shrink:0}.wl-radio-toolbar label{white-space:nowrap}.wl-radio-toolbar input[type=checkbox]{width:16px;height:16px;margin:0;flex:none}.wl-gateway-table input[type=radio]{width:15px;height:15px;margin:0}.wl-radio-panel~.mail-layout{min-height:560px}
+25
View File
@@ -0,0 +1,25 @@
(() => {
let directory=null,selectedId=null,fetching=false,requesting=false,session=null,expanded=false;
const header=$('#winlink .chat-actions');$('#wl-sync').textContent='↻ Sync Internet';const toggle=document.createElement('button');toggle.className='secondary';toggle.id='wl-radio-toggle';toggle.textContent='◉ Sync Radio';toggle.setAttribute('aria-expanded','false');header.insertBefore(toggle,$('#wl-compose'));
const gatewayPanel=document.createElement('section');gatewayPanel.className='wl-radio-panel card';gatewayPanel.hidden=true;gatewayPanel.innerHTML=`<div class="wl-radio-heading"><div><span class="wl-radio-eyebrow">WINLINK · RADIO</span><h2>Scegli un gateway</h2><p id="wl-directory-meta">Directory ufficiale · canali PUBLIC</p></div><button id="wl-gateway-refresh" class="secondary">↻ Aggiorna elenco</button></div><div class="wl-radio-toolbar"><input type="search" id="wl-gateway-search" aria-label="Cerca gateway Winlink" placeholder="Nominativo, locator o località…"><select id="wl-gateway-band" aria-label="Banda gateway"><option value="40,20">40 e 20 metri</option><option value="40">40 metri</option><option value="20">20 metri</option><option value="vhf">VHF · 2 metri</option><option value="uhf">UHF · 70 centimetri</option><option value="vhf,uhf">VHF e UHF</option><option value="hf">Tutte le bande HF</option><option value="all">HF, VHF e UHF</option></select><label><input type="checkbox" id="wl-gateway-open" checked> In orario e report recente</label><select id="wl-gateway-sort" aria-label="Ordina gateway"><option value="distance">Distanza crescente</option><option value="call">Nominativo</option><option value="frequency">Frequenza</option></select></div><div id="wl-directory-error" class="wl-directory-error" role="status" hidden></div><div class="wl-gateway-caption"><span id="wl-gateway-count">Caricamento…</span><span>Frequenze sul display · USB / FM · orari UTC</span></div><div class="wl-gateway-scroll"><table class="wl-gateway-table"><thead><tr><th></th><th>Gateway</th><th>Frequenza / modo</th><th>Modo / banda</th><th>Locator / distanza</th><th>Orari UTC</th><th>Ultimo report</th></tr></thead><tbody id="wl-gateway-rows"></tbody></table></div><footer class="wl-radio-connect"><div><strong id="wl-radio-selected">Nessun gateway selezionato</strong><p id="wl-radio-selected-detail">Seleziona un canale nell’elenco.</p></div><button id="wl-radio-connect" class="primary" disabled>Connetti e sincronizza →</button></footer><div id="wl-radio-progress" class="wl-radio-progress" role="status" hidden></div><p class="wl-radio-footnote">La distanza non indica la qualità del collegamento. Il report conferma la pubblicazione del gateway, non che il canale radio sia libero. La frequenza centrale è disponibile nel dettaglio del canale selezionato.</p>`;
$('#winlink .wl-status').before(gatewayPanel);$('#winlink .wl-status span:last-child').id='wl-transport-label';
const hz=f=>(f/1e6).toFixed(6)+' MHz';
const time=t=>t?new Date(t).toLocaleString(BPQI18n.locale(),{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'}):'Non disponibile';
const band=hz=>hz>=430e6&&hz<=440e6?'uhf':hz>=144e6&&hz<=146e6?'vhf':hz>=7e6&&hz<=7.3e6?'40':hz>=14e6&&hz<=14.35e6?'20':hz>=3.5e6&&hz<=4e6?'80':hz>=10.1e6&&hz<=10.15e6?'30':hz>=18.068e6&&hz<=18.168e6?'17':hz>=21e6&&hz<=21.45e6?'15':hz>=24.89e6&&hz<=24.99e6?'12':hz>=28e6?'10':'HF';
const available=c=>directory&&!directory.stale&&c.fresh&&c.open===true&&c.supported!==false;
function rows(){const q=$('#wl-gateway-search').value.trim().toUpperCase(),bands=$('#wl-gateway-band').value,open=$('#wl-gateway-open').checked,sort=$('#wl-gateway-sort').value;return (directory?.channels||[]).filter(c=>(bands==='all'||bands==='hf'&&!['vhf','uhf'].includes(band(c.dialHz))||bands.split(',').includes(band(c.dialHz)))&&(!open||!directory.stale&&c.fresh&&c.open===true)&&(!q||[c.call,c.grid,c.qth].join(' ').toUpperCase().includes(q))).sort((a,b)=>sort==='call'?a.call.localeCompare(b.call)||a.dialHz-b.dialHz:sort==='frequency'?a.dialHz-b.dialHz:(a.distanceKm??Infinity)-(b.distanceKm??Infinity)||a.call.localeCompare(b.call)||a.dialHz-b.dialHz);}
function render(){if(!directory)return;const list=rows();$('#wl-directory-meta').textContent='Winlink PUBLIC · '+directory.mode+' · aggiornato '+time(directory.fetchedAt)+' · '+mailTimezone();$('#wl-directory-error').hidden=!!wlData?.radioSupported&&!directory.error&&!directory.stale;$('#wl-directory-error').textContent=!wlData?'Verifica configurazione radio…':!wlData.radioSupported?'Sync radio non configurato: verifica modem e controllo CAT.':directory.stale?'Elenco non aggiornato: aggiorna prima di collegarti.':directory.error||'';$('#wl-gateway-count').textContent=list.length+(list.length===1?' canale · ':' canali · ')+new Set(list.map(c=>c.call)).size+' gateway';const focused=document.activeElement?.matches('input[name="wl-channel"]')?document.activeElement.closest('[data-channel]').dataset.channel:null;const scroll=$('.wl-gateway-scroll').scrollTop;$('#wl-gateway-rows').innerHTML=list.map(c=>`<tr data-channel="${esc(c.id)}" class="${selectedId===c.id?'selected':''} ${available(c)?'':'unavailable'}"><td><input type="radio" name="wl-channel" aria-label="Seleziona ${esc(c.call)} ${hz(c.dialHz)}" ${selectedId===c.id?'checked':''} ${available(c)?'':'disabled'}></td><td><b>${esc(c.call)}</b><small>${esc(c.qth)}</small></td><td class="wl-channel-frequency">${hz(c.dialHz)}<small>${esc(c.radioMode||'USB')}</small></td><td>${esc(c.mode)}<small>${band(c.dialHz)==='vhf'?'VHF · 2 m':band(c.dialHz)==='uhf'?'UHF · 70 cm':band(c.dialHz)+' m'}</small></td><td>${esc(c.grid)}<small>${c.distanceKm==null?'Distanza non disponibile':c.distanceKm.toLocaleString(BPQI18n.locale())+' km'}</small></td><td>${esc(c.hours||'Non dichiarati')}<small>${c.open===true?'In orario':c.open===false?'Fuori orario':'Orari non riconosciuti'}</small></td><td>${time(c.postedAt)}<small class="${c.fresh?'fresh':'old'}">${c.fresh?'Recente':'Report scaduto / assente'}</small>${c.supported===false?'<small>'+esc(c.reason)+'</small>':''}</td></tr>`).join('')||'<tr><td colspan="7" class="empty">Nessun canale corrisponde ai filtri.</td></tr>';$('.wl-gateway-scroll').scrollTop=scroll;if(focused)$('[data-channel="'+focused+'"] input')?.focus({preventScroll:true});selection();}
function selection(){const c=directory?.channels.find(c=>c.id===selectedId);$('#wl-radio-selected').textContent=c?c.call+' · '+hz(c.dialHz)+' '+(c.radioMode||'USB'):'Nessun gateway selezionato';$('#wl-radio-selected-detail').textContent=c?(c.family==='Packet'?'Frequenza FM: ':'Centro: ')+hz(c.centerHz)+' · '+c.grid+' · '+c.mode+' · porta '+c.port:'Seleziona un canale nell’elenco.';const active=Boolean(session?.restoring);$('#wl-radio-connect').disabled=requesting||active||!c||!available(c)||!wlData?.radioSupported;$('#wl-radio-connect').textContent=requesting?'Richiesta…':active?'Sessione in corso…':'Connetti e sincronizza →';}
async function load(force=false){if(fetching||!csrf)return;fetching=true;$('#wl-gateway-refresh').disabled=true;try{directory=await api('/winlink/gateways'+(force?'?refresh=1':''));render();}catch(e){$('#wl-directory-error').hidden=false;$('#wl-directory-error').textContent=e.message;$('#wl-gateway-count').textContent='Elenco non disponibile';}finally{fetching=false;$('#wl-gateway-refresh').disabled=false;}}
toggle.onclick=()=>{expanded=!expanded;gatewayPanel.hidden=!expanded;toggle.setAttribute('aria-expanded',String(expanded));toggle.classList.toggle('active',expanded);if(expanded){if(!wlData?.radioSupported){$('#wl-directory-error').hidden=false;$('#wl-directory-error').textContent='Sync radio non configurato: serve un modem supportato e il controllo CAT abilitato.';}load();}};
$('#wl-gateway-refresh').onclick=()=>load(true);for(const id of ['wl-gateway-search','wl-gateway-band','wl-gateway-open','wl-gateway-sort'])$('#'+id).oninput=render;
gatewayPanel.addEventListener('click',e=>{const row=e.target.closest('[data-channel]');if(!row)return;const c=directory.channels.find(c=>c.id===row.dataset.channel);if(!available(c))return;selectedId=c.id;render();});
gatewayPanel.addEventListener('change',e=>{if(e.target.matches('input[name="wl-channel"]')){selectedId=e.target.closest('[data-channel]').dataset.channel;render();}});
$('#wl-radio-connect').onclick=async()=>{if(requesting||!selectedId)return;requesting=true;selection();try{await window.bpqSync.start({kind:'winlink-radio',channelId:selectedId});updateSession();setTimeout(wlLoad,1200);}catch(e){$('#wl-directory-error').hidden=false;$('#wl-directory-error').textContent=e.message;toast(e.message);}finally{requesting=false;selection();}};
function updateSession(){session=wlData?.radioSession||session;const active=session?.restoring;restore.hidden=!(active&&['conflict','error'].includes(session.state));$('#wl-sync').disabled=Boolean(active);$('#wl-transport-label').textContent=wlData?.transport==='radio'||active?'Radio · '+(session?.channel.call||'RMS'):'CMS · Internet';const box=$('#wl-radio-progress');box.hidden=!session;if(session){const label={preparing:'Preparazione modem packet e frequenza',requested:'Richiesta inviata a BPQ',calling:'Chiamata radio in corso',connected:'Collegato · scambio posta',complete:'Sync radio completato',ended:'Profilo Internet ripristinato',failed:'Collegamento non riuscito',incomplete:'Sessione interrotta',error:'Errore nella richiesta',conflict:'Ripristino da verificare'}[session.state]||session.state;box.className='wl-radio-progress '+(active?'running':session.state==='complete'?'complete':'');box.textContent=(active?'◉ ':'')+label+' · '+session.channel.call+' · '+hz(session.channel.dialHz)+(session.sent!=null?' · TX '+session.sent+' / RX '+session.received:'')+(active?' · profilo Internet sospeso':session.endedAt?' · '+time(session.endedAt):'')+(session.error?' · '+session.error:'');}selection();}
setInterval(()=>{if(expanded&&csrf&&!document.hidden)load();},60000);
const restore=document.createElement('button');restore.className='secondary wl-radio-restore';restore.textContent='Ripristina profilo Internet';restore.hidden=true;$('#wl-radio-progress').after(restore);restore.onclick=async()=>{restore.disabled=true;try{session=await api('/winlink/radio/restore',{method:'POST',body:'{}'});await wlLoad();}catch(e){toast(e.message);}finally{restore.disabled=false;}};
const previousRender=wlRender;wlRender=function(){previousRender();if(directory){$('#wl-directory-error').hidden=!!wlData?.radioSupported&&!directory.error&&!directory.stale;$('#wl-directory-error').textContent=!wlData?'Verifica configurazione radio…':!wlData.radioSupported?'Sync radio non configurato: verifica modem e controllo CAT.':directory.stale?'Elenco non aggiornato: aggiorna prima di collegarti.':directory.error||'';}updateSession();};
document.addEventListener('bpq-languagechange',()=>{if(directory)render();});
document.addEventListener('station-ready',()=>{directory=null;selectedId=null;session=null;gatewayPanel.hidden=true;expanded=false;toggle.setAttribute('aria-expanded','false');toggle.hidden=!station.features.radio;});
})();
+28 -10
View File
@@ -1,17 +1,35 @@
let wlData=null,wlFolder='inbox',wlSelected=null,wlLoading=false,wlGeneration=0,wlCompose=false; let wlData=null,wlFolder='inbox',wlSelected=null,wlLoadTask=null,wlRefreshVersion=0,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">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 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(fresh=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)))} if(!csrf)return;if(fresh)wlRefreshVersion++;
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>`}} if(wlLoadTask){if(!fresh)return wlLoadTask;await wlLoadTask;return wlLoad();}
$$('[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; const version=wlRefreshVersion,call=station.call;
const task=(async()=>{try{const data=await api('/winlink',{busy:fresh||!wlData});if(version!==wlRefreshVersion||!csrf||station.call!==call)return;data.messages=data.messages.filter(m=>!deletedMessageIds.has(m.id));wlData=data;$('#wl-sync-state').textContent=data.sync.text;$('#wl-sync-state').className='wl-state '+data.sync.state;$('#wl-sync-time').textContent=data.sync.at?logTime(data.sync.at)+' · '+mailTimezone():'';wlRender();}catch(e){if(version===wlRefreshVersion)$('#wl-sync-state').textContent=e.message;}})();
wlLoadTask=task;try{await task;}finally{if(wlLoadTask===task)wlLoadTask=null;}
}
function wlRender(){$$('[data-wlfolder]').forEach(button=>{const active=button.dataset.wlfolder===wlFolder;button.classList.toggle('active',active);button.setAttribute('aria-pressed',String(active));});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.read?'Letto':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>`;markMessageRead(id).catch(error=>toast(error.message));$('#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;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='Nominativo oppure indirizzo email';}); const baseOpenCompose=openCompose;openCompose=function(data={}){window.bpqComposeAttachments?.reset();baseOpenCompose(data);};
$('#wl-compose').onclick=()=>wlNew();$('#compose').addEventListener('close',()=>{wlCompose=false;window.bpqComposeAttachments?.reset();$('#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 window.bpqSync.start({kind:'winlink-internet'});$('#wl-sync-state').textContent='Sincronizzazione richiesta…';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);
const deleteDialog=document.createElement('dialog');deleteDialog.innerHTML='<h2>Eliminare il messaggio?</h2><p id="delete-subject" class="delete-subject"></p><p class="delete-note">Verrà rimosso dalla BBS locale di BPQ. Una email già inviata non può essere richiamata.</p><footer><button id="delete-cancel" class="secondary">Annulla</button><button id="delete-confirm" class="danger">Elimina messaggio</button></footer>';document.body.append(deleteDialog);let deleteId=null; const deleteDialog=document.createElement('dialog');deleteDialog.innerHTML='<h2>Eliminare il messaggio?</h2><p id="delete-subject" class="delete-subject"></p><p class="delete-note">Verrà rimosso dalla BBS locale di BPQ. Una email già inviata non può essere richiamata.</p><p id="delete-error" class="error" role="alert" hidden></p><footer><button id="delete-cancel" class="secondary">Annulla</button><button id="delete-confirm" class="danger">Elimina messaggio</button></footer>';document.body.append(deleteDialog);let deleteId=null,deleting=false;
function askDelete(id,subject){deleteId=id;$('#delete-subject').textContent='#'+id+' · '+subject;deleteDialog.showModal()} function askDelete(id,subject){if(deleting)return;deleteId=id;$('#delete-error').hidden=true;$('#delete-error').textContent='';$('#delete-subject').textContent='#'+id+' · '+subject;deleteDialog.showModal()}
$('#delete-cancel').onclick=()=>deleteDialog.close();$('#delete-confirm').onclick=async()=>{const b=$('#delete-confirm');b.disabled=true;try{await api('/messages/'+deleteId+'/delete',{method:'POST',body:'{}'});deleteDialog.close();if(selected===deleteId){selected=null;$('#reader').innerHTML='<div class="reader-empty"><h2>Messaggio eliminato</h2></div>'}if(wlSelected===deleteId){wlSelected=null;wlGeneration++;$('#wl-reader').innerHTML='<div class="reader-empty"><h2>Email eliminata</h2></div>'}await loadMessages();await wlLoad();loadDashboard();toast('Messaggio #'+deleteId+' eliminato da BPQ');}catch(e){toast(e.message)}finally{b.disabled=false}}; $('#delete-cancel').onclick=()=>{if(!deleting)deleteDialog.close();};deleteDialog.addEventListener('cancel',e=>{if(deleting)e.preventDefault();});
$('#delete-confirm').onclick=async()=>{
if(deleting||!deleteId)return;const id=deleteId,b=$('#delete-confirm');deleting=true;b.disabled=true;b.textContent='Eliminazione…';$('#delete-cancel').disabled=true;$('#delete-error').hidden=true;
try{await api('/messages/'+id+'/delete',{method:'POST',body:'{}',signal:AbortSignal.timeout(30000)});
deletedMessageIds.add(id);allMessages=allMessages.filter(m=>m.id!==id);if(wlData)wlData.messages=wlData.messages.filter(m=>m.id!==id);wlRefreshVersion++;
deleteDialog.close();if(selected===id){selected=null;loadGeneration++;$('#reader').innerHTML='<div class="reader-empty"><h2>Messaggio eliminato</h2></div>';}if(wlSelected===id){wlSelected=null;wlGeneration++;$('#wl-reader').innerHTML='<div class="reader-empty"><h2>Email eliminata</h2></div>';}
renderMessages();wlRender();toast('Messaggio #'+id+' eliminato da BPQ');loadMessages();wlLoad(true);loadDashboard();
}catch(e){$('#delete-error').hidden=false;$('#delete-error').textContent=e.name==='TimeoutError'?'BPQ non ha risposto in tempo. Aggiorna l’elenco prima di riprovare.':e.message;}
finally{deleting=false;b.disabled=false;b.textContent='Elimina messaggio';$('#delete-cancel').disabled=false;}
};
const wlOldRead=readMessage;readMessage=async function(id){await wlOldRead(id);if(selected!==id)return;const footer=$('#reader .reader-footer');if(!footer)return;const b=document.createElement('button');b.className='danger';b.textContent='Elimina';b.onclick=()=>askDelete(id,allMessages.find(m=>m.id===id)?.subject||'Messaggio');footer.append(b);}; const wlOldRead=readMessage;readMessage=async function(id){await wlOldRead(id);if(selected!==id)return;const footer=$('#reader .reader-footer');if(!footer)return;const b=document.createElement('button');b.className='danger';b.textContent='Elimina';b.onclick=()=>askDelete(id,allMessages.find(m=>m.id===id)?.subject||'Messaggio');footer.append(b);};
+1
View File
@@ -0,0 +1 @@
{"type":"FeatureCollection","name":"ne_110m_land","crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:OGC:1.3:CRS84"}},"features":[{"type":"Feature","properties":{"featurecla":"Land","scalerank":1,"min_zoom":1},"bbox":[-66.290031,-81.000327,-59.572095,-79.628679],"geometry":{"type":"Polygon","coordinates":[[[-59.572095,-80.040179],[-59.865849,-80.549657],[-60.159656,-81.000327],[-62.255393,-80.863178],[-64.488125,-80.921934],[-65.741666,-80.588827],[-65.741666,-80.549657],[-66.290031,-80.255773],[-64.037688,-80.294944],[-61.883246,-80.39287],[-61.138976,-79.981371],[-60.610119,-79.628679],[-59.572095,-80.040179]]]}},{"type":"Feature","properties":{"featurecla":"Land","scalerank":1,"min_zoom":1},"bbox":[-163.712896,-79.634209,-159.208184,-78.223338],"geometry":{"type":"Polygon","coordinates":[[[-159.208184,-79.497059],[-161.127601,-79.634209],[-162.439847,-79.281465],[-163.027408,-78.928774],[-163.066604,-78.869966],[-163.712896,-78.595667],[-163.712896,-78.595667],[-163.105801,-78.223338],[-161.245113,-78.380176],[-160.246208,-78.693645],[-159.482405,-79.046338],[-159.208184,-79.497059]]]}},{"type":"Feature","properties":{"featurecla":"Land","scalerank":1,"min_zoom":0},"bbox":[-54.164259,-81.025442,-43.333267,-77.831476],"geometry":{"type":"Polygon","coordinates":[[[-45.154758,-78.04707],[-43.920828,-78.478103],[-43.48995,-79.08556],[-43.372438,-79.516645],[-43.333267,-80.026123],[-44.880537,-80.339644],[-46.506174,-80.594357],[-48.386421,-80.829485],[-50.482107,-81.025442],[-52.851988,-80.966685],[-54.164259,-80.633528],[-53.987991,-80.222028],[-51.853134,-79.94773],[-50.991326,-79.614623],[-50.364595,-79.183487],[-49.914131,-78.811209],[-49.306959,-78.458569],[-48.660616,-78.047018],[-48.660616,-78.047019],[-48.151396,-78.04707],[-46.662857,-77.831476],[-45.154758,-78.04707]]]}},{"type":"Feature","properties":{"featurecla":"Land","scalerank":1,"min_zoom":1},"bbox":[-122.621735,-74.08881,-118.724143,-73.324619],"geometry":{"type":"Polygon","coordinates":[[[-121.211511,-73.50099],[-119.918851,-73.657725],[-118.724143,-73.481353],[-119.292119,-73.834097],[-120.232217,-74.08881],[-121.62283,-74.010468],[-122.621735,-73.657778],[-122.621735,-73.657777],[-122.406245,-73.324619],[-121.211511,-73.50099]]]}},{"type":"Feature","properties":{"featurecla":"Land","scalerank":1,"min_zoom":1},"bbox":[-127.28313,-73.873268,-124.031882,-73.246226],"geometry":{"type":"Polygon","coordinates":[[[-125.559566,-73.481353],[-124.031882,-73.873268],[-124.619469,-73.834097],[-125.912181,-73.736118],[-127.28313,-73.461769],[-127.28313,-73.461768],[-126.558472,-73.246226],[-125.559566,-73.481353]]]}},{"type":"Feature","properties":{"featurecla":"Land","scalerank":1,"min_zoom":1},"bbox":[-102.330725,-72.521205,-96.20035,-71.717792],"geometry":{"type":"Polygon","coordinates":[[[-98.98155,-71.933334],[-97.884743,-72.070535],[-96.787937,-71.952971],[-96.20035,-72.521205],[-96.983765,-72.442864],[-98.198083,-72.482035],[-99.432013,-72.442864],[-100.783455,-72.50162],[-101.801868,-72.305663],[-102.330725,-71.894164],[-102.330725,-71.894164],[-101.703967,-71.717792],[-100.430919,-71.854993],[-98.98155,-71.933334]]]}},{"type":"Feature","properties":{"featurecla":"Land","scalerank":1,"min_zoom":1},"bbox":[-75.012625,-72.503842,-68.333834,-68.87874],"geometry":{"type":"Polygon","coordinates":[[[-68.451346,-70.955823],[-68.333834,-71.406493],[-68.510128,-71.798407],[-68.784297,-72.170736],[-69.959471,-72.307885],[-71.075889,-72.503842],[-72.388134,-72.484257],[-71.8985,-72.092343],[-73.073622,-72.229492],[-74.19004,-72.366693],[-74.953895,-72.072757],[-75.012625,-71.661258],[-73.915819,-71.269345],[-73.915819,-71.269344],[-73.230331,-71.15178],[-72.074717,-71.190951],[-71.780962,-70.681473],[-71.72218,-70.309196],[-71.741791,-69.505782],[-71.173815,-69.035475],[-70.253252,-68.87874],[-69.724447,-69.251017],[-69.489422,-69.623346],[-69.058518,-70.074016],[-68.725541,-70.505153],[-68.451346,-70.955823]]]}},{"type":"Feature","properties":{"featurecla":"Land","scalerank":0,"min_zoom":0},"bbox":[-180,-90,180,-63.27066],"geometry":{"type":"Polygon","coordinates":[[[-58.614143,-64.152467],[-59.045073,-64.36801],[-59.789342,-64.211223],[-60.611928,-64.309202],[-61.297416,-64.54433],[-62.0221,-64.799094],[-62.51176,-65.09303],[-62.648858,-65.484942],[-62.590128,-65.857219],[-62.120079,-66.190326],[-62.805567,-66.425505],[-63.74569,-66.503847],[-64.294106,-66.837004],[-64.881693,-67.150474],[-65.508425,-67.58161],[-65.665082,-67.953887],[-65.312545,-68.365335],[-64.783715,-68.678908],[-63.961103,-68.913984],[-63.1973,-69.227556],[-62.785955,-69.619419],[-62.570516,-69.991747],[-62.276736,-70.383661],[-61.806661,-70.716768],[-61.512906,-71.089045],[-61.375809,-72.010074],[-61.081977,-72.382351],[-61.003661,-72.774265],[-60.690269,-73.166179],[-60.827367,-73.695242],[-61.375809,-74.106742],[-61.96337,-74.439848],[-63.295201,-74.576997],[-63.74569,-74.92974],[-64.352836,-75.262847],[-65.860987,-75.635124],[-67.192818,-75.79191],[-68.446282,-76.0074Line truncated
+13
View File
@@ -0,0 +1,13 @@
import {readFile,writeFile,rename} from 'node:fs/promises';
import path from 'node:path';import {randomUUID} from 'node:crypto';
export function scanChannels(text,rig=1){
const lines=text.split(/\r?\n/);let inside=false;const out=[];
for(let i=0;i<lines.length;i++){if(new RegExp('^\\s*RADIO\\s+'+rig+'\\s*$','i').test(lines[i])){inside=true;continue;}if(inside&&/^\s*\*{4}/.test(lines[i]))break;if(!inside)continue;const m=lines[i].match(/^\s*(; CONSOLE-OFF )?(\d+(?:\.\d+)?),([\d.]+),([A-Z0-9-]+)(.*)$/i);if(m){const hz=Math.round(Number(m[3])*1e6);out.push({id:hz+'-'+m[4].toUpperCase(),frequencyMHz:hz/1e6,mode:m[4].toUpperCase(),dwellSeconds:Number(m[2]),enabled:!m[1],line:i,entry:m[2]+','+m[3]+','+m[4]+m[5]});}}
return out;
}
export function scanConfig(text,rig,enabled){const rows=scanChannels(text,rig),ids=new Set(rows.map(r=>r.id));if(!Array.isArray(enabled)||!enabled.length||enabled.some(id=>!ids.has(id))||new Set(enabled).size!==enabled.length)throw Error('Seleziona almeno una frequenza configurata');const lines=text.split(/\r?\n/);for(const row of rows)lines[row.line]=' '+(enabled.includes(row.id)?'':'; CONSOLE-OFF ')+row.entry;return lines.join(text.includes('\r\n')?'\r\n':'\n');}
export class RadioControl{
constructor(config){this.config=config;this.options=config.radioControl;this.request=null;}
async snapshot(){const rows=scanChannels(await readFile(path.join(this.config.root,'BPQ32.cfg'),'utf8'),this.options?.rig||1);let state=null;try{state=JSON.parse(await readFile(this.options.statusFile,'utf8'));}catch{}try{this.request=JSON.parse(await readFile(this.options.requestFile,'utf8'));}catch{}this.blocked=Boolean(this.request&&state?.appliedRevision!==this.request.revision);this.txSuspended=Boolean(this.request?.txSuspended||state?.txSuspended);const ready=Boolean(this.options&&state&&Date.now()-Date.parse(state.at)<6000);return {supported:ready,appliedPortRevision:state?.appliedPortRevision,channels:rows.map(({entry,line,...r})=>({...r,enabled:this.request?this.request.enabled.includes(r.id):r.enabled,current:state&&Math.abs(Number(state.frequency)-r.frequencyMHz)<0.0001})),txSuspended:this.txSuspended,pending:Boolean(this.request&&state?.appliedRevision!==this.request.revision),error:state?.error||null,at:state?.at||null};}
async update(data){const current=await this.snapshot();if(!current.supported)throw Error('Controller radio non disponibile');if(typeof data.txSuspended!=='boolean')throw Error('Stato TX non valido');const text=await readFile(path.join(this.config.root,'BPQ32.cfg'),'utf8');scanConfig(text,this.options.rig||1,data.enabled);this.request={revision:randomUUID(),enabled:data.enabled,txSuspended:data.txSuspended};await writeFile(this.options.requestFile+'.tmp',JSON.stringify(this.request));await rename(this.options.requestFile+'.tmp',this.options.requestFile);return this.snapshot();}
}
+4
View File
@@ -0,0 +1,4 @@
import {test} from 'node:test';import assert from 'node:assert/strict';import {mkdtemp,readFile,writeFile,rm} from 'node:fs/promises';import path from 'node:path';import os from 'node:os';import {scanChannels,scanConfig,RadioControl} from './radio-control.mjs';
const fixture='NODECALL=N0TEST-7\r\nRADIO 1\r\n COM1 38400 YAESU FT991A\r\n 15,7.050,USB,VW\r\n 15,14.122,USB,VW\r\n 15,144.950,DATA-FM,V0\r\n****\r\nPORT\r\n PORTNUM=1\r\nENDPORT\r\n';
test('scan selection preserves native settings, reversibly comments channels and rejects invalid or empty lists',()=>{const rows=scanChannels(fixture),ids=rows.map(r=>r.id);assert.equal(rows.length,3);const changed=scanConfig(fixture,1,[ids[0],ids[2]]);assert.ok(changed.includes('; CONSOLE-OFF 15,14.122,USB,VW'));assert.equal(scanChannels(changed)[1].enabled,false);assert.equal(scanConfig(changed,1,ids),fixture);assert.throws(()=>scanConfig(fixture,1,[]));assert.throws(()=>scanConfig(fixture,1,['999-USB']));assert.ok(changed.endsWith('PORTNUM=1\r\nENDPORT\r\n'));});
test('radio controls require a live adapter, validate changes, and distinguish request from acknowledgement',async()=>{const dir=await mkdtemp(path.join(os.tmpdir(),'radio-control-')),requestFile=path.join(dir,'request.json'),statusFile=path.join(dir,'status.json');const config={root:dir,radioControl:{rig:1,requestFile,statusFile}};await writeFile(path.join(dir,'BPQ32.cfg'),fixture);const c=new RadioControl(config);try{assert.equal((await c.snapshot()).supported,false);await assert.rejects(c.update({enabled:['7050000-USB'],txSuspended:true}),/non disponibile/);await writeFile(statusFile,JSON.stringify({at:new Date().toISOString(),appliedRevision:null,txSuspended:false}));await assert.rejects(c.update({enabled:[],txSuspended:false}));const state=await c.update({enabled:['7050000-USB'],txSuspended:true});assert.equal(state.pending,true);assert.equal(state.txSuspended,true);assert.equal((await readFile(path.join(dir,'BPQ32.cfg'),'utf8')),fixture);const r=JSON.parse(await readFile(requestFile));await writeFile(statusFile,JSON.stringify({at:new Date().toISOString(),appliedRevision:r.revision,txSuspended:true,frequency:'7.050'}));const done=await c.snapshot();assert.equal(done.pending,false);assert.equal(done.channels[0].current,true);}finally{await rm(dir,{recursive:true,force:true});}});
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff. Show more