//! Application state shared by the web server and background tasks. use crate::clients::Clients; use crate::db::Db; use crate::dvb::{self, AdapterInfo, DeliverySystem}; use crate::hls::HlsManager; use crate::scanjob::ScanState; use crate::settings::Settings; use crate::ts::si::EpgItem; use crate::tuner::TunerManager; use anyhow::Result; use std::collections::HashMap; use std::net::IpAddr; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, RwLock}; use std::time::{Duration, Instant}; use tokio::sync::{mpsc, Notify}; pub type State = Arc; #[derive(Debug, Clone)] pub struct Options { pub data_dir: PathBuf, pub dev_root: String, pub virtual_dirs: Vec, /// Stream port (tvheadend-compatible), if enabled. pub stream_port: Option, /// HTSP port, if enabled. pub htsp_port: Option, /// Panel port (for links such as the TV pairing page). pub panel_port: u16, } #[derive(Default, Clone, serde::Serialize)] pub struct EpgStatus { pub last_grab: Option, pub grabbing_mux: Option, pub last_xmltv: Option, pub xmltv_result: String, pub ota_events_written: u64, } pub struct AppState { pub db: Db, pub settings: RwLock, pub opts: Options, pub tuners: Arc, pub hls: HlsManager, pub clients: Arc, pub scan: ScanState, pub started: Instant, pub http: reqwest::Client, pub login_failures: Mutex>, pub recordings_running: Mutex>>, pub epg_status: Mutex, pub epg_wakeup: Notify, pub xmltv_wakeup: Notify, pub rec_wakeup: Notify, /// Bumped whenever any change is committed to the database (see `db::watch_changes`). pub db_changed: tokio::sync::watch::Sender, pub shutting_down: AtomicBool, pub stats: crate::stats::Stats, /// The separate stream port is bound (it may wait for tvheadend to release it). pub stream_port_active: AtomicBool, pub htsp_port_active: AtomicBool, pub icon_job: Mutex, /// `ffmpeg -version` first line, or None when ffmpeg is not available. pub ffmpeg: Mutex>, /// Wakes the ACL host-name resolver (settings/tokens changed). 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 { pub async fn new( db: Db, opts: Options, ) -> Result<(State, mpsc::UnboundedReceiver<(i64, Vec)>)> { let mut settings: Settings = match db.get_setting("config").await? { Some(s) => serde_json::from_str(&s).unwrap_or_default(), None => Settings::default(), }; // default server name from before the project was renamed if settings.server_name == "simple-dvbt" { settings.server_name = "simply-dvb".into(); } let (epg_tx, epg_rx) = mpsc::unbounded_channel(); let tuners = TunerManager::new(epg_tx); let (pmt_tx, mut pmt_rx) = mpsc::unbounded_channel::<(i64, Vec)>(); *tuners.pmt_tx.lock().unwrap() = Some(pmt_tx); { let db = db.clone(); tokio::spawn(async move { while let Some((mux_id, pmts)) = pmt_rx.recv().await { for p in pmts { match db.update_service_pmt(mux_id, &p).await { Ok(true) => tracing::info!( "service {} on mux {mux_id}: streams updated from PMT ({})", p.program, p.streams .iter() .map(|s| s.kind.label()) .collect::>() .join(", ") ), Ok(false) => {} Err(e) => tracing::warn!("updating service streams: {e:#}"), } } } }); } tuners .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)) .connect_timeout(Duration::from_secs(15)) .build()?; let state = Arc::new(AppState { db, settings: RwLock::new(settings), opts, tuners, hls: HlsManager::default(), clients: Arc::new(Clients::default()), scan: ScanState::default(), started: Instant::now(), http, login_failures: Mutex::new(HashMap::new()), recordings_running: Mutex::new(HashMap::new()), epg_status: Mutex::new(EpgStatus::default()), epg_wakeup: Notify::new(), xmltv_wakeup: Notify::new(), rec_wakeup: Notify::new(), db_changed: tokio::sync::watch::channel(0).0, shutting_down: AtomicBool::new(false), stats: crate::stats::Stats::default(), stream_port_active: AtomicBool::new(false), htsp_port_active: AtomicBool::new(false), icon_job: Mutex::new(crate::icons::IconJob::default()), 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?; Ok((state, epg_rx)) } /// Checks whether the configured ffmpeg can be started (transcoding profiles need it). pub async fn detect_ffmpeg(&self) { let path = self.settings().ffmpeg_path; let out = tokio::process::Command::new(&path) .arg("-version") .stdin(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .output() .await; let v = match out { Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout) .lines() .next() .map(|l| l.chars().take(120).collect()), _ => None, }; match &v { Some(v) => tracing::info!("ffmpeg: {v}"), None => tracing::warn!( "ffmpeg not found ({path}) – browser transcoding profiles (aac, h264) are unavailable" ), } *self.ffmpeg.lock().unwrap() = v; } pub fn has_ffmpeg(&self) -> bool { self.ffmpeg.lock().unwrap().is_some() } pub fn settings(&self) -> Settings { self.settings.read().unwrap().clone() } pub async fn save_settings(&self, s: Settings) -> Result<()> { 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; } } /// Discovers adapters (Linux DVB + virtual) and updates the tuner manager. pub async fn refresh_adapters(&self) -> Result> { let dev_root = self.opts.dev_root.clone(); let mut found = tokio::task::spawn_blocking(move || dvb::discover(&dev_root)).await?; for (i, dir) in self.opts.virtual_dirs.iter().enumerate() { found.push(AdapterInfo { id: format!("virtual{i}"), name: format!("Virtual adapter ({dir})"), kind: "virtual".into(), path: dir.clone(), delivery_systems: vec![ DeliverySystem::Dvbt, DeliverySystem::Dvbt2, DeliverySystem::Dvbc, ], }); } let mut list = Vec::new(); for a in &found { let (en, prio) = self.db.adapter_config(&a.id).await?; list.push((a.clone(), en, prio)); } self.tuners.set_adapters(list); Ok(found) } pub fn data_path(&self, name: &str) -> PathBuf { self.opts.data_dir.join(name) } pub fn recordings_dir(&self) -> PathBuf { let s = self.settings(); if s.recordings_dir.trim().is_empty() { self.data_path("recordings") } else { PathBuf::from(s.recordings_dir.trim()) } } }