v0.1.10
build / test (push) Waiting to run

This commit is contained in:
Mateusz Gruszczyński committed 2026-11-16 22:48:34 +01:00
1 parent 052a27bc48
commit 528017b0e6
36 files changed
+3394 -216

No files matched your search

Generated
+11 -1
View File
@@ -312,6 +312,15 @@ dependencies = [
"strsim",
]
[[package]]
name = "clap_complete"
version = "4.6.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "037e2a1a92236d0aff7e845093f64661d6df4c02c9fcc61a60e9e1d736fa392f"
dependencies = [
"clap",
]
[[package]]
name = "clap_derive"
version = "4.6.7"
@@ -1885,7 +1894,7 @@ checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
[[package]]
name = "simply-dvb"
version = "0.1.5"
version = "0.1.10"
dependencies = [
"anyhow",
"argon2",
@@ -1894,6 +1903,7 @@ dependencies = [
"bytes",
"chrono",
"clap",
"clap_complete",
"encoding_rs",
"flate2",
"futures-util",
+3 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "simply-dvb"
version = "0.1.5"
version = "0.1.10"
edition = "2021"
rust-version = "1.85"
description = "simply-dvb - lightweight DVB-T/T2/C server: scanning, HLS, M3U, EPG/XMLTV, recording and a web panel"
@@ -48,7 +48,8 @@ tokio-util = { version = "0.7", features = ["io"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt", "registry"] }
unicode-normalization = "0.1"
sysinfo = { version = "0.36.1", default-features = false, features = ["system", "network", "component"] }
sysinfo = { version = "0.36.1", default-features = false, features = ["system", "component"] }
clap_complete = "4.6.11"
[build-dependencies]
serde_json = "1.0"
+32 -4
View File
@@ -26,7 +26,7 @@ Tested with **Silicon Labs Si2168** (DVB-T/T2/C) cards + Si2157 tuner.
| Area | What you get |
|---|---|
| Tuners | Native Linux DVB API v5 (ioctl, no `dvbv5-zap`/`w_scan`), multiple adapters, signal strength (dBm/%), SNR (dB), error counter, one multiplex shared by many clients, priorities (recordings > watching > background EPG), virtual adapter from `.ts` files |
| Tuners | Native Linux DVB API v5 (ioctl, no `dvbv5-zap`/`w_scan`), multiple adapters, signal strength (dBm/%), SNR (dB), error counter, one multiplex shared by many clients, **kernel PID filtering** (only the PIDs clients need plus EPG/SI tables are read – far less CPU than reading the whole multiplex; can be switched off in Settings), priorities (recordings > watching > background EPG), virtual adapter from `.ts` files |
| Scanning | DVB-T, DVB-T2 (PLP), DVB-C (symbol rate, QAM). Lists: Europe UHF 21–48 (after the 700 MHz refarming) and 21–69, VHF III + UHF, Italy, Australia (7 MHz), New Zealand, cable 114–858 MHz, custom list, rescan of saved muxes. **NIT discovery** (muxes announced by the network are queued automatically), LCN, automatic channel creation, **background scan** of saved muxes on an idle adapter (every 24 h by default; it gives way immediately when someone starts watching or recording); DVB text in every character table (ISO 6937, ISO 8859-1…16, UTF-8, UCS-2, GB2312, Big5) |
| Channels | Drag-and-drop ordering, numbering, groups, enable/disable, icons (automatic lookup in logo repositories in the background, upload, URL), manual service binding; filters (type, group, enabled, hide scrambled/broken, without icon/EPG) with bulk enable/disable/delete of the filtered list |
| Streams | Live HLS (segmented on keyframes, H.264/HEVC/MPEG-2), continuous MPEG-TS (starting at a keyframe), ffmpeg profiles: `pass` (original), `aac` (audio → AAC), `h264` (HEVC/MPEG-2 → H.264 720p) |
@@ -38,10 +38,11 @@ Tested with **Silicon Labs Si2168** (DVB-T/T2/C) cards + Si2157 tuner.
| Security | Panel login (argon2, HttpOnly sessions, CSRF protection, rate limit), *administrator* / *viewer* roles, ACL: networks with token-free stream access, networks allowed to reach the panel, access tokens (optionally limited to networks), trusted reverse proxies. ACL entries may be networks, addresses or **DDNS host names** (for a dynamic public IP; re-resolved every minute) |
| Recording | From the EPG (with padding) or manual; **series rules** (title fragment or regex, optional channel – like tvheadend's autorec) with a preview of matching programmes; `.ts` file + index, in-browser playback (HLS VOD with byte ranges), download, resume after restart; automatic cleanup (age, minimum free space); **schedule** view per day with **tuner-conflict detection** |
| Player | Keyboard shortcuts: ↑/↓ channel, digits – channel number, F – fullscreen, P – picture-in-picture, M – mute, space – pause, ? – help; OSD with channel number and name |
| Monitoring | Live charts on the overview (15 min history): CPU (system and process), memory, process RSS, streaming throughput, network, clients/HLS sessions, temperature, load; per tuner: mux bitrate, signal strength (%/dBm), SNR, uncorrected blocks. `/metrics` in Prometheus format. Active clients with protocol, device (from the User-Agent / HTSP client name), address, access, duration and rate |
| Monitoring | Live charts on the overview (15 min history): CPU (system and process), memory, process RSS, streaming throughput, **application traffic** per protocol (MPEG-TS, HLS, HTSP) and from the tuners, clients/HLS sessions, temperature, load; per tuner: mux bitrate, signal strength (%/dBm), SNR, uncorrected blocks, **BER**, **stream errors (CC/TEI)**, lock stages (signal/carrier/FEC/sync/lock), transmission parameters, PIDs/stuffing and **hardware details** (bus, driver, product, USB speed, frequency range, capabilities). **Antenna meter** (*Tuners → Antenna meter*): big live strength/SNR readout with a quality verdict and optional beeps for aligning the antenna from a phone. `/metrics` in Prometheus format. Active clients with protocol, device, address, access, duration and rate |
| Statistics | Viewing history: watch time, most watched channels, viewers, devices, protocols, time of day and per day (24 h / 7 / 30 days / year) |
| Logs | *Logs* page with categories (application, tuners & devices, streaming, access, EPG, recording, system), level filter, search, live follow and download; logins, denied requests, tokens and HTSP sessions are logged under *access* |
| Backup | Configuration export/import (muxes, services, channels, rules, tokens, settings) as JSON |
| Interface | English by default, Polish included, **any number of languages** (`langs/<locale>.json` files, picker in the top bar); playback in the browser or **VLC** (single-channel playlist); themes: dark (default), midnight (OLED), light, system; 7 accent colours, density, scale, pinned sidebar, start page, default player profile, EPG grid zoom, clock, logos/programme progress, animations – stored in the browser (*Settings → Appearance*) |
| Backup | Configuration export/import (muxes, services, channels, rules, tokens, settings) as JSON; full database copy from the panel or `simply-dvb db backup` |
| Interface | English by default, Polish included, **any number of languages** (`langs/<locale>.json` files, picker in the top bar); playback in the browser or **VLC** (single-channel playlist); themes: dark (default), midnight (OLED), light, system; 7 accent colours, density, scale, pinned sidebar, start page, default player profile, EPG grid zoom, clock, logos/programme progress, animations – stored in the **user profile** (follow you to every device). **Favourite channels** (★, own filter and M3U), **programme reminders** (notification 2 min before the start), signed-in devices with remote sign-out, mobile layout with a bottom tab bar, installable as an app (PWA, HTTPS) |
| Distribution | `.deb` package with a (hardened) systemd service, Docker image, `compose.yml` |
## Quick start
@@ -268,6 +269,33 @@ The interface, server messages and logs are in English; translations are JSON fi
* Signal strength is reported by the Si2157 tuner in dBm, SNR by the Si2168 in dB.
* DVB-T2 with multiple PLPs: set the PLP when adding a mux manually.
## Command line tools
Run them on the server (as root or `sudo -u simply-dvb`; files created as root get the data
directory's owner). They work directly on the database, also when the panel is unreachable, and a
running server applies changed settings within a few seconds.
```sh
simply-dvb user reset-admin # forgotten password: new random password for the administrator
simply-dvb user passwd <login> [--generate] # change a password (signs the user out everywhere)
simply-dvb user list | add <login> [--role viewer] [--generate] | role <login> admin|viewer | logout <login> | delete <login>
simply-dvb access show # who may reach the panel / streams without a token
simply-dvb access reset-panel # locked out by the panel network limit? allow everywhere again
simply-dvb access open-add myhome.ddns.net # token-free streams for a network/address/DDNS name
simply-dvb token add tv --allow myhome.ddns.net --base-url http://192.168.1.10:9981 # prints ready URLs
simply-dvb token list | enable <name> | disable <name> | delete <name>
simply-dvb settings show [key] | set <key> <value> | unset <key>
simply-dvb channels list [--all] | m3u [--base-url …] [--token …] | enable 1 2 3 | disable 4
simply-dvb db backup [file] | check | vacuum | restore <file> # restore: stop the service first
simply-dvb status # version, server state, counts, next recording, adapters
simply-dvb doctor # health check: data dir, database, adapters/permissions, disk, ffmpeg
simply-dvb adapters | tune --freq 634 # tuner diagnostics
simply-dvb completions bash > /etc/bash_completion.d/simply-dvb # tab completion (bash/zsh/fish)
```
Personal panel preferences (language, theme, accent, filters) are stored in the user's profile and
follow the account to every browser and phone.
## Architecture
```
+32 -4
View File
@@ -26,7 +26,7 @@ Testowany z kartami na **Silicon Labs Si2168** (DVB-T/T2/C) + tuner Si2157.
| Obszar | Co jest |
|---|---|
| Tunery | Natywne Linux DVB API v5 (ioctl, bez `dvbv5-zap`/`w_scan`), wiele adapterów, siła sygnału (dBm/%), SNR (dB), licznik błędów, współdzielenie multipleksu przez wielu klientów, priorytety (nagrania > oglądanie > EPG w tle), adapter wirtualny z plików `.ts` |
| Tunery | Natywne Linux DVB API v5 (ioctl, bez `dvbv5-zap`/`w_scan`), wiele adapterów, siła sygnału (dBm/%), SNR (dB), licznik błędów, współdzielenie multipleksu przez wielu klientów, **filtrowanie PID w jądrze** (czytane są tylko PID-y potrzebne klientom oraz tabele EPG/SI – dużo mniej CPU niż cały multipleks; można wyłączyć w Ustawieniach), priorytety (nagrania > oglądanie > EPG w tle), adapter wirtualny z plików `.ts` |
| Skanowanie | DVB-T, DVB-T2 (PLP), DVB-C (symbol rate, QAM). Listy: Europa UHF 21–48 (po refarmingu 700 MHz) i 21–69, VHF III + UHF, Włochy, Australia (7 MHz), Nowa Zelandia, kablówka 114–858 MHz, własna lista, ponowne skanowanie zapisanych. **Odkrywanie przez NIT** (multipleksy ogłaszane przez sieć dopisywane do kolejki), LCN, automatyczne tworzenie kanałów, **skanowanie w tle** zapisanych multipleksów na wolnym adapterze (domyślnie co 24 h; ustępuje od razu, gdy ktoś zaczyna oglądać lub nagrywać); teksty DVB we wszystkich tablicach znaków (ISO 6937, ISO 8859-1…16, UTF-8, UCS-2, GB2312, Big5) |
| Kanały | Lista z przeciąganiem (kolejność), numeracja, grupy, włącz/wyłącz, ikony (automatyczne wyszukiwanie w tle, wgrywanie, URL), ręczne powiązanie z usługą; filtry (typ, grupa, włączone, ukryj kodowane/uszkodzone, bez ikony/EPG) i zbiorcze włącz/wyłącz/usuń przefiltrowanej listy |
| Strumienie | HLS live (segmentacja na klatkach kluczowych, H.264/HEVC/MPEG-2), ciągły MPEG-TS (start od klatki kluczowej), profile ffmpeg: `pass` (oryginał), `aac` (audio → AAC), `h264` (HEVC/MPEG-2 → H.264 720p) |
@@ -39,9 +39,10 @@ Testowany z kartami na **Silicon Labs Si2168** (DVB-T/T2/C) + tuner Si2157.
| Nagrywanie | Z EPG (z marginesami) lub ręcznie; **reguły seryjne** (fragment tytułu lub regex, opcjonalnie kanał – jak autorec w tvheadend) z podglądem pasujących audycji; plik `.ts` + indeks, odtwarzanie w przeglądarce (HLS VOD z byte-range), pobieranie, wznowienie po restarcie; automatyczne porządkowanie (wiek, minimalne wolne miejsce) |
| Odtwarzacz | Skróty klawiszowe: ↑/↓ zmiana kanału, cyfry – numer kanału, F – pełny ekran, P – obraz w obrazie, M – wycisz, spacja – pauza, ? – pomoc; OSD z numerem i nazwą kanału |
| Logi | Zakładka *Logi* z kategoriami (aplikacja, tunery i urządzenia, strumieniowanie, dostęp, EPG, nagrywanie, system), filtrem poziomu, wyszukiwaniem, śledzeniem na żywo i pobieraniem; logowania, odrzucone żądania, tokeny i sesje HTSP trafiają do kategorii *dostęp*. Aktywni klienci: protokół, urządzenie (z User-Agent / nazwy klienta HTSP), adres, dostęp, czas, przepływność; harmonogram nagrań z wykrywaniem konfliktów tunerów |
| Monitoring | Wykresy na żywo w przeglądzie (historia 15 min): CPU (system i proces), pamięć, RSS procesu, przepustowość strumieni, sieć, klienci/sesje HLS, temperatura, obciążenie; dla tunera: przepływność, siła sygnału (%/dBm), SNR, bloki z błędami. `/metrics` w formacie Prometheus |
| Kopia zapasowa | Eksport/import konfiguracji (multipleksy, usługi, kanały, reguły, tokeny, ustawienia) jako JSON |
| Interfejs | Angielski (domyślnie) i polski, **dowolna liczba języków** (pliki `langs/<locale>.json` – każdy plik pojawia się po zbudowaniu w liście wyboru języka); odtwarzanie w przeglądarce lub **VLC** (playlista jednego kanału); motywy: ciemny (domyślny), północ (OLED), jasny, systemowy; 7 kolorów akcentu, gęstość, skala, przypięty pasek boczny, strona startowa, domyślny profil odtwarzacza, powiększenie siatki EPG, zegar, logotypy/postęp audycji, animacje – zapisywane w przeglądarce (*Ustawienia → Wygląd*) |
| Monitoring | Wykresy na żywo w przeglądzie (historia 15 min): CPU (system i proces), pamięć, RSS procesu, przepustowość strumieni, **ruch aplikacji** wg protokołu (MPEG-TS, HLS, HTSP) i z tunerów, klienci/sesje HLS, temperatura, obciążenie; dla tunera: przepływność, siła sygnału (%/dBm), SNR, bloki z błędami, **BER**, **błędy strumienia (CC/TEI)**, etapy synchronizacji (sygnał/nośna/FEC/sync/lock), parametry transmisji, PID-y/wypełnienie i **dane sprzętu** (magistrala, sterownik, produkt, prędkość USB, zakres częstotliwości, możliwości). **Miernik anteny** (*Tunery → Miernik anteny*): duży odczyt siły/SNR na żywo z oceną jakości i opcjonalnym dźwiękiem – do ustawiania anteny z telefonem w ręku. `/metrics` w formacie Prometheus |
| Statystyki | Historia oglądania: czas oglądania, najczęściej oglądane kanały, widzowie, urządzenia, protokoły, pora dnia i dni (24 h / 7 / 30 dni / rok) |
| Kopia zapasowa | Eksport/import konfiguracji (multipleksy, usługi, kanały, reguły, tokeny, ustawienia) jako JSON; pełna kopia bazy z panelu lub `simply-dvb db backup` |
| Interfejs | Angielski (domyślnie) i polski, **dowolna liczba języków** (pliki `langs/<locale>.json` – każdy plik pojawia się po zbudowaniu w liście wyboru języka); odtwarzanie w przeglądarce lub **VLC** (playlista jednego kanału); motywy: ciemny (domyślny), północ (OLED), jasny, systemowy; 7 kolorów akcentu, gęstość, skala, przypięty pasek boczny, strona startowa, domyślny profil odtwarzacza, powiększenie siatki EPG, zegar, logotypy/postęp audycji, animacje – zapisywane w **profilu użytkownika** (działają na każdym urządzeniu). **Ulubione kanały** (★, własny filtr i M3U), **przypomnienia o audycjach** (powiadomienie 2 min przed startem), lista zalogowanych urządzeń z wylogowaniem zdalnym, widok na telefon z dolnym paskiem, instalacja jako aplikacja (PWA, HTTPS) |
| Dystrybucja | Paczka `.deb` z usługą systemd (utwardzoną), obraz Docker, `compose.yml` |
## Szybki start
@@ -264,6 +265,33 @@ Interfejs, komunikaty serwera i logi są po angielsku; tłumaczenia to pliki JSO
* Siła sygnału jest raportowana przez tuner Si2157 w dBm, SNR przez Si2168 w dB.
* DVB-T2 z wieloma PLP: PLP ustawisz przy ręcznym dodawaniu multipleksu.
## Narzędzia wiersza poleceń
Uruchamiaj je na serwerze (jako root lub `sudo -u simply-dvb`; pliki tworzone jako root dostają
właściciela katalogu danych). Działają bezpośrednio na bazie, także gdy panel jest niedostępny, a
działający serwer stosuje zmienione ustawienia w ciągu kilku sekund.
```sh
simply-dvb user reset-admin # zapomniane hasło: nowe losowe hasło administratora
simply-dvb user passwd <login> [--generate] # zmiana hasła (wylogowuje użytkownika wszędzie)
simply-dvb user list | add <login> [--role viewer] [--generate] | role <login> admin|viewer | logout <login> | delete <login>
simply-dvb access show # kto ma dostęp do panelu / strumieni bez tokenu
simply-dvb access reset-panel # zablokowany przez ograniczenie sieci panelu? dostęp zewsząd
simply-dvb access open-add mojdom.ddns.net # strumienie bez tokenu dla sieci/adresu/nazwy DDNS
simply-dvb token add tv --allow mojdom.ddns.net --base-url http://192.168.1.10:9981 # wypisuje gotowe adresy
simply-dvb token list | enable <nazwa> | disable <nazwa> | delete <nazwa>
simply-dvb settings show [klucz] | set <klucz> <wartość> | unset <klucz>
simply-dvb channels list [--all] | m3u [--base-url …] [--token …] | enable 1 2 3 | disable 4
simply-dvb db backup [plik] | check | vacuum | restore <plik> # restore: najpierw zatrzymaj usługę
simply-dvb status # wersja, stan serwera, liczniki, najbliższe nagranie, adaptery
simply-dvb doctor # diagnostyka: katalog danych, baza, adaptery/uprawnienia, dysk, ffmpeg
simply-dvb adapters | tune --freq 634 # diagnostyka tunera
simply-dvb completions bash > /etc/bash_completion.d/simply-dvb # podpowiedzi Tab (bash/zsh/fish)
```
Osobiste ustawienia panelu (język, motyw, kolor, filtry) są zapisywane w profilu użytkownika i działają
w każdej przeglądarce i na telefonie.
## Architektura
```
+105 -19
View File
@@ -62,7 +62,6 @@
"Arts & culture": "Arts & culture",
"Arts / Culture": "Arts / Culture",
"Assign numbers 1..n in the current order?": "Assign numbers 1..n in the current order?",
"Audio → AAC": "Audio → AAC",
"Australia – VHF 6–12 + UHF 28–51 (7 MHz)": "Australia – VHF 6–12 + UHF 28–51 (7 MHz)",
"automatic": "automatic",
"Automatic": "Automatic",
@@ -73,7 +72,6 @@
"background scan stopped – the adapter is needed": "background scan stopped – the adapter is needed",
"Background scan: create channels for new services": "Background scan: create channels for new services",
"Background scan: follow the NIT to new muxes": "Background scan: follow the NIT to new muxes",
"Background scanning is off (Settings → Scanning).": "Background scanning is off (Settings → Scanning).",
"Backup": "Backup",
"Backup restored": "Backup restored",
"Bandwidth": "Bandwidth",
@@ -106,7 +104,6 @@
"Children's / Youth": "Children's / Youth",
"choose a channel": "choose a channel",
"Clear view": "Clear view",
"Click ▶ to play": "Click ▶ to play",
"Client": "Client",
"Clients": "Clients",
"clients": "clients",
@@ -254,7 +251,6 @@
"in": "in",
"Information": "Information",
"Install ffmpeg on the server to enable transcoding, or open the channel in VLC.": "Install ffmpeg on the server to enable transcoding, or open the channel in VLC.",
"Interface preferences are stored in this browser.": "Interface preferences are stored in this browser.",
"Interface preferences reset": "Interface preferences reset",
"Interface scale": "Interface scale",
"invalid recording time (max. 12 h)": "invalid recording time (max. 12 h)",
@@ -480,7 +476,6 @@
"set the end time": "set the end time",
"Settings": "Settings",
"Settings saved": "Settings saved",
"Shortcuts: ↑/↓ channel, digits – number, F – fullscreen, P – picture-in-picture, M – mute, ? – help.": "Shortcuts: ↑/↓ channel, digits – number, F – fullscreen, P – picture-in-picture, M – mute, ? – help.",
"Show / Game show": "Show / Game show",
"Show clock in the top bar": "Show clock in the top bar",
"Si2168 usually locks DVB-T2 within ~1–2 s": "Si2168 usually locks DVB-T2 within ~1–2 s",
@@ -576,7 +571,6 @@
"user already exists": "user already exists",
"Username": "Username",
"Video recorder": "Video recorder",
"Video unchanged, audio → AAC (browsers)": "Video unchanged, audio → AAC (browsers)",
"viewer": "viewer",
"viewer (watch only)": "viewer (watch only)",
"Violet": "Violet",
@@ -598,18 +592,12 @@
"· new channels:": "· new channels:",
"· services:": "· services:",
"— none —": "— none —",
"⎋ Sign out": "⎋ Sign out",
"■ Stop": "■ Stop",
"▶ Open in VLC": "▶ Open in VLC",
"▶ Play": "▶ Play",
"▶ Watch": "▶ Watch",
"▶ Watch channel": "▶ Watch channel",
"● Record": "● Record",
"● Record programme": "● Record programme",
"⛶ Fullscreen": "⛶ Fullscreen",
"⤒ Restore from file": "⤒ Restore from file",
"⤓ Download": "⤓ Download",
"⤓ Download backup (JSON)": "⤓ Download backup (JSON)",
"Open in VLC": "Open in VLC",
"Watch": "Watch",
"Watch channel": "Watch channel",
"Record programme": "Record programme",
"Restore from file": "Restore from file",
"Download backup (JSON)": "Download backup (JSON)",
"One entry per line: a network (192.168.0.0/16), an address or a DDNS host name (myhome.ddns.net, re-resolved every minute). Empty = a token or panel session is always required.": "One entry per line: a network (192.168.0.0/16), an address or a DDNS host name (myhome.ddns.net, re-resolved every minute). Empty = a token or panel session is always required.",
"e.g. 83.1.2.3, 10.8.0.0/24, myhome.ddns.net": "e.g. 83.1.2.3, 10.8.0.0/24, myhome.ddns.net",
"Networks, addresses or DDNS host names. Empty = panel reachable from anywhere (login still required).": "Networks, addresses or DDNS host names. Empty = panel reachable from anywhere (login still required).",
@@ -623,7 +611,105 @@
"Stream detection is already running": "Stream detection is already running",
"Detecting streams of": "Detecting streams of",
"channels on": "channels on",
"muxes…": "muxes…"
"muxes…": "muxes…",
"Interface preferences are saved in your user profile and follow you to every device.": "Interface preferences are saved in your user profile and follow you to every device.",
"Timeline": "Timeline",
"Application traffic": "Application traffic",
"from tuners": "from tuners",
"Bit error rate (BER)": "Bit error rate (BER)",
"Stream errors": "Stream errors",
"Transmission": "Transmission",
"Packets": "Packets",
"Errors": "Errors",
"stuffing": "stuffing",
"Hardware": "Hardware",
"Bus": "Bus",
"Driver": "Driver",
"IDs": "IDs",
"Frequency range": "Frequency range",
"Capabilities": "Capabilities",
"Favourites": "Favourites",
"Remove from favourites": "Remove from favourites",
"Add to favourites": "Add to favourites",
"Added to favourites": "Added to favourites",
"Removed from favourites": "Removed from favourites",
"Remind me": "Remind me",
"Reminder set": "Reminder set",
"You will be reminded 2 minutes before the start": "You will be reminded 2 minutes before the start",
"Reminder removed": "Reminder removed",
"Starting soon": "Starting soon",
"Full database copy": "Full database copy",
"Full database copy: everything incl. users, EPG and statistics – restore it with": "Full database copy: everything incl. users, EPG and statistics – restore it with",
"Your account": "Your account",
"Sign out other devices": "Sign out other devices",
"User": "User",
"Signed-in devices": "Signed-in devices",
"all users": "all users",
"Last active": "Last active",
"Signed in": "Signed in",
"this device": "this device",
"Signed out devices:": "Signed out devices:",
"Signed out": "Signed out",
"Viewing": "Viewing",
"Statistics": "Statistics",
"What is watched, by whom, on which devices and when. Sessions shorter than 10 s (zapping) are not counted.": "What is watched, by whom, on which devices and when. Sessions shorter than 10 s (zapping) are not counted.",
"24 h": "24 h",
"7 days": "7 days",
"30 days": "30 days",
"year": "year",
"Clear history": "Clear history",
"No viewing yet in this period.": "No viewing yet in this period.",
"Watch time": "Watch time",
"sessions": "sessions",
"Data sent": "Data sent",
"Most watched": "Most watched",
"Viewers": "Viewers",
"devices": "devices",
"Most watched channels": "Most watched channels",
"Devices": "Devices",
"Time of day": "Time of day",
"Per day": "Per day",
"Delete the whole viewing history?": "Delete the whole viewing history?",
"History cleared": "History cleared",
"Antenna": "Antenna",
"Antenna meter": "Antenna meter",
"Live signal of a tuner, refreshed every second – handy while aligning the antenna (open it on the phone).": "Live signal of a tuner, refreshed every second – handy while aligning the antenna (open it on the phone).",
"Sound": "Sound",
"Tuner": "Tuner",
"Tune multiplex": "Tune multiplex",
"Tune": "Tune",
"Tuning…": "Tuning…",
"No lock": "No lock",
"Locked": "Locked",
"Excellent": "Excellent",
"Good": "Good",
"Fair": "Fair",
"Weak": "Weak",
"No DVB adapters detected.": "No DVB adapters detected.",
"The tuner is idle. Start watching a channel or pick a multiplex above and press “Tune”.": "The tuner is idle. Start watching a channel or pick a multiplex above and press “Tune”.",
"MPEG-TS": "MPEG-TS",
"Show all": "Show all",
"AAC audio": "AAC audio",
"Background scanning is off (Settings, section Scanning).": "Background scanning is off (Settings, section Scanning).",
"Click Play to start": "Click Play to start",
"Shortcuts: arrow up/down – channel, digits – number, F – fullscreen, P – picture-in-picture, M – mute, ? – help.": "Shortcuts: arrow up/down – channel, digits – number, F – fullscreen, P – picture-in-picture, M – mute, ? – help.",
"Arrow up / down": "Arrow up / down",
"Sound on": "Sound on",
"Sound off": "Sound off",
"VLC (.m3u)": "VLC (.m3u)",
"PiP": "PiP",
"M3U": "M3U",
"Video unchanged, audio converted to AAC (browsers)": "Video unchanged, audio converted to AAC (browsers)",
"PID filter": "PID filter",
"Only the PIDs that clients need are read from the tuner – less CPU. The bitrate covers just these PIDs.": "Only the PIDs that clients need are read from the tuner – less CPU. The bitrate covers just these PIDs.",
"Read only the PIDs clients need (less CPU)": "Read only the PIDs clients need (less CPU)",
"The kernel passes only the selected programmes and the EPG/SI tables instead of the whole multiplex. Turn off if a tuner driver misbehaves.": "The kernel passes only the selected programmes and the EPG/SI tables instead of the whole multiplex. Turn off if a tuner driver misbehaves.",
"EPG & icons": "EPG & icons",
"Backup & monitoring": "Backup & monitoring",
"Monitoring (Prometheus)": "Monitoring (Prometheus)",
"Open": "Open",
"Metrics for Prometheus/Grafana: tuners (signal, SNR, errors, bitrate), clients, traffic, recordings and the process. Add this address as a scrape target.": "Metrics for Prometheus/Grafana: tuners (signal, SNR, errors, bitrate), clients, traffic, recordings and the process. Add this address as a scrape target.",
"Browsers and apps signed in to the panel. Signing a device out ends its session immediately.": "Browsers and apps signed in to the panel. Signing a device out ends its session immediately."
},
"patterns": []
}
+105 -19
View File
@@ -62,7 +62,6 @@
"Arts & culture": "Kultura",
"Arts / Culture": "Kultura",
"Assign numbers 1..n in the current order?": "Nadać numery 1..n według bieżącej kolejności?",
"Audio → AAC": "Audio → AAC",
"Australia – VHF 6–12 + UHF 28–51 (7 MHz)": "Australia – VHF 6–12 + UHF 28–51 (7 MHz)",
"automatic": "automatycznie",
"Automatic": "Automatyczny",
@@ -73,7 +72,6 @@
"background scan stopped – the adapter is needed": "skanowanie w tle przerwane – adapter jest potrzebny",
"Background scan: create channels for new services": "Skanowanie w tle: twórz kanały dla nowych usług",
"Background scan: follow the NIT to new muxes": "Skanowanie w tle: szukaj nowych multipleksów w NIT",
"Background scanning is off (Settings → Scanning).": "Skanowanie w tle jest wyłączone (Ustawienia → Skanowanie).",
"Backup": "Kopia zapasowa",
"Backup restored": "Przywrócono kopię",
"Bandwidth": "Szerokość",
@@ -106,7 +104,6 @@
"Children's / Youth": "Dla dzieci",
"choose a channel": "podaj kanał",
"Clear view": "Wyczyść widok",
"Click ▶ to play": "Kliknij ▶, aby odtworzyć",
"Client": "Klient",
"Clients": "Klienci",
"clients": "klienci",
@@ -254,7 +251,6 @@
"in": "odbierane",
"Information": "Informacje",
"Install ffmpeg on the server to enable transcoding, or open the channel in VLC.": "Zainstaluj ffmpeg na serwerze, aby włączyć transkodowanie, albo otwórz kanał w VLC.",
"Interface preferences are stored in this browser.": "Ustawienia interfejsu są zapisywane w tej przeglądarce.",
"Interface preferences reset": "Przywrócono domyślne ustawienia interfejsu",
"Interface scale": "Skala interfejsu",
"invalid recording time (max. 12 h)": "nieprawidłowy czas nagrania (maks. 12 h)",
@@ -480,7 +476,6 @@
"set the end time": "podaj czas zakończenia",
"Settings": "Ustawienia",
"Settings saved": "Zapisano ustawienia",
"Shortcuts: ↑/↓ channel, digits – number, F – fullscreen, P – picture-in-picture, M – mute, ? – help.": "Skróty: ↑/↓ kanał, cyfry – numer, F – pełny ekran, P – obraz w obrazie, M – wycisz, ? – pomoc.",
"Show / Game show": "Rozrywka",
"Show clock in the top bar": "Pokaż zegar w górnym pasku",
"Si2168 usually locks DVB-T2 within ~1–2 s": "Si2168 zwykle synchronizuje DVB-T2 w ~1–2 s",
@@ -576,7 +571,6 @@
"user already exists": "użytkownik już istnieje",
"Username": "Użytkownik",
"Video recorder": "Magnetowid",
"Video unchanged, audio → AAC (browsers)": "Wideo bez zmian, audio → AAC (przeglądarki)",
"viewer": "widz",
"viewer (watch only)": "widz (tylko oglądanie)",
"Violet": "Fioletowy",
@@ -598,18 +592,12 @@
"· new channels:": "· nowych kanałów:",
"· services:": "· usług:",
"— none —": "— brak —",
"⎋ Sign out": "⎋ Wyloguj",
"■ Stop": "■ Zatrzymaj",
"▶ Open in VLC": "▶ Otwórz w VLC",
"▶ Play": "▶ Odtwórz",
"▶ Watch": "▶ Oglądaj",
"▶ Watch channel": "▶ Oglądaj kanał",
"● Record": "● Nagraj",
"● Record programme": "● Nagraj audycję",
"⛶ Fullscreen": "⛶ Pełny ekran",
"⤒ Restore from file": "⤒ Przywróć z pliku",
"⤓ Download": "⤓ Pobierz",
"⤓ Download backup (JSON)": "⤓ Pobierz kopię (JSON)",
"Open in VLC": "Otwórz w VLC",
"Watch": "Oglądaj",
"Watch channel": "Oglądaj kanał",
"Record programme": "Nagraj audycję",
"Restore from file": "Przywróć z pliku",
"Download backup (JSON)": "Pobierz kopię (JSON)",
"One entry per line: a network (192.168.0.0/16), an address or a DDNS host name (myhome.ddns.net, re-resolved every minute). Empty = a token or panel session is always required.": "Jeden wpis w linii: sieć (192.168.0.0/16), adres lub nazwa hosta DDNS (mojdom.ddns.net, odświeżana co minutę). Puste = zawsze wymagany token lub sesja panelu.",
"e.g. 83.1.2.3, 10.8.0.0/24, myhome.ddns.net": "np. 83.1.2.3, 10.8.0.0/24, mojdom.ddns.net",
"Networks, addresses or DDNS host names. Empty = panel reachable from anywhere (login still required).": "Sieci, adresy lub nazwy hostów DDNS. Puste = panel dostępny zewsząd (nadal wymaga logowania).",
@@ -623,7 +611,105 @@
"Stream detection is already running": "Wykrywanie strumieni już trwa",
"Detecting streams of": "Wykrywanie strumieni",
"channels on": "kanałów na",
"muxes…": "muksach…"
"muxes…": "muksach…",
"Interface preferences are saved in your user profile and follow you to every device.": "Ustawienia interfejsu są zapisywane w Twoim profilu i działają na każdym urządzeniu.",
"Timeline": "Harmonogram",
"Application traffic": "Ruch aplikacji",
"from tuners": "z tunerów",
"Bit error rate (BER)": "Bitowa stopa błędów (BER)",
"Stream errors": "Błędy strumienia",
"Transmission": "Transmisja",
"Packets": "Pakiety",
"Errors": "Błędy",
"stuffing": "wypełnienie",
"Hardware": "Sprzęt",
"Bus": "Magistrala",
"Driver": "Sterownik",
"IDs": "Identyfikatory",
"Frequency range": "Zakres częstotliwości",
"Capabilities": "Możliwości",
"Favourites": "Ulubione",
"Remove from favourites": "Usuń z ulubionych",
"Add to favourites": "Dodaj do ulubionych",
"Added to favourites": "Dodano do ulubionych",
"Removed from favourites": "Usunięto z ulubionych",
"Remind me": "Przypomnij",
"Reminder set": "Przypomnienie ustawione",
"You will be reminded 2 minutes before the start": "Przypomnienie pojawi się 2 minuty przed startem",
"Reminder removed": "Przypomnienie usunięte",
"Starting soon": "Za chwilę się zaczyna",
"Full database copy": "Pełna kopia bazy",
"Full database copy: everything incl. users, EPG and statistics – restore it with": "Pełna kopia bazy: wszystko, także użytkownicy, EPG i statystyki – przywrócisz ją poleceniem",
"Your account": "Twoje konto",
"Sign out other devices": "Wyloguj inne urządzenia",
"User": "Użytkownik",
"Signed-in devices": "Zalogowane urządzenia",
"all users": "wszyscy użytkownicy",
"Last active": "Ostatnia aktywność",
"Signed in": "Zalogowano",
"this device": "to urządzenie",
"Signed out devices:": "Wylogowane urządzenia:",
"Signed out": "Wylogowano",
"Viewing": "Oglądalność",
"Statistics": "Statystyki",
"What is watched, by whom, on which devices and when. Sessions shorter than 10 s (zapping) are not counted.": "Co jest oglądane, przez kogo, na jakich urządzeniach i kiedy. Sesje krótsze niż 10 s (przełączanie kanałów) nie są liczone.",
"24 h": "24 h",
"7 days": "7 dni",
"30 days": "30 dni",
"year": "rok",
"Clear history": "Wyczyść historię",
"No viewing yet in this period.": "Brak oglądania w tym okresie.",
"Watch time": "Czas oglądania",
"sessions": "sesji",
"Data sent": "Wysłane dane",
"Most watched": "Najczęściej oglądany",
"Viewers": "Widzowie",
"devices": "urządzeń",
"Most watched channels": "Najczęściej oglądane kanały",
"Devices": "Urządzenia",
"Time of day": "Pora dnia",
"Per day": "Dziennie",
"Delete the whole viewing history?": "Usunąć całą historię oglądania?",
"History cleared": "Historia wyczyszczona",
"Antenna": "Antena",
"Antenna meter": "Miernik anteny",
"Live signal of a tuner, refreshed every second – handy while aligning the antenna (open it on the phone).": "Sygnał tunera na żywo, odświeżany co sekundę – przydatny przy ustawianiu anteny (otwórz go na telefonie).",
"Sound": "Dźwięk",
"Tuner": "Tuner",
"Tune multiplex": "Dostrój multipleks",
"Tune": "Dostrój",
"Tuning…": "Strojenie…",
"No lock": "Brak synchronizacji",
"Locked": "Zsynchronizowany",
"Excellent": "Doskonały",
"Good": "Dobry",
"Fair": "Przeciętny",
"Weak": "Słaby",
"No DVB adapters detected.": "Nie wykryto adapterów DVB.",
"The tuner is idle. Start watching a channel or pick a multiplex above and press “Tune”.": "Tuner jest wolny. Włącz kanał albo wybierz multipleks powyżej i naciśnij „Dostrój”.",
"MPEG-TS": "MPEG-TS",
"Show all": "Pokaż wszystkie",
"AAC audio": "Audio AAC",
"Background scanning is off (Settings, section Scanning).": "Skanowanie w tle jest wyłączone (Ustawienia, sekcja Skanowanie).",
"Click Play to start": "Kliknij Odtwórz, aby zacząć",
"Shortcuts: arrow up/down – channel, digits – number, F – fullscreen, P – picture-in-picture, M – mute, ? – help.": "Skróty: strzałka w górę/w dół – kanał, cyfry – numer, F – pełny ekran, P – obraz w obrazie, M – wycisz, ? – pomoc.",
"Arrow up / down": "Strzałka w górę / w dół",
"Sound on": "Dźwięk włączony",
"Sound off": "Dźwięk wyłączony",
"VLC (.m3u)": "VLC (.m3u)",
"PiP": "PiP",
"M3U": "M3U",
"Video unchanged, audio converted to AAC (browsers)": "Wideo bez zmian, audio zamienione na AAC (przeglądarki)",
"PID filter": "filtr PID",
"Only the PIDs that clients need are read from the tuner – less CPU. The bitrate covers just these PIDs.": "Z tunera czytane są tylko PID-y potrzebne klientom – mniejsze obciążenie CPU. Przepływność dotyczy tylko tych PID-ów.",
"Read only the PIDs clients need (less CPU)": "Czytaj tylko PID-y potrzebne klientom (mniej CPU)",
"The kernel passes only the selected programmes and the EPG/SI tables instead of the whole multiplex. Turn off if a tuner driver misbehaves.": "Jądro przekazuje tylko wybrane programy i tabele EPG/SI zamiast całego multipleksu. Wyłącz, jeśli sterownik tunera sprawia problemy.",
"EPG & icons": "EPG i ikony",
"Backup & monitoring": "Kopia i monitoring",
"Monitoring (Prometheus)": "Monitoring (Prometheus)",
"Open": "Otwórz",
"Metrics for Prometheus/Grafana: tuners (signal, SNR, errors, bitrate), clients, traffic, recordings and the process. Add this address as a scrape target.": "Metryki dla Prometheus/Grafana: tunery (sygnał, SNR, błędy, przepływność), klienci, ruch, nagrania i proces. Dodaj ten adres jako cel zbierania (scrape target).",
"Browsers and apps signed in to the panel. Signing a device out ends its session immediately.": "Przeglądarki i aplikacje zalogowane do panelu. Wylogowanie urządzenia od razu kończy jego sesję."
},
"patterns": [
{
+18
View File
@@ -0,0 +1,18 @@
-- Device details of panel sessions (Profile → Signed-in devices).
ALTER TABLE sessions ADD COLUMN user_agent TEXT NOT NULL DEFAULT '';
ALTER TABLE sessions ADD COLUMN last_seen INTEGER NOT NULL DEFAULT 0;
-- Finished viewing sessions (statistics: most watched channels, who watched how long).
CREATE TABLE IF NOT EXISTS watch_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
channel_id INTEGER,
channel_name TEXT NOT NULL,
kind TEXT NOT NULL,
who TEXT NOT NULL DEFAULT '',
ip TEXT NOT NULL DEFAULT '',
device TEXT NOT NULL DEFAULT '',
started INTEGER NOT NULL,
ended INTEGER NOT NULL,
bytes INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS watch_history_started ON watch_history(started);
+33 -1
View File
@@ -67,6 +67,8 @@ pub struct AppState {
pub acl_refresh: Notify,
/// A stream detection (probe) of channels without known streams is running.
pub probing: AtomicBool,
/// Antenna meter: muxes kept tuned until the given time (mux id → deadline).
pub signal_hold: Mutex<HashMap<i64, std::time::Instant>>,
}
impl AppState {
@@ -112,6 +114,9 @@ impl AppState {
.epg_enabled
.store(settings.epg_ota_enabled, Ordering::Relaxed);
*tuners.linger.lock().unwrap() = Duration::from_secs(settings.tuner_linger_seconds as u64);
tuners
.pid_filter
.store(settings.tuner_pid_filter, Ordering::Relaxed);
let http = reqwest::Client::builder()
.user_agent(concat!("simply-dvb/", env!("CARGO_PKG_VERSION")))
.timeout(Duration::from_secs(120))
@@ -141,6 +146,7 @@ impl AppState {
ffmpeg: Mutex::new(None),
acl_refresh: Notify::new(),
probing: AtomicBool::new(false),
signal_hold: Mutex::new(HashMap::new()),
});
state.detect_ffmpeg().await;
state.refresh_adapters().await?;
@@ -184,17 +190,43 @@ impl AppState {
self.db
.set_setting("config", &serde_json::to_string(&s)?)
.await?;
self.apply_settings(s).await;
Ok(())
}
/// Picks up settings changed in the database by the command line tool
/// (`simply-dvb settings set …`, `access reset-panel`) – checked every few seconds.
pub async fn settings_watch(self: Arc<Self>) {
loop {
tokio::time::sleep(Duration::from_secs(3)).await;
let Ok(Some(raw)) = self.db.get_setting("config").await else {
continue;
};
let Ok(mut s) = serde_json::from_str::<Settings>(&raw) else {
continue;
};
if s.validate().is_err() || s == self.settings() {
continue;
}
tracing::info!("settings changed outside the panel (command line) – applied");
self.apply_settings(s).await;
}
}
async fn apply_settings(&self, s: Settings) {
self.tuners
.epg_enabled
.store(s.epg_ota_enabled, Ordering::Relaxed);
*self.tuners.linger.lock().unwrap() = Duration::from_secs(s.tuner_linger_seconds as u64);
self.tuners
.pid_filter
.store(s.tuner_pid_filter, Ordering::Relaxed);
let ffmpeg_changed = self.settings.read().unwrap().ffmpeg_path != s.ffmpeg_path;
*self.settings.write().unwrap() = s;
self.acl_refresh.notify_one();
if ffmpeg_changed {
self.detect_ffmpeg().await;
}
Ok(())
}
/// Discovers adapters (Linux DVB + virtual) and updates the tuner manager.
+870
View File
@@ -0,0 +1,870 @@
//! Administration commands: users, access tokens, settings, channels, backups and a
//! health check. They work directly on the database, so they also work when the panel
//! is unreachable (forgotten password, panel locked to the wrong network…).
use anyhow::{bail, Context, Result};
use clap::Subcommand;
use serde_json::Value;
use simply_dvb::app::Options;
use simply_dvb::auth;
use simply_dvb::db::Db;
use simply_dvb::settings::Settings;
use std::io::{BufRead, IsTerminal, Write};
use std::path::{Path, PathBuf};
#[derive(Subcommand)]
pub enum UserCmd {
/// List users
List,
/// Add a user (password from standard input, or --generate)
Add {
name: String,
/// admin or viewer
#[arg(long, default_value = "admin")]
role: String,
/// Generate a random password and print it
#[arg(long)]
generate: bool,
},
/// Change a user's password and sign them out everywhere
Passwd {
name: String,
/// Generate a random password and print it
#[arg(long)]
generate: bool,
},
/// Forgotten password: give the first administrator (or a new "admin" account) a
/// new random password, sign it out everywhere and print the password
ResetAdmin,
/// Change a user's role (admin or viewer)
Role { name: String, role: String },
/// Sign a user out of all browsers
Logout { name: String },
/// Delete a user
Delete { name: String },
}
#[derive(Subcommand)]
pub enum TokenCmd {
/// List access tokens (for TV apps, players, PVR clients)
List,
/// Create a token and print it with ready-to-use URLs
Add {
name: String,
/// Allowed networks/addresses/DDNS host names (comma separated; empty = anywhere)
#[arg(long, default_value = "")]
allow: String,
/// Server address used in the printed URLs
#[arg(long, default_value = "http://SERVER:9981")]
base_url: String,
},
/// Enable or disable a token
Enable {
name: String,
},
Disable {
name: String,
},
/// Delete a token
Delete {
name: String,
},
}
#[derive(Subcommand)]
pub enum SettingsCmd {
/// Print all settings (JSON) or one value
Show { key: Option<String> },
/// Set one value, e.g. `settings set hls_segment_seconds 4` or
/// `settings set stream_open_cidrs '["192.168.0.0/16","myhome.ddns.net"]'`
Set { key: String, value: String },
/// Restore the default value of one setting
Unset { key: String },
}
#[derive(Subcommand)]
pub enum AccessCmd {
/// Show who may open the panel and the streams without a token
Show,
/// Locked out of the panel? Allow it from everywhere again (login still required)
ResetPanel,
/// Add a network, address or DDNS host name to the token-free stream networks
OpenAdd { entry: String },
/// Remove an entry from the token-free stream networks
OpenRemove { entry: String },
}
#[derive(Subcommand)]
pub enum ChannelCmd {
/// List channels (number, name, group, state)
List {
/// Also list disabled channels
#[arg(long)]
all: bool,
},
/// Print an M3U playlist (e.g. to import in a player)
M3u {
/// Server address used in the URLs
#[arg(long, default_value = "http://127.0.0.1:9981")]
base_url: String,
/// Access token appended to the URLs
#[arg(long, default_value = "")]
token: String,
/// ts (MPEG-TS, like tvheadend) or hls
#[arg(long, default_value = "ts")]
format: String,
},
/// Enable channels by number (e.g. `enable 1 2 15`)
Enable { numbers: Vec<i64> },
/// Disable channels by number
Disable { numbers: Vec<i64> },
}
#[derive(Subcommand)]
pub enum DbCmd {
/// Check the database for corruption
Check,
/// Compact the database file
Vacuum,
/// Copy the database to a file (safe while the server is running)
Backup {
/// Target file (default: <data-dir>/backups/simply-dvb-<date>.db)
file: Option<PathBuf>,
},
/// Replace the database with a backup (stop the service first!)
Restore { file: PathBuf },
}
fn read_password() -> Result<String> {
if std::io::stdin().is_terminal() {
eprint!("New password (min. 8 characters): ");
std::io::stderr().flush().ok();
}
let mut line = String::new();
std::io::stdin().lock().read_line(&mut line)?;
let pw = line.trim_end_matches(['\r', '\n']).to_string();
if pw.chars().count() < 8 {
bail!("password must be at least 8 characters");
}
Ok(pw)
}
fn new_password(generate: bool) -> Result<(String, bool)> {
if generate {
Ok((gen_password(), true))
} else {
Ok((read_password()?, false))
}
}
fn check_role(role: &str) -> Result<()> {
if role != "admin" && role != "viewer" {
bail!("role must be admin or viewer");
}
Ok(())
}
const RESTART_NOTE: &str = "A running server applies the change within a few seconds.";
/// Random password that is easy to type (no look-alike characters, no leading dash).
fn gen_password() -> String {
const A: &[u8] = b"abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
let mut buf = [0u8; 14];
getrandom::fill(&mut buf).expect("getrandom");
buf.iter()
.map(|b| A[*b as usize % A.len()] as char)
.collect()
}
pub async fn user(db: &Db, cmd: UserCmd) -> Result<()> {
match cmd {
UserCmd::List => {
println!("{:<20} {:<8} CREATED", "USER", "ROLE");
for u in db.users().await? {
println!(
"{:<20} {:<8} {}",
u.username,
u.role,
fmt_time(u.created_at)
);
}
}
UserCmd::Add {
name,
role,
generate,
} => {
check_role(&role)?;
if db.user_by_name(&name).await?.is_some() {
bail!("user {name} already exists (use `user passwd {name}`)");
}
let (pw, show) = new_password(generate)?;
db.create_user(&name, &auth::hash_password(&pw)?, &role)
.await?;
println!("User {name} added ({role})");
if show {
println!("Password: {pw}");
}
}
UserCmd::Passwd { name, generate } => {
let u = db
.user_by_name(&name)
.await?
.with_context(|| format!("no user {name}"))?;
let (pw, show) = new_password(generate)?;
db.update_user(u.id, Some(&auth::hash_password(&pw)?), None)
.await?;
db.delete_user_sessions(u.id).await?;
println!("Password changed for {name} (signed out everywhere)");
if show {
println!("Password: {pw}");
}
}
UserCmd::ResetAdmin => {
let pw = gen_password();
let hash = auth::hash_password(&pw)?;
let users = db.users().await?;
let name = match users.iter().find(|u| u.role == "admin") {
Some(u) => {
db.update_user(u.id, Some(&hash), None).await?;
db.delete_user_sessions(u.id).await?;
u.username.clone()
}
None => {
let name = if users.iter().any(|u| u.username == "admin") {
let u = users.iter().find(|u| u.username == "admin").unwrap();
db.update_user(u.id, Some(&hash), Some("admin")).await?;
db.delete_user_sessions(u.id).await?;
"admin".to_string()
} else {
db.create_user("admin", &hash, "admin").await?;
"admin".to_string()
};
name
}
};
println!("Administrator: {name}");
println!("Password: {pw}");
println!("Change it after signing in (Settings, Your account).");
}
UserCmd::Role { name, role } => {
check_role(&role)?;
let u = db
.user_by_name(&name)
.await?
.with_context(|| format!("no user {name}"))?;
if u.role == "admin" && role != "admin" {
let admins = db
.users()
.await?
.iter()
.filter(|u| u.role == "admin")
.count();
if admins <= 1 {
bail!("{name} is the only administrator");
}
}
db.update_user(u.id, None, Some(&role)).await?;
println!("{name} is now {role}");
}
UserCmd::Logout { name } => {
let u = db
.user_by_name(&name)
.await?
.with_context(|| format!("no user {name}"))?;
let n = db.delete_user_sessions(u.id).await?;
println!("{name} signed out ({n} session(s))");
}
UserCmd::Delete { name } => {
let u = db
.user_by_name(&name)
.await?
.with_context(|| format!("no user {name}"))?;
if u.role == "admin" {
let admins = db
.users()
.await?
.iter()
.filter(|u| u.role == "admin")
.count();
if admins <= 1 {
bail!("{name} is the only administrator");
}
}
db.delete_user(u.id).await?;
println!("User {name} deleted");
}
}
Ok(())
}
async fn token_by_name(db: &Db, name: &str) -> Result<simply_dvb::db::AccessToken> {
db.tokens()
.await?
.into_iter()
.find(|t| t.name == name)
.with_context(|| format!("no token named {name}"))
}
pub async fn token(db: &Db, cmd: TokenCmd) -> Result<()> {
match cmd {
TokenCmd::List => {
println!(
"{:<20} {:<8} {:<34} {:<30} LAST USED",
"NAME", "STATE", "TOKEN", "ALLOWED FROM"
);
for t in db.tokens().await? {
println!(
"{:<20} {:<8} {:<34} {:<30} {}",
t.name,
if t.enabled { "enabled" } else { "disabled" },
t.token,
if t.allow_cidrs.is_empty() {
"anywhere".to_string()
} else {
t.allow_cidrs.clone()
},
t.last_used.map(fmt_time).unwrap_or_else(|| "never".into())
);
}
}
TokenCmd::Add {
name,
allow,
base_url,
} => {
simply_dvb::settings::parse_cidrs(&allow).map_err(anyhow::Error::msg)?;
if db.tokens().await?.iter().any(|t| t.name == name) {
bail!("a token named {name} already exists");
}
let token = auth::random_token(24);
db.create_token(&name, &token, &allow).await?;
let b = base_url.trim_end_matches('/');
println!("Token {name}: {token}");
println!(" Playlist (M3U): {b}/playlist.m3u?token={token}");
println!(" EPG (XMLTV): {b}/epg.xml?token={token}");
println!(" tvheadend apps: user any, password {token}");
}
TokenCmd::Enable { name } => {
let t = token_by_name(db, &name).await?;
db.update_token(t.id, &t.name, &t.allow_cidrs, true).await?;
println!("Token {name} enabled");
}
TokenCmd::Disable { name } => {
let t = token_by_name(db, &name).await?;
db.update_token(t.id, &t.name, &t.allow_cidrs, false)
.await?;
println!("Token {name} disabled");
}
TokenCmd::Delete { name } => {
let t = token_by_name(db, &name).await?;
db.delete_token(t.id).await?;
println!("Token {name} deleted");
}
}
Ok(())
}
async fn load_settings(db: &Db) -> Result<Settings> {
Ok(match db.get_setting("config").await? {
Some(s) => serde_json::from_str(&s).unwrap_or_default(),
None => Settings::default(),
})
}
async fn save_settings(db: &Db, mut s: Settings) -> Result<()> {
s.validate().map_err(anyhow::Error::msg)?;
db.set_setting("config", &serde_json::to_string(&s)?)
.await?;
Ok(())
}
pub async fn settings(db: &Db, cmd: SettingsCmd) -> Result<()> {
let s = load_settings(db).await?;
let mut v = serde_json::to_value(&s)?;
match cmd {
SettingsCmd::Show { key: None } => println!("{}", serde_json::to_string_pretty(&v)?),
SettingsCmd::Show { key: Some(k) } => {
let x = v.get(&k).with_context(|| format!("unknown setting {k}"))?;
println!("{}", serde_json::to_string_pretty(x)?);
}
SettingsCmd::Set { key, value } => {
let obj = v.as_object_mut().unwrap();
let old = obj
.get(&key)
.with_context(|| format!("unknown setting {key} (see `settings show`)"))?
.clone();
// JSON where it parses (numbers, true/false, lists), text otherwise;
// a comma separated text is accepted for lists
let new = match serde_json::from_str::<Value>(&value) {
Ok(x) if !(old.is_string() && !x.is_string()) => x,
_ if old.is_array() => Value::Array(
value
.split(',')
.map(|x| x.trim())
.filter(|x| !x.is_empty())
.map(|x| Value::String(x.into()))
.collect(),
),
_ => Value::String(value.clone()),
};
obj.insert(key.clone(), new.clone());
let s: Settings = serde_json::from_value(v)
.with_context(|| format!("invalid value for {key}: {value}"))?;
save_settings(db, s).await?;
println!("{key}: {old} -> {new}");
println!("{RESTART_NOTE}");
}
SettingsCmd::Unset { key } => {
let def = serde_json::to_value(Settings::default())?;
let d = def
.get(&key)
.with_context(|| format!("unknown setting {key}"))?
.clone();
v.as_object_mut().unwrap().insert(key.clone(), d.clone());
save_settings(db, serde_json::from_value(v)?).await?;
println!("{key} reset to {d}");
println!("{RESTART_NOTE}");
}
}
Ok(())
}
pub async fn access(db: &Db, cmd: AccessCmd) -> Result<()> {
let mut s = load_settings(db).await?;
let list = |l: &[simply_dvb::settings::AclEntry]| {
if l.is_empty() {
"(none)".to_string()
} else {
l.iter()
.map(|e| e.to_string())
.collect::<Vec<_>>()
.join(", ")
}
};
match cmd {
AccessCmd::Show => {
println!(
"Panel allowed from: {}",
if s.panel_allow_cidrs.is_empty() {
"anywhere (login required)".into()
} else {
list(&s.panel_allow_cidrs)
}
);
println!("Streams without a token: {}", list(&s.stream_open_cidrs));
println!(
"Trusted reverse proxies: {}",
if s.trusted_proxies.is_empty() {
"(none)".to_string()
} else {
s.trusted_proxies
.iter()
.map(|n| n.to_string())
.collect::<Vec<_>>()
.join(", ")
}
);
let n = db.tokens().await?.len();
println!("Access tokens: {n} (see `token list`)");
}
AccessCmd::ResetPanel => {
s.panel_allow_cidrs.clear();
save_settings(db, s).await?;
println!("The panel is allowed from everywhere again (login still required).");
println!("{RESTART_NOTE}");
}
AccessCmd::OpenAdd { entry } => {
let e = simply_dvb::acl::AclEntry::parse(&entry).map_err(anyhow::Error::msg)?;
if !s.stream_open_cidrs.contains(&e) {
s.stream_open_cidrs.push(e);
}
println!("Streams without a token: {}", list(&s.stream_open_cidrs));
save_settings(db, s).await?;
println!("{RESTART_NOTE}");
}
AccessCmd::OpenRemove { entry } => {
let e = simply_dvb::acl::AclEntry::parse(&entry).map_err(anyhow::Error::msg)?;
let before = s.stream_open_cidrs.len();
s.stream_open_cidrs.retain(|x| x != &e);
if s.stream_open_cidrs.len() == before {
bail!("{entry} is not on the list");
}
println!("Streams without a token: {}", list(&s.stream_open_cidrs));
save_settings(db, s).await?;
println!("{RESTART_NOTE}");
}
}
Ok(())
}
pub async fn channel(db: &Db, cmd: ChannelCmd) -> Result<()> {
match cmd {
ChannelCmd::List { all } => {
println!("{:>5} {:<32} {:<16} STATE", "NO", "NAME", "GROUP");
for c in db.channels().await? {
if !all && !c.enabled {
continue;
}
println!(
"{:>5} {:<32} {:<16} {}",
c.number,
c.name,
c.grp,
if !c.enabled {
"disabled"
} else if c.service_id.is_none() {
"no service"
} else {
"ok"
}
);
}
}
ChannelCmd::M3u {
base_url,
token,
format,
} => {
if format != "ts" && format != "hls" {
bail!("format: ts or hls");
}
let chans: Vec<_> = db
.channels()
.await?
.into_iter()
.filter(|c| c.enabled)
.collect();
let auth = if token.is_empty() {
String::new()
} else {
format!("token={token}")
};
print!(
"{}",
simply_dvb::m3u::build(
&chans,
&simply_dvb::m3u::M3uOptions {
base: base_url.trim_end_matches('/'),
format: &format,
profile: "pass",
auth: &auth,
}
)
);
}
ChannelCmd::Enable { numbers } => set_enabled(db, &numbers, true).await?,
ChannelCmd::Disable { numbers } => set_enabled(db, &numbers, false).await?,
}
Ok(())
}
async fn set_enabled(db: &Db, numbers: &[i64], on: bool) -> Result<()> {
if numbers.is_empty() {
bail!("give channel numbers, e.g. 1 2 15");
}
for mut c in db.channels().await? {
if numbers.contains(&c.number) {
c.enabled = on;
db.update_channel(&c).await?;
println!(
"{:>5} {} {}",
c.number,
c.name,
if on { "enabled" } else { "disabled" }
);
}
}
Ok(())
}
pub async fn database(db: &Db, opts: &Options, cmd: DbCmd) -> Result<()> {
match cmd {
DbCmd::Check => {
let r = db.integrity_check().await?;
if r.len() == 1 && r[0] == "ok" {
println!("Database OK");
} else {
for l in &r {
println!("{l}");
}
bail!("the database has problems – restore a backup (`db restore`)");
}
}
DbCmd::Vacuum => {
let path = opts.data_dir.join("simply-dvb.db");
let before = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
db.vacuum().await?;
let after = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
println!("Database compacted: {} -> {}", mib(before), mib(after));
}
DbCmd::Backup { file } => {
let file = match file {
Some(f) => f,
None => {
let dir = opts.data_dir.join("backups");
std::fs::create_dir_all(&dir)?;
dir.join(format!(
"simply-dvb-{}.db",
chrono::Local::now().format("%Y%m%d-%H%M%S")
))
}
};
if file.exists() {
bail!("{} already exists", file.display());
}
db.backup_to(&file).await?;
fix_ownership(&opts.data_dir, &file);
println!(
"Backup written: {} ({})",
file.display(),
mib(std::fs::metadata(&file)?.len())
);
}
DbCmd::Restore { .. } => unreachable!("handled before opening the database"),
}
Ok(())
}
/// `db restore` runs without the database open.
pub fn restore(opts: &Options, file: &Path) -> Result<()> {
if server_running() {
bail!("the server is running – stop it first (systemctl stop simply-dvb)");
}
let head = std::fs::read(file).with_context(|| format!("reading {}", file.display()))?;
if !head.starts_with(b"SQLite format 3\0") {
bail!("{} is not an SQLite database", file.display());
}
let path = opts.data_dir.join("simply-dvb.db");
if path.exists() {
let keep = opts.data_dir.join(format!(
"simply-dvb.db.before-restore-{}",
chrono::Local::now().format("%Y%m%d-%H%M%S")
));
std::fs::rename(&path, &keep)?;
println!("Current database kept as {}", keep.display());
}
for ext in ["-wal", "-shm"] {
let _ = std::fs::remove_file(format!("{}{ext}", path.display()));
}
std::fs::copy(file, &path)?;
fix_ownership(&opts.data_dir, &path);
println!("Restored {} – start the service again.", file.display());
Ok(())
}
/// Health check: data directory, database, adapters, ports, ffmpeg.
pub async fn doctor(db: &Db, opts: &Options) -> Result<()> {
let mut problems = 0;
let mut line = |ok: bool, what: &str, detail: String| {
if !ok {
problems += 1;
}
println!("[{}] {what}: {detail}", if ok { " OK " } else { "FAIL" });
};
// data directory
let probe = opts.data_dir.join(".write-test");
let writable = std::fs::write(&probe, b"x").is_ok();
let _ = std::fs::remove_file(&probe);
line(
writable,
"data directory",
opts.data_dir.display().to_string(),
);
// database
let r = db.integrity_check().await?;
line(r == ["ok"], "database", r.join("; "));
let s = load_settings(db).await?;
// adapters
let adapters = simply_dvb::dvb::discover(&opts.dev_root);
line(
!adapters.is_empty() || !opts.virtual_dirs.is_empty(),
"DVB adapters",
if adapters.is_empty() {
format!(
"none in {} (driver/firmware loaded? `dmesg | grep -i dvb`)",
opts.dev_root
)
} else {
adapters
.iter()
.map(|a| format!("{} {}", a.id, a.name))
.collect::<Vec<_>>()
.join(", ")
},
);
for a in &adapters {
let fe = format!("{}/frontend0", a.path);
let ok = std::fs::OpenOptions::new().read(true).open(&fe).is_ok();
line(
ok,
&format!("{} access", a.id),
if ok {
fe
} else {
format!("{fe} not readable – is the user in the \"video\" group?")
},
);
}
// channels / EPG
let chans = db.channels().await?;
line(
!chans.is_empty(),
"channels",
format!(
"{} ({} enabled)",
chans.len(),
chans.iter().filter(|c| c.enabled).count()
),
);
// recordings directory
let rec = if s.recordings_dir.is_empty() {
opts.data_dir.join("recordings")
} else {
PathBuf::from(&s.recordings_dir)
};
let free = simply_dvb::recorder::free_space(&rec);
line(
free.is_none_or(|f| f > 2 << 30),
"recordings",
format!(
"{} – free {}",
rec.display(),
free.map(gib).unwrap_or_else(|| "?".into())
),
);
// ffmpeg (optional)
let ff = std::process::Command::new("ffmpeg")
.arg("-version")
.output()
.ok()
.filter(|o| o.status.success())
.and_then(|o| {
String::from_utf8_lossy(&o.stdout)
.lines()
.next()
.map(|l| l.to_string())
});
println!(
"[{}] ffmpeg (optional, transcoding): {}",
if ff.is_some() { " OK " } else { " -- " },
ff.unwrap_or_else(|| "not installed – only native playback".into())
);
// server
let running = server_running();
println!(
"[{}] server: {}",
if running { " OK " } else { " -- " },
if running {
format!("listening on {}", panel_addr())
} else {
format!("nothing listening on {}", panel_addr())
}
);
println!();
if problems == 0 {
println!("No problems found.");
Ok(())
} else {
bail!("{problems} problem(s) found")
}
}
/// Short overview of the installation.
pub async fn status(db: &Db, opts: &Options) -> Result<()> {
println!("simply-dvb {}", env!("CARGO_PKG_VERSION"));
println!("Data directory: {}", opts.data_dir.display());
let running = server_running();
println!(
"Server: {}",
if running {
format!("running – panel {}", panel_addr())
} else {
"not running".into()
}
);
for (t, n) in db.table_counts().await? {
println!(" {t:<14} {n}");
}
let recs = db.recordings_by_status("scheduled").await?;
if let Some(r) = recs.iter().min_by_key(|r| r.start) {
println!(
"Next recording: {} – {} ({})",
fmt_time(r.start),
r.title,
r.channel_name
);
}
for a in simply_dvb::dvb::discover(&opts.dev_root) {
let sys: Vec<_> = a.delivery_systems.iter().map(|d| d.label()).collect();
println!("Adapter: {} {} ({})", a.id, a.name, sys.join(", "));
}
Ok(())
}
fn panel_addr() -> String {
let v = std::env::var("SIMPLY_DVB_LISTEN").unwrap_or_else(|_| "0.0.0.0:9980".into());
v.split('#')
.next()
.unwrap_or("")
.trim()
.trim_matches('"')
.to_string()
}
fn server_running() -> bool {
let a = panel_addr();
let port = a.rsplit(':').next().and_then(|p| p.parse::<u16>().ok());
port.is_some_and(|p| {
std::net::TcpStream::connect_timeout(
&std::net::SocketAddr::from(([127, 0, 0, 1], p)),
std::time::Duration::from_millis(500),
)
.is_ok()
})
}
/// When run as root (sudo), files created in the data directory get the owner of the
/// directory – otherwise the service (user simply-dvb) could no longer write them.
pub fn fix_ownership(data_dir: &Path, file: &Path) {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
if unsafe { libc::geteuid() } != 0 {
return;
}
let Ok(m) = std::fs::metadata(data_dir) else {
return;
};
let _ = std::os::unix::fs::chown(file, Some(m.uid()), Some(m.gid()));
}
}
/// Database files after a command (sqlite may have created -wal/-shm as root).
pub fn fix_db_ownership(opts: &Options) {
let base = opts.data_dir.join("simply-dvb.db");
for ext in ["", "-wal", "-shm"] {
let p = PathBuf::from(format!("{}{ext}", base.display()));
if p.exists() {
fix_ownership(&opts.data_dir, &p);
}
}
}
fn fmt_time(t: i64) -> String {
chrono::DateTime::from_timestamp(t, 0)
.map(|d| {
d.with_timezone(&chrono::Local)
.format("%Y-%m-%d %H:%M")
.to_string()
})
.unwrap_or_else(|| "-".into())
}
fn mib(b: u64) -> String {
format!("{:.1} MiB", b as f64 / 1048576.0)
}
fn gib(b: u64) -> String {
format!("{:.1} GiB", b as f64 / 1073741824.0)
}
+44
View File
@@ -31,6 +31,12 @@ pub struct Clients {
sent: AtomicU64,
/// Total bytes written by recordings since start.
recorded: AtomicU64,
/// Bytes sent per protocol: MPEG-TS over HTTP, HLS, HTSP.
sent_ts: AtomicU64,
sent_hls: AtomicU64,
sent_htsp: AtomicU64,
/// Finished viewing sessions go here (written to the watch history).
history: Mutex<Option<tokio::sync::mpsc::UnboundedSender<crate::db::WatchRecord>>>,
}
pub struct ClientGuard {
@@ -49,6 +55,24 @@ impl ClientGuard {
impl Drop for ClientGuard {
fn drop(&mut self) {
self.owner.map.lock().unwrap().remove(&self.clients.id);
let c = &self.clients;
let ended = now();
// sessions shorter than 10 s are channel zapping / probes, not viewing
if c.kind != "recording" && ended - c.started >= 10 {
if let Some(tx) = self.owner.history.lock().unwrap().as_ref() {
let _ = tx.send(crate::db::WatchRecord {
channel_id: Some(c.channel_id).filter(|id| *id > 0),
channel_name: c.channel_name.clone(),
kind: c.kind.clone(),
who: c.who.clone(),
ip: c.ip.clone(),
device: device_name(&c.user_agent),
started: c.started,
ended,
bytes: c.bytes.load(Ordering::Relaxed) as i64,
});
}
}
}
}
@@ -63,12 +87,32 @@ pub struct NewClient<'a> {
}
impl Clients {
/// Enables the watch history (finished sessions are sent to `tx`).
pub fn set_history(&self, tx: tokio::sync::mpsc::UnboundedSender<crate::db::WatchRecord>) {
*self.history.lock().unwrap() = Some(tx);
}
fn count(&self, kind: &str, n: u64) {
if kind == "recording" {
self.recorded.fetch_add(n, Ordering::Relaxed);
} else {
self.sent.fetch_add(n, Ordering::Relaxed);
match kind {
"hls" => &self.sent_hls,
"htsp" => &self.sent_htsp,
_ => &self.sent_ts,
}
.fetch_add(n, Ordering::Relaxed);
}
}
/// Bytes sent since start per protocol: (TS over HTTP, HLS, HTSP).
pub fn by_protocol(&self) -> (u64, u64, u64) {
(
self.sent_ts.load(Ordering::Relaxed),
self.sent_hls.load(Ordering::Relaxed),
self.sent_htsp.load(Ordering::Relaxed),
)
}
/// (bytes sent to clients, bytes recorded) since start.
+195 -3
View File
@@ -181,6 +181,33 @@ pub struct AccessToken {
pub last_used: Option<i64>,
}
/// A panel session (signed-in browser).
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct SessionInfo {
pub token_hash: String,
pub user_id: i64,
pub username: String,
pub created_at: i64,
pub expires_at: i64,
pub last_seen: i64,
pub ip: String,
pub user_agent: String,
}
/// A finished viewing session.
#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
pub struct WatchRecord {
pub channel_id: Option<i64>,
pub channel_name: String,
pub kind: String,
pub who: String,
pub ip: String,
pub device: String,
pub started: i64,
pub ended: i64,
pub bytes: i64,
}
/// New EPG event to store.
#[derive(Debug, Clone)]
pub struct NewEpg {
@@ -224,6 +251,65 @@ impl Db {
Ok(Db { pool })
}
// ------------------------------------------------------------ maintenance (CLI)
/// Closes the pool (checkpoints the WAL).
pub async fn close(&self) {
self.pool.close().await;
}
/// Consistent copy of the database (safe while the server is running).
pub async fn backup_to(&self, path: &std::path::Path) -> Result<()> {
sqlx::query("VACUUM INTO ?")
.bind(path.to_string_lossy().to_string())
.execute(&self.pool)
.await?;
Ok(())
}
/// `PRAGMA integrity_check` – "ok" or the list of problems.
pub async fn integrity_check(&self) -> Result<Vec<String>> {
Ok(sqlx::query_scalar("PRAGMA integrity_check")
.fetch_all(&self.pool)
.await?)
}
pub async fn vacuum(&self) -> Result<()> {
sqlx::query("VACUUM").execute(&self.pool).await?;
Ok(())
}
/// Signs a user out everywhere.
pub async fn delete_user_sessions(&self, user_id: i64) -> Result<u64> {
Ok(sqlx::query("DELETE FROM sessions WHERE user_id = ?")
.bind(user_id)
.execute(&self.pool)
.await?
.rows_affected())
}
/// Row counts of the main tables (for `simply-dvb status`).
pub async fn table_counts(&self) -> Result<Vec<(&'static str, i64)>> {
let mut out = Vec::new();
for t in [
"muxes",
"services",
"channels",
"epg_events",
"recordings",
"autorec",
"users",
"access_tokens",
] {
let n: i64 = sqlx::query_scalar(&format!("SELECT COUNT(*) FROM {t}"))
.fetch_one(&self.pool)
.await
.unwrap_or(-1);
out.push((t, n));
}
Ok(out)
}
// ------------------------------------------------------------ settings
pub async fn get_setting(&self, key: &str) -> Result<Option<String>> {
@@ -323,14 +409,17 @@ impl Db {
user_id: i64,
ttl: i64,
ip: &str,
user_agent: &str,
) -> Result<()> {
let n = now();
sqlx::query("INSERT INTO sessions(token_hash, user_id, created_at, expires_at, ip) VALUES(?, ?, ?, ?, ?)")
sqlx::query("INSERT INTO sessions(token_hash, user_id, created_at, expires_at, ip, user_agent, last_seen) VALUES(?, ?, ?, ?, ?, ?, ?)")
.bind(token_hash)
.bind(user_id)
.bind(n)
.bind(n + ttl)
.bind(ip)
.bind(user_agent.chars().take(300).collect::<String>())
.bind(n)
.execute(&self.pool)
.await?;
sqlx::query("DELETE FROM sessions WHERE expires_at < ?")
@@ -341,15 +430,118 @@ impl Db {
}
pub async fn session_user(&self, token_hash: &str) -> Result<Option<User>> {
Ok(sqlx::query_as(
let n = now();
let u: Option<User> = sqlx::query_as(
"SELECT u.* FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.token_hash = ? AND s.expires_at > ?",
)
.bind(token_hash)
.bind(now())
.bind(n)
.fetch_optional(&self.pool)
.await?;
if u.is_some() {
// "last active" for the device list – at most one write a minute per session
sqlx::query("UPDATE sessions SET last_seen = ? WHERE token_hash = ? AND last_seen < ?")
.bind(n)
.bind(token_hash)
.bind(n - 60)
.execute(&self.pool)
.await?;
}
Ok(u)
}
/// Panel sessions (of one user, or of everybody).
pub async fn sessions(&self, user_id: Option<i64>) -> Result<Vec<SessionInfo>> {
Ok(sqlx::query_as(
"SELECT s.token_hash, s.user_id, u.username, s.created_at, s.expires_at, s.last_seen, s.ip, s.user_agent
FROM sessions s JOIN users u ON u.id = s.user_id
WHERE s.expires_at > ? AND (? IS NULL OR s.user_id = ?)
ORDER BY s.last_seen DESC",
)
.bind(now())
.bind(user_id)
.bind(user_id)
.fetch_all(&self.pool)
.await?)
}
/// Ends sessions whose hash starts with `prefix` (optionally only one user's).
pub async fn delete_session_prefix(&self, prefix: &str, user_id: Option<i64>) -> Result<u64> {
if prefix.len() < 12 || !prefix.chars().all(|c| c.is_ascii_hexdigit()) {
return Ok(0);
}
Ok(sqlx::query(
"DELETE FROM sessions WHERE substr(token_hash, 1, ?) = ? AND (? IS NULL OR user_id = ?)",
)
.bind(prefix.len() as i64)
.bind(prefix)
.bind(user_id)
.bind(user_id)
.execute(&self.pool)
.await?
.rows_affected())
}
/// Ends all sessions of a user except the given one.
pub async fn delete_other_sessions(&self, user_id: i64, keep_hash: &str) -> Result<u64> {
Ok(
sqlx::query("DELETE FROM sessions WHERE user_id = ? AND token_hash <> ?")
.bind(user_id)
.bind(keep_hash)
.execute(&self.pool)
.await?
.rows_affected(),
)
}
// ------------------------------------------------------------ watch history
pub async fn add_watch(&self, w: &WatchRecord) -> Result<()> {
sqlx::query(
"INSERT INTO watch_history(channel_id, channel_name, kind, who, ip, device, started, ended, bytes)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
)
.bind(w.channel_id)
.bind(&w.channel_name)
.bind(&w.kind)
.bind(&w.who)
.bind(&w.ip)
.bind(&w.device)
.bind(w.started)
.bind(w.ended)
.bind(w.bytes)
.execute(&self.pool)
.await?;
Ok(())
}
/// Viewing sessions that overlap [from, to).
pub async fn watch_history(&self, from: i64, to: i64) -> Result<Vec<WatchRecord>> {
Ok(sqlx::query_as(
"SELECT channel_id, channel_name, kind, who, ip, device, started, ended, bytes
FROM watch_history WHERE ended > ? AND started < ? ORDER BY started",
)
.bind(from)
.bind(to)
.fetch_all(&self.pool)
.await?)
}
pub async fn prune_watch_history(&self, before: i64) -> Result<u64> {
Ok(sqlx::query("DELETE FROM watch_history WHERE ended < ?")
.bind(before)
.execute(&self.pool)
.await?
.rows_affected())
}
pub async fn clear_watch_history(&self) -> Result<u64> {
Ok(sqlx::query("DELETE FROM watch_history")
.execute(&self.pool)
.await?
.rows_affected())
}
pub async fn delete_session(&self, token_hash: &str) -> Result<()> {
sqlx::query("DELETE FROM sessions WHERE token_hash = ?")
.bind(token_hash)
+276 -1
View File
@@ -1,7 +1,7 @@
//! Native Linux DVB API v5 support (frontend, demux, dvr) via ioctl.
//! Tested hardware: Silicon Labs Si2168 (DVB-T/T2/C) with an Si2157 tuner.
use super::{DeliverySystem, SignalStatus, Source, TuneParams};
use super::{DeliverySystem, DeviceDetails, SignalStatus, Source, TuneParams, TunedInfo};
use anyhow::{bail, Context, Result};
use std::ffi::CString;
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
@@ -20,6 +20,10 @@ const FE_SET_PROPERTY: u64 = 0x4008_6f52;
#[cfg(target_pointer_width = "32")]
const FE_GET_PROPERTY: u64 = 0x8008_6f53;
const DMX_STOP: u64 = 0x6f2a;
const DMX_START: u64 = 0x6f29;
/// _IOW('o', 51, __u16) / _IOW('o', 52, __u16)
const DMX_ADD_PID: u64 = 0x4002_6f33;
const DMX_REMOVE_PID: u64 = 0x4002_6f34;
const DMX_SET_PES_FILTER: u64 = 0x4014_6f2c;
const BATCH_BYTES: usize = 188 * 256;
const BATCH_WAIT: Duration = Duration::from_millis(15);
@@ -41,7 +45,10 @@ const DTV_STREAM_ID: u32 = 42;
const DTV_ENUM_DELSYS: u32 = 44;
const DTV_STAT_SIGNAL_STRENGTH: u32 = 62;
const DTV_STAT_CNR: u32 = 63;
const DTV_STAT_POST_ERROR_BIT_COUNT: u32 = 66;
const DTV_STAT_POST_TOTAL_BIT_COUNT: u32 = 67;
const DTV_STAT_ERROR_BLOCK_COUNT: u32 = 68;
const DTV_STAT_TOTAL_BLOCK_COUNT: u32 = 69;
const SYS_DVBC_ANNEX_A: u32 = 1;
const SYS_DVBT: u32 = 3;
@@ -59,6 +66,8 @@ const NO_STREAM_ID_FILTER: u32 = u32::MAX;
const FE_HAS_SIGNAL: u32 = 0x01;
const FE_HAS_CARRIER: u32 = 0x02;
const FE_HAS_VITERBI: u32 = 0x04;
const FE_HAS_SYNC: u32 = 0x08;
const FE_HAS_LOCK: u32 = 0x10;
const FE_SCALE_DECIBEL: u8 = 1;
@@ -213,6 +222,10 @@ pub struct LinuxSource {
demux: Option<OwnedFd>,
dvr: Option<OwnedFd>,
overflows: u64,
/// PIDs passed by the kernel demux (None = whole multiplex).
pids: Option<std::collections::BTreeSet<u16>>,
/// The driver refused PID lists – stay on the whole multiplex.
pid_filter_failed: bool,
}
impl LinuxSource {
@@ -228,6 +241,8 @@ impl LinuxSource {
demux: None,
dvr: None,
overflows: 0,
pids: None,
pid_filter_failed: false,
})
}
@@ -274,6 +289,47 @@ impl LinuxSource {
}
}
impl LinuxSource {
fn pes_filter(&self, pid: u16, start: bool) -> std::io::Result<()> {
let Some(dmx) = &self.demux else {
return Ok(());
};
let mut f = DmxPesFilterParams {
pid,
input: 0,
output: 2,
pes_type: 20,
flags: if start { 4 } else { 0 },
};
unsafe { ioctl(dmx, DMX_SET_PES_FILTER, &mut f) }
}
fn pid_op(&self, op: u64, pid: u16) -> std::io::Result<()> {
let Some(dmx) = &self.demux else {
return Ok(());
};
let mut p = pid;
unsafe { ioctl(dmx, op, &mut p) }
}
fn raw(&self, op: u64) {
if let Some(d) = &self.demux {
unsafe {
let _ = libc::ioctl(d.as_raw_fd(), op as _);
}
}
}
/// Back to the whole multiplex (also the fallback after any PID-list error).
fn full_ts(&mut self) {
self.raw(DMX_STOP);
if let Err(e) = self.pes_filter(0x2000, true) {
tracing::warn!("{}: DMX_SET_PES_FILTER (full TS): {e}", self.path);
}
self.pids = None;
}
}
impl Drop for LinuxSource {
fn drop(&mut self) {
if let Some(d) = &self.demux {
@@ -350,6 +406,217 @@ impl Source for LinuxSource {
fn status(&mut self) -> SignalStatus {
self.read_status_full()
}
fn set_pids(&mut self, pids: Option<&[u16]>) -> bool {
if self.demux.is_none() || self.pid_filter_failed {
return false;
}
let Some(list) = pids.filter(|l| !l.is_empty()) else {
if self.pids.is_some() {
self.full_ts();
}
return true;
};
let want: std::collections::BTreeSet<u16> = list.iter().copied().collect();
if self.pids.as_ref() == Some(&want) {
return true;
}
let result = match self.pids.clone() {
// switching from the whole multiplex: one short restart of the demux
None => (|| -> std::io::Result<()> {
self.raw(DMX_STOP);
let mut it = want.iter();
self.pes_filter(*it.next().unwrap(), false)?;
for p in it {
self.pid_op(DMX_ADD_PID, *p)?;
}
if unsafe { libc::ioctl(self.demux.as_ref().unwrap().as_raw_fd(), DMX_START as _) }
< 0
{
return Err(std::io::Error::last_os_error());
}
Ok(())
})(),
// already filtering: add/remove without interrupting the running stream
Some(cur) => (|| -> std::io::Result<()> {
for p in want.difference(&cur) {
self.pid_op(DMX_ADD_PID, *p)?;
}
for p in cur.difference(&want) {
self.pid_op(DMX_REMOVE_PID, *p)?;
}
Ok(())
})(),
};
match result {
Ok(()) => {
tracing::debug!("{}: PID filter {:?}", self.path, want);
self.pids = Some(want);
true
}
Err(e) => {
tracing::warn!(
"{}: kernel PID filtering not available ({e}) – reading the whole multiplex",
self.path
);
self.pid_filter_failed = true;
self.full_ts();
false
}
}
}
fn tuned_info(&mut self) -> Option<TunedInfo> {
let mut props = [
DtvProperty::new(DTV_MODULATION, 0),
DtvProperty::new(DTV_CODE_RATE_HP, 0),
DtvProperty::new(DTV_GUARD_INTERVAL, 0),
DtvProperty::new(DTV_TRANSMISSION_MODE, 0),
];
get_props(&self.fe, &mut props).ok()?;
let v = |p: &DtvProperty| {
let u = p.u;
u32::from_ne_bytes([u[0], u[1], u[2], u[3]])
};
let modulation = match v(&props[0]) {
0 => Some("QPSK"),
1 => Some("QAM-16"),
2 => Some("QAM-32"),
3 => Some("QAM-64"),
4 => Some("QAM-128"),
5 => Some("QAM-256"),
_ => None,
};
let code_rate = match v(&props[1]) {
1 => Some("1/2"),
2 => Some("2/3"),
3 => Some("3/4"),
4 => Some("4/5"),
5 => Some("5/6"),
6 => Some("6/7"),
7 => Some("7/8"),
8 => Some("8/9"),
10 => Some("3/5"),
11 => Some("9/10"),
12 => Some("2/5"),
13 => Some("1/3"),
_ => None,
};
let guard_interval = match v(&props[2]) {
0 => Some("1/32"),
1 => Some("1/16"),
2 => Some("1/8"),
3 => Some("1/4"),
5 => Some("1/128"),
6 => Some("19/128"),
7 => Some("19/256"),
_ => None,
};
let transmission_mode = match v(&props[3]) {
0 => Some("2k"),
1 => Some("8k"),
3 => Some("4k"),
4 => Some("1k"),
5 => Some("16k"),
6 => Some("32k"),
_ => None,
};
let t = TunedInfo {
modulation: modulation.map(Into::into),
code_rate: code_rate.map(Into::into),
guard_interval: guard_interval.map(Into::into),
transmission_mode: transmission_mode.map(Into::into),
};
(t != TunedInfo::default()).then_some(t)
}
}
/// Bus/driver/product from sysfs and the frequency range/capabilities from FE_GET_INFO.
pub fn details(adapter_path: &str) -> DeviceDetails {
let mut d = DeviceDetails::default();
let num = adapter_path
.rsplit("adapter")
.next()
.and_then(|n| n.parse::<u32>().ok());
if let Ok(fe) = open_dev(
&format!("{adapter_path}/frontend0"),
libc::O_RDONLY | libc::O_NONBLOCK,
) {
let mut info = FeInfo {
name: [0; 128],
rest: [0; 10],
};
if unsafe { ioctl(&fe, FE_GET_INFO, &mut info) }.is_ok() {
// terrestrial/cable frontends report Hz
if info.rest[1] > 0 {
d.freq_min_mhz = Some(info.rest[1] as f64 / 1e6);
}
if info.rest[2] > 0 {
d.freq_max_mhz = Some(info.rest[2] as f64 / 1e6);
}
let caps = info.rest[9];
for (bit, name) in [
(0x1, "inversion auto"),
(0x200, "FEC auto"),
(0x10000, "QAM auto"),
(0x20000, "transmission mode auto"),
(0x40000, "bandwidth auto"),
(0x80000, "guard interval auto"),
(0x100000, "hierarchy auto"),
(0x10000000, "multistream (PLP)"),
(0x20000000, "2nd generation (T2/C2/S2)"),
] {
if caps & bit != 0 {
d.caps.push(name.into());
}
}
}
}
let Some(num) = num else {
return d;
};
let dev = std::path::PathBuf::from(format!("/sys/class/dvb/dvb{num}.frontend0/device"));
let link_name = |p: std::path::PathBuf| {
std::fs::read_link(p)
.ok()
.and_then(|l| l.file_name().map(|n| n.to_string_lossy().to_string()))
};
d.driver = link_name(dev.join("driver"));
d.bus = link_name(dev.join("subsystem"));
let read = |p: std::path::PathBuf| {
std::fs::read_to_string(p)
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
};
match d.bus.as_deref() {
Some("usb") => {
// the frontend hangs off a USB interface; vendor data sits on its parent device
let base = std::fs::canonicalize(&dev).unwrap_or(dev.clone());
let usb = if base.join("idVendor").exists() {
base
} else {
base.parent().map(|p| p.to_path_buf()).unwrap_or(base)
};
d.vendor = read(usb.join("manufacturer"));
d.product = read(usb.join("product"));
d.usb_speed = read(usb.join("speed"));
if let (Some(v), Some(p)) = (read(usb.join("idVendor")), read(usb.join("idProduct"))) {
d.ids = Some(format!("{v}:{p}"));
}
}
Some("pci") => {
let hex = |p| read(dev.join(p)).map(|s| s.trim_start_matches("0x").to_string());
if let (Some(v), Some(p)) = (hex("vendor"), hex("device")) {
d.ids = Some(format!("{v}:{p}"));
}
if let (Some(v), Some(p)) = (hex("subsystem_vendor"), hex("subsystem_device")) {
d.product = Some(format!("subsystem {v}:{p}"));
}
}
_ => {}
}
d
}
impl LinuxSource {
@@ -410,12 +677,17 @@ impl LinuxSource {
locked: st & FE_HAS_LOCK != 0,
has_signal: st & FE_HAS_SIGNAL != 0,
has_carrier: st & FE_HAS_CARRIER != 0,
has_viterbi: st & FE_HAS_VITERBI != 0,
has_sync: st & FE_HAS_SYNC != 0,
..Default::default()
};
let mut props = [
DtvProperty::new(DTV_STAT_SIGNAL_STRENGTH, 0),
DtvProperty::new(DTV_STAT_CNR, 0),
DtvProperty::new(DTV_STAT_ERROR_BLOCK_COUNT, 0),
DtvProperty::new(DTV_STAT_POST_ERROR_BIT_COUNT, 0),
DtvProperty::new(DTV_STAT_POST_TOTAL_BIT_COUNT, 0),
DtvProperty::new(DTV_STAT_TOTAL_BLOCK_COUNT, 0),
];
if get_props(&self.fe, &mut props).is_ok() {
for (i, p) in props.iter().enumerate() {
@@ -431,6 +703,9 @@ impl LinuxSource {
(1, FE_SCALE_DECIBEL) => s.snr_db = Some(raw as i64 as f64 / 1000.0),
(1, FE_SCALE_RELATIVE) => s.snr_pct = Some(raw as f64 * 100.0 / 65535.0),
(2, FE_SCALE_COUNTER) => s.uncorrected = Some(raw),
(3, FE_SCALE_COUNTER) => s.post_bit_errors = Some(raw),
(4, FE_SCALE_COUNTER) => s.post_bit_total = Some(raw),
(5, FE_SCALE_COUNTER) => s.block_total = Some(raw),
_ => {}
}
}
+68
View File
@@ -94,6 +94,65 @@ pub struct SignalStatus {
pub snr_pct: Option<f64>,
/// Uncorrected block counter.
pub uncorrected: Option<u64>,
/// Viterbi/inner FEC is stable (FE_HAS_VITERBI).
pub has_viterbi: bool,
/// Sync bytes found (FE_HAS_SYNC).
pub has_sync: bool,
/// Bit errors after the inner FEC and the number of bits counted (cumulative).
pub post_bit_errors: Option<u64>,
pub post_bit_total: Option<u64>,
/// Total blocks counted (pairs with `uncorrected`).
pub block_total: Option<u64>,
/// Bit error rate over the last measuring interval (computed from the counters).
pub ber: Option<f64>,
}
/// Transmission parameters reported by the demodulator after lock (None = not reported).
#[derive(Debug, Clone, Default, Serialize, PartialEq)]
pub struct TunedInfo {
pub modulation: Option<String>,
pub code_rate: Option<String>,
pub guard_interval: Option<String>,
pub transmission_mode: Option<String>,
}
/// Hardware details of a DVB adapter (bus, driver, product, frequency range).
#[derive(Debug, Clone, Default, Serialize)]
pub struct DeviceDetails {
/// usb, pci, platform…
pub bus: Option<String>,
/// Kernel bridge driver, e.g. dvb_usb_dvbsky, cx23885, smipcie.
pub driver: Option<String>,
pub vendor: Option<String>,
pub product: Option<String>,
/// vendor:product ids, e.g. 0572:c68a
pub ids: Option<String>,
/// USB link speed (Mbit/s)
pub usb_speed: Option<String>,
pub freq_min_mhz: Option<f64>,
pub freq_max_mhz: Option<f64>,
pub caps: Vec<String>,
}
/// Hardware details (cached – they do not change while the adapter exists).
pub fn device_details(info: &AdapterInfo) -> DeviceDetails {
use std::sync::{Mutex, OnceLock};
static CACHE: OnceLock<Mutex<std::collections::HashMap<String, DeviceDetails>>> =
OnceLock::new();
let cache = CACHE.get_or_init(Default::default);
if let Some(d) = cache.lock().unwrap().get(&info.path) {
return d.clone();
}
let d = match info.kind.as_str() {
"linux" => linux::details(&info.path),
_ => DeviceDetails {
bus: Some("virtual".into()),
driver: Some("simply-dvb (.ts files)".into()),
..Default::default()
},
};
cache.lock().unwrap().insert(info.path.clone(), d.clone());
d
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
@@ -113,6 +172,15 @@ pub trait Source: Send {
/// Reads TS data (blocking with a short timeout). 0 = no data.
fn read(&mut self, buf: &mut [u8]) -> anyhow::Result<usize>;
fn status(&mut self) -> SignalStatus;
/// Parameters the demodulator found (modulation, FEC…), if it reports them.
fn tuned_info(&mut self) -> Option<TunedInfo> {
None
}
/// Limits the data read from the tuner to these PIDs (`None` = the whole multiplex).
/// Returns false when the source cannot filter (it then keeps delivering everything).
fn set_pids(&mut self, _pids: Option<&[u16]>) -> bool {
false
}
}
/// Opens the source for the given adapter.
+6
View File
@@ -124,6 +124,12 @@ impl Source for VirtualSource {
snr_db: self.locked.then_some(28.5),
snr_pct: None,
uncorrected: self.locked.then_some(0),
has_viterbi: self.locked,
has_sync: self.locked,
post_bit_errors: self.locked.then_some(0),
post_bit_total: self.locked.then_some(0),
block_total: None,
ber: self.locked.then_some(0.0),
}
}
}
+5 -1
View File
@@ -108,7 +108,11 @@ pub async fn grabber_task(state: State) {
break;
}
state.epg_status.lock().unwrap().grabbing_mux = Some(mux.id);
match state.tuners.subscribe(&mux, Priority::Background).await {
match state
.tuners
.subscribe_pids(&mux, Priority::Background, Some(vec![]))
.await
{
Ok(mut sub) => {
tracing::info!("EPG: grabbing from {}", mux.params().describe());
let until = Instant::now() + Duration::from_secs(s.epg_grab_seconds as u64);
+104 -55
View File
@@ -1,9 +1,11 @@
mod cli;
use anyhow::{bail, Context, Result};
use clap::{Parser, Subcommand};
use simply_dvb::app::{AppState, Options};
use simply_dvb::db::Db;
use simply_dvb::{auth, dvb, epg, recorder, web};
use std::io::{BufRead, Write};
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
@@ -60,11 +62,42 @@ enum Cmd {
#[arg(long, env = "SIMPLY_DVB_HTSP_LISTEN", default_value = "0.0.0.0:9982")]
htsp_listen: String,
},
/// Manage panel users
/// Panel users: list, add, passwd, reset-admin (forgotten password), role, logout, delete
User {
#[command(subcommand)]
cmd: UserCmd,
cmd: cli::UserCmd,
},
/// Access tokens for TV apps and players: list, add, enable, disable, delete
Token {
#[command(subcommand)]
cmd: cli::TokenCmd,
},
/// Who may reach the panel and streams (incl. reset-panel when locked out)
Access {
#[command(subcommand)]
cmd: cli::AccessCmd,
},
/// Show or change settings
Settings {
#[command(subcommand)]
cmd: cli::SettingsCmd,
},
/// Channels: list, m3u, enable, disable
Channels {
#[command(subcommand)]
cmd: cli::ChannelCmd,
},
/// Database: check, vacuum, backup, restore
Db {
#[command(subcommand)]
cmd: cli::DbCmd,
},
/// Overview: version, server state, counts, next recording, adapters
Status,
/// Health check: data directory, database, adapters and permissions, disk, ffmpeg
Doctor,
/// Shell completion script, e.g. `simply-dvb completions bash > /etc/bash_completion.d/simply-dvb`
Completions { shell: clap_complete::Shell },
/// List detected DVB adapters
Adapters,
/// Quick tuner test: tune a frequency and list its services
@@ -98,34 +131,18 @@ enum Cmd {
},
}
#[derive(Subcommand)]
enum UserCmd {
/// Adds a user (password read from standard input)
Add {
name: String,
#[arg(long, default_value = "admin")]
role: String,
},
/// Changes a user's password (password read from standard input)
Passwd { name: String },
/// List users
List,
}
fn read_password() -> Result<String> {
eprint!("Password: ");
std::io::stderr().flush().ok();
let mut line = String::new();
std::io::stdin().lock().read_line(&mut line)?;
let pw = line.trim_end_matches(['\r', '\n']).to_string();
if pw.chars().count() < 8 {
bail!("password must be at least 8 characters");
}
Ok(pw)
}
#[tokio::main]
async fn main() -> Result<()> {
async fn main() -> std::process::ExitCode {
match run().await {
Ok(()) => std::process::ExitCode::SUCCESS,
Err(e) => {
eprintln!("Error: {e:#}");
std::process::ExitCode::from(2)
}
}
}
async fn run() -> Result<()> {
{
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
@@ -195,33 +212,43 @@ async fn main() -> Result<()> {
opts.htsp_port = htsp.map(|a| a.port());
serve(opts, listen, stream, htsp).await
}
Cmd::User { cmd } => {
let db = open_db(&opts).await?;
match cmd {
UserCmd::Add { name, role } => {
if role != "admin" && role != "viewer" {
bail!("role: admin or viewer");
}
let pw = read_password()?;
db.create_user(&name, &auth::hash_password(&pw)?, &role)
.await?;
println!("User {name} added ({role})");
}
UserCmd::Passwd { name } => {
let u = db.user_by_name(&name).await?.context("no such user")?;
let pw = read_password()?;
db.update_user(u.id, Some(&auth::hash_password(&pw)?), None)
.await?;
println!("Password changed for user {name}");
}
UserCmd::List => {
for u in db.users().await? {
println!("{}\t{}", u.username, u.role);
}
}
}
Cmd::Db {
cmd: cli::DbCmd::Restore { file },
} => cli::restore(&opts, &file),
Cmd::Completions { shell } => {
use clap::CommandFactory;
clap_complete::generate(
shell,
&mut Cli::command(),
"simply-dvb",
&mut std::io::stdout(),
);
Ok(())
}
cmd @ (Cmd::User { .. }
| Cmd::Token { .. }
| Cmd::Access { .. }
| Cmd::Settings { .. }
| Cmd::Channels { .. }
| Cmd::Db { .. }
| Cmd::Status
| Cmd::Doctor) => {
let db = open_db(&opts).await?;
let r = match cmd {
Cmd::User { cmd } => cli::user(&db, cmd).await,
Cmd::Token { cmd } => cli::token(&db, cmd).await,
Cmd::Access { cmd } => cli::access(&db, cmd).await,
Cmd::Settings { cmd } => cli::settings(&db, cmd).await,
Cmd::Channels { cmd } => cli::channel(&db, cmd).await,
Cmd::Db { cmd } => cli::database(&db, &opts, cmd).await,
Cmd::Status => cli::status(&db, &opts).await,
Cmd::Doctor => cli::doctor(&db, &opts).await,
_ => unreachable!(),
};
db.close().await;
cli::fix_db_ownership(&opts);
r
}
Cmd::Adapters => {
let list = dvb::discover(&opts.dev_root);
if list.is_empty() {
@@ -467,6 +494,28 @@ async fn serve(
tokio::spawn(simply_dvb::stats::sampler_task(state.clone()));
tokio::spawn(simply_dvb::scanjob::idle_scan_task(state.clone()));
tokio::spawn(simply_dvb::acl::resolver_task(state.clone()));
{
// watch history writer (+ keeps one year)
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<simply_dvb::db::WatchRecord>();
state.clients.set_history(tx);
let st = state.clone();
tokio::spawn(async move {
let mut pruned = std::time::Instant::now() - Duration::from_secs(86_400);
while let Some(w) = rx.recv().await {
if let Err(e) = st.db.add_watch(&w).await {
tracing::warn!("watch history: {e:#}");
}
if pruned.elapsed() > Duration::from_secs(86_400) {
pruned = std::time::Instant::now();
let _ = st
.db
.prune_watch_history(simply_dvb::db::now() - 366 * 86_400)
.await;
}
}
});
}
tokio::spawn(state.clone().settings_watch());
{
let st = state.clone();
tokio::spawn(async move {
+27 -3
View File
@@ -15,7 +15,7 @@ use tokio::task::JoinHandle;
pub const PROFILES: &[(&str, &str)] = &[
("pass", "Original (no transcoding)"),
("aac", "Video unchanged, audio → AAC (browsers)"),
("aac", "Video unchanged, audio converted to AAC (browsers)"),
("h264", "Full transcoding to H.264 720p + AAC"),
];
@@ -75,6 +75,22 @@ pub async fn resolve(state: &State, channel_id: i64) -> Result<ChannelSource> {
})
}
/// Tells the tuner which PIDs this client needs whenever the service's PMT changes.
#[derive(Default)]
struct PidFollower {
last: Option<Vec<u16>>,
}
impl PidFollower {
fn check(&mut self, filter: &ServiceFilter, sub: &crate::tuner::Subscription) {
let want = filter.wanted_pids();
if want != self.last {
sub.want_pids(want.clone());
self.last = want;
}
}
}
/// Saves the stream list of the played service once its PMT is seen, so the channel
/// list shows codecs even when the scan timed out before the PMT arrived.
struct PmtLearner {
@@ -241,11 +257,15 @@ pub async fn open_service(
}
}
let source = resolve(state, channel_id).await?;
let mut sub = state.tuners.subscribe(&source.mux, prio).await?;
let pmt_pid = source.service.pmt_pid as u16;
// PAT + PMT until the PMT names the elementary streams (see `follow_pids`)
let mut sub = state
.tuners
.subscribe_pids(&source.mux, prio, Some(vec![0, pmt_pid]))
.await?;
let adapter = sub.adapter.clone();
let (tx, rx) = mpsc::channel::<Bytes>(512);
let sid = source.service.sid as u16;
let pmt_pid = source.service.pmt_pid as u16;
let error = Arc::new(Mutex::new(String::new()));
let learn = PmtLearner::new(state, source.service.id, &source.service.streams);
@@ -255,9 +275,11 @@ pub async fn open_service(
let mut aligner = Aligner::new();
let mut out = Vec::with_capacity(188 * 400);
let mut learn = learn;
let mut follow = PidFollower::default();
while let Some(chunk) = sub.recv().await {
aligner.push(&chunk, |p| filter.push(p, &mut out));
learn.check(&filter);
follow.check(&filter, &sub);
if !out.is_empty() {
let b = Bytes::from(std::mem::replace(&mut out, Vec::with_capacity(188 * 400)));
if tx.send(b).await.is_err() {
@@ -297,9 +319,11 @@ pub async fn open_service(
let mut aligner = Aligner::new();
let mut out = Vec::with_capacity(188 * 400);
let mut learn = learn;
let mut follow = PidFollower::default();
while let Some(chunk) = sub.recv().await {
aligner.push(&chunk, |p| filter.push(p, &mut out));
learn.check(&filter);
follow.check(&filter, &sub);
if !out.is_empty() {
if stdin.write_all(&out).await.is_err() {
break;
+4
View File
@@ -42,6 +42,9 @@ pub struct Settings {
pub hls_idle_seconds: u32,
/// How many seconds a tuner stays tuned after the last client leaves.
pub tuner_linger_seconds: u32,
/// Let the kernel pass only the PIDs that clients need instead of the whole
/// multiplex (much less CPU). Off = always read the whole multiplex.
pub tuner_pid_filter: bool,
/// Default M3U format: "hls" or "ts".
pub m3u_format: String,
@@ -110,6 +113,7 @@ impl Default for Settings {
hls_window: 8,
hls_idle_seconds: 30,
tuner_linger_seconds: 8,
tuner_pid_filter: true,
m3u_format: "ts".into(),
ffmpeg_path: "ffmpeg".into(),
ffmpeg_h264_args: "-vf yadif=0:-1:1,scale=-2:720 -c:v libx264 -preset veryfast -tune zerolatency -crf 23 -g 50 -bf 0 -pix_fmt yuv420p".into(),
+51 -20
View File
@@ -30,9 +30,12 @@ pub struct Sample {
pub out_bps: f64,
/// Bytes/s written by recordings.
pub rec_bps: f64,
/// Network interfaces (without lo), bytes/s.
pub net_rx: Option<f64>,
pub net_tx: Option<f64>,
/// Bytes/s sent per protocol (only this application's traffic).
pub out_ts_bps: f64,
pub out_hls_bps: f64,
pub out_htsp_bps: f64,
/// Bytes/s received from all tuned multiplexes.
pub tuner_in_bps: f64,
pub clients: usize,
pub hls_sessions: usize,
pub tuners_active: usize,
@@ -47,6 +50,11 @@ pub struct TunerSample {
pub snr: Option<f64>,
/// Uncorrected blocks since the previous sample.
pub unc: Option<u64>,
/// Bit error rate (after inner FEC), when the driver reports it.
pub ber: Option<f64>,
/// Continuity errors / transport-error packets since the previous sample.
pub cc: u64,
pub tei: u64,
pub clients: usize,
pub locked: bool,
}
@@ -108,7 +116,6 @@ impl Stats {
/// System metrics through the `sysinfo` crate (portable, no hand-parsed /proc files).
struct SysProbe {
sys: sysinfo::System,
nets: sysinfo::Networks,
comps: sysinfo::Components,
pid: Option<sysinfo::Pid>,
}
@@ -117,7 +124,6 @@ impl SysProbe {
fn new() -> Self {
let mut p = SysProbe {
sys: sysinfo::System::new(),
nets: sysinfo::Networks::new_with_refreshed_list(),
comps: sysinfo::Components::new_with_refreshed_list(),
pid: sysinfo::get_current_pid().ok(),
};
@@ -137,7 +143,6 @@ impl SysProbe {
ProcessRefreshKind::nothing().with_cpu().with_memory(),
);
}
self.nets.refresh(true);
self.comps.refresh(false);
}
@@ -176,16 +181,6 @@ impl SysProbe {
Some(best.map_or(c, |b| b.max(c)))
})
}
/// Bytes (rx, tx) of all interfaces except loopback since the previous refresh.
fn net_delta(&self) -> (u64, u64) {
self.nets
.iter()
.filter(|(name, _)| name.as_str() != "lo")
.fold((0, 0), |(r, t), (_, d)| {
(r + d.received(), t + d.transmitted())
})
}
}
/// 1-minute load average (None where the OS has none).
@@ -198,7 +193,10 @@ pub fn load_average() -> Option<[f64; 3]> {
pub async fn sampler_task(state: State) {
let mut probe = SysProbe::new();
let (mut prev_out, mut prev_rec) = state.clients.totals();
let mut prev_proto = state.clients.by_protocol();
let mut prev_unc: HashMap<String, u64> = HashMap::new();
let mut prev_err: HashMap<String, (u64, u64)> = HashMap::new();
let mut proto_win: [VecDeque<f64>; 3] = Default::default();
let mut prev_t = std::time::Instant::now();
// HLS clients fetch whole segments, so raw per-interval throughput is spiky: average 3 intervals
let mut out_win: VecDeque<f64> = VecDeque::new();
@@ -216,8 +214,20 @@ pub async fn sampler_task(state: State) {
prev_t = std::time::Instant::now();
probe.refresh();
let (rx, tx) = probe.net_delta();
let (net_rx, net_tx) = (Some(rx as f64 / dt), Some(tx as f64 / dt));
let proto = state.clients.by_protocol();
let out_ts_bps = smooth(
&mut proto_win[0],
proto.0.saturating_sub(prev_proto.0) as f64 / dt,
);
let out_hls_bps = smooth(
&mut proto_win[1],
proto.1.saturating_sub(prev_proto.1) as f64 / dt,
);
let out_htsp_bps = smooth(
&mut proto_win[2],
proto.2.saturating_sub(prev_proto.2) as f64 / dt,
);
prev_proto = proto;
let (out, rec) = state.clients.totals();
let out_bps = smooth(&mut out_win, out.saturating_sub(prev_out) as f64 / dt);
let rec_bps = smooth(&mut rec_win, rec.saturating_sub(prev_rec) as f64 / dt);
@@ -240,9 +250,23 @@ pub async fn sampler_task(state: State) {
prev_unc.insert(s.id.clone(), u);
d
});
let (cc, tei) = {
let p = prev_err
.get(&s.id)
.copied()
.unwrap_or((a.ts.cc_errors, a.ts.tei_errors));
prev_err.insert(s.id.clone(), (a.ts.cc_errors, a.ts.tei_errors));
(
a.ts.cc_errors.saturating_sub(p.0),
a.ts.tei_errors.saturating_sub(p.1),
)
};
TunerSample {
t,
bitrate: a.bitrate_bps,
ber: a.signal.ber,
cc,
tei,
strength: a.signal.strength_pct,
strength_dbm: a.signal.strength_dbm,
snr: a.signal.snr_db,
@@ -253,6 +277,7 @@ pub async fn sampler_task(state: State) {
}
None => {
prev_unc.remove(&s.id);
prev_err.remove(&s.id);
TunerSample {
t,
..Default::default()
@@ -271,8 +296,14 @@ pub async fn sampler_task(state: State) {
load1: load_average().map(|l| l[0]),
out_bps,
rec_bps,
net_rx,
net_tx,
out_ts_bps,
out_hls_bps,
out_htsp_bps,
tuner_in_bps: tuner_status
.iter()
.filter_map(|s| s.active.as_ref())
.map(|a| a.bitrate_bps as f64 / 8.0)
.sum(),
clients: state
.clients
.list()
+16
View File
@@ -84,6 +84,18 @@ impl ServiceFilter {
self.pmt_out.psi(&pmt, out);
}
/// PIDs this service needs from the tuner (PAT, PMT, PCR and its elementary
/// streams); `None` while the PMT PID is unknown (= whole multiplex).
pub fn wanted_pids(&self) -> Option<Vec<u16>> {
let pmt = self.pmt_pid?;
let mut v: Vec<u16> = self.pids.iter().copied().collect();
v.push(0);
v.push(pmt);
v.sort_unstable();
v.dedup();
Some(v)
}
/// Processes a source packet; packets belonging to the service go to `out`.
pub fn push(&mut self, pkt: &[u8], out: &mut Vec<u8>) {
let pid = packet::pid(pkt);
@@ -177,6 +189,10 @@ mod tests {
}
assert!(f.ready());
assert_eq!(f.primary().unwrap().0, b.video_pid);
let mut want = vec![0, b.pmt_pid, b.video_pid, b.audio_pid];
want.sort_unstable();
want.dedup();
assert_eq!(f.wanted_pids(), Some(want));
let mut si = SiCollector::new(false);
let mut pids = HashSet::new();
for p in out.chunks(188) {
+5
View File
@@ -57,6 +57,11 @@ impl SiCollector {
|| self.pmt_pids.contains_key(&pid)
}
/// PMT PIDs announced in the PAT.
pub fn pmt_pid_list(&self) -> Vec<u16> {
self.pmt_pids.keys().copied().collect()
}
pub fn push(&mut self, pkt: &[u8]) {
let pid = packet::pid(pkt);
if !self.wants(pid) {
+237 -5
View File
@@ -41,9 +41,87 @@ pub struct Active {
bitrate: AtomicU64,
started: Instant,
state: watch::Receiver<TuneState>,
ts: Mutex<TsStatus>,
tuned: Mutex<Option<dvb::TunedInfo>>,
/// PIDs each subscription needs (None = whole multiplex) and a change counter.
wanted: Mutex<HashMap<u64, Option<Vec<u16>>>>,
wanted_ver: AtomicU64,
/// Whether the source is currently limited to a PID list.
pub filtered: AtomicBool,
}
/// Transport stream health of the tuned multiplex (counted since tuning).
#[derive(Debug, Clone, Default, Serialize)]
pub struct TsStatus {
pub packets: u64,
/// Continuity counter jumps = lost/damaged packets.
pub cc_errors: u64,
/// Packets flagged by the demodulator as uncorrectable (transport error indicator).
pub tei_errors: u64,
/// Stuffing packets (PID 0x1FFF), i.e. unused capacity.
pub null_packets: u64,
/// Packets with scrambled payload.
pub scrambled: u64,
/// Distinct PIDs seen.
pub pids: usize,
}
/// Per-packet checks for [`TsStatus`].
struct TsCheck {
last_cc: Vec<u8>,
st: TsStatus,
}
impl TsCheck {
fn new() -> Self {
TsCheck {
last_cc: vec![0xFF; 8192],
st: TsStatus::default(),
}
}
fn push(&mut self, p: &[u8]) {
if p.len() < 4 {
return;
}
self.st.packets += 1;
if p[1] & 0x80 != 0 {
self.st.tei_errors += 1;
return;
}
let pid = (((p[1] & 0x1F) as usize) << 8) | p[2] as usize;
if pid == 0x1FFF {
self.st.null_packets += 1;
return;
}
if p[3] & 0xC0 != 0 {
self.st.scrambled += 1;
}
let afc = (p[3] >> 4) & 3;
let cc = p[3] & 0x0F;
let prev = self.last_cc[pid];
if prev == 0xFF {
self.st.pids += 1;
self.last_cc[pid] = cc;
return;
}
// discontinuity indicator in the adaptation field resets the counter
let discontinuity = afc & 2 != 0 && p.len() > 5 && p[4] > 0 && p[5] & 0x80 != 0;
if afc & 1 != 0 {
// payload: counter must advance by one (a single duplicate is allowed)
if !discontinuity && cc != (prev + 1) & 0x0F && cc != prev {
self.st.cc_errors += 1;
}
}
self.last_cc[pid] = cc;
}
}
impl Active {
fn declare(&self, id: u64, pids: Option<Vec<u16>>) {
self.wanted.lock().unwrap().insert(id, pids);
self.wanted_ver.fetch_add(1, Ordering::Relaxed);
}
fn max_priority(&self) -> Option<Priority> {
self.subs.lock().unwrap().values().copied().max()
}
@@ -116,8 +194,30 @@ impl Subscription {
}
}
impl Subscription {
/// Declares the PIDs this client needs (`None` = the whole multiplex, the default).
/// The tuner then reads only the union of all clients' PIDs plus the SI tables.
pub fn want_pids(&self, pids: Option<Vec<u16>>) {
let mut w = self.active.wanted.lock().unwrap();
if w.get(&self.id) != Some(&pids) {
w.insert(self.id, pids);
self.active.wanted_ver.fetch_add(1, Ordering::Relaxed);
}
}
}
impl Drop for Subscription {
fn drop(&mut self) {
if self
.active
.wanted
.lock()
.unwrap()
.remove(&self.id)
.is_some()
{
self.active.wanted_ver.fetch_add(1, Ordering::Relaxed);
}
let mut subs = self.active.subs.lock().unwrap();
subs.remove(&self.id);
if subs.is_empty() {
@@ -138,6 +238,7 @@ pub struct SlotStatus {
pub priority: u64,
pub last_error: String,
pub active: Option<ActiveStatus>,
pub device: dvb::DeviceDetails,
}
#[derive(Serialize)]
@@ -150,6 +251,10 @@ pub struct ActiveStatus {
pub signal: SignalStatus,
pub bitrate_bps: u64,
pub uptime_secs: u64,
pub ts: TsStatus,
pub tuned: Option<dvb::TunedInfo>,
/// Only the PIDs clients need are read (bitrate and TS counters cover just those).
pub pid_filtered: bool,
}
/// Channel for PMTs seen while streaming: (mux id, PMTs).
@@ -160,6 +265,8 @@ pub struct TunerManager {
next_id: AtomicU64,
epg_tx: mpsc::UnboundedSender<(i64, Vec<EpgItem>)>,
pub epg_enabled: AtomicBool,
/// Kernel PID filtering (only the PIDs clients need are read from the tuner).
pub pid_filter: Arc<AtomicBool>,
pub linger: Mutex<Duration>,
/// Receives the PMTs seen while streaming (mux id, PMTs) so service stream
/// lists stay current even when a scan timed out before a PMT arrived.
@@ -173,6 +280,7 @@ impl TunerManager {
next_id: AtomicU64::new(1),
epg_tx,
epg_enabled: AtomicBool::new(true),
pid_filter: Arc::new(AtomicBool::new(true)),
linger: Mutex::new(Duration::from_secs(8)),
pmt_tx: Mutex::new(None),
})
@@ -238,6 +346,9 @@ impl TunerManager {
signal,
bitrate_bps: a.bitrate.load(Ordering::Relaxed),
uptime_secs: a.started.elapsed().as_secs(),
ts: a.ts.lock().unwrap().clone(),
tuned: a.tuned.lock().unwrap().clone(),
pid_filtered: a.filtered.load(Ordering::Relaxed),
}
});
SlotStatus {
@@ -256,6 +367,7 @@ impl TunerManager {
priority: s.priority.load(Ordering::Relaxed),
last_error: s.last_error.lock().unwrap().clone(),
active,
device: dvb::device_details(&s.info),
}
})
.collect()
@@ -362,8 +474,19 @@ impl TunerManager {
Ok(ScanGuard((*slot).clone()))
}
/// Joins a multiplex (sharing) or tunes a free adapter.
/// Joins a multiplex (sharing) or tunes a free adapter; the client gets the whole multiplex.
pub async fn subscribe(self: &Arc<Self>, mux: &Mux, prio: Priority) -> Result<Subscription> {
self.subscribe_pids(mux, prio, None).await
}
/// Like [`subscribe`](Self::subscribe), declaring the PIDs the client needs up front
/// (`Some(vec![])` = only the SI tables, e.g. EPG collection).
pub async fn subscribe_pids(
self: &Arc<Self>,
mux: &Mux,
prio: Priority,
pids: Option<Vec<u16>>,
) -> Result<Subscription> {
let params = mux.params();
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
// A background scan gives way to anything a user (or a recording) asked for.
@@ -390,6 +513,7 @@ impl TunerManager {
&& !x.is_stopped()
&& !matches!(&*x.state.borrow(), TuneState::Failed(_))
{
x.declare(id, pids.clone());
x.subs.lock().unwrap().insert(id, prio);
*x.idle_since.lock().unwrap() = None;
found = Some((x.clone(), s.info.id.clone()));
@@ -402,6 +526,7 @@ impl TunerManager {
None => {
let slot = self.pick_slot(&slots, &params, prio)?;
let active = self.start(&slot, mux.id, params.clone());
active.declare(id, pids.clone());
active.subs.lock().unwrap().insert(id, prio);
(active, slot.info.id.clone())
}
@@ -498,6 +623,11 @@ impl TunerManager {
subs: Mutex::new(HashMap::new()),
idle_since: Mutex::new(None),
signal: Mutex::new(SignalStatus::default()),
ts: Mutex::new(TsStatus::default()),
tuned: Mutex::new(None),
wanted: Mutex::new(HashMap::new()),
wanted_ver: AtomicU64::new(0),
filtered: AtomicBool::new(false),
bitrate: AtomicU64::new(0),
started: Instant::now(),
state: state_rx,
@@ -508,6 +638,7 @@ impl TunerManager {
let a = active.clone();
let epg_tx = self.epg_tx.clone();
let collect_eit = self.epg_enabled.load(Ordering::Relaxed);
let pid_filter = self.pid_filter.clone();
let pmt_tx = self.pmt_tx.lock().unwrap().clone();
let slot2 = slot.clone();
let handle = std::thread::Builder::new()
@@ -516,7 +647,15 @@ impl TunerManager {
if let Some(p) = prev {
let _ = p.join();
}
let r = reader_thread(&info, &a, &state_tx, epg_tx, pmt_tx, collect_eit);
let r = reader_thread(
&info,
&a,
&state_tx,
epg_tx,
pmt_tx,
collect_eit,
&pid_filter,
);
if let Err(e) = r {
let msg = format!("{e:#}");
tracing::warn!("{}: {}", info.id, msg);
@@ -568,6 +707,23 @@ impl TunerManager {
}
}
/// PIDs the tuner has to deliver: every client's PIDs plus the SI tables (PAT, NIT, SDT,
/// EIT, TDT) and all PMTs. `None` when a client needs the whole multiplex.
fn wanted_pids(a: &Active, pmts: &[u16]) -> Option<Vec<u16>> {
let w = a.wanted.lock().unwrap();
let mut set: std::collections::BTreeSet<u16> =
[0x00, 0x10, 0x11, 0x12, 0x14].into_iter().collect();
// a client that has not declared its PIDs (scan, recording of the whole mux…)
if a.subs.lock().unwrap().keys().any(|id| !w.contains_key(id)) {
return None;
}
for pids in w.values() {
set.extend(pids.as_ref()?.iter().copied());
}
set.extend(pmts.iter().copied());
Some(set.into_iter().collect())
}
fn reader_thread(
info: &AdapterInfo,
a: &Arc<Active>,
@@ -575,6 +731,7 @@ fn reader_thread(
epg_tx: mpsc::UnboundedSender<(i64, Vec<EpgItem>)>,
pmt_tx: Option<PmtSender>,
collect_eit: bool,
pid_filter: &AtomicBool,
) -> Result<()> {
let mut src = dvb::open(info)?;
tracing::info!("{}: tuning {}", info.id, a.params.describe());
@@ -582,8 +739,14 @@ fn reader_thread(
*a.signal.lock().unwrap() = src.status();
bail!("no lock on {}", a.params.describe());
}
*a.signal.lock().unwrap() = src.status();
let mut prev_sig = src.status();
*a.signal.lock().unwrap() = prev_sig.clone();
*a.tuned.lock().unwrap() = src.tuned_info();
let _ = state.send(TuneState::Locked);
let mut ts = TsCheck::new();
// PID filtering state: (subscription version, PMT PIDs known, filter on/off)
let mut applied: Option<(u64, Vec<u16>, bool)> = None;
let mut last_check = Instant::now() - Duration::from_secs(1);
let mut buf = vec![0u8; 188 * 348];
let mut si = SiCollector::new(collect_eit);
let mut aligner = Aligner::new();
@@ -594,10 +757,28 @@ fn reader_thread(
let n = src.read(&mut buf)?;
if n > 0 {
bytes += n as u64;
aligner.push(&buf[..n], |p| si.push(p));
aligner.push(&buf[..n], |p| {
ts.push(p);
si.push(p)
});
let _ = a.tx.send(Bytes::copy_from_slice(&buf[..n]));
}
// re-evaluate the PID list when clients change (cheap check, at most 10x a second)
if last_check.elapsed() >= Duration::from_millis(100) {
last_check = Instant::now();
let ver = a.wanted_ver.load(Ordering::Relaxed);
let on = pid_filter.load(Ordering::Relaxed);
let mut pmts = si.pmt_pid_list();
pmts.sort_unstable();
if applied.as_ref() != Some(&(ver, pmts.clone(), on)) {
let list = if on { wanted_pids(a, &pmts) } else { None };
let ok = src.set_pids(list.as_deref());
a.filtered.store(ok && list.is_some(), Ordering::Relaxed);
applied = Some((ver, pmts, on));
}
}
let el = last_stat.elapsed();
if el >= Duration::from_secs(2) {
a.bitrate.store(
@@ -606,7 +787,21 @@ fn reader_thread(
);
bytes = 0;
last_stat = Instant::now();
*a.signal.lock().unwrap() = src.status();
let mut sig = src.status();
sig.ber = match (
prev_sig.post_bit_errors,
sig.post_bit_errors,
prev_sig.post_bit_total,
sig.post_bit_total,
) {
(Some(e0), Some(e1), Some(t0), Some(t1)) if t1 > t0 && e1 >= e0 => {
Some((e1 - e0) as f64 / (t1 - t0) as f64)
}
_ => prev_sig.ber,
};
*a.signal.lock().unwrap() = sig.clone();
prev_sig = sig;
*a.ts.lock().unwrap() = ts.st.clone();
let items = si.take_epg();
if !items.is_empty() {
let _ = epg_tx.send((a.mux_id, items));
@@ -634,3 +829,40 @@ fn reader_thread(
tracing::debug!("{}: reader thread finished", info.id);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn pkt(pid: u16, cc: u8, afc: u8) -> [u8; 188] {
let mut p = [0xFFu8; 188];
p[0] = 0x47;
p[1] = (pid >> 8) as u8 & 0x1F;
p[2] = pid as u8;
p[3] = (afc << 4) | (cc & 0x0F);
p
}
#[test]
fn ts_check_counts_continuity_errors() {
let mut t = TsCheck::new();
for cc in 0..20u8 {
t.push(&pkt(0x100, cc, 1));
}
assert_eq!(t.st.cc_errors, 0);
t.push(&pkt(0x100, 3, 1)); // last was 19 & 15 = 3 → duplicate, allowed
t.push(&pkt(0x100, 7, 1)); // jump
assert_eq!(t.st.cc_errors, 1);
t.push(&pkt(0x100, 7, 2)); // adaptation only: counter does not advance
t.push(&pkt(0x100, 8, 1));
assert_eq!(t.st.cc_errors, 1);
t.push(&pkt(0x1FFF, 0, 1));
let mut bad = pkt(0x101, 0, 1);
bad[1] |= 0x80;
t.push(&bad);
assert_eq!(t.st.null_packets, 1);
assert_eq!(t.st.tei_errors, 1);
assert_eq!(t.st.pids, 1);
assert_eq!(t.st.packets, 26);
}
}
+365 -1
View File
@@ -85,7 +85,13 @@ pub async fn login(
let ttl = state.settings().session_hours as i64 * 3600;
state
.db
.create_session(&auth::token_hash(&token), user.id, ttl, &ip.to_string())
.create_session(
&auth::token_hash(&token),
user.id,
ttl,
&ip.to_string(),
&user_agent(&headers),
)
.await?;
tracing::info!(target: "access", "signed in {} from {ip} ({})", user.username, user_agent(&headers));
let secure = headers
@@ -119,6 +125,364 @@ pub async fn me(Extension(CurrentUser(u)): Extension<CurrentUser>) -> Js {
Json(json!(u))
}
fn require_admin(u: &crate::db::User) -> Result<(), ApiError> {
if u.role == "admin" {
Ok(())
} else {
Err(ApiError::forbidden())
}
}
/// Short public id of a session (its hash is the database key; the token itself is never stored).
fn session_id(hash: &str) -> String {
hash.chars().take(16).collect()
}
#[derive(Deserialize)]
pub struct SessionsQuery {
#[serde(default)]
all: bool,
}
/// Signed-in browsers of the current user (administrators: of everybody with `?all=1`).
pub async fn my_sessions(
AxState(state): AxState<State>,
Extension(CurrentUser(u)): Extension<CurrentUser>,
headers: HeaderMap,
Query(q): Query<SessionsQuery>,
) -> ApiResult<Value> {
let current = auth::cookie_value(&headers, SESSION_COOKIE)
.map(|t| auth::token_hash(&t))
.unwrap_or_default();
let filter = if q.all && u.role == "admin" {
None
} else {
Some(u.id)
};
let list: Vec<Value> = state
.db
.sessions(filter)
.await?
.into_iter()
.map(|s| {
json!({
"id": session_id(&s.token_hash),
"user": s.username,
"device": crate::clients::device_name(&s.user_agent),
"user_agent": s.user_agent,
"ip": s.ip,
"created": s.created_at,
"last_seen": if s.last_seen > 0 { s.last_seen } else { s.created_at },
"expires": s.expires_at,
"current": s.token_hash == current,
})
})
.collect();
Ok(Json(json!(list)))
}
/// Signs one browser out (own sessions; administrators: any).
pub async fn end_session(
AxState(state): AxState<State>,
Extension(CurrentUser(u)): Extension<CurrentUser>,
Path(id): Path<String>,
) -> ApiResult<Value> {
let owner = if u.role == "admin" { None } else { Some(u.id) };
let n = state.db.delete_session_prefix(&id, owner).await?;
if n == 0 {
return Err(ApiError(StatusCode::NOT_FOUND, "no such session".into()));
}
tracing::info!(target: "access", "{} ended session {id}", u.username);
ok()
}
/// Signs the current user out everywhere except this browser.
pub async fn end_other_sessions(
AxState(state): AxState<State>,
Extension(CurrentUser(u)): Extension<CurrentUser>,
headers: HeaderMap,
) -> ApiResult<Value> {
let current = auth::cookie_value(&headers, SESSION_COOKIE)
.map(|t| auth::token_hash(&t))
.unwrap_or_default();
let n = state.db.delete_other_sessions(u.id, &current).await?;
tracing::info!(target: "access", "{} signed out {n} other session(s)", u.username);
Ok(Json(json!({"ok": true, "ended": n})))
}
/// Downloads a consistent copy of the database (administrators).
pub async fn backup_download(
AxState(state): AxState<State>,
Extension(CurrentUser(u)): Extension<CurrentUser>,
) -> Result<Response, ApiError> {
require_admin(&u)?;
let dir = state.opts.data_dir.join("backups");
std::fs::create_dir_all(&dir).map_err(|e| ApiError::bad(e.to_string()))?;
let name = format!(
"simply-dvb-{}.db",
chrono::Local::now().format("%Y%m%d-%H%M%S")
);
let path = dir.join(format!(".download-{name}"));
let _ = std::fs::remove_file(&path);
state.db.backup_to(&path).await?;
let data = tokio::fs::read(&path)
.await
.map_err(|e| ApiError::bad(e.to_string()))?;
let _ = std::fs::remove_file(&path);
tracing::info!(target: "access", "{} downloaded a database backup ({} bytes)", u.username, data.len());
Ok((
[
(header::CONTENT_TYPE, "application/vnd.sqlite3".to_string()),
(
header::CONTENT_DISPOSITION,
format!("attachment; filename=\"{name}\""),
),
],
data,
)
.into_response())
}
#[derive(Deserialize)]
pub struct ViewingQuery {
#[serde(default = "default_days")]
days: i64,
}
fn default_days() -> i64 {
7
}
/// Viewing statistics from the watch history (administrators).
pub async fn viewing_stats(
AxState(state): AxState<State>,
Extension(CurrentUser(u)): Extension<CurrentUser>,
Query(q): Query<ViewingQuery>,
) -> ApiResult<Value> {
require_admin(&u)?;
let days = q.days.clamp(1, 366);
let to = now();
let from = to - days * 86_400;
let mut list = state.db.watch_history(from, to).await?;
// sessions running right now count too
for c in state.clients.list() {
if c.kind != "recording" {
list.push(crate::db::WatchRecord {
channel_id: Some(c.channel_id),
channel_name: c.channel_name.clone(),
kind: c.kind.clone(),
who: c.who.clone(),
ip: c.ip.clone(),
device: crate::clients::device_name(&c.user_agent),
started: c.started,
ended: to,
bytes: c.bytes.load(Ordering::Relaxed) as i64,
});
}
}
#[derive(Default)]
struct Agg {
secs: i64,
sessions: i64,
bytes: i64,
}
let mut by_channel: HashMap<String, Agg> = HashMap::new();
let mut by_who: HashMap<String, Agg> = HashMap::new();
let mut by_device: HashMap<String, Agg> = HashMap::new();
let mut by_kind: HashMap<String, Agg> = HashMap::new();
let mut by_hour = [0i64; 24];
let mut by_day: std::collections::BTreeMap<String, i64> = Default::default();
let mut total = Agg::default();
let offset = chrono::Local::now().offset().local_minus_utc() as i64;
for w in &list {
let (a, b) = (w.started.max(from), w.ended.min(to));
if b <= a {
continue;
}
let secs = b - a;
for (map, key) in [
(&mut by_channel, w.channel_name.clone()),
(
&mut by_who,
if w.who.is_empty() {
w.ip.clone()
} else {
w.who.clone()
},
),
(
&mut by_device,
if w.device.is_empty() {
"?".into()
} else {
w.device.clone()
},
),
(&mut by_kind, w.kind.clone()),
] {
let e = map.entry(key).or_default();
e.secs += secs;
e.sessions += 1;
e.bytes += w.bytes;
}
total.secs += secs;
total.sessions += 1;
total.bytes += w.bytes;
// spread the time over local hours of the day and days
let mut t = a;
while t < b {
let local = t + offset;
let hour_end = (local / 3600 + 1) * 3600 - offset;
let seg = hour_end.min(b) - t;
by_hour[((local / 3600) % 24) as usize] += seg;
let day = chrono::DateTime::from_timestamp(local, 0)
.map(|d| d.format("%Y-%m-%d").to_string())
.unwrap_or_default();
*by_day.entry(day).or_default() += seg;
t += seg;
}
}
let top = |m: HashMap<String, Agg>, n: usize| {
let mut v: Vec<_> = m.into_iter().collect();
v.sort_by_key(|x| std::cmp::Reverse(x.1.secs));
v.into_iter()
.take(n)
.map(|(k, a)| json!({"name": k, "seconds": a.secs, "sessions": a.sessions, "bytes": a.bytes}))
.collect::<Vec<_>>()
};
Ok(Json(json!({
"days": days,
"total": {"seconds": total.secs, "sessions": total.sessions, "bytes": total.bytes},
"channels": top(by_channel, 20),
"users": top(by_who, 20),
"devices": top(by_device, 20),
"protocols": top(by_kind, 5),
"hours": by_hour,
"per_day": by_day.into_iter().map(|(d, s)| json!({"day": d, "seconds": s})).collect::<Vec<_>>(),
})))
}
pub async fn viewing_stats_clear(
AxState(state): AxState<State>,
Extension(CurrentUser(u)): Extension<CurrentUser>,
) -> ApiResult<Value> {
require_admin(&u)?;
let n = state.db.clear_watch_history().await?;
Ok(Json(json!({"ok": true, "deleted": n})))
}
#[derive(Deserialize)]
pub struct HoldReq {
mux_id: i64,
/// 0 = release
#[serde(default = "default_hold")]
seconds: u64,
}
fn default_hold() -> u64 {
90
}
/// Antenna meter: keeps a multiplex tuned (without a viewer) so its signal can be watched
/// while aligning the antenna. The page renews the hold; it ends by itself afterwards.
pub async fn signal_hold(
AxState(state): AxState<State>,
Extension(CurrentUser(u)): Extension<CurrentUser>,
Json(r): Json<HoldReq>,
) -> ApiResult<Value> {
require_admin(&u)?;
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(r.seconds.min(600));
let renewing = {
let mut m = state.signal_hold.lock().unwrap();
if r.seconds == 0 {
m.remove(&r.mux_id);
return ok();
}
m.insert(r.mux_id, deadline).is_some()
};
if renewing {
return ok();
}
let mux = state
.db
.mux(r.mux_id)
.await?
.ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "no such mux".into()))?;
let mut sub = match state
.tuners
.subscribe_pids(&mux, crate::tuner::Priority::Normal, Some(vec![]))
.await
{
Ok(s) => s,
Err(e) => {
state.signal_hold.lock().unwrap().remove(&r.mux_id);
return Err(ApiError::bad(format!("{e:#}")));
}
};
tracing::info!(
"antenna meter: holding {} for {}",
mux.params().describe(),
u.username
);
let st = state.clone();
let id = r.mux_id;
tokio::spawn(async move {
loop {
let until = st.signal_hold.lock().unwrap().get(&id).copied();
match until {
Some(t) if t > std::time::Instant::now() => {}
_ => break,
}
if let Ok(None) =
tokio::time::timeout(std::time::Duration::from_millis(500), sub.recv()).await
{
break; // tuner taken over / stopped
}
}
st.signal_hold.lock().unwrap().remove(&id);
tracing::info!("antenna meter: released mux #{id}");
});
ok()
}
fn prefs_key(user_id: i64) -> String {
format!("prefs:user:{user_id}")
}
/// Personal panel settings (language, theme, filters…) kept with the user account so they
/// follow the user to every browser and device.
pub async fn my_prefs(
AxState(state): AxState<State>,
Extension(CurrentUser(u)): Extension<CurrentUser>,
) -> ApiResult<Value> {
let v = state
.db
.get_setting(&prefs_key(u.id))
.await?
.and_then(|s| serde_json::from_str::<Value>(&s).ok())
.unwrap_or_else(|| json!({}));
Ok(Json(v))
}
pub async fn save_my_prefs(
AxState(state): AxState<State>,
Extension(CurrentUser(u)): Extension<CurrentUser>,
Json(v): Json<serde_json::Map<String, Value>>,
) -> ApiResult<Value> {
if v.len() > 32
|| v.iter()
.any(|(k, x)| !k.starts_with("sdvb-") || k.len() > 40 || !x.is_string())
{
return Err(ApiError::bad("unexpected preference keys"));
}
let s = serde_json::to_string(&v).map_err(|e| ApiError::bad(e.to_string()))?;
if s.len() > 32 * 1024 {
return Err(ApiError::bad("preferences too large"));
}
state.db.set_setting(&prefs_key(u.id), &s).await?;
Ok(Json(json!({"ok": true})))
}
#[derive(Deserialize)]
pub struct PasswordReq {
current: String,
+84
View File
@@ -13,6 +13,29 @@ const INDEX: &str = include_str!("../../web/index.html");
const CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/app.css"));
const JS: &str = include_str!(concat!(env!("OUT_DIR"), "/app.js"));
const FAVICON: &str = include_str!("../../web/favicon.svg");
const ICON_192: &[u8] = include_bytes!("../../web/icon-192.png");
const ICON_512: &[u8] = include_bytes!("../../web/icon-512.png");
/// Service worker: makes the panel installable as an app (PWA). It only answers page
/// navigations when the server is unreachable – streams, API calls and assets always go
/// straight to the network.
const SERVICE_WORKER: &str = r#"self.addEventListener('install', function (e) { self.skipWaiting(); });
self.addEventListener('activate', function (e) { e.waitUntil(self.clients.claim()); });
self.addEventListener('fetch', function (e) {
if (e.request.mode !== 'navigate') return;
e.respondWith(fetch(e.request).catch(function () {
return new Response('<!doctype html><meta name=viewport content="width=device-width"><body style="background:#131615;color:#ddd;font:15px sans-serif;padding:24px"><h2>simply-dvb</h2><p>The server is not reachable. Check the connection and try again.</p>', { headers: { 'Content-Type': 'text/html; charset=utf-8' } });
}));
});
self.addEventListener('notificationclick', function (e) {
e.notification.close();
var url = (e.notification.data && e.notification.data.url) || '/';
e.waitUntil(self.clients.matchAll({ type: 'window' }).then(function (list) {
for (var i = 0; i < list.length; i++) { if ('focus' in list[i]) { list[i].navigate(url); return list[i].focus(); } }
return self.clients.openWindow(url);
}));
});
"#;
fn head_assets() -> String {
format!(
@@ -36,6 +59,22 @@ pub fn stream_routes() -> Router<State> {
pub fn routes() -> Router<State> {
Router::new()
.route("/", get(index))
.route("/manifest.webmanifest", get(manifest))
.route(
"/sw.js",
get(|| async {
(
[
(
header::CONTENT_TYPE,
"application/javascript; charset=utf-8",
),
(header::CACHE_CONTROL, "no-cache"),
],
SERVICE_WORKER,
)
}),
)
.route("/assets/{file}", get(asset))
.route("/favicon.ico", get(|| async { svg(FAVICON) }))
}
@@ -51,6 +90,38 @@ fn svg(s: &'static str) -> Response {
.into_response()
}
/// Web app manifest: "Add to home screen" opens the panel full screen like an app.
async fn manifest(axum::extract::State(state): axum::extract::State<State>) -> Response {
let name = state.settings().server_name;
let body = serde_json::json!({
"name": name,
"short_name": name.chars().take(12).collect::<String>(),
"description": "DVB-T/T2/C TV server",
"start_url": "/",
"scope": "/",
"display": "standalone",
"background_color": "#050605",
"theme_color": "#050605",
"icons": [
{"src": "/assets/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any maskable"},
{"src": "/assets/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable"}
],
"shortcuts": [
{"name": "TV", "url": "/#/tv"},
{"name": "TV guide", "url": "/#/epg"},
{"name": "Recordings", "url": "/#/recordings"}
]
});
(
[
(header::CONTENT_TYPE, "application/manifest+json"),
(header::CACHE_CONTROL, "no-cache"),
],
body.to_string(),
)
.into_response()
}
async fn index() -> Response {
(
[
@@ -76,6 +147,19 @@ async fn asset(Path(file): Path<String>) -> Response {
("application/javascript; charset=utf-8", JS)
} else if file == "favicon.svg" {
return svg(FAVICON);
} else if file == "icon-192.png" || file == "icon-512.png" {
return (
[
(header::CONTENT_TYPE, "image/png"),
(header::CACHE_CONTROL, "public, max-age=86400"),
],
if file == "icon-192.png" {
ICON_192
} else {
ICON_512
},
)
.into_response();
} else {
return (StatusCode::NOT_FOUND, "").into_response();
};
+15 -5
View File
@@ -14,7 +14,7 @@ use axum::extract::{ConnectInfo, Request, State as AxState};
use axum::http::{Method, StatusCode};
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post, put};
use axum::routing::{delete, get, post, put};
use axum::{Json, Router};
use std::net::SocketAddr;
@@ -91,7 +91,7 @@ async fn api_guard(
let Some(user) = auth::session_user(&state, req.headers()).await else {
return ApiError(StatusCode::UNAUTHORIZED, "login required".into()).into_response();
};
let viewer_ok = path == "/api/logout" || path == "/api/me/password";
let viewer_ok = path == "/api/logout" || path == "/api/me/password" || path == "/api/me/prefs";
if mutating && user.role != "admin" && !viewer_ok {
return ApiError::forbidden().into_response();
}
@@ -147,11 +147,11 @@ async fn request_log(
|| path == "/healthz"
|| path == "/metrics";
if status.is_client_error() || status.is_server_error() {
tracing::warn!(target: "access", "{ip} {method} {path}{query} → {} ({ms} ms) · {ua}", status.as_u16());
tracing::warn!(target: "access", "{ip} {method} {path}{query} status {} ({ms} ms) · {ua}", status.as_u16());
} else if noisy {
tracing::debug!(target: "access", "{ip} {method} {path}{query} → {} ({ms} ms) · {ua}", status.as_u16());
tracing::debug!(target: "access", "{ip} {method} {path}{query} status {} ({ms} ms) · {ua}", status.as_u16());
} else {
tracing::info!(target: "access", "{ip} {method} {path}{query} → {} ({ms} ms) · {ua}", status.as_u16());
tracing::info!(target: "access", "{ip} {method} {path}{query} status {} ({ms} ms) · {ua}", status.as_u16());
}
res
}
@@ -173,6 +173,16 @@ pub fn router(state: State) -> Router {
.route("/api/logout", post(api::logout))
.route("/api/me", get(api::me))
.route("/api/me/password", post(api::change_password))
.route("/api/me/prefs", get(api::my_prefs).put(api::save_my_prefs))
.route("/api/me/sessions", get(api::my_sessions))
.route("/api/me/sessions/others", post(api::end_other_sessions))
.route("/api/me/sessions/{id}", delete(api::end_session))
.route("/api/backup/database", get(api::backup_download))
.route("/api/signal/hold", post(api::signal_hold))
.route(
"/api/stats/viewing",
get(api::viewing_stats).delete(api::viewing_stats_clear),
)
.route("/api/status", get(api::status))
.route("/api/stats", get(api::stats))
.route("/api/logs", get(api::logs))
+21 -1
View File
@@ -28,6 +28,10 @@ pub struct StreamQuery {
share: Option<String>,
profile: Option<String>,
format: Option<String>,
/// M3U: only these channels (comma separated channel ids, e.g. the favourites)
channels: Option<String>,
/// M3U: only this channel group
group: Option<String>,
}
impl StreamQuery {
@@ -123,10 +127,26 @@ pub async fn playlist(
Ok(p) => p,
Err(e) => return e.into_response(),
};
let channels = match state.db.channels().await {
let mut channels = match state.db.channels().await {
Ok(c) => c,
Err(e) => return ApiError::from(e).into_response(),
};
if let Some(ids) = q.channels.as_deref().filter(|s| !s.is_empty()) {
// keeps the given order (e.g. favourites in the order they were added)
let ids: Vec<i64> = ids
.split(',')
.filter_map(|x| x.trim().parse().ok())
.collect();
let mut picked: Vec<crate::db::Channel> = ids
.iter()
.filter_map(|id| channels.iter().find(|c| c.id == *id).cloned())
.collect();
picked.sort_by_key(|c| ids.iter().position(|i| *i == c.id));
channels = picked;
}
if let Some(g) = q.group.as_deref().filter(|s| !s.is_empty()) {
channels.retain(|c| c.grp == g);
}
let auth_q = ctx.access.query();
let body = crate::m3u::build(
&channels,
+24
View File
@@ -180,6 +180,30 @@ async fn full_flow() {
// virtual adapter
let ad = json_of(&env.lan, Method::GET, "/api/adapters", &c, None).await;
assert_eq!(ad.as_array().unwrap().len(), 1);
assert_eq!(ad[0]["device"]["bus"], "virtual");
// profile: preferences, signed-in devices, viewing statistics, PWA manifest
json_of(
&env.lan,
Method::PUT,
"/api/me/prefs",
&c,
Some(json!({"sdvb-lang": "pl_PL", "sdvb-fav": "[1,2]"})),
)
.await;
let prefs = json_of(&env.lan, Method::GET, "/api/me/prefs", &c, None).await;
assert_eq!(prefs["sdvb-fav"], "[1,2]");
let sessions = json_of(&env.lan, Method::GET, "/api/me/sessions", &c, None).await;
assert!(sessions
.as_array()
.unwrap()
.iter()
.any(|s| s["current"] == true));
let views = json_of(&env.lan, Method::GET, "/api/stats/viewing?days=7", &c, None).await;
assert_eq!(views["hours"].as_array().unwrap().len(), 24);
let (st, body) = call(&env.lan, Method::GET, "/manifest.webmanifest", "", None).await;
assert_eq!(st, StatusCode::OK);
assert!(String::from_utf8_lossy(&body).contains("standalone"));
eprintln!("== adapters ok");
// scanning
+14
View File
@@ -90,3 +90,17 @@ label.check { flex-direction: row; align-items: center; gap: 8px; font: 12px var
.toast.err { background: #ffd2bd; color: #42241b; border-color: #ff9f7a; }
@keyframes slide { from { transform: translateY(10px); opacity: 0; } }
/* line icons (inline SVG, same style as the side menu) */
.i { width: 1.1em; height: 1.1em; flex: 0 0 auto; vertical-align: -.2em; fill: none; stroke: currentColor; stroke-width: 1.9; stroke-linecap: round; stroke-linejoin: round; }
.i .f { fill: currentColor; stroke: none; }
.i:not(:last-child) { margin-right: .45em; }
.i:last-child:not(:first-child) { margin-left: .45em; }
.pill .i { width: 1em; height: 1em; }
.osd .i { width: 1.3em; height: 1.3em; }
td.drag .i { width: 14px; height: 14px; margin: 0; color: var(--subtle); }
/* simple alert box (e.g. sign-in errors) */
.alert { padding: 9px 12px; border: 1px solid var(--line); border-left-width: 3px; border-radius: 3px; font-size: 12px; line-height: 1.45; background: var(--panel2); color: var(--text); }
.alert.err { border-color: var(--red); background: color-mix(in srgb, var(--red) 12%, var(--panel)); }
label.btn { display: inline-flex; flex-direction: row; align-items: center; gap: 0; }
+53 -3
View File
@@ -1,7 +1,10 @@
/* ---------------------------------------------------------------- login */
.login { min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 20px; }
.login-card { width: 340px; background: var(--panel); border: 1px solid var(--line); padding: 28px; border-radius: 4px; display: flex; flex-direction: column; gap: 12px; }
.login-card h1 { font-size: 24px; margin-bottom: 6px; }
.login-card h1 { font-size: 24px; margin: 4px 0 2px; }
.login-brand { display: flex; align-items: center; gap: 14px; }
.login-brand .brand-mark.big { margin: 0; }
.login-brand .eyebrow { margin: 0; }
.login-card input { padding: 9px 10px; font-size: 13px; }
/* ---------------------------------------------------------------- tuner cards */
@@ -56,7 +59,7 @@
.epg-ev .tm { font: 10px var(--mono); color: var(--muted); }
.epg-ev.cur { border-color: #6d5a45; background: #2a2620; }
html[data-theme=light] .epg-ev.cur { background: #fbeee6; }
.epg-ev.rec::after { content: "●"; color: #e25b45; position: absolute; right: 5px; top: 3px; font-size: 10px; }
.epg-ev.rec::after { content: ""; background: #e25b45; position: absolute; right: 5px; top: 5px; width: 7px; height: 7px; border-radius: 50%; }
.epg-head { display: flex; position: sticky; top: 0; z-index: 4; background: var(--panel); border-bottom: 1px solid var(--line); height: 26px; }
.epg-head .corner { position: sticky; left: 0; width: 170px; flex: 0 0 170px; background: var(--panel); border-right: 1px solid var(--line); z-index: 5; }
.epg-head .hours { position: relative; flex: 1; }
@@ -96,7 +99,8 @@ body.bare { min-height: 100vh; }
.chart .area { opacity: .12; stroke: none; }
.chart rect { opacity: .85; }
.chart .cursor { stroke: var(--muted); stroke-width: 1; stroke-dasharray: 3 3; vector-effect: non-scaling-stroke; }
.chart-scale { position: absolute; right: 16px; top: 36px; bottom: 26px; display: flex; flex-direction: column; justify-content: space-between; font: 9px var(--mono); color: var(--subtle); pointer-events: none; text-align: right; }
.chart-box { position: relative; }
.chart-scale { position: absolute; right: 2px; top: 0; bottom: 0; display: flex; flex-direction: column; justify-content: space-between; font: 9px var(--mono); color: var(--subtle); pointer-events: none; text-align: right; }
.chart-hover { min-height: 14px; margin-top: 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.tuner-charts { margin-top: 4px; }
.tuner-charts .chart-card { background: var(--panel2); }
@@ -139,3 +143,49 @@ tr.off td:last-child, tr.off td:nth-last-child(2), tr.off td:nth-last-child(3) {
.sched-bar.live { box-shadow: 0 0 0 1px var(--red) inset; }
.sched-bar.conflict { background: repeating-linear-gradient(135deg, color-mix(in srgb, var(--red) 35%, transparent) 0 6px, color-mix(in srgb, var(--red) 15%, transparent) 6px 12px); border-left-color: var(--red); }
tr.row-warn td { background: color-mix(in srgb, var(--red) 8%, transparent); }
/* tuner hardware / stream health */
.lock-bits { display: flex; flex-wrap: wrap; gap: 4px; align-items: center; margin: 8px 0 4px; }
.lock-bits .pill { font: 10px var(--mono); letter-spacing: .06em; opacity: .55; }
.lock-bits .pill.ok { opacity: 1; }
.lock-bits .mono { margin-left: 6px; }
.ts-kv { margin-top: 6px; }
details.hw { margin-top: 8px; border-top: 1px solid var(--row-line); padding-top: 6px; }
details.hw summary { cursor: pointer; font: 11px var(--mono); letter-spacing: .08em; text-transform: uppercase; color: var(--muted); }
details.hw .kv { margin-top: 6px; }
/* favourites */
.ch-item .name { display: flex; align-items: center; gap: 6px; }
.ch-item .fav { margin-left: auto; background: none; border: 0; color: var(--subtle); cursor: pointer; font-size: 15px; line-height: 1; padding: 2px 4px; opacity: 0; }
.ch-item:hover .fav, .ch-item .fav.on, .ch-item.active .fav { opacity: 1; }
.ch-item .fav.on { color: var(--yellow); }
@media (hover: none) { .ch-item .fav { opacity: .6; } .ch-item .fav.on { opacity: 1; } }
/* statistics */
.bar-list { display: flex; flex-direction: column; gap: 7px; }
.bl-row { display: grid; grid-template-columns: minmax(90px, 1.2fr) 2fr 60px; grid-template-rows: auto auto; column-gap: 10px; align-items: center; font-size: 12px; }
.bl-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.bl-bar { height: 8px; background: var(--row-line); border-radius: 2px; overflow: hidden; }
.bl-bar i { display: block; height: 100%; background: var(--accent); border-radius: 2px; }
.bl-val { text-align: right; }
.bl-sub { grid-column: 2 / 4; font-size: 10px; }
.cols { display: flex; align-items: flex-end; gap: 3px; height: 130px; padding-top: 6px; }
.col { flex: 1 1 0; display: flex; flex-direction: column; justify-content: flex-end; align-items: center; height: 100%; min-width: 0; }
.col i { display: block; width: 100%; background: var(--accent); opacity: .8; border-radius: 2px 2px 0 0; min-height: 1px; }
.col span { font: 9px var(--mono); color: var(--subtle); margin-top: 3px; white-space: nowrap; overflow: hidden; max-width: 100%; }
.stat .small-value { font-size: 17px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* antenna meter */
.sg-pick { gap: 10px; flex-wrap: wrap; align-items: flex-end; }
.sg-pick label { display: flex; flex-direction: column; gap: 4px; font: 11px var(--mono); color: var(--muted); }
.sg-main { text-align: left; }
.sg-verdict { font-size: 22px; font-weight: 700; }
.sg-verdict.ok { color: var(--green); } .sg-verdict.warn { color: var(--yellow); } .sg-verdict.bad { color: var(--red); }
.sg-mux { margin: 2px 0 12px; font-size: 12px; }
.sg-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; }
.sg-big { font: 600 54px/1.05 var(--mono); margin: 4px 0 6px; }
.sg-big small { font-size: 20px; margin-left: 4px; color: var(--muted); }
@media (max-width: 640px) { .sg-big { font-size: 40px; } .sg-grid { gap: 12px; } }
.topbar { padding-top: env(safe-area-inset-top); height: calc(42px + env(safe-area-inset-top)); }
.sg-pick label { min-width: 0; max-width: 100%; }
.sg-pick select { max-width: 100%; }
+47
View File
@@ -10,3 +10,50 @@
.epg-ch .logo, .epg-ch .logo-ph { display: none; }
}
/* ---------------------------------------------------------------- phones
* The side rail becomes a bottom tab bar (icons only), the top bar keeps only the page
* name and compact buttons, wide rows scroll inside their own box instead of the page. */
@media (max-width: 640px) {
html { -webkit-text-size-adjust: 100%; }
body { overflow-x: clip; }
.sidebar, .sidebar:hover,
html[data-sidebar] .sidebar, html[data-sidebar] .sidebar:hover {
inset: auto 0 0 0; width: 100%; height: calc(54px + env(safe-area-inset-bottom)); flex-direction: row; justify-content: space-around;
padding: 0 0 env(safe-area-inset-bottom); gap: 0; border-right: 0; border-top: 1px solid var(--line); box-shadow: 0 -4px 14px #0005; transition: none;
}
.sidebar a, html[data-sidebar] .sidebar a { flex: 1 1 0; justify-content: center; padding: 0; height: 54px; border-left: 0; border-top: 2px solid transparent; min-width: 0; }
.sidebar a.active { border-left: 0; border-top-color: var(--green); }
.sidebar a span, .sidebar:hover a span { display: none !important; }
.sidebar a.brand, .sidebar-foot { display: none; }
.main, html[data-sidebar] .main, html[data-sidebar=pinned] .main { margin-left: 0 !important; padding-bottom: calc(60px + env(safe-area-inset-bottom)); }
.topbar { padding-left: 10px; padding-right: 10px; gap: 8px; }
.crumbs { min-width: 0; overflow: hidden; white-space: nowrap; }
.crumbs .crumb-root, .crumbs .sep { display: none; }
.crumbs #crumb { overflow: hidden; text-overflow: ellipsis; font-size: 13px; }
.top-actions { gap: 4px; flex: 0 0 auto; }
.top-actions .clock { display: none; }
#logout .lbl { display: none; }
#lang-switch .lang-select { max-width: 64px; }
.view { padding: 10px 10px 24px; }
.page-head { margin-bottom: 12px; gap: 10px; }
.page-head h1 { font-size: 21px; }
.actions .btn { flex: 0 0 auto; }
.tabs { overflow-x: auto; scrollbar-width: none; -webkit-overflow-scrolling: touch; }
.tabs::-webkit-scrollbar { display: none; }
.tabs button { white-space: nowrap; flex: 0 0 auto; }
.modal { padding: 10px 6px; }
.modal-card, .modal-card.wide { padding: 12px; }
.filters { gap: 6px; }
.filters input, .filters select { max-width: 100%; }
input, select, textarea { font-size: 16px; } /* no zoom-in on focus (iOS) */
.toast-wrap, .toasts { left: 10px; right: 10px; bottom: calc(66px + env(safe-area-inset-bottom)); }
}
/* any box holding a table scrolls sideways instead of widening the page */
*:has(> table) { overflow-x: auto; }
@media (max-width: 640px) {
.search { flex-wrap: wrap; }
.search > input { flex: 1 1 160px; min-width: 0; }
.search > select { flex: 1 1 120px; min-width: 0; max-width: 100%; }
}
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

+12 -6
View File
@@ -2,21 +2,26 @@
<html lang="pl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>simply-dvb</title>
<link rel="icon" href="/assets/favicon.svg">
<link rel="manifest" href="/manifest.webmanifest">
<link rel="apple-touch-icon" href="/assets/icon-192.png">
<meta name="theme-color" content="#050605">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
__ASSETS__
</head>
<body>
<div id="login" class="login hidden">
<form id="login-form" class="login-card" autocomplete="on">
<div class="brand-mark big">s/d</div>
<div class="eyebrow">simply-dvb · panel</div>
<div class="login-brand"><div class="brand-mark big">s/d</div><div class="eyebrow">simply-dvb · panel</div></div>
<h1>Sign in</h1>
<div id="login-error" class="alert err hidden" role="alert"></div>
<label>Username<input name="username" autocomplete="username" required autofocus></label>
<label>Password<input name="password" type="password" autocomplete="current-password" required></label>
<button class="btn primary wide" type="submit">Sign in</button>
<p id="login-error" class="error-text"></p>
</form>
</div>
@@ -29,6 +34,7 @@ __ASSETS__
<a data-route="channels" href="#/channels" title="Channels"><svg viewBox="0 0 24 24"><path d="M8 6h13M8 12h13M8 18h13"/><circle cx="4" cy="6" r="1"/><circle cx="4" cy="12" r="1"/><circle cx="4" cy="18" r="1"/></svg><span>Channels</span></a>
<a data-route="recordings" href="#/recordings" title="Recordings"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="3.5" class="fill"/></svg><span>Recordings</span></a>
<a data-route="tuners" href="#/tuners" title="Tuners & scanning"><svg viewBox="0 0 24 24"><path d="M5 12.5a10 10 0 0 1 14 0M8.5 16a5 5 0 0 1 7 0"/><circle cx="12" cy="19.5" r="1" class="fill"/><path d="M2 9a14.5 14.5 0 0 1 20 0"/></svg><span>Tuners</span></a>
<a data-route="stats" href="#/stats" title="Statistics"><svg viewBox="0 0 24 24"><path d="M4 20V10M10 20V4M16 20v-7M22 20H2"/></svg><span>Statistics</span></a>
<a data-route="access" href="#/access" title="Access & sharing"><svg viewBox="0 0 24 24"><path d="M12 3l8 3v6c0 4.5-3.4 8.3-8 9-4.6-.7-8-4.5-8-9V6z"/><path d="M9 12l2 2 4-4"/></svg><span>Access</span></a>
<a data-route="logs" href="#/logs" title="Logs"><svg viewBox="0 0 24 24"><path d="M4 5h16M4 10h10M4 15h16M4 20h7"/></svg><span>Logs</span></a>
<a data-route="settings" href="#/settings" title="Settings"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg><span>Settings</span></a>
@@ -42,14 +48,14 @@ __ASSETS__
<div id="lang-switch" data-no-i18n></div>
<button class="btn ghost icon" id="theme-toggle" title="Theme"><svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true"><circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="2"/><path d="M12 3a9 9 0 0 1 0 18z" fill="currentColor"/></svg></button>
<span class="who" id="who"></span>
<button class="btn ghost" id="logout">⎋ Sign out</button>
<button class="btn ghost" id="logout" title="Sign out"><svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M15 4h4a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1h-4M10 8l-4 4 4 4M6 12h10"/></svg><span class="lbl">Sign out</span></button>
</div>
</header>
<section id="view" class="view"></section>
</div>
</div>
<div id="modal" class="modal hidden"><div class="modal-card" role="dialog"><header><h2 id="modal-title"></h2><button class="btn ghost icon" id="modal-close" title="Close">✕</button></header><div id="modal-body"></div></div></div>
<div id="modal" class="modal hidden"><div class="modal-card" role="dialog"><header><h2 id="modal-title"></h2><button class="btn ghost icon" id="modal-close" title="Close"><svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg></button></header><div id="modal-body"></div></div></div>
<div id="toasts" class="toasts"></div>
</body>
+69 -4
View File
@@ -5,6 +5,69 @@
* than English is active, every text node inserted into the DOM (and placeholder/title/
* aria-label) is translated; missing entries fall back to the English source text.
* Pattern replacements use $1..$9 for raw groups and $t1..$t9 for groups translated again. */
/* Personal settings store: localStorage on this device, mirrored to the user's profile on
* the server (GET/PUT /api/me/prefs) so language, theme and filters follow the account. */
(function () {
'use strict';
var SYNCED = ['sdvb-lang', 'sdvb-prefs', 'sdvb-chfilter', 'sdvb-group', 'sdvb-fav', 'sdvb-remind'];
var enabled = false;
function local() {
var o = {};
SYNCED.forEach(function (k) {
var v = null;
try { v = localStorage.getItem(k); } catch (e) {}
if (v !== null) o[k] = v;
});
return o;
}
function push() {
if (!enabled) return;
try {
// keepalive: a language change reloads the page right away
fetch('/api/me/prefs', { method: 'PUT', keepalive: true, credentials: 'same-origin',
headers: { 'X-Requested-With': 'simply-dvb', 'Content-Type': 'application/json' },
body: JSON.stringify(local()) }).catch(function () {});
} catch (e) {}
}
window.SDVB_STORE = {
get: function (k) { try { return localStorage.getItem(k); } catch (e) { return null; } },
set: function (k, v) {
try { localStorage.setItem(k, v); } catch (e) {}
if (SYNCED.indexOf(k) >= 0) push();
},
remove: function (k) {
try { localStorage.removeItem(k); } catch (e) {}
if (SYNCED.indexOf(k) >= 0) push();
},
/** After login: takes the profile's settings (or uploads this device's ones when the
* profile has none yet). Resolves to the list of keys that changed. */
pull: function () {
return fetch('/api/me/prefs', { credentials: 'same-origin', headers: { 'X-Requested-With': 'simply-dvb' } })
.then(function (r) { return r.ok ? r.json() : null; })
.then(function (remote) {
enabled = true;
if (!remote) return [];
var keys = Object.keys(remote).filter(function (k) { return SYNCED.indexOf(k) >= 0; });
if (!keys.length) { push(); return []; }
var changed = [];
SYNCED.forEach(function (k) {
var cur = null;
try { cur = localStorage.getItem(k); } catch (e) {}
var nv = Object.prototype.hasOwnProperty.call(remote, k) ? remote[k] : null;
if (nv !== cur) {
changed.push(k);
try { if (nv === null) localStorage.removeItem(k); else localStorage.setItem(k, nv); } catch (e) {}
}
});
return changed;
})
.catch(function () { enabled = true; return []; });
},
/** On logout: stop mirroring until the next login. */
stop: function () { enabled = false; }
};
})();
(function () {
'use strict';
@@ -127,7 +190,7 @@
});
},
setLang: function (l) {
try { localStorage.setItem(LANG_KEY, resolve(l) || DEFAULT); } catch (e) {}
window.SDVB_STORE.set(LANG_KEY, resolve(l) || DEFAULT);
location.reload();
},
/** For tooling: English keys with no translation in the given language. */
@@ -142,7 +205,7 @@
(function () {
'use strict';
var KEY = 'sdvb-prefs';
var DEFAULTS = { chartWindow: 10, theme: 'dark', accent: 'orange', density: 'comfortable', scale: 100, sidebar: 'hover', start: 'overview',
var DEFAULTS = { chartWindow: 10, theme: 'midnight', accent: 'orange', density: 'comfortable', scale: 100, sidebar: 'hover', start: 'overview',
logos: true, progress: true, autoplay: false, epgZoom: 4, clock: false, motion: true };
var ACCENTS = {
orange: ['#f69b74', '#ffb090', '#221810', '#b85b38'],
@@ -183,10 +246,12 @@
all: function () { return JSON.parse(JSON.stringify(prefs)); },
set: function (k, v) {
prefs[k] = v;
try { localStorage.setItem(KEY, JSON.stringify(prefs)); } catch (e) {}
window.SDVB_STORE.set(KEY, JSON.stringify(prefs));
apply();
},
reset: function () { try { localStorage.removeItem(KEY); } catch (e) {} load(); apply(); },
reset: function () { window.SDVB_STORE.remove(KEY); load(); apply(); },
/** Re-reads the stored values (after the profile's settings were pulled). */
reload: function () { load(); apply(); },
accents: Object.keys(ACCENTS),
accentColor: function (k) { return (ACCENTS[k] || ACCENTS.orange)[0]; }
};
+4 -3
View File
@@ -39,7 +39,7 @@
}
/**
* Best profile for this browser: pass → aac → h264. Without ffmpeg on the server only
* Best profile for this browser: pass, then aac, then h264. Without ffmpeg on the server only
* "pass" is possible, so it is always tried first.
*/
function pickProfile(video, audio, transcode) {
@@ -101,7 +101,8 @@
overlay.appendChild(el('div', null, msg));
if (hint) overlay.appendChild(el('div', 'hint', hint));
if (err && opts.vlcUrl) {
var a = el('a', 'btn small', '▶ Open in VLC');
var a = el('a', 'btn small', 'Open in VLC');
if (window.SDVB_ICON) a.innerHTML = window.SDVB_ICON('vlc') + a.innerHTML;
a.href = opts.vlcUrl;
a.setAttribute('download', '');
overlay.appendChild(a);
@@ -157,7 +158,7 @@
});
hls.on(window.Hls.Events.MANIFEST_PARSED, function () {
var p = video.play();
if (p && p.catch) p.catch(function () { status('Click ▶ to play', true); });
if (p && p.catch) p.catch(function () { status('Click Play to start', true); });
});
hls.on(window.Hls.Events.FRAG_BUFFERED, function () { status(null); retries = 0; });
hls.on(window.Hls.Events.ERROR, function (_e, data) {
+439 -55
View File
@@ -47,6 +47,32 @@
t.remove();
}
}
/** Line icons (same style as the side menu) – used instead of emoji/special characters. */
var ICONS = {
play: '<path class="f" d="M7.5 4.8v14.4L19 12z"/>',
prev: '<path d="M15 5l-7 7 7 7"/>',
next: '<path d="M9 5l7 7-7 7"/>',
record: '<circle class="f" cx="12" cy="12" r="6"/>',
stop: '<rect class="f" x="6.5" y="6.5" width="11" height="11" rx="1"/>',
pip: '<rect x="2.5" y="4.5" width="19" height="15" rx="1.5"/><rect class="f" x="12" y="11.5" width="7" height="5.5" rx=".5"/>',
fullscreen: '<path d="M3.5 9V3.5H9M20.5 9V3.5H15M3.5 15v5.5H9M20.5 15v5.5H15"/>',
check: '<path d="M4.5 12.5l4.8 4.8L19.5 7"/>',
cross: '<path d="M6 6l12 12M18 6L6 18"/>',
star: '<path d="M12 3.2l2.7 5.6 6.1.8-4.5 4.2 1.1 6.1L12 17l-5.4 2.9 1.1-6.1-4.5-4.2 6.1-.8z"/>',
starOn: '<path class="f" d="M12 3.2l2.7 5.6 6.1.8-4.5 4.2 1.1 6.1L12 17l-5.4 2.9 1.1-6.1-4.5-4.2 6.1-.8z"/>',
bell: '<path d="M6 16.5V11a6 6 0 0 1 12 0v5.5l1.8 1.8H4.2z"/><path d="M10 21h4"/>',
antenna: '<path d="M5 12.5a10 10 0 0 1 14 0M8.5 16a5 5 0 0 1 7 0M2 9a14.5 14.5 0 0 1 20 0"/><circle class="f" cx="12" cy="19.5" r="1"/>',
download: '<path d="M12 3.5v11.5M7 10l5 5 5-5M4 20.5h16"/>',
upload: '<path d="M12 15.5V4M7 9l5-5 5 5M4 20.5h16"/>',
warn: '<path d="M12 3.5l9.5 17h-19z"/><path d="M12 10v4.5M12 17.5v.2"/>',
grip: '<circle class="f" cx="9" cy="6" r="1.3"/><circle class="f" cx="15" cy="6" r="1.3"/><circle class="f" cx="9" cy="12" r="1.3"/><circle class="f" cx="15" cy="12" r="1.3"/><circle class="f" cx="9" cy="18" r="1.3"/><circle class="f" cx="15" cy="18" r="1.3"/>',
volume: '<path d="M4 9.5h3.5L12 5.5v13l-4.5-4H4z"/><path d="M15.5 9a4 4 0 0 1 0 6M18 6.5a7.5 7.5 0 0 1 0 11"/>',
mute: '<path d="M4 9.5h3.5L12 5.5v13l-4.5-4H4z"/><path d="M16 9.5l5 5M21 9.5l-5 5"/>',
vlc: '<path d="M9 3.5h6l4.5 16h-15z"/><path d="M7.2 13h9.6"/>'
};
function ico(name) { return '<svg class="i" viewBox="0 0 24 24" aria-hidden="true">' + (ICONS[name] || '') + '</svg>'; }
window.SDVB_ICON = ico;
function toast(msg, err) {
var t = document.createElement('div');
t.className = 'toast' + (err ? ' err' : '');
@@ -116,6 +142,8 @@
app.cleanup.push(function () { document.removeEventListener('visibilitychange', onVis); });
}
function resetPage() {
// a dialog belongs to the page it was opened on (e.g. Watch in an EPG event)
if (!$('#modal').classList.contains('hidden')) closeModal();
app.timers.forEach(clearInterval); app.timers = [];
app.cleanup.forEach(function (f) { try { f(); } catch (e) {} }); app.cleanup = [];
}
@@ -128,6 +156,8 @@
channels: ['Channels', pageChannels],
recordings: ['Recordings', pageRecordings],
tuners: ['Tuners & scanning', pageTuners],
stats: ['Statistics', pageStats],
signal: ['Antenna meter', pageSignal],
access: ['Access & sharing', pageAccess],
logs: ['Logs', pageLogs],
settings: ['Settings', pageSettings]
@@ -156,6 +186,10 @@
$('#login').classList.remove('hidden');
}
function boot() {
// installable app (PWA); service workers need HTTPS or localhost
if ('serviceWorker' in navigator && window.isSecureContext) {
navigator.serviceWorker.register('/sw.js').catch(function () {});
}
renderLangSwitch();
applyClock();
api('GET', '/api/info').then(function (i) {
@@ -165,6 +199,13 @@
}).catch(function () {});
api('GET', '/api/me').then(function (me) {
app.me = me;
return window.SDVB_STORE.pull().then(function (changed) {
// the profile has another language: reload once with it
if (changed.indexOf('sdvb-lang') >= 0) { location.reload(); throw new Error('reload'); }
if (changed.length) { window.SDVB_PREFS.reload(); applyClock(); }
return me;
});
}).then(function (me) {
$('#who').textContent = me.username + ' · ' + (me.role === 'admin' ? 'administrator' : 'viewer');
$('#login').classList.add('hidden');
$('#shell').classList.remove('hidden');
@@ -174,12 +215,13 @@
$('#login-form').addEventListener('submit', function (e) {
e.preventDefault();
var f = e.target;
$('#login-error').textContent = '';
var le = $('#login-error');
le.textContent = ''; le.classList.add('hidden');
api('POST', '/api/login', { username: f.username.value, password: f.password.value })
.then(function () { f.password.value = ''; boot(); })
.catch(function (err) { $('#login-error').textContent = err.message; });
.catch(function (err) { var le = $('#login-error'); var m = T(err.message); le.textContent = m.charAt(0).toUpperCase() + m.slice(1); le.classList.remove('hidden'); });
});
$('#logout').addEventListener('click', function () { api('POST', '/api/logout').then(showLogin).catch(showLogin); });
$('#logout').addEventListener('click', function () { window.SDVB_STORE.stop(); api('POST', '/api/logout').then(showLogin).catch(showLogin); });
var THEMES = ['dark', 'midnight', 'light', 'system'];
$('#theme-toggle').addEventListener('click', function () {
var i = THEMES.indexOf(P.get('theme'));
@@ -190,7 +232,8 @@
/** Language picker built from the packs embedded at build time (langs/*.json). */
function langSelect(id, short) {
return '<select class="lang-select" id="' + id + '" data-no-i18n title="Language">' + window.I18N.languages().map(function (l) {
var label = short ? l.short + ' · ' + l.name : l.name + (l.name !== l.english ? ' (' + l.english + ')' : '');
var phone = window.matchMedia && window.matchMedia('(max-width: 640px)').matches;
var label = short ? (phone ? l.short : l.short + ' · ' + l.name) : l.name + (l.name !== l.english ? ' (' + l.english + ')' : '');
return '<option value="' + esc(l.code) + '"' + (l.code === window.I18N.lang ? ' selected' : '') + '>' + esc(label) + '</option>';
}).join('') + '</select>';
}
@@ -229,6 +272,7 @@
if (unit === 'dB') return v.toFixed(1) + ' dB';
if (unit === 'dBm') return v.toFixed(1) + ' dBm';
if (unit === 'bps') return bps(v);
if (unit === 'ber') return v === 0 ? '0' : v.toExponential(1);
return (Math.round(v * 100) / 100) + (unit ? ' ' + unit : '');
}
/**
@@ -274,9 +318,9 @@
var area = si === 0 && !opts.noArea && first != null ? '<path class="area" style="fill:' + color + '" d="' + d + ' L' + x(last).toFixed(1) + ',' + (H - 4) + ' L' + x(first).toFixed(1) + ',' + (H - 4) + ' Z"/>' : '';
return area + '<path class="ln" style="stroke:' + color + '" d="' + d + '"/>';
}).join('');
return '<svg class="chart" viewBox="0 0 ' + W + ' ' + H + '" preserveAspectRatio="none">' + grid + paths +
return '<div class="chart-box"><svg class="chart" viewBox="0 0 ' + W + ' ' + H + '" preserveAspectRatio="none">' + grid + paths +
'<line class="cursor hidden" x1="0" x2="0" y1="0" y2="' + H + '"/></svg>' +
'<div class="chart-scale"><span>' + esc(fmtNum(max, opts.unit)) + '</span><span>' + esc(fmtNum(min, opts.unit)) + '</span></div>';
'<div class="chart-scale"><span>' + esc(fmtNum(max, opts.unit)) + '</span><span>' + esc(fmtNum(min, opts.unit)) + '</span></div></div>';
}
/** A chart panel: title, current values and the chart; hovering shows the value at that time. */
function chartCard(id, title, series, times, opts) {
@@ -321,10 +365,45 @@
'<div class="small muted mono">' + (sig.locked ? 'LOCK' : sig.has_signal ? 'signal, no lock' : 'no signal') + '</div></div></div>';
}
/** Demodulator lock stages: signal, carrier, FEC, sync, lock. */
function lockBits(sig) {
if (!sig) return '';
return '<div class="lock-bits">' + [['SIGNAL', sig.has_signal], ['CARRIER', sig.has_carrier], ['FEC', sig.has_viterbi], ['SYNC', sig.has_sync], ['LOCK', sig.locked]].map(function (b) {
return '<span class="pill ' + (b[1] ? 'ok' : '') + '">' + b[0] + '</span>';
}).join('') + (sig.ber != null ? '<span class="mono small muted">BER ' + esc(fmtNum(sig.ber, 'ber')) + '</span>' : '') + '</div>';
}
/** Transport stream health since tuning (lost packets, damaged packets, stuffing). */
function tsHealth(a) {
var ts = a.ts, tu = a.tuned;
if (!ts || !ts.packets) return '';
var pct = function (n) { return (n * 100 / ts.packets).toFixed(n * 100 / ts.packets < 1 ? 2 : 1) + '%'; };
return '<div class="kv ts-kv">' +
(tu ? '<span>Transmission</span><span class="mono">' + esc([tu.modulation, tu.code_rate && 'FEC ' + tu.code_rate, tu.guard_interval && 'GI ' + tu.guard_interval, tu.transmission_mode].filter(Boolean).join(' · ')) + '</span>' : '') +
'<span>Packets</span><span class="mono">' + ts.packets.toLocaleString() + ' · ' + ts.pids + ' PIDs · ' + esc(T('stuffing')) + ' ' + pct(ts.null_packets) + (ts.scrambled ? ' · ' + esc(T('scrambled')) + ' ' + pct(ts.scrambled) : '') + '</span>' +
'<span>Errors</span><span class="mono ' + (ts.cc_errors || ts.tei_errors ? 'warn-text' : '') + '">CC ' + ts.cc_errors + ' · TEI ' + ts.tei_errors + '</span></div>';
}
/** Adapter hardware: bus, driver, product, ids, frequency range, capabilities. */
function hardwareBlock(t) {
var d = t.device;
if (!d) return '';
var rows = [
['Bus', [d.bus && d.bus.toUpperCase(), d.usb_speed && d.usb_speed + ' Mbit/s'].filter(Boolean).join(' · ')],
['Driver', d.driver],
['Device', [d.vendor, d.product].filter(Boolean).join(' ')],
['IDs', d.ids],
['Frequency range', d.freq_min_mhz != null && d.freq_max_mhz != null ? d.freq_min_mhz.toFixed(0) + '–' + d.freq_max_mhz.toFixed(0) + ' MHz' : ''],
['Capabilities', (d.caps || []).join(', ')]
].filter(function (r) { return r[1]; });
if (!rows.length) return '';
return '<details class="hw" data-hw="' + esc(t.id) + '"><summary>' + esc(T('Hardware')) + '</summary><div class="kv">' + rows.map(function (r) {
return '<span>' + esc(T(r[0])) + '</span><span class="mono">' + esc(r[1]) + '</span>';
}).join('') + '</div></details>';
}
function pageOverview(view) {
var windowMin = +P.get('chartWindow') || 10;
view.innerHTML = head('Connected to server', 'Television, in focus.', 'Tuners, streams, clients and EPG in one place.',
'<a class="btn" href="#/tv">▶ Watch</a><a class="btn" href="#/tuners">Scan channels</a>') +
'<a class="btn" href="#/tv">' + ico('play') + 'Watch</a><a class="btn" href="#/tuners">Scan channels</a>') +
'<div class="grid g4" id="ov-stats"></div>' +
'<div class="section-head"><h2>Live</h2><div class="seg" id="ov-window">' + [5, 10, 15].map(function (m) {
return '<button data-w="' + m + '"' + (m === windowMin ? ' class="on"' : '') + '>' + m + ' min</button>';
@@ -357,7 +436,7 @@
add('mem', 'Memory', [{ name: 'used', values: pick(S, 'mem') }], { unit: '%', min: 0, max: 100 });
add('rss', 'Process memory (RSS)', [{ name: 'RSS', values: pick(S, 'rss') }], { unit: 'B', min: 0 });
add('stream', 'Streaming throughput', [{ name: 'to clients', values: pick(S, 'out_bps') }, { name: 'recordings', values: pick(S, 'rec_bps') }], { unit: 'Bps', min: 0, floor: 1000 });
add('net', 'Network', [{ name: 'out', values: pick(S, 'net_tx') }, { name: 'in', values: pick(S, 'net_rx') }], { unit: 'Bps', min: 0, floor: 1000 });
add('net', 'Application traffic', [{ name: 'MPEG-TS', values: pick(S, 'out_ts_bps') }, { name: 'HLS', values: pick(S, 'out_hls_bps') }, { name: 'HTSP', values: pick(S, 'out_htsp_bps') }, { name: 'from tuners', values: pick(S, 'tuner_in_bps') }], { unit: 'Bps', min: 0, floor: 1000, noArea: true });
add('clients', 'Clients & sessions', [{ name: 'clients', values: pick(S, 'clients') }, { name: 'HLS sessions', values: pick(S, 'hls_sessions') }, { name: 'active tuners', values: pick(S, 'tuners_active') }], { min: 0, floor: 2, noArea: true });
add('temp', 'Temperature', [{ name: 'max', values: pick(S, 'temp') }], { unit: '°C', auto: true });
add('load', 'Load average (1 min)', [{ name: 'load', values: pick(S, 'load1') }], { min: 0, floor: 1 });
@@ -368,6 +447,8 @@
function renderTuners() {
if (!status) return;
var tdata = {};
// keep the "Hardware" sections the user opened across the 2 s refreshes
var openHw = $$('details.hw[open]', $('#ov-tuners')).map(function (d) { return d.getAttribute('data-hw'); });
$('#ov-tuners').className = 'grid ' + (status.tuners.length > 1 ? 'g2' : 'g1');
$('#ov-tuners').innerHTML = status.tuners.map(function (t) {
var a = t.active;
@@ -384,16 +465,20 @@
add('dbm', 'Signal level', [{ name: 'dBm', values: pick(TS, 'strength_dbm') }], { unit: 'dBm', auto: true, noArea: true });
add('snr', 'SNR', [{ name: 'SNR', values: pick(TS, 'snr') }], { unit: 'dB', min: 0, floor: 10 });
add('unc', 'Uncorrected blocks', [{ name: 'per 2 s', values: pick(TS, 'unc') }], { min: 0, floor: 1, bars: true });
add('ber', 'Bit error rate (BER)', [{ name: 'BER', values: pick(TS, 'ber') }], { unit: 'ber', min: 0, floor: 1e-6, noArea: true });
add('tserr', 'Stream errors', [{ name: 'CC', values: pick(TS, 'cc') }, { name: 'TEI', values: pick(TS, 'tei') }], { min: 0, floor: 1, bars: true });
return '<div class="panel tuner"><div class="t-head"><div><h3>' + esc(t.name) + '</h3><div class="t-meta">' + esc(t.id) + ' · ' + esc(t.delivery_systems.join(' / ')) + ' · ' + esc(t.path) + '</div></div>' +
'<div class="actions">' + (!t.enabled ? '<span class="pill">disabled</span>' : t.busy ? '<span class="pill warn">scanning</span>' :
a ? '<span class="pill ' + (a.state === 'locked' ? 'ok' : a.state === 'tuning' ? 'warn' : 'err') + '">' + esc(a.state === 'locked' ? 'LOCK' : a.state) + '</span>' : '<span class="pill">idle</span>') + '</div></div>' +
(a ? '<div class="kv"><span>Mux</span><span>' + esc(a.tuning) + (a.network_name ? ' · ' + esc(a.network_name) : '') + '</span>' +
'<span>Clients</span><span>' + a.subscribers + (a.top_priority ? ' · priority ' + esc(a.top_priority) : '') + '</span>' +
'<span>Stream</span><span class="mono">' + bps(a.bitrate_bps) + ' · ' + dur(a.uptime_secs) + '</span></div>' + signalBlock(a.signal)
'<span>Stream</span><span class="mono">' + bps(a.bitrate_bps) + ' · ' + dur(a.uptime_secs) + (a.pid_filtered ? ' · <span title="' + esc(T('Only the PIDs that clients need are read from the tuner – less CPU. The bitrate covers just these PIDs.')) + '">' + esc(T('PID filter')) + '</span>' : '') + '</span></div>' + signalBlock(a.signal) + lockBits(a.signal) + tsHealth(a)
: '<div class="muted small">' + (t.last_error ? 'Last error: ' + esc(t.last_error) : 'Tuner is waiting for clients.') + '</div>') +
hardwareBlock(t) +
(charts ? '<div class="grid ' + (status.tuners.length > 1 ? 'g2' : 'g4') + ' tuner-charts">' + charts + '</div>' : '') +
'</div>';
}).join('') || '<div class="panel"><div class="empty">No DVB adapters detected. Check /dev/dvb and permissions (group <code>video</code>).</div></div>';
openHw.forEach(function (id) { var d = $('details.hw[data-hw="' + id + '"]', $('#ov-tuners')); if (d) d.open = true; });
bindChartHover($('#ov-tuners'), tdata);
}
function renderStatus(s) {
@@ -431,6 +516,18 @@
// ------------------------------------------------------------ TV
function loadChannels() { return api('GET', '/api/channels'); }
/** Favourite channels (ids), kept in the user's profile. */
var FAV = {
list: function () { try { var v = JSON.parse(SDVB_STORE.get('sdvb-fav') || '[]'); return Array.isArray(v) ? v : []; } catch (e) { return []; } },
has: function (id) { return FAV.list().indexOf(id) >= 0; },
toggle: function (id) {
var l = FAV.list(), i = l.indexOf(id);
if (i >= 0) l.splice(i, 1); else l.push(id);
SDVB_STORE.set('sdvb-fav', JSON.stringify(l));
return i < 0;
}
};
var FAV_GROUP = '__fav';
function pageTv(view, args) {
view.innerHTML = '<div class="tv"><div class="panel tv-list" id="tv-list"></div><div><div class="player" id="tv-player"><div class="overlay"><div>Pick a channel from the list</div></div></div>' +
@@ -444,22 +541,38 @@
var f = filter.toLowerCase();
var groups = [];
channels.forEach(function (c) { if (c.enabled && c.grp && groups.indexOf(c.grp) < 0) groups.push(c.grp); });
if (group && groups.indexOf(group) < 0) group = '';
var list = channels.filter(function (c) { return c.enabled && (!group || c.grp === group) && (!f || c.name.toLowerCase().indexOf(f) >= 0 || String(c.number) === f); });
var favs = FAV.list();
var hasFav = channels.some(function (c) { return c.enabled && favs.indexOf(c.id) >= 0; });
if (group && group !== FAV_GROUP && groups.indexOf(group) < 0) group = '';
if (group === FAV_GROUP && !hasFav) group = '';
var list = channels.filter(function (c) {
return c.enabled && (!group || (group === FAV_GROUP ? favs.indexOf(c.id) >= 0 : c.grp === group)) && (!f || c.name.toLowerCase().indexOf(f) >= 0 || String(c.number) === f);
});
$('#tv-list').classList.toggle('hide-logos', !P.get('logos'));
$('#tv-list').classList.toggle('hide-progress', !P.get('progress'));
$('#tv-list').innerHTML = '<div class="search"><input id="tv-search" placeholder="Search channel…" value="' + esc(filter) + '">' +
(groups.length > 1 ? '<select id="tv-group"><option value="">' + esc(T('All')) + '</option>' + groups.map(function (g) { return '<option' + (g === group ? ' selected' : '') + '>' + esc(g) + '</option>'; }).join('') + '</select>' : '') + '</div>' +
(groups.length > 1 || hasFav ? '<select id="tv-group"><option value="">' + esc(T('All')) + '</option>' +
(hasFav ? '<option value="' + FAV_GROUP + '"' + (group === FAV_GROUP ? ' selected' : '') + '>' + esc(T('Favourites')) + '</option>' : '') +
(groups.length > 1 ? groups.map(function (g) { return '<option' + (g === group ? ' selected' : '') + '>' + esc(g) + '</option>'; }).join('') : '') + '</select>' : '') + '</div>' +
(list.length ? list.map(function (c) {
var fav = favs.indexOf(c.id) >= 0;
return '<div class="ch-item' + (current && current.id === c.id ? ' active' : '') + '" data-id="' + c.id + '"><div class="n">' + c.number + '</div>' + logo(c) +
'<div class="t"><div class="name">' + esc(c.name) + '</div><div class="now">' + (c.now ? hm(c.now.start) + ' ' + esc(c.now.title) : (c.kind === 'radio' ? 'radio' : '&nbsp;')) + '</div>' +
'<div class="t"><div class="name">' + esc(c.name) + '<button class="fav' + (fav ? ' on' : '') + '" data-fav="' + c.id + '" title="' + esc(T(fav ? 'Remove from favourites' : 'Add to favourites')) + '">' + ico(fav ? 'starOn' : 'star') + '</button></div><div class="now">' + (c.now ? hm(c.now.start) + ' ' + esc(c.now.title) : (c.kind === 'radio' ? 'radio' : '&nbsp;')) + '</div>' +
(c.now ? '<div class="meter"><i style="width:' + progressPct(c.now) + '%"></i></div>' : '') + '</div></div>';
}).join('') : '<div class="empty">No channels – run a scan on the Tuners page.</div>');
var gs = $('#tv-group');
if (gs) gs.addEventListener('change', function () { group = gs.value; try { localStorage.setItem('sdvb-group', group); } catch (e) {} renderList(); });
if (gs) gs.addEventListener('change', function () { group = gs.value; try { SDVB_STORE.set('sdvb-group', group); } catch (e) {} renderList(); });
var s = $('#tv-search');
s.addEventListener('input', function () { filter = s.value; var pos = s.selectionStart; renderList(); var n = $('#tv-search'); n.focus(); n.setSelectionRange(pos, pos); });
$$('.ch-item', $('#tv-list')).forEach(function (e) { e.addEventListener('click', function () { play(+e.getAttribute('data-id')); }); });
$$('[data-fav]', $('#tv-list')).forEach(function (b) {
b.addEventListener('click', function (ev) {
ev.stopPropagation();
var on = FAV.toggle(+b.getAttribute('data-fav'));
toast(T(on ? 'Added to favourites' : 'Removed from favourites'));
renderList();
});
});
}
function renderInfo() {
@@ -471,8 +584,8 @@
'<div class="desc">' + esc(n.description || n.summary || '') + '</div>' : '<h2>' + esc(c.name) + '</h2><div class="muted">No EPG data for this moment.</div>') +
(nx ? '<div class="small muted" style="margin-top:8px">Next: <b>' + hm(nx.start) + '</b> ' + esc(nx.title) + '</div>' : '') +
'</div><div class="actions" style="align-items:flex-start">' +
(n && isAdmin() ? '<button class="btn" id="tv-rec">● Record programme</button>' : '') +
'<button class="btn" id="tv-pip" title="Picture-in-picture (P)">⧉ PiP</button><button class="btn" id="tv-full" title="F">⛶ Fullscreen</button></div></div>';
(n && isAdmin() ? '<button class="btn" id="tv-rec">' + ico('record') + 'Record programme</button>' : '') +
'<button class="btn" id="tv-pip" title="Picture-in-picture (P)">' + ico('pip') + 'PiP</button><button class="btn" id="tv-full" title="F">' + ico('fullscreen') + 'Fullscreen</button></div></div>';
var r = $('#tv-rec');
if (r) r.addEventListener('click', function () { api('POST', '/api/recordings', { event_id: n.id }).then(function () { toast('Recording scheduled: ' + n.title); }).catch(fail); });
$('#tv-full').addEventListener('click', fullscreen);
@@ -489,7 +602,7 @@
(evs.length ? evs.map(function (e) {
var cls = e.stop < t ? 'past' : e.start <= t ? 'cur' : '';
return '<div class="ev ' + cls + '"><span class="tm">' + hm(e.start) + '</span><span>' + esc(e.title) + '</span>' +
(e.start > t && isAdmin() ? '<button class="btn small ghost" data-rec="' + e.id + '" title="Record">●</button>' : '<span></span>') + '</div>';
(e.start > t && isAdmin() ? '<button class="btn small ghost" data-rec="' + e.id + '" title="Record">' + ico('record') + '</button>' : '<span></span>') + '</div>';
}).join('') : '<div class="muted">No EPG yet. Data appears after EIT is collected from the mux or XMLTV is imported.</div>') + '</div>';
$$('[data-rec]', $('#tv-day')).forEach(function (b) {
b.addEventListener('click', function () { api('POST', '/api/recordings', { event_id: +b.getAttribute('data-rec') }).then(function () { toast('Recording scheduled'); renderDay(); }).catch(fail); });
@@ -501,12 +614,12 @@
var c = current;
if (!c) return;
var svc = c.service || {};
var profiles = [['auto', 'Automatic'], ['pass', 'Original'], ['aac', 'Audio → AAC'], ['h264', 'H.264 720p']];
var profiles = [['auto', 'Automatic'], ['pass', 'Original'], ['aac', 'AAC audio'], ['h264', 'H.264 720p']];
var noFfmpeg = app.info && app.info.ffmpeg === false;
var caps = [svc.video].concat((svc.audio || []).map(function (a) { return a.replace(/ \(.*\)$/, ''); })).filter(function (x, i, a) { return x && a.indexOf(x) === i; });
var capsHtml = caps.map(function (x) {
var ok = window.SDVB.codecSupported(x);
return '<span class="pill ' + (ok ? 'ok' : 'err') + '" title="' + esc(T(ok ? 'Supported by this browser' : 'Not supported by this browser')) + '">' + esc(x) + ' ' + (ok ? '✓' : '✗') + '</span>';
return '<span class="pill ' + (ok ? 'ok' : 'err') + '" title="' + esc(T(ok ? 'Supported by this browser' : 'Not supported by this browser')) + '">' + esc(x) + ' ' + ico(ok ? 'check' : 'cross') + '</span>';
}).join(' ');
var why = window.SDVB.explain(svc.video, svc.audio);
$('#tv-tools').innerHTML = '<header><h2>Stream</h2><span class="pill">' + esc(svc.video || (c.kind === 'radio' ? 'radio' : '?')) + ' · ' + esc((svc.audio || []).join(', ') || '–') + '</span></header>' +
@@ -521,8 +634,8 @@
(why ? '<p class="hint">' + esc(why) + (noFfmpeg ? ' ' + esc(T('Without ffmpeg on the server use VLC or a browser/device that decodes these codecs.')) : '') + '</p>' : '') +
'<div style="margin-top:10px" class="copy-row"><code>' + esc(location.origin + '/hls/' + c.id + '/index.m3u8') + '</code><button class="btn small" data-copy="hls">HLS</button></div>' +
'<div class="copy-row"><code>' + esc(location.origin + '/stream/channelid/' + c.id + '?profile=pass') + '</code><button class="btn small" data-copy="ts">TS</button></div>' +
'<div class="row" style="margin-top:6px"><a class="btn small" href="/playlist/channelid/' + c.id + '" download="' + esc(c.name) + '.m3u">▶ VLC (.m3u)</a></div>' +
'<p class="hint">' + esc(T('Shortcuts: ↑/↓ channel, digits – number, F – fullscreen, P – picture-in-picture, M – mute, ? – help.')) + '</p>' +
'<div class="row" style="margin-top:6px"><a class="btn small" href="/playlist/channelid/' + c.id + '" download="' + esc(c.name) + '.m3u">' + ico('vlc') + 'VLC (.m3u)</a></div>' +
'<p class="hint">' + esc(T('Shortcuts: arrow up/down – channel, digits – number, F – fullscreen, P – picture-in-picture, M – mute, ? – help.')) + '</p>' +
'<p class="hint">The “Automatic” profile checks which codecs your browser supports (e.g. HEVC, AC-3) and enables ffmpeg transcoding when needed.</p>';
$('#tv-profile').addEventListener('change', function (e) {
wantProfile = e.target.value;
@@ -540,7 +653,7 @@
current = c;
if (app.player) { app.player.destroy(); app.player = null; }
$('#tv-player').innerHTML = '<div class="overlay"><div style="text-align:center"><div class="eyebrow">' + esc(c.number + ' · ' + c.name) + '</div>' +
'<button class="btn primary" id="tv-start" style="margin-top:10px">▶ ' + esc(T('Play')) + '</button></div></div>';
'<button class="btn primary" id="tv-start" style="margin-top:10px">' + ico('play') + esc(T('Play')) + '</button></div></div>';
$('#tv-start').addEventListener('click', function () { play(c.id); });
renderList(); renderInfo(); renderDay(); renderTools('');
}
@@ -582,11 +695,11 @@
play(list[(i + delta + list.length) % list.length].id);
}
var digits = '', digitTimer = null;
function osd(text) {
function osd(text, icon) {
var box = $('#tv-player');
var o = $('.osd', box);
if (!o) { o = document.createElement('div'); o.className = 'osd'; box.appendChild(o); }
o.textContent = text;
o.innerHTML = (icon ? ico(icon) : '') + esc(text);
o.classList.add('show');
clearTimeout(o._t);
o._t = setTimeout(function () { o.classList.remove('show'); }, 1500);
@@ -600,7 +713,7 @@
else if (k === 'ArrowDown' || k === 'PageDown') { zap(1); e.preventDefault(); }
else if (k === 'f' || k === 'F') fullscreen();
else if (k === 'p' || k === 'P') pip();
else if ((k === 'm' || k === 'M') && v) { v.muted = !v.muted; osd(v.muted ? '🔇' : '🔊'); }
else if ((k === 'm' || k === 'M') && v) { v.muted = !v.muted; osd(T(v.muted ? 'Sound off' : 'Sound on'), v.muted ? 'mute' : 'volume'); }
else if (k === ' ' && v) { if (v.paused) v.play(); else v.pause(); e.preventDefault(); }
else if (k === '?') shortcutsHelp();
else if (/^[0-9]$/.test(k)) {
@@ -615,7 +728,7 @@
}
}
function shortcutsHelp() {
modal('Keyboard shortcuts', '<div class="kv">' + [['↑ / ↓', 'Previous / next channel'], ['0–9', 'Select channel by number'], ['F', 'Fullscreen'], ['P', 'Picture-in-picture'], ['M', 'Mute'], ['Space', 'Pause / resume'], ['?', 'This help']].map(function (x) {
modal('Keyboard shortcuts', '<div class="kv">' + [['Arrow up / down', 'Previous / next channel'], ['0–9', 'Select channel by number'], ['F', 'Fullscreen'], ['P', 'Picture-in-picture'], ['M', 'Mute'], ['Space', 'Pause / resume'], ['?', 'This help']].map(function (x) {
return '<span>' + esc(x[0]) + '</span><span>' + esc(x[1]) + '</span>';
}).join('') + '</div>');
}
@@ -628,7 +741,7 @@
var id = +(args[0] || 0) || (function () { try { return +localStorage.getItem('sdvb-last') || 0; } catch (e) { return 0; } })();
if (id && channels.some(function (c) { return c.id === id; })) {
// the TV tab (also #/tv/<id> after a reload or history navigation) only selects
// the channel; playback starts on click, from an explicit ▶ link (#/tv/<id>/play)
// the channel; playback starts on click, from an explicit play link (#/tv/<id>/play)
// or when autoplay is on in Preferences – so visiting the tab does not take a tuner
if (args[1] === 'play' || P.get('autoplay')) play(id); else select(id);
}
@@ -645,13 +758,63 @@
}
// ------------------------------------------------------------ EPG
/** Programme reminders (kept in the profile): a notification 2 min before the start
* while the panel is open in any tab or on any device. */
var REMIND = {
LEAD: 120,
list: function () { try { var v = JSON.parse(SDVB_STORE.get('sdvb-remind') || '[]'); return Array.isArray(v) ? v : []; } catch (x) { return []; } },
save: function (l) { SDVB_STORE.set('sdvb-remind', JSON.stringify(l)); },
key: function (e) { return e.channel_id + ':' + e.start; },
has: function (e) { var k = REMIND.key(e); return REMIND.list().some(function (r) { return r.k === k; }); },
toggle: function (e, ch) {
var k = REMIND.key(e), l = REMIND.list(), i = -1;
l.forEach(function (r, j) { if (r.k === k) i = j; });
if (i >= 0) { l.splice(i, 1); REMIND.save(l); return false; }
l.push({ k: k, ch: ch.id, chName: ch.name, title: e.title, start: e.start });
REMIND.save(l);
if (window.Notification && Notification.permission === 'default') { try { Notification.requestPermission(); } catch (x) {} }
return true;
},
check: function () {
var t = now(), l = REMIND.list(), keep = [], fired = false;
l.forEach(function (r) {
if (r.start - t > REMIND.LEAD) { keep.push(r); return; }
fired = true;
if (r.start < t - 600) return; // missed long ago (panel was closed)
var msg = r.title + ' – ' + r.chName + ' ' + hm(r.start);
toast(msg);
if (window.Notification && Notification.permission === 'granted') {
try {
var opts = { body: msg, tag: r.k, icon: '/assets/icon-192.png', data: { url: '/#/tv/' + r.ch + '/play' } };
// installed app (service worker): the notification also works from the background
if (navigator.serviceWorker && navigator.serviceWorker.controller) {
navigator.serviceWorker.ready.then(function (reg) { reg.showNotification(T('Starting soon'), opts); });
} else {
var n = new Notification(T('Starting soon'), opts);
n.onclick = function () { window.focus(); location.hash = '#/tv/' + r.ch + '/play'; n.close(); };
}
} catch (x) {}
}
});
if (fired) REMIND.save(keep);
}
};
setInterval(function () { if (app.me) REMIND.check(); }, 20000);
function eventModal(e, ch) {
var body = modal(e.title,
'<div class="kv"><span>Channel</span><span>' + esc(ch ? ch.number + ' · ' + ch.name : '') + '</span><span>Time</span><span>' + dt(e.start) + ' – ' + hm(e.stop) + ' (' + dur(e.stop - e.start) + ')</span>' +
(e.genre ? '<span>Genre</span><span>' + esc(e.genre) + '</span>' : '') + (e.rating ? '<span>Age</span><span>' + e.rating + '+</span>' : '') +
'<span>Source</span><span>' + esc(e.source === 'xmltv' ? 'XMLTV' : 'EIT (broadcast)') + '</span></div>' +
(e.summary ? '<p><b>' + esc(e.summary) + '</b></p>' : '') + '<p style="white-space:pre-line">' + esc(e.description || '') + '</p>' +
'<div class="modal-foot">' + (ch ? '<a class="btn" href="#/tv/' + ch.id + '/play">▶ Watch channel</a>' : '') + (isAdmin() && e.stop > now() ? '<button class="btn primary" id="ev-rec">● Record</button>' : '') + '</div>');
'<div class="modal-foot">' + (ch && e.start > now() ? '<button class="btn" id="ev-remind">' + ico('bell') + '<span>' + esc(T(REMIND.has(e) ? 'Reminder set' : 'Remind me')) + '</span></button>' : '') +
(ch ? '<a class="btn" href="#/tv/' + ch.id + '/play">' + ico('play') + 'Watch channel</a>' : '') + (isAdmin() && e.stop > now() ? '<button class="btn primary" id="ev-rec">' + ico('record') + 'Record</button>' : '') + '</div>');
var rm = $('#ev-remind', body);
if (rm) rm.addEventListener('click', function () {
var on = REMIND.toggle(e, ch);
$('span', rm).textContent = T(on ? 'Reminder set' : 'Remind me');
toast(on ? T('You will be reminded 2 minutes before the start') : T('Reminder removed'));
});
var r = $('#ev-rec', body);
if (r) r.addEventListener('click', function () {
api('POST', '/api/recordings', { event_id: e.id }).then(function () { toast('Recording scheduled: ' + e.title); closeModal(); }).catch(fail);
@@ -664,7 +827,7 @@
var start = Math.floor((now() - 3600) / 1800) * 1800;
var hours = 12;
view.innerHTML = head('Electronic programme guide', 'TV guide', 'EPG from the broadcast (EIT) and external XMLTV sources.',
'<button class="btn" id="epg-prev">◀ 6 h</button><button class="btn" id="epg-now">Now</button><button class="btn" id="epg-next">6 h ▶</button>' +
'<button class="btn" id="epg-prev">' + ico('prev') + '6 h</button><button class="btn" id="epg-now">Now</button><button class="btn" id="epg-next">6 h' + ico('next') + '</button>' +
(isAdmin() ? '<button class="btn" id="epg-grab">Grab EPG now</button>' : '')) + '<div class="epg" id="epg"></div>';
function render() {
var end = start + hours * 3600;
@@ -742,7 +905,7 @@
return true;
});
}
function saveFilters() { try { localStorage.setItem('sdvb-chfilter', JSON.stringify(F)); } catch (e) {} }
function saveFilters() { try { SDVB_STORE.set('sdvb-chfilter', JSON.stringify(F)); } catch (e) {} }
function renderFilters() {
var groups = [];
channels.forEach(function (c) { if (c.grp && groups.indexOf(c.grp) < 0) groups.push(c.grp); });
@@ -795,13 +958,13 @@
list.map(function (c) {
var s = c.service || {};
var pr = problem(c);
return '<tr data-id="' + c.id + '" draggable="' + (isAdmin() ? 'true' : 'false') + '"' + (c.enabled ? '' : ' class="off"') + '><td class="drag">⠿</td><td class="num">' + c.number + '</td><td>' + logo(c) + '</td><td><b>' + esc(c.name) + '</b>' +
return '<tr data-id="' + c.id + '" draggable="' + (isAdmin() ? 'true' : 'false') + '"' + (c.enabled ? '' : ' class="off"') + '><td class="drag">' + ico('grip') + '</td><td class="num">' + c.number + '</td><td>' + logo(c) + '</td><td><b>' + esc(c.name) + '</b>' +
(pr ? ' <span class="pill err">' + esc(T(pr)) + '</span>' : '') + (!pr && unknownStreams(c) ? ' <span class="pill" title="' + esc(T('The scan did not see this service\'s stream list in time. It is filled in when the channel is played or with “Detect streams”.')) + '">' + esc(T('streams unknown')) + '</span>' : '') + (s.scrambled ? ' <span class="pill warn">scrambled</span>' : '') + (c.kind === 'radio' ? ' <span class="pill">radio</span>' : '') + '</td><td>' + esc(c.grp) + '</td>' +
'<td class="small mono">' + esc([s.video].concat(s.audio || []).filter(Boolean).join(' · ')) + '</td><td class="small muted">' + esc(c.mux || '') + '</td>' +
'<td class="small">' + (c.now ? esc(c.now.title) : '<span class="muted">–</span>') + '</td>' +
'<td>' + sw(c.enabled, 'data-en="' + c.id + '"' + (isAdmin() ? '' : ' disabled')) + '</td>' +
'<td>' + sw(c.share_enabled, 'data-sh="' + c.id + '"' + (isAdmin() ? '' : ' disabled')) + (c.share_enabled && c.share_token ? ' <button class="btn small" data-shcopy="' + esc(c.share_token) + '">Copy link</button>' : '') + '</td>' +
'<td class="actions-cell"><a class="btn small" href="#/tv/' + c.id + '/play">▶</a> <a class="btn small" href="/playlist/channelid/' + c.id + '" download="' + esc(c.name) + '.m3u" title="VLC">VLC</a>' + (isAdmin() ? ' <button class="btn small" data-edit="' + c.id + '">Edit</button>' : '') + '</td></tr>';
'<td class="actions-cell"><a class="btn small" href="#/tv/' + c.id + '/play" title="Watch">' + ico('play') + '</a> <a class="btn small" href="/playlist/channelid/' + c.id + '" download="' + esc(c.name) + '.m3u" title="VLC">VLC</a>' + (isAdmin() ? ' <button class="btn small" data-edit="' + c.id + '">Edit</button>' : '') + '</td></tr>';
}).join('') + '</tbody></table>';
bind();
}
@@ -931,7 +1094,7 @@
function pageRecordings(view) {
view.innerHTML = head('Video recorder', 'Recordings', 'Schedule from the EPG or manually. Play finished recordings in the browser or download them as .ts.',
isAdmin() ? '<button class="btn primary" id="rec-new">+ New recording</button>' : '') +
'<div class="panel"><div class="tabs" id="rec-tabs"><button data-t="upcoming" class="active">Scheduled & running</button><button data-t="schedule">Schedule</button><button data-t="done">Finished</button><button data-t="failed">Failed / cancelled</button><button data-t="rules">Rules (series)</button></div><div class="table-wrap" id="rec-table"></div></div>';
'<div class="panel"><div class="tabs" id="rec-tabs"><button data-t="upcoming" class="active">Scheduled & running</button><button data-t="schedule">Timeline</button><button data-t="done">Finished</button><button data-t="failed">Failed / cancelled</button><button data-t="rules">Rules (series)</button></div><div class="table-wrap" id="rec-table"></div></div>';
var tab = 'upcoming', recs = [];
/** Timeline of upcoming recordings, one row per day, with tuner-conflict warnings. */
function renderSchedule() {
@@ -972,7 +1135,7 @@
var left = (x._s0 - day) / 864, width = Math.max(0.4, (x._s1 - x._s0) / 864);
var cls = 'sched-bar' + (x.conflict ? ' conflict' : '') + (x.status === 'recording' ? ' live' : '');
return '<div class="' + cls + '" style="left:' + left + '%;width:' + width + '%;top:' + (x._lane * 26 + 16) + 'px;--c:' + color(x.mux_id) + '" title="' + esc(x.title + '\n' + x.channel_name + '\n' + hm(x.start) + '–' + hm(x.stop) + (x.conflict ? '\n' + T('Conflict: not enough tuners') : '')) + '">' +
(x.conflict ? '⚠ ' : '') + esc(x.title) + ' <span class="muted">' + esc(x.channel_name) + '</span></div>';
(x.conflict ? ico('warn') : '') + esc(x.title) + ' <span class="muted">' + esc(x.channel_name) + '</span></div>';
}).join('') + '</div></div>';
});
html += '<table style="margin-top:12px"><thead><tr><th>Start</th><th>End</th><th>Title</th><th>Channel</th><th>Status</th></tr></thead><tbody>' + list.map(function (x) {
@@ -1046,8 +1209,8 @@
var st = REC_STATUS[r.status] || [r.status, ''];
return '<tr><td><span class="pill ' + st[1] + '">' + st[0] + '</span></td><td><b>' + esc(r.title) + '</b>' + (r.error ? '<div class="small error-text">' + esc(r.error) + '</div>' : '') + '</td><td>' + esc(r.channel_name) + '</td>' +
'<td class="mono small">' + dt(r.start) + '</td><td class="mono small">' + hm(r.stop) + '</td><td class="num">' + (r.duration ? dur(r.duration) : dur(r.stop - r.start)) + '</td><td class="num">' + (r.size ? bytes(r.size) : '–') + '</td>' +
'<td class="actions-cell">' + (r.autorec_id ? '<span class="pill blue" title="' + esc(T('From a rule')) + '">R</span> ' : '') + (r.file && r.size ? '<button class="btn small" data-play="' + r.id + '">▶ Play</button> <a class="btn small" href="/recordings/' + r.id + '/file" download>Download</a> ' : '') +
(isAdmin() && (r.status === 'scheduled' || r.status === 'recording') ? '<button class="btn small" data-stop="' + r.id + '">' + (r.status === 'recording' ? '■ Stop' : 'Cancel') + '</button> ' : '') +
'<td class="actions-cell">' + (r.autorec_id ? '<span class="pill blue" title="' + esc(T('From a rule')) + '">R</span> ' : '') + (r.file && r.size ? '<button class="btn small" data-play="' + r.id + '">' + ico('play') + 'Play</button> <a class="btn small" href="/recordings/' + r.id + '/file" download>Download</a> ' : '') +
(isAdmin() && (r.status === 'scheduled' || r.status === 'recording') ? '<button class="btn small" data-stop="' + r.id + '">' + (r.status === 'recording' ? ico('stop') + 'Stop' : 'Cancel') + '</button> ' : '') +
(isAdmin() ? '<button class="btn small danger" data-del="' + r.id + '">Delete</button>' : '') + '</td></tr>';
}).join('') + '</tbody></table>' : '<div class="empty">No recordings in this category.</div>';
$$('[data-play]').forEach(function (b) {
@@ -1095,7 +1258,7 @@
// ------------------------------------------------------------ TUNERS
function pageTuners(view) {
view.innerHTML = head('Hardware & muxes', 'Tuners & scanning', 'DVB-T/T2/C cards (e.g. Si2168), frequency scanning and saved muxes.',
isAdmin() ? '<button class="btn" id="ad-refresh">Detect adapters</button>' : '') +
'<a class="btn" href="#/signal">' + ico('antenna') + 'Antenna meter</a>' + (isAdmin() ? '<button class="btn" id="ad-refresh">Detect adapters</button>' : '')) +
'<div class="grid g2"><div class="panel"><header><h2>Adapters</h2></header><div id="ad-list"></div></div>' +
'<div class="panel"><header><h2>Scanning</h2><span id="scan-pill"></span></header><div id="scan-box"></div></div></div>' +
'<div class="panel"><header><h2>Muxes</h2>' + (isAdmin() ? '<button class="btn small" id="mux-add">+ Add manually</button>' : '') + '</header><div class="table-wrap" id="mux-table"></div></div>';
@@ -1176,7 +1339,7 @@
if (idle && s.idle_scan) {
idle.textContent = s.idle_scan.enabled
? T('Background scan of saved muxes when tuners are idle: every') + ' ' + s.idle_scan.every_hours + ' h · ' + T('last:') + ' ' + (s.idle_scan.last ? dt(s.idle_scan.last) : '–')
: T('Background scanning is off (Settings → Scanning).');
: T('Background scanning is off (Settings, section Scanning).');
}
var go = $('#scan-go'), stop = $('#scan-stop');
// a manual scan may replace a background one
@@ -1257,6 +1420,7 @@
'<p class="hint">A token allows playing streams from outside the local network (e.g. a TV at your family’s place). It can be limited to selected addresses/networks.</p></div>' +
'<div class="panel"><header><h2>Panel users</h2>' + (isAdmin() ? '<button class="btn small" id="usr-add">+ New user</button>' : '') + '</header><div id="users"></div>' +
'<div class="row" style="margin-top:10px"><button class="btn small" id="pw-change">Change my password</button></div></div></div>' +
'<div class="panel" id="account" style="margin-top:10px"></div>' +
(isAdmin() ? '<div class="panel"><header><h2>Access control (ACL)</h2><button class="btn small primary" id="acl-save">Save ACL</button></header><div class="form-grid" id="acl"></div></div>' : '');
function links() {
@@ -1269,6 +1433,7 @@
return '<div style="margin-top:10px"><div class="label">' + esc(l.name) + '</div>' +
'<div class="copy-row"><span class="pill acc">M3U</span><code>' + esc(l.m3u) + '</code><button class="btn small" data-c>Copy</button></div>' +
'<div class="copy-row"><span class="pill blue">HLS</span><code>' + esc(l.m3u_hls) + '</code><button class="btn small" data-c>Copy</button></div>' +
(FAV.list().length ? '<div class="copy-row"><span class="pill acc">' + ico('starOn') + 'M3U</span><code>' + esc(l.m3u + (l.m3u.indexOf('?') >= 0 ? '&' : '?') + 'channels=' + FAV.list().join(',')) + '</code><button class="btn small" data-c>Copy</button></div>' : '') +
'<div class="copy-row"><span class="pill ok">EPG</span><code>' + esc(l.epg) + '</code><button class="btn small" data-c>Copy</button></div>' +
'<div class="copy-row"><span class="pill warn">TVH</span><code>' + esc(l.tvh_playlist) + '</code><button class="btn small" data-c>Copy</button></div>' +
'<div class="copy-row"><span class="pill warn">TVH</span><code>' + esc(l.tvh_xmltv) + '</code><button class="btn small" data-c>Copy</button></div></div>';
@@ -1316,7 +1481,7 @@
var hosts = Object.keys(m || {});
if (!hosts.length) return '';
return '<div class="full small muted">' + esc(T('DDNS host names now resolve to:')) + ' ' + hosts.map(function (h) {
return '<span class="mono">' + esc(h) + ' → ' + esc((m[h] || []).join(', ') || T('not resolved')) + '</span>';
return '<span class="mono">' + esc(h) + ': ' + esc((m[h] || []).join(', ') || T('not resolved')) + '</span>';
}).join(' · ') + '</div>';
}
function acl() {
@@ -1334,7 +1499,7 @@
};
}).catch(fail);
}
links(); tokens(); users(); acl();
links(); tokens(); users(); acl(); renderAccount();
$('#pw-change').addEventListener('click', function () {
var body = modal('Change password', '<div class="form-grid"><label class="full">Current password<input type="password" name="cur" autocomplete="current-password"></label><label class="full">New password<input type="password" name="new" autocomplete="new-password"></label></div><div class="modal-foot"><button class="btn primary" id="pw-save">Change</button></div>');
$('#pw-save', body).addEventListener('click', function () {
@@ -1360,7 +1525,7 @@
// ------------------------------------------------------------ LOGS
function pageLogs(view) {
view.innerHTML = head('Diagnostics', 'Logs', 'What the server is doing: tuners, streams, access, EPG and recordings. The last 4000 entries are kept in memory.',
'<a class="btn" href="/api/logs/download" download>⤓ Download</a><button class="btn" id="log-clear">Clear view</button>') +
'<a class="btn" href="/api/logs/download" download>' + ico('download') + 'Download</a><button class="btn" id="log-clear">Clear view</button>') +
'<div class="panel"><div class="tabs" id="log-cats"></div>' +
'<div class="filters" style="border:0;padding:8px 0 4px"><select id="log-level"><option value="">' + esc(T('All levels')) + '</option><option value="info">info+</option><option value="warn">' + esc(T('warnings and errors')) + '</option><option value="error">' + esc(T('errors only')) + '</option></select>' +
'<input id="log-q" placeholder="' + esc(T('Search…')) + '"><label class="check"><input type="checkbox" id="log-follow" checked> ' + esc(T('Follow')) + '</label><span class="spacer"></span><span class="muted small mono" id="log-count"></span></div>' +
@@ -1422,7 +1587,7 @@
var profile = 'auto';
try { profile = localStorage.getItem('sdvb-profile') || 'auto'; } catch (e) {}
box.innerHTML = '<header><h2>Appearance</h2><button class="btn small" id="prefs-reset">Reset to defaults</button></header>' +
'<p class="hint" style="margin-top:-4px">Interface preferences are stored in this browser.</p>' +
'<p class="hint" style="margin-top:-4px">Interface preferences are saved in your user profile and follow you to every device.</p>' +
row('Language', langSelect('pref-lang', false)) +
row('Theme', seg('theme', [['dark', 'Dark'], ['midnight', 'Midnight (OLED)'], ['light', 'Light'], ['system', 'System default']])) +
row('Accent colour', '<div class="swatches">' + P.accents.map(function (a) {
@@ -1432,7 +1597,7 @@
row('Interface scale', seg('scale', [[90, '90%'], [100, '100%'], [110, '110%'], [125, '125%']])) +
row('Sidebar', seg('sidebar', [['hover', 'Expand on hover'], ['pinned', 'Always expanded']])) +
row('Start page', seg('start', [['overview', 'Overview'], ['tv', 'TV'], ['epg', 'TV guide'], ['channels', 'Channels']])) +
row('Default player profile', '<div class="seg" id="pref-profile">' + [['auto', 'Automatic'], ['pass', 'Original'], ['aac', 'Audio → AAC'], ['h264', 'H.264 720p']].map(function (o) {
row('Default player profile', '<div class="seg" id="pref-profile">' + [['auto', 'Automatic'], ['pass', 'Original'], ['aac', 'AAC audio'], ['h264', 'H.264 720p']].map(function (o) {
return '<button data-p="' + o[0] + '"' + (profile === o[0] ? ' class="on"' : '') + '>' + esc(o[1]) + '</button>';
}).join('') + '</div>') +
row('EPG grid zoom', seg('epgZoom', [[3, 'Narrow'], [4, 'Normal'], [6, 'Wide']])) +
@@ -1460,10 +1625,225 @@
}
// ------------------------------------------------------------ SETTINGS
function pageSettings(view) {
// ------------------------------------------------------------ ANTENNA METER
function pageSignal(view) {
view.innerHTML = head('Antenna', 'Antenna meter', 'Live signal of a tuner, refreshed every second – handy while aligning the antenna (open it on the phone).',
'<label class="check"><input type="checkbox" id="sg-sound"> ' + esc(T('Sound')) + '</label>') +
'<div class="panel"><div class="row sg-pick" id="sg-pick"></div></div><div id="sg-body"></div>';
var adapters = [], muxes = [], sel = SDVB_STORE.get('sdvb-sigad') || '', hist = { t: [], snr: [], str: [] };
var holdMux = null, holdTimer = null, audio = null, beepTimer = null, lastSnr = null;
function quality(snr, locked) {
if (!locked) return ['No lock', 'bad'];
if (snr == null) return ['Locked', 'ok'];
// DVB-T2 256-QAM needs ~20 dB, DVB-T 64-QAM ~18 dB
if (snr >= 26) return ['Excellent', 'ok'];
if (snr >= 21) return ['Good', 'ok'];
if (snr >= 17) return ['Fair', 'warn'];
return ['Weak', 'bad'];
}
function pick() {
var adOpts = adapters.map(function (a) { return '<option value="' + esc(a.id) + '"' + (a.id === sel ? ' selected' : '') + '>' + esc(a.id + ' · ' + a.name) + '</option>'; }).join('');
var muxOpts = muxes.map(function (m) { return '<option value="' + m.id + '">' + esc(m.description + (m.network_name ? ' · ' + m.network_name : '')) + '</option>'; }).join('');
$('#sg-pick').innerHTML = '<label>' + esc(T('Tuner')) + '<select id="sg-ad">' + adOpts + '</select></label>' +
(isAdmin() && muxes.length ? '<label>' + esc(T('Tune multiplex')) + '<select id="sg-mux"><option value="">–</option>' + muxOpts + '</select></label>' +
'<button class="btn" id="sg-tune">' + esc(T('Tune')) + '</button>' : '');
$('#sg-ad').addEventListener('change', function () { sel = $('#sg-ad').value; SDVB_STORE.set('sdvb-sigad', sel); hist = { t: [], snr: [], str: [] }; });
var tb = $('#sg-tune');
if (tb) tb.addEventListener('click', function () {
var id = +$('#sg-mux').value;
if (!id) return;
release();
api('POST', '/api/signal/hold', { mux_id: id, seconds: 90 }).then(function () {
holdMux = id; hist = { t: [], snr: [], str: [] };
toast(T('Tuning…'));
holdTimer = setInterval(function () { api('POST', '/api/signal/hold', { mux_id: id, seconds: 90 }).catch(function () {}); }, 60000);
}).catch(fail);
});
}
function release() {
if (holdTimer) { clearInterval(holdTimer); holdTimer = null; }
if (holdMux) { api('POST', '/api/signal/hold', { mux_id: holdMux, seconds: 0 }).catch(function () {}); holdMux = null; }
}
function beep() {
// satellite-finder style: the better the SNR, the faster and higher the beeps
if (!$('#sg-sound') || !$('#sg-sound').checked || lastSnr == null) { beepTimer = setTimeout(beep, 500); return; }
try {
audio = audio || new (window.AudioContext || window.webkitAudioContext)();
var o = audio.createOscillator(), g = audio.createGain();
o.frequency.value = 300 + Math.max(0, Math.min(35, lastSnr)) * 30;
g.gain.value = 0.08;
o.connect(g); g.connect(audio.destination);
o.start(); o.stop(audio.currentTime + 0.06);
} catch (e) {}
beepTimer = setTimeout(beep, Math.max(90, 1100 - Math.max(0, lastSnr) * 30));
}
function render(a) {
var act = a && a.active, sig = act && act.signal;
if (!a) { $('#sg-body').innerHTML = '<div class="panel"><div class="empty">' + esc(T('No DVB adapters detected.')) + '</div></div>'; return; }
if (!sig) {
lastSnr = null;
$('#sg-body').innerHTML = '<div class="panel"><div class="empty">' + esc(T('The tuner is idle. Start watching a channel or pick a multiplex above and press “Tune”.')) + '</div></div>';
return;
}
var q = quality(sig.snr_db, sig.locked);
lastSnr = sig.locked ? sig.snr_db : null;
hist.t.push(now()); hist.snr.push(sig.snr_db); hist.str.push(sig.strength_pct);
if (hist.t.length > 120) { hist.t.shift(); hist.snr.shift(); hist.str.shift(); }
var snrPct = sig.snr_db != null ? Math.min(100, Math.max(0, sig.snr_db * 100 / 32)) : (sig.snr_pct || 0);
$('#sg-body').innerHTML =
'<div class="panel sg-main"><div class="sg-verdict ' + q[1] + '">' + esc(T(q[0])) + '</div>' +
'<div class="sg-mux mono muted">' + esc(act.tuning) + '</div>' +
'<div class="sg-grid">' +
'<div><div class="label">' + esc(T('Strength')) + '</div><div class="sg-big">' + (sig.strength_pct != null ? sig.strength_pct.toFixed(0) + '<small>%</small>' : '–') + '</div>' +
'<div class="meter ' + (sig.strength_pct > 50 ? 'good' : sig.strength_pct > 25 ? '' : 'bad') + '"><i style="width:' + (sig.strength_pct || 0) + '%"></i></div>' +
'<div class="mono small muted">' + (sig.strength_dbm != null ? sig.strength_dbm.toFixed(1) + ' dBm' : '&nbsp;') + '</div></div>' +
'<div><div class="label">SNR</div><div class="sg-big">' + (sig.snr_db != null ? sig.snr_db.toFixed(1) + '<small>dB</small>' : sig.snr_pct != null ? sig.snr_pct.toFixed(0) + '<small>%</small>' : '–') + '</div>' +
'<div class="meter blue"><i style="width:' + snrPct + '%"></i></div><div class="mono small muted">' + (sig.ber != null ? 'BER ' + esc(fmtNum(sig.ber, 'ber')) : '&nbsp;') + '</div></div>' +
'</div>' + lockBits(sig) +
'<div class="kv" style="margin-top:8px"><span>' + esc(T('Uncorrected blocks')) + '</span><span class="mono">' + (sig.uncorrected != null ? sig.uncorrected : '–') + '</span>' +
'<span>' + esc(T('Stream errors')) + '</span><span class="mono">CC ' + act.ts.cc_errors + ' · TEI ' + act.ts.tei_errors + '</span>' +
'<span>' + esc(T('Multiplex bitrate')) + '</span><span class="mono">' + bps(act.bitrate_bps) + '</span></div></div>' +
'<div class="grid g2" style="margin-top:10px">' +
chartCard('sg-snr', 'SNR', [{ name: 'SNR', values: hist.snr }], hist.t, { unit: 'dB', min: 0, floor: 10, noArea: true }) +
chartCard('sg-str', 'Signal strength', [{ name: '%', values: hist.str }], hist.t, { unit: '%', min: 0, max: 100 }) + '</div>';
}
function poll() {
api('GET', '/api/adapters').then(function (list) {
var changed = list.length !== adapters.length;
adapters = list;
if (!sel || !list.some(function (a) { return a.id === sel; })) {
var busy = list.filter(function (a) { return a.active; })[0];
sel = (busy || list[0] || {}).id || '';
changed = true;
}
if (changed) pick();
render(list.filter(function (a) { return a.id === sel; })[0]);
}).catch(function () {});
}
api('GET', '/api/muxes').then(function (m) { muxes = m.filter(function (x) { return x.enabled; }); pick(); }).catch(function () {});
every(1000, poll);
beep();
app.cleanup.push(function () { release(); clearTimeout(beepTimer); if (audio) try { audio.close(); } catch (e) {} });
}
// ------------------------------------------------------------ STATISTICS
function pageStats(view) {
var days = +(SDVB_STORE.get('sdvb-statdays') || 7);
view.innerHTML = head('Viewing', 'Statistics', 'What is watched, by whom, on which devices and when. Sessions shorter than 10 s (zapping) are not counted.',
'<div class="seg" id="st-days">' + [[1, '24 h'], [7, '7 days'], [30, '30 days'], [365, 'year']].map(function (d) {
return '<button data-d="' + d[0] + '"' + (d[0] === days ? ' class="on"' : '') + '>' + esc(T(d[1])) + '</button>';
}).join('') + '</div>' + (isAdmin() ? '<button class="btn small danger" id="st-clear">' + esc(T('Clear history')) + '</button>' : '')) +
'<div id="st-body"></div>';
function hours(sec) {
if (sec < 3600) return Math.round(sec / 60) + ' min';
return (sec / 3600).toFixed(sec < 36000 ? 1 : 0) + ' h';
}
function barList(title, rows, total) {
return '<div class="panel"><header><h2>' + esc(T(title)) + '</h2></header>' + (rows.length ? '<div class="bar-list">' + rows.map(function (r) {
var pct = total ? r.seconds * 100 / total : 0;
return '<div class="bl-row"><div class="bl-name" title="' + esc(r.name) + '">' + esc(r.name || '?') + '</div><div class="bl-bar"><i style="width:' + pct.toFixed(1) + '%"></i></div>' +
'<div class="bl-val mono">' + hours(r.seconds) + '</div><div class="bl-sub mono muted">' + r.sessions + ' ' + esc(T('sessions')) + ' · ' + bytes(r.bytes) + '</div></div>';
}).join('') + '</div>' : '<div class="empty">' + esc(T('No viewing yet in this period.')) + '</div>') + '</div>';
}
function columns(title, values, labels) {
var max = Math.max.apply(null, values.concat([1]));
return '<div class="panel"><header><h2>' + esc(T(title)) + '</h2></header><div class="cols">' + values.map(function (v, i) {
return '<div class="col" title="' + esc(labels[i] + ': ' + hours(v)) + '"><i style="height:' + (v * 100 / max).toFixed(1) + '%"></i><span>' + esc(labels[i]) + '</span></div>';
}).join('') + '</div></div>';
}
function load() {
api('GET', '/api/stats/viewing?days=' + days).then(function (r) {
var t = r.total, top = r.channels[0];
var hourLabels = r.hours.map(function (_, i) { return String(i); });
var perDay = r.per_day.slice(-31);
$('#st-body').innerHTML =
'<div class="grid g4">' +
'<div class="panel stat"><div class="label">' + esc(T('Watch time')) + '</div><div class="value">' + hours(t.seconds) + '</div><div class="sub">' + t.sessions + ' ' + esc(T('sessions')) + '</div></div>' +
'<div class="panel stat"><div class="label">' + esc(T('Data sent')) + '</div><div class="value">' + bytes(t.bytes) + '</div><div class="sub">' + esc(r.protocols.map(function (p) { return p.name.toUpperCase() + ' ' + hours(p.seconds); }).join(' · ') || '–') + '</div></div>' +
'<div class="panel stat"><div class="label">' + esc(T('Most watched')) + '</div><div class="value small-value">' + esc(top ? top.name : '–') + '</div><div class="sub">' + (top ? hours(top.seconds) : '') + '</div></div>' +
'<div class="panel stat"><div class="label">' + esc(T('Viewers')) + '</div><div class="value">' + r.users.length + '</div><div class="sub">' + r.devices.length + ' ' + esc(T('devices')) + '</div></div>' +
'</div><div class="grid g2" style="margin-top:10px">' +
barList('Most watched channels', r.channels, t.seconds) +
'<div>' + barList('Viewers', r.users, t.seconds) + barList('Devices', r.devices, t.seconds) + '</div>' +
columns('Time of day', r.hours, hourLabels) +
(perDay.length > 1 ? columns('Per day', perDay.map(function (d) { return d.seconds; }), perDay.map(function (d) { return d.day.slice(5); })) : '') +
'</div>';
}).catch(function (e) {
$('#st-body').innerHTML = '<div class="panel"><div class="empty">' + esc(isAdmin() ? e.message : T('Administrators only.')) + '</div></div>';
});
}
$$('[data-d]', view).forEach(function (b) {
b.addEventListener('click', function () {
days = +b.getAttribute('data-d'); SDVB_STORE.set('sdvb-statdays', String(days));
$$('[data-d]', view).forEach(function (x) { x.classList.toggle('on', x === b); });
load();
});
});
var cl = $('#st-clear');
if (cl) cl.addEventListener('click', function () {
if (confirmBox('Delete the whole viewing history?')) api('DELETE', '/api/stats/viewing').then(function () { toast('History cleared'); load(); }).catch(fail);
});
load();
every(30000, load);
}
/** Your account: password and the browsers/devices signed in (admins: everybody's). */
function renderAccount() {
var box = $('#account');
if (!box || !app.me) return;
var all = box.getAttribute('data-all') === '1', expanded = box.getAttribute('data-more') === '1';
api('GET', '/api/me/sessions' + (all ? '?all=1' : '')).then(function (full) {
var list = expanded ? full : full.slice(0, 6);
box.innerHTML = '<header><h2>' + esc(T('Signed-in devices')) + '</h2><div class="actions">' +
(full.filter(function (x) { return !x.current && (!all || x.user === app.me.username); }).length ? '<button class="btn small" id="acc-others">' + esc(T('Sign out other devices')) + '</button>' : '') + '</div></header>' +
'<div class="section-head"><span class="small muted">' + esc(T('Browsers and apps signed in to the panel. Signing a device out ends its session immediately.')) + '</span>' +
(isAdmin() ? '<label class="check small"><input type="checkbox" id="acc-all"' + (all ? ' checked' : '') + '> ' + esc(T('all users')) + '</label>' : '') + '</div>' +
'<div class="table-wrap"><table><thead><tr>' + (all ? '<th>' + esc(T('User')) + '</th>' : '') + '<th>' + esc(T('Device')) + '</th><th>' + esc(T('Address')) + '</th><th>' + esc(T('Last active')) + '</th><th>' + esc(T('Signed in')) + '</th><th></th></tr></thead><tbody>' +
list.map(function (x) {
return '<tr>' + (all ? '<td>' + esc(x.user) + '</td>' : '') + '<td title="' + esc(x.user_agent) + '">' + esc(x.device || '?') + (x.current ? ' <span class="pill ok">' + esc(T('this device')) + '</span>' : '') + '</td>' +
'<td class="mono small">' + esc(x.ip) + '</td><td class="mono small">' + dt(x.last_seen) + '</td><td class="mono small">' + dt(x.created) + '</td>' +
'<td class="actions-cell">' + (x.current ? '' : '<button class="btn small" data-sess="' + esc(x.id) + '">' + esc(T('Sign out')) + '</button>') + '</td></tr>';
}).join('') + '</tbody></table></div>' +
(full.length > list.length ? '<button class="btn small ghost" id="acc-more">' + esc(T('Show all')) + ' (' + full.length + ')</button>' : '');
var more = $('#acc-more', box);
if (more) more.addEventListener('click', function () { box.setAttribute('data-more', '1'); renderAccount(); });
var ot = $('#acc-others', box);
if (ot) ot.addEventListener('click', function () {
api('POST', '/api/me/sessions/others').then(function (r) { toast(T('Signed out devices:') + ' ' + r.ended); renderAccount(); }).catch(fail);
});
var al = $('#acc-all', box);
if (al) al.addEventListener('change', function () { box.setAttribute('data-all', al.checked ? '1' : '0'); renderAccount(); });
$$('[data-sess]', box).forEach(function (b) {
b.addEventListener('click', function () {
api('DELETE', '/api/me/sessions/' + b.getAttribute('data-sess')).then(function () { toast('Signed out'); renderAccount(); }).catch(fail);
});
});
}).catch(fail);
}
function pageSettings(view, args) {
var SECTIONS = [['appearance', 'Appearance'], ['general', 'General'], ['streaming', 'Streaming'], ['epg', 'EPG & icons'], ['recording', 'Recording'], ['tuners', 'Scanning']].concat(isAdmin() ? [['maintenance', 'Backup & monitoring']] : []);
var sec = SECTIONS.some(function (x) { return x[0] === args[0]; }) ? args[0] : 'appearance';
view.innerHTML = head('Configuration', 'Settings', 'Changes apply immediately (to new stream sessions).', isAdmin() ? '<button class="btn primary" id="set-save">Save settings</button>' : '') +
'<div class="panel" id="prefs"></div><div id="set-body"></div>';
'<div class="tabs set-tabs" id="set-tabs">' + SECTIONS.map(function (x) { return '<button data-sec="' + x[0] + '"' + (x[0] === sec ? ' class="active"' : '') + '>' + esc(T(x[1])) + '</button>'; }).join('') + '</div>' +
'<div class="panel" id="prefs" data-sec="appearance"></div><div id="set-body"></div>';
function showSection() {
$$('[data-sec]', view).forEach(function (el) {
if (el.parentNode && el.parentNode.id === 'set-tabs') el.classList.toggle('active', el.getAttribute('data-sec') === sec);
else el.classList.toggle('hidden', el.getAttribute('data-sec') !== sec);
});
var sv = $('#set-save');
if (sv) sv.classList.toggle('hidden', sec === 'appearance' || sec === 'maintenance');
}
$$('#set-tabs button', view).forEach(function (b) {
b.addEventListener('click', function () {
sec = b.getAttribute('data-sec');
history.replaceState(null, '', '#/settings/' + sec);
showSection();
});
});
renderPrefs();
showSection();
var cur = null;
function field(name, label, type, hint, extra) {
var v = cur[name];
@@ -1474,39 +1854,43 @@
}
function render() {
$('#set-body').innerHTML =
'<div class="panel"><header><h2>General</h2></header><div class="form-grid">' +
'<div class="panel" data-sec="general"><header><h2>General</h2></header><div class="form-grid">' +
field('server_name', 'Server name') + field('public_url', 'Public URL (for links)', 'text', 'e.g. https://tv.example.com – empty = from the Host header') +
field('session_hours', 'Panel session lifetime (h)', 'number') + '</div></div>' +
'<div class="panel"><header><h2>Streaming (HLS / TS)</h2></header><div class="form-grid">' +
'<div class="panel" data-sec="streaming"><header><h2>Streaming (HLS / TS)</h2></header><div class="form-grid">' +
field('hls_segment_seconds', 'HLS segment length (s)', 'number', 'Cut on keyframes – actual length depends on the broadcaster’s GOP') +
field('hls_window', 'Segments in playlist', 'number') + field('hls_idle_seconds', 'Close idle HLS session after (s)', 'number') +
field('tuner_linger_seconds', 'Keep tuner after last client (s)', 'number', 'Faster zapping between channels of the same mux') +
field('tuner_pid_filter', 'Read only the PIDs clients need (less CPU)', 'bool', 'The kernel passes only the selected programmes and the EPG/SI tables instead of the whole multiplex. Turn off if a tuner driver misbehaves.') +
field('m3u_format', 'Default M3U format', 'select', 'TS – lightest for TVs, HLS – for apps that require HLS', [['ts', 'MPEG-TS (continuous stream)'], ['hls', 'HLS (m3u8)']]) + '</div></div>' +
'<div class="panel"><header><h2>Transcoding (ffmpeg)</h2></header><div class="form-grid">' + field('ffmpeg_path', 'ffmpeg path') +
'<div class="panel" data-sec="streaming"><header><h2>Transcoding (ffmpeg)</h2></header><div class="form-grid">' + field('ffmpeg_path', 'ffmpeg path') +
field('ffmpeg_h264_args', 'H.264 profile arguments', 'wide', 'Used by the “h264” profile (e.g. HEVC in browsers without a hardware decoder). Hardware acceleration can be added: -c:v h264_vaapi etc.') + '</div></div>' +
'<div class="panel"><header><h2>EPG</h2>' + (isAdmin() ? '<div class="actions"><button class="btn small" id="xmltv-now">Import XMLTV now</button></div>' : '') + '</header><div class="form-grid">' +
'<div class="panel" data-sec="epg"><header><h2>EPG</h2>' + (isAdmin() ? '<div class="actions"><button class="btn small" id="xmltv-now">Import XMLTV now</button></div>' : '') + '</header><div class="form-grid">' +
field('epg_ota_enabled', 'Collect EPG from the broadcast (EIT)', 'bool', 'While watching and periodically from every mux') +
field('epg_grab_interval_hours', 'Grab all muxes every (h)', 'number', '0 = only while watching') + field('epg_grab_seconds', 'Grab time per mux (s)', 'number') +
field('epg_keep_past_hours', 'Keep past programmes (h)', 'number') + field('xmltv_interval_hours', 'Import XMLTV every (h)', 'number') +
'<label class="full">XMLTV sources (one URL per line, .xml or .xml.gz)<textarea name="xmltv_sources" placeholder="https://epg.ovh/pl.xml">' + esc(cur.xmltv_sources.map(function (s) { return (s.enabled ? '' : '# ') + s.url; }).join('\n')) + '</textarea>' +
'<span class="hint">Channels are matched by the channel’s “EPG ID” or by name. A line starting with # is disabled. XMLTV data takes precedence over EIT.</span></label>' +
'<div class="full small muted" id="xmltv-status"></div></div></div>' +
'<div class="panel"><header><h2>Channel icons</h2></header><div class="form-grid"><label class="full">Icon URL templates<textarea name="icon_sources">' + esc(cur.icon_sources.join('\n')) + '</textarea>' +
'<div class="panel" data-sec="epg"><header><h2>Channel icons</h2></header><div class="form-grid"><label class="full">Icon URL templates<textarea name="icon_sources">' + esc(cur.icon_sources.join('\n')) + '</textarea>' +
'<span class="hint">{slug} is replaced with the channel name, e.g. “tvp-1”, “polsat-news”. First hit wins; icons are stored locally.</span></label></div></div>' +
'<div class="panel"><header><h2>Recording</h2></header><div class="form-grid">' + field('recordings_dir', 'Recordings directory', 'text', 'Empty = ' + cur.data_dir + '/recordings') +
'<div class="panel" data-sec="recording"><header><h2>Recording</h2></header><div class="form-grid">' + field('recordings_dir', 'Recordings directory', 'text', 'Empty = ' + cur.data_dir + '/recordings') +
field('recording_pre_padding_min', 'Padding before (min)', 'number') + field('recording_post_padding_min', 'Padding after (min)', 'number') +
field('recordings_keep_days', 'Delete recordings older than (days)', 'number', '0 = never') +
field('recordings_min_free_gb', 'Minimum free space (GiB)', 'number', 'Below this threshold the oldest recordings are deleted; 0 = disabled') + '</div></div>' +
'<div class="panel"><header><h2>Scanning</h2></header><div class="form-grid">' + field('scan_create_channels', 'Create channels automatically', 'bool') +
'<div class="panel" data-sec="tuners"><header><h2>Scanning</h2></header><div class="form-grid">' + field('scan_create_channels', 'Create channels automatically', 'bool') +
field('scan_include_radio', 'Add radio stations', 'bool') + field('scan_include_scrambled', 'Add scrambled channels', 'bool') +
field('scan_lock_timeout_ms', 'Lock timeout (ms)', 'number', 'Si2168 usually locks DVB-T2 within ~1–2 s') +
field('idle_scan_hours', 'Background scan every (h)', 'number', 'Rescans saved muxes (and the NIT) on an idle adapter; stops as soon as someone starts watching or recording. 0 = off') +
field('idle_scan_quiet_minutes', 'Start after all tuners are idle for (min)', 'number') +
field('idle_scan_follow_nit', 'Background scan: follow the NIT to new muxes', 'bool') +
field('idle_scan_create_channels', 'Background scan: create channels for new services', 'bool', 'Off = new services only appear in “Add from services”') + '</div></div>' +
(isAdmin() ? '<div class="panel"><header><h2>Backup</h2></header><p class="hint">Muxes, services, channels (order, groups, links), recording rules, tokens and settings. Without user accounts, EPG, icons and recording files.</p>' +
'<div class="row"><a class="btn" href="/api/backup" download>⤓ Download backup (JSON)</a><label class="btn">⤒ Restore from file<input type="file" id="restore-file" accept="application/json,.json" class="hidden"></label>' +
'<a class="btn ghost" href="/metrics" target="_blank">Prometheus metrics</a></div></div>' : '');
(isAdmin() ? '<div class="panel" data-sec="maintenance"><header><h2>Backup</h2></header><p class="hint">Muxes, services, channels (order, groups, links), recording rules, tokens and settings. Without user accounts, EPG, icons and recording files.</p><p class="hint">Full database copy: everything incl. users, EPG and statistics – restore it with <code>simply-dvb db restore &lt;file&gt;</code>.</p>' +
'<div class="row"><a class="btn" href="/api/backup" download>' + ico('download') + 'Download backup (JSON)</a><a class="btn" href="/api/backup/database" download>' + ico('download') + 'Full database copy</a><label class="btn">' + ico('upload') + 'Restore from file<input type="file" id="restore-file" accept="application/json,.json" class="hidden"></label></div></div>' +
'<div class="panel" data-sec="maintenance"><header><h2>Monitoring (Prometheus)</h2></header>' +
'<p class="hint">Metrics for Prometheus/Grafana: tuners (signal, SNR, errors, bitrate), clients, traffic, recordings and the process. Add this address as a scrape target.</p>' +
'<div class="copy-row"><code>' + esc(location.origin + '/metrics') + '</code><a class="btn small" href="/metrics" target="_blank">' + esc(T('Open')) + '</a></div></div>' : '');
showSection();
api('GET', '/api/epg/status').then(function (s) {
var e = $('#xmltv-status');
if (e) e.textContent = (s.status.last_xmltv ? T('Last XMLTV import:') + ' ' + dt(s.status.last_xmltv) + '\n' + T(s.status.xmltv_result || '') : '') + ' · ' + T('programmes in database:') + ' ' + s.events;