From 528017b0e6e8d14547ef0c3e672f652c1bb68d52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Gruszczy=C5=84ski?= Date: Mon, 16 Nov 2026 22:48:34 +0100 Subject: [PATCH] v0.1.10 --- Cargo.lock | 12 +- Cargo.toml | 5 +- README.md | 36 +- README.pl.md | 36 +- langs/en_US.json | 124 +++- langs/pl_PL.json | 124 +++- migrations/0004_sessions_history.sql | 18 + src/app.rs | 34 +- src/cli.rs | 870 +++++++++++++++++++++++++++ src/clients.rs | 44 ++ src/db.rs | 198 +++++- src/dvb/linux.rs | 277 ++++++++- src/dvb/mod.rs | 68 +++ src/dvb/virt.rs | 6 + src/epg.rs | 6 +- src/main.rs | 159 +++-- src/pipeline.rs | 30 +- src/settings.rs | 4 + src/stats.rs | 71 ++- src/stream/filter.rs | 16 + src/ts/si.rs | 5 + src/tuner.rs | 242 +++++++- src/web/api.rs | 366 ++++++++++- src/web/assets.rs | 84 +++ src/web/mod.rs | 20 +- src/web/public.rs | 22 +- tests/e2e.rs | 24 + web/css/30-components.css | 14 + web/css/40-pages.css | 56 +- web/css/90-responsive.css | 47 ++ web/icon-192.png | Bin 0 -> 7427 bytes web/icon-512.png | Bin 0 -> 5981 bytes web/index.html | 18 +- web/js/10-i18n.js | 73 ++- web/js/20-player.js | 7 +- web/js/30-app.js | 494 +++++++++++++-- 36 files changed, 3394 insertions(+), 216 deletions(-) create mode 100644 migrations/0004_sessions_history.sql create mode 100644 src/cli.rs create mode 100644 web/icon-192.png create mode 100644 web/icon-512.png diff --git a/Cargo.lock b/Cargo.lock index 72169ed..1e49033 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", diff --git a/Cargo.toml b/Cargo.toml index eaa936e..d5b5a12 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/README.md b/README.md index f98a935..9cf1b5e 100644 --- a/README.md +++ b/README.md @@ -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/.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/.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 [--generate] # change a password (signs the user out everywhere) +simply-dvb user list | add [--role viewer] [--generate] | role admin|viewer | logout | delete +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 | disable | delete +simply-dvb settings show [key] | set | unset +simply-dvb channels list [--all] | m3u [--base-url …] [--token …] | enable 1 2 3 | disable 4 +simply-dvb db backup [file] | check | vacuum | restore # 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 ``` diff --git a/README.pl.md b/README.pl.md index a01e483..b31b69d 100644 --- a/README.pl.md +++ b/README.pl.md @@ -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/.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/.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 [--generate] # zmiana hasła (wylogowuje użytkownika wszędzie) +simply-dvb user list | add [--role viewer] [--generate] | role admin|viewer | logout | delete +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 | disable | delete +simply-dvb settings show [klucz] | set | unset +simply-dvb channels list [--all] | m3u [--base-url …] [--token …] | enable 1 2 3 | disable 4 +simply-dvb db backup [plik] | check | vacuum | restore # 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 ``` diff --git a/langs/en_US.json b/langs/en_US.json index b487afc..56aeccd 100644 --- a/langs/en_US.json +++ b/langs/en_US.json @@ -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": [] } diff --git a/langs/pl_PL.json b/langs/pl_PL.json index 69cbd31..cb2918c 100644 --- a/langs/pl_PL.json +++ b/langs/pl_PL.json @@ -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": [ { diff --git a/migrations/0004_sessions_history.sql b/migrations/0004_sessions_history.sql new file mode 100644 index 0000000..5eeed83 --- /dev/null +++ b/migrations/0004_sessions_history.sql @@ -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); diff --git a/src/app.rs b/src/app.rs index 459c8d8..69b33b2 100644 --- a/src/app.rs +++ b/src/app.rs @@ -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>, } 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) { + 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::(&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. diff --git a/src/cli.rs b/src/cli.rs new file mode 100644 index 0000000..1f65d85 --- /dev/null +++ b/src/cli.rs @@ -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 }, + /// 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 }, + /// Disable channels by number + Disable { numbers: Vec }, +} + +#[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: /backups/simply-dvb-.db) + file: Option, + }, + /// Replace the database with a backup (stop the service first!) + Restore { file: PathBuf }, +} + +fn read_password() -> Result { + 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 { + 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 { + 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) { + 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::>() + .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::>() + .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::>() + .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::().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) +} diff --git a/src/clients.rs b/src/clients.rs index 0721d3b..8f1d09d 100644 --- a/src/clients.rs +++ b/src/clients.rs @@ -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>>, } 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,14 +87,34 @@ 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) { + *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. pub fn totals(&self) -> (u64, u64) { ( diff --git a/src/db.rs b/src/db.rs index 51664e6..400f136 100644 --- a/src/db.rs +++ b/src/db.rs @@ -181,6 +181,33 @@ pub struct AccessToken { pub last_used: Option, } +/// 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, + 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> { + 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 { + 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> { + 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> { @@ -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::()) + .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> { - Ok(sqlx::query_as( + let n = now(); + let u: Option = 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) -> Result> { + 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) -> Result { + 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 { + 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> { + 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 { + 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 { + 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) diff --git a/src/dvb/linux.rs b/src/dvb/linux.rs index b44093c..4e5f6e9 100644 --- a/src/dvb/linux.rs +++ b/src/dvb/linux.rs @@ -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, dvr: Option, overflows: u64, + /// PIDs passed by the kernel demux (None = whole multiplex). + pids: Option>, + /// 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 = 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 { + 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::().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), _ => {} } } diff --git a/src/dvb/mod.rs b/src/dvb/mod.rs index 70ceb78..3fd65e8 100644 --- a/src/dvb/mod.rs +++ b/src/dvb/mod.rs @@ -94,6 +94,65 @@ pub struct SignalStatus { pub snr_pct: Option, /// Uncorrected block counter. pub uncorrected: Option, + /// 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, + pub post_bit_total: Option, + /// Total blocks counted (pairs with `uncorrected`). + pub block_total: Option, + /// Bit error rate over the last measuring interval (computed from the counters). + pub ber: Option, +} + +/// Transmission parameters reported by the demodulator after lock (None = not reported). +#[derive(Debug, Clone, Default, Serialize, PartialEq)] +pub struct TunedInfo { + pub modulation: Option, + pub code_rate: Option, + pub guard_interval: Option, + pub transmission_mode: Option, +} + +/// 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, + /// Kernel bridge driver, e.g. dvb_usb_dvbsky, cx23885, smipcie. + pub driver: Option, + pub vendor: Option, + pub product: Option, + /// vendor:product ids, e.g. 0572:c68a + pub ids: Option, + /// USB link speed (Mbit/s) + pub usb_speed: Option, + pub freq_min_mhz: Option, + pub freq_max_mhz: Option, + pub caps: Vec, +} + +/// 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>> = + 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; fn status(&mut self) -> SignalStatus; + /// Parameters the demodulator found (modulation, FEC…), if it reports them. + fn tuned_info(&mut self) -> Option { + 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. diff --git a/src/dvb/virt.rs b/src/dvb/virt.rs index 41ff8fe..0ff9106 100644 --- a/src/dvb/virt.rs +++ b/src/dvb/virt.rs @@ -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), } } } diff --git a/src/epg.rs b/src/epg.rs index 1d5790d..730d605 100644 --- a/src/epg.rs +++ b/src/epg.rs @@ -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); diff --git a/src/main.rs b/src/main.rs index 568c5ec..78dd5b7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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 { - 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::(); + 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 { diff --git a/src/pipeline.rs b/src/pipeline.rs index 7284af3..e217379 100644 --- a/src/pipeline.rs +++ b/src/pipeline.rs @@ -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 { }) } +/// Tells the tuner which PIDs this client needs whenever the service's PMT changes. +#[derive(Default)] +struct PidFollower { + last: Option>, +} + +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::(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; diff --git a/src/settings.rs b/src/settings.rs index 1427b87..7722cee 100644 --- a/src/settings.rs +++ b/src/settings.rs @@ -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(), diff --git a/src/stats.rs b/src/stats.rs index 5c59570..d870ed7 100644 --- a/src/stats.rs +++ b/src/stats.rs @@ -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, - pub net_tx: Option, + /// 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, /// Uncorrected blocks since the previous sample. pub unc: Option, + /// Bit error rate (after inner FEC), when the driver reports it. + pub ber: Option, + /// 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, } @@ -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 = HashMap::new(); + let mut prev_err: HashMap = HashMap::new(); + let mut proto_win: [VecDeque; 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 = 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() diff --git a/src/stream/filter.rs b/src/stream/filter.rs index 128d700..b880730 100644 --- a/src/stream/filter.rs +++ b/src/stream/filter.rs @@ -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> { + let pmt = self.pmt_pid?; + let mut v: Vec = 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) { 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) { diff --git a/src/ts/si.rs b/src/ts/si.rs index 9da213a..b8107f4 100644 --- a/src/ts/si.rs +++ b/src/ts/si.rs @@ -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 { + self.pmt_pids.keys().copied().collect() + } + pub fn push(&mut self, pkt: &[u8]) { let pid = packet::pid(pkt); if !self.wants(pid) { diff --git a/src/tuner.rs b/src/tuner.rs index d1d1465..85c4e62 100644 --- a/src/tuner.rs +++ b/src/tuner.rs @@ -41,9 +41,87 @@ pub struct Active { bitrate: AtomicU64, started: Instant, state: watch::Receiver, + ts: Mutex, + tuned: Mutex>, + /// PIDs each subscription needs (None = whole multiplex) and a change counter. + wanted: Mutex>>>, + 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, + 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>) { + self.wanted.lock().unwrap().insert(id, pids); + self.wanted_ver.fetch_add(1, Ordering::Relaxed); + } fn max_priority(&self) -> Option { 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>) { + 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, + 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, + /// 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)>, pub epg_enabled: AtomicBool, + /// Kernel PID filtering (only the PIDs clients need are read from the tuner). + pub pid_filter: Arc, pub linger: Mutex, /// 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, mux: &Mux, prio: Priority) -> Result { + 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, + mux: &Mux, + prio: Priority, + pids: Option>, + ) -> Result { 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, ¶ms, 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> { + let w = a.wanted.lock().unwrap(); + let mut set: std::collections::BTreeSet = + [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, @@ -575,6 +731,7 @@ fn reader_thread( epg_tx: mpsc::UnboundedSender<(i64, Vec)>, pmt_tx: Option, 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, 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); + } +} diff --git a/src/web/api.rs b/src/web/api.rs index f9958f2..69f4b14 100644 --- a/src/web/api.rs +++ b/src/web/api.rs @@ -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) -> 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, + Extension(CurrentUser(u)): Extension, + headers: HeaderMap, + Query(q): Query, +) -> ApiResult { + 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 = 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, + Extension(CurrentUser(u)): Extension, + Path(id): Path, +) -> ApiResult { + 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, + Extension(CurrentUser(u)): Extension, + headers: HeaderMap, +) -> ApiResult { + 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, ¤t).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, + Extension(CurrentUser(u)): Extension, +) -> Result { + 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, + Extension(CurrentUser(u)): Extension, + Query(q): Query, +) -> ApiResult { + 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 = HashMap::new(); + let mut by_who: HashMap = HashMap::new(); + let mut by_device: HashMap = HashMap::new(); + let mut by_kind: HashMap = HashMap::new(); + let mut by_hour = [0i64; 24]; + let mut by_day: std::collections::BTreeMap = 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, 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::>() + }; + 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::>(), + }))) +} + +pub async fn viewing_stats_clear( + AxState(state): AxState, + Extension(CurrentUser(u)): Extension, +) -> ApiResult { + 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, + Extension(CurrentUser(u)): Extension, + Json(r): Json, +) -> ApiResult { + 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, + Extension(CurrentUser(u)): Extension, +) -> ApiResult { + let v = state + .db + .get_setting(&prefs_key(u.id)) + .await? + .and_then(|s| serde_json::from_str::(&s).ok()) + .unwrap_or_else(|| json!({})); + Ok(Json(v)) +} + +pub async fn save_my_prefs( + AxState(state): AxState, + Extension(CurrentUser(u)): Extension, + Json(v): Json>, +) -> ApiResult { + 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, diff --git a/src/web/assets.rs b/src/web/assets.rs index 0c4d568..0ea2890 100644 --- a/src/web/assets.rs +++ b/src/web/assets.rs @@ -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('

simply-dvb

The server is not reachable. Check the connection and try again.

', { 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 { pub fn routes() -> Router { 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) -> Response { + let name = state.settings().server_name; + let body = serde_json::json!({ + "name": name, + "short_name": name.chars().take(12).collect::(), + "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) -> 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(); }; diff --git a/src/web/mod.rs b/src/web/mod.rs index 135a055..ce02db7 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -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)) diff --git a/src/web/public.rs b/src/web/public.rs index 2a02406..ec4d648 100644 --- a/src/web/public.rs +++ b/src/web/public.rs @@ -28,6 +28,10 @@ pub struct StreamQuery { share: Option, profile: Option, format: Option, + /// M3U: only these channels (comma separated channel ids, e.g. the favourites) + channels: Option, + /// M3U: only this channel group + group: Option, } 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 = ids + .split(',') + .filter_map(|x| x.trim().parse().ok()) + .collect(); + let mut picked: Vec = 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, diff --git a/tests/e2e.rs b/tests/e2e.rs index 175433a..3927165 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -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 diff --git a/web/css/30-components.css b/web/css/30-components.css index 64aca3e..ffc500e 100644 --- a/web/css/30-components.css +++ b/web/css/30-components.css @@ -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; } diff --git a/web/css/40-pages.css b/web/css/40-pages.css index c1ca0ae..7e643da 100644 --- a/web/css/40-pages.css +++ b/web/css/40-pages.css @@ -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%; } diff --git a/web/css/90-responsive.css b/web/css/90-responsive.css index 5d92cf8..2b489b6 100644 --- a/web/css/90-responsive.css +++ b/web/css/90-responsive.css @@ -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%; } +} diff --git a/web/icon-192.png b/web/icon-192.png new file mode 100644 index 0000000000000000000000000000000000000000..8d795d9b0a4ce22fe2fe484646ea09e6c2c3846e GIT binary patch literal 7427 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 literal 0 HcmV?d00001 diff --git a/web/icon-512.png b/web/icon-512.png new file mode 100644 index 0000000000000000000000000000000000000000..1b6818554381f76caf6b8390a0ca56900c1b5ba4 GIT binary patch literal 5981 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 literal 0 HcmV?d00001 diff --git a/web/index.html b/web/index.html index 6d0fa30..a3ed0c8 100644 --- a/web/index.html +++ b/web/index.html @@ -2,21 +2,26 @@ - + simply-dvb + + + + + + __ASSETS__ @@ -29,6 +34,7 @@ __ASSETS__ Channels Recordings Tuners + Statistics Access Logs Settings @@ -42,14 +48,14 @@ __ASSETS__
- +
- +
diff --git a/web/js/10-i18n.js b/web/js/10-i18n.js index 70daae5..943b3d5 100644 --- a/web/js/10-i18n.js +++ b/web/js/10-i18n.js @@ -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]; } }; diff --git a/web/js/20-player.js b/web/js/20-player.js index 78083e9..9330a9f 100644 --- a/web/js/20-player.js +++ b/web/js/20-player.js @@ -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) { diff --git a/web/js/30-app.js b/web/js/30-app.js index 72fa077..d46bd9d 100644 --- a/web/js/30-app.js +++ b/web/js/30-app.js @@ -47,6 +47,32 @@ t.remove(); } } + /** Line icons (same style as the side menu) – used instead of emoji/special characters. */ + var ICONS = { + play: '', + prev: '', + next: '', + record: '', + stop: '', + pip: '', + fullscreen: '', + check: '', + cross: '', + star: '', + starOn: '', + bell: '', + antenna: '', + download: '', + upload: '', + warn: '', + grip: '', + volume: '', + mute: '', + vlc: '' + }; + function ico(name) { return ''; } + 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 ''; } @@ -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 ? '' : ''; return area + ''; }).join(''); - return '' + grid + paths + + return '
' + grid + paths + '' + - '
' + esc(fmtNum(max, opts.unit)) + '' + esc(fmtNum(min, opts.unit)) + '
'; + '
' + esc(fmtNum(max, opts.unit)) + '' + esc(fmtNum(min, opts.unit)) + '
'; } /** 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 @@ '
' + (sig.locked ? 'LOCK' : sig.has_signal ? 'signal, no lock' : 'no signal') + '
'; } + /** Demodulator lock stages: signal, carrier, FEC, sync, lock. */ + function lockBits(sig) { + if (!sig) return ''; + return '
' + [['SIGNAL', sig.has_signal], ['CARRIER', sig.has_carrier], ['FEC', sig.has_viterbi], ['SYNC', sig.has_sync], ['LOCK', sig.locked]].map(function (b) { + return '' + b[0] + ''; + }).join('') + (sig.ber != null ? 'BER ' + esc(fmtNum(sig.ber, 'ber')) + '' : '') + '
'; + } + /** 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 '
' + + (tu ? 'Transmission' + esc([tu.modulation, tu.code_rate && 'FEC ' + tu.code_rate, tu.guard_interval && 'GI ' + tu.guard_interval, tu.transmission_mode].filter(Boolean).join(' · ')) + '' : '') + + 'Packets' + ts.packets.toLocaleString() + ' · ' + ts.pids + ' PIDs · ' + esc(T('stuffing')) + ' ' + pct(ts.null_packets) + (ts.scrambled ? ' · ' + esc(T('scrambled')) + ' ' + pct(ts.scrambled) : '') + '' + + 'ErrorsCC ' + ts.cc_errors + ' · TEI ' + ts.tei_errors + '
'; + } + /** 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 '
' + esc(T('Hardware')) + '
' + rows.map(function (r) { + return '' + esc(T(r[0])) + '' + esc(r[1]) + ''; + }).join('') + '
'; + } + 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.', - '▶ WatchScan channels') + + '' + ico('play') + 'WatchScan channels') + '
' + '

Live

' + [5, 10, 15].map(function (m) { return ''; @@ -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 '

' + esc(t.name) + '

' + esc(t.id) + ' · ' + esc(t.delivery_systems.join(' / ')) + ' · ' + esc(t.path) + '
' + '
' + (!t.enabled ? 'disabled' : t.busy ? 'scanning' : a ? '' + esc(a.state === 'locked' ? 'LOCK' : a.state) + '' : 'idle') + '
' + (a ? '
Mux' + esc(a.tuning) + (a.network_name ? ' · ' + esc(a.network_name) : '') + '' + 'Clients' + a.subscribers + (a.top_priority ? ' · priority ' + esc(a.top_priority) : '') + '' + - 'Stream' + bps(a.bitrate_bps) + ' · ' + dur(a.uptime_secs) + '
' + signalBlock(a.signal) + 'Stream' + bps(a.bitrate_bps) + ' · ' + dur(a.uptime_secs) + (a.pid_filtered ? ' · ' + esc(T('PID filter')) + '' : '') + '
' + signalBlock(a.signal) + lockBits(a.signal) + tsHealth(a) : '
' + (t.last_error ? 'Last error: ' + esc(t.last_error) : 'Tuner is waiting for clients.') + '
') + + hardwareBlock(t) + (charts ? '
' + charts + '
' : '') + '
'; }).join('') || '
No DVB adapters detected. Check /dev/dvb and permissions (group video).
'; + 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 = '
Pick a channel from the list
' + @@ -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 = '' + + (groups.length > 1 || hasFav ? '' : '') + '
' + (list.length ? list.map(function (c) { + var fav = favs.indexOf(c.id) >= 0; return '
' + c.number + '
' + logo(c) + - '
' + esc(c.name) + '
' + (c.now ? hm(c.now.start) + ' ' + esc(c.now.title) : (c.kind === 'radio' ? 'radio' : ' ')) + '
' + + '
' + esc(c.name) + '
' + (c.now ? hm(c.now.start) + ' ' + esc(c.now.title) : (c.kind === 'radio' ? 'radio' : ' ')) + '
' + (c.now ? '
' : '') + '
'; }).join('') : '
No channels – run a scan on the Tuners page.
'); 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 @@ '
' + esc(n.description || n.summary || '') + '
' : '

' + esc(c.name) + '

No EPG data for this moment.
') + (nx ? '
Next: ' + hm(nx.start) + ' ' + esc(nx.title) + '
' : '') + '
' + - (n && isAdmin() ? '' : '') + - '
'; + (n && isAdmin() ? '' : '') + + '
'; 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 '
' + hm(e.start) + '' + esc(e.title) + '' + - (e.start > t && isAdmin() ? '' : '') + '
'; + (e.start > t && isAdmin() ? '' : '') + ''; }).join('') : '
No EPG yet. Data appears after EIT is collected from the mux or XMLTV is imported.
') + ''; $$('[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 '' + esc(x) + ' ' + (ok ? '✓' : '✗') + ''; + return '' + esc(x) + ' ' + ico(ok ? 'check' : 'cross') + ''; }).join(' '); var why = window.SDVB.explain(svc.video, svc.audio); $('#tv-tools').innerHTML = '

Stream

' + esc(svc.video || (c.kind === 'radio' ? 'radio' : '?')) + ' · ' + esc((svc.audio || []).join(', ') || '–') + '
' + @@ -521,8 +634,8 @@ (why ? '

' + esc(why) + (noFfmpeg ? ' ' + esc(T('Without ffmpeg on the server use VLC or a browser/device that decodes these codecs.')) : '') + '

' : '') + '
' + esc(location.origin + '/hls/' + c.id + '/index.m3u8') + '
' + '
' + esc(location.origin + '/stream/channelid/' + c.id + '?profile=pass') + '
' + - '' + - '

' + esc(T('Shortcuts: ↑/↓ channel, digits – number, F – fullscreen, P – picture-in-picture, M – mute, ? – help.')) + '

' + + '' + + '

' + esc(T('Shortcuts: arrow up/down – channel, digits – number, F – fullscreen, P – picture-in-picture, M – mute, ? – help.')) + '

' + '

The “Automatic” profile checks which codecs your browser supports (e.g. HEVC, AC-3) and enables ffmpeg transcoding when needed.

'; $('#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 = '
' + esc(c.number + ' · ' + c.name) + '
' + - '
'; + ''; $('#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', '
' + [['↑ / ↓', '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', '
' + [['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 '' + esc(x[0]) + '' + esc(x[1]) + ''; }).join('') + '
'); } @@ -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/ after a reload or history navigation) only selects - // the channel; playback starts on click, from an explicit ▶ link (#/tv//play) + // the channel; playback starts on click, from an explicit play link (#/tv//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, '
Channel' + esc(ch ? ch.number + ' · ' + ch.name : '') + 'Time' + dt(e.start) + ' – ' + hm(e.stop) + ' (' + dur(e.stop - e.start) + ')' + (e.genre ? 'Genre' + esc(e.genre) + '' : '') + (e.rating ? 'Age' + e.rating + '+' : '') + 'Source' + esc(e.source === 'xmltv' ? 'XMLTV' : 'EIT (broadcast)') + '
' + (e.summary ? '

' + esc(e.summary) + '

' : '') + '

' + esc(e.description || '') + '

' + - ''); + ''); + 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.', - '' + + '' + (isAdmin() ? '' : '')) + '
'; 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 '⠿' + c.number + '' + logo(c) + '' + esc(c.name) + '' + + return '' + ico('grip') + '' + c.number + '' + logo(c) + '' + esc(c.name) + '' + (pr ? ' ' + esc(T(pr)) + '' : '') + (!pr && unknownStreams(c) ? ' ' + esc(T('streams unknown')) + '' : '') + (s.scrambled ? ' scrambled' : '') + (c.kind === 'radio' ? ' radio' : '') + '' + esc(c.grp) + '' + '' + esc([s.video].concat(s.audio || []).filter(Boolean).join(' · ')) + '' + esc(c.mux || '') + '' + '' + (c.now ? esc(c.now.title) : '–') + '' + '' + sw(c.enabled, 'data-en="' + c.id + '"' + (isAdmin() ? '' : ' disabled')) + '' + '' + sw(c.share_enabled, 'data-sh="' + c.id + '"' + (isAdmin() ? '' : ' disabled')) + (c.share_enabled && c.share_token ? ' ' : '') + '' + - '▶ VLC' + (isAdmin() ? ' ' : '') + ''; + '' + ico('play') + ' VLC' + (isAdmin() ? ' ' : '') + ''; }).join('') + ''; 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() ? '' : '') + - '
'; + '
'; 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 '
' + - (x.conflict ? '⚠ ' : '') + esc(x.title) + ' ' + esc(x.channel_name) + '
'; + (x.conflict ? ico('warn') : '') + esc(x.title) + ' ' + esc(x.channel_name) + '
'; }).join('') + ''; }); html += '' + list.map(function (x) { @@ -1046,8 +1209,8 @@ var st = REC_STATUS[r.status] || [r.status, '']; return '' + '' + - ''; }).join('') + '
StartEndTitleChannelStatus
' + st[0] + '' + esc(r.title) + '' + (r.error ? '
' + esc(r.error) + '
' : '') + '
' + esc(r.channel_name) + '' + dt(r.start) + '' + hm(r.stop) + '' + (r.duration ? dur(r.duration) : dur(r.stop - r.start)) + '' + (r.size ? bytes(r.size) : '–') + '' + (r.autorec_id ? 'R ' : '') + (r.file && r.size ? ' Download ' : '') + - (isAdmin() && (r.status === 'scheduled' || r.status === 'recording') ? ' ' : '') + + '' + (r.autorec_id ? 'R ' : '') + (r.file && r.size ? ' Download ' : '') + + (isAdmin() && (r.status === 'scheduled' || r.status === 'recording') ? ' ' : '') + (isAdmin() ? '' : '') + '
' : '
No recordings in this category.
'; $$('[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() ? '' : '') + + '' + ico('antenna') + 'Antenna meter' + (isAdmin() ? '' : '')) + '

Adapters

' + '

Scanning

' + '

Muxes

' + (isAdmin() ? '' : '') + '
'; @@ -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 @@ '

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.

' + '

Panel users

' + (isAdmin() ? '' : '') + '
' + '
' + + '
' + (isAdmin() ? '

Access control (ACL)

' : ''); function links() { @@ -1269,6 +1433,7 @@ return '
' + esc(l.name) + '
' + '
M3U' + esc(l.m3u) + '
' + '
HLS' + esc(l.m3u_hls) + '
' + + (FAV.list().length ? '
' + ico('starOn') + 'M3U' + esc(l.m3u + (l.m3u.indexOf('?') >= 0 ? '&' : '?') + 'channels=' + FAV.list().join(',')) + '
' : '') + '
EPG' + esc(l.epg) + '
' + '
TVH' + esc(l.tvh_playlist) + '
' + '
TVH' + esc(l.tvh_xmltv) + '
'; @@ -1316,7 +1481,7 @@ var hosts = Object.keys(m || {}); if (!hosts.length) return ''; return '
' + esc(T('DDNS host names now resolve to:')) + ' ' + hosts.map(function (h) { - return '' + esc(h) + ' → ' + esc((m[h] || []).join(', ') || T('not resolved')) + ''; + return '' + esc(h) + ': ' + esc((m[h] || []).join(', ') || T('not resolved')) + ''; }).join(' · ') + '
'; } 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', '
'); $('#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.', - '⤓ Download') + + '' + ico('download') + 'Download') + '
' + '
' + '
' + @@ -1422,7 +1587,7 @@ var profile = 'auto'; try { profile = localStorage.getItem('sdvb-profile') || 'auto'; } catch (e) {} box.innerHTML = '

Appearance

' + - '

Interface preferences are stored in this browser.

' + + '

Interface preferences are saved in your user profile and follow you to every device.

' + row('Language', langSelect('pref-lang', false)) + row('Theme', seg('theme', [['dark', 'Dark'], ['midnight', 'Midnight (OLED)'], ['light', 'Light'], ['system', 'System default']])) + row('Accent colour', '
' + 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', '
' + [['auto', 'Automatic'], ['pass', 'Original'], ['aac', 'Audio → AAC'], ['h264', 'H.264 720p']].map(function (o) { + row('Default player profile', '
' + [['auto', 'Automatic'], ['pass', 'Original'], ['aac', 'AAC audio'], ['h264', 'H.264 720p']].map(function (o) { return ''; }).join('') + '
') + 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).', + '') + + '
'; + 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 ''; }).join(''); + var muxOpts = muxes.map(function (m) { return ''; }).join(''); + $('#sg-pick').innerHTML = '' + + (isAdmin() && muxes.length ? '' + + '' : ''); + $('#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 = '
' + esc(T('No DVB adapters detected.')) + '
'; return; } + if (!sig) { + lastSnr = null; + $('#sg-body').innerHTML = '
' + esc(T('The tuner is idle. Start watching a channel or pick a multiplex above and press “Tune”.')) + '
'; + 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 = + '
' + esc(T(q[0])) + '
' + + '
' + esc(act.tuning) + '
' + + '
' + + '
' + esc(T('Strength')) + '
' + (sig.strength_pct != null ? sig.strength_pct.toFixed(0) + '%' : '–') + '
' + + '
' + + '
' + (sig.strength_dbm != null ? sig.strength_dbm.toFixed(1) + ' dBm' : ' ') + '
' + + '
SNR
' + (sig.snr_db != null ? sig.snr_db.toFixed(1) + 'dB' : sig.snr_pct != null ? sig.snr_pct.toFixed(0) + '%' : '–') + '
' + + '
' + (sig.ber != null ? 'BER ' + esc(fmtNum(sig.ber, 'ber')) : ' ') + '
' + + '
' + lockBits(sig) + + '
' + esc(T('Uncorrected blocks')) + '' + (sig.uncorrected != null ? sig.uncorrected : '–') + '' + + '' + esc(T('Stream errors')) + 'CC ' + act.ts.cc_errors + ' · TEI ' + act.ts.tei_errors + '' + + '' + esc(T('Multiplex bitrate')) + '' + bps(act.bitrate_bps) + '
' + + '
' + + 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 }) + '
'; + } + 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.', + '
' + [[1, '24 h'], [7, '7 days'], [30, '30 days'], [365, 'year']].map(function (d) { + return ''; + }).join('') + '
' + (isAdmin() ? '' : '')) + + '
'; + 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 '

' + esc(T(title)) + '

' + (rows.length ? '
' + rows.map(function (r) { + var pct = total ? r.seconds * 100 / total : 0; + return '
' + esc(r.name || '?') + '
' + + '
' + hours(r.seconds) + '
' + r.sessions + ' ' + esc(T('sessions')) + ' · ' + bytes(r.bytes) + '
'; + }).join('') + '
' : '
' + esc(T('No viewing yet in this period.')) + '
') + '
'; + } + function columns(title, values, labels) { + var max = Math.max.apply(null, values.concat([1])); + return '

' + esc(T(title)) + '

' + values.map(function (v, i) { + return '
' + esc(labels[i]) + '
'; + }).join('') + '
'; + } + 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 = + '
' + + '
' + esc(T('Watch time')) + '
' + hours(t.seconds) + '
' + t.sessions + ' ' + esc(T('sessions')) + '
' + + '
' + esc(T('Data sent')) + '
' + bytes(t.bytes) + '
' + esc(r.protocols.map(function (p) { return p.name.toUpperCase() + ' ' + hours(p.seconds); }).join(' · ') || '–') + '
' + + '
' + esc(T('Most watched')) + '
' + esc(top ? top.name : '–') + '
' + (top ? hours(top.seconds) : '') + '
' + + '
' + esc(T('Viewers')) + '
' + r.users.length + '
' + r.devices.length + ' ' + esc(T('devices')) + '
' + + '
' + + barList('Most watched channels', r.channels, t.seconds) + + '
' + barList('Viewers', r.users, t.seconds) + barList('Devices', r.devices, t.seconds) + '
' + + 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); })) : '') + + '
'; + }).catch(function (e) { + $('#st-body').innerHTML = '
' + esc(isAdmin() ? e.message : T('Administrators only.')) + '
'; + }); + } + $$('[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 = '

' + esc(T('Signed-in devices')) + '

' + + (full.filter(function (x) { return !x.current && (!all || x.user === app.me.username); }).length ? '' : '') + '
' + + '
' + esc(T('Browsers and apps signed in to the panel. Signing a device out ends its session immediately.')) + '' + + (isAdmin() ? '' : '') + '
' + + '
' + (all ? '' : '') + '' + + list.map(function (x) { + return '' + (all ? '' : '') + '' + + '' + + ''; + }).join('') + '
' + esc(T('User')) + '' + esc(T('Device')) + '' + esc(T('Address')) + '' + esc(T('Last active')) + '' + esc(T('Signed in')) + '
' + esc(x.user) + '' + esc(x.device || '?') + (x.current ? ' ' + esc(T('this device')) + '' : '') + '' + esc(x.ip) + '' + dt(x.last_seen) + '' + dt(x.created) + '' + (x.current ? '' : '') + '
' + + (full.length > list.length ? '' : ''); + 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() ? '' : '') + - '
'; + '
' + SECTIONS.map(function (x) { return ''; }).join('') + '
' + + '
'; + 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 = - '

General

' + + '

General

' + 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') + '
' + - '

Streaming (HLS / TS)

' + + '

Streaming (HLS / TS)

' + 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)']]) + '
' + - '

Transcoding (ffmpeg)

' + field('ffmpeg_path', 'ffmpeg path') + + '

Transcoding (ffmpeg)

' + 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.') + '
' + - '

EPG

' + (isAdmin() ? '
' : '') + '
' + + '

EPG

' + (isAdmin() ? '
' : '') + '
' + 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') + '' + '
' + - '

Channel icons