first commit
This commit is contained in:
commit
c30064b531
93 files changed
+26367
No files matched your search
+238
@@ -0,0 +1,238 @@
|
||||
//! 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<AppState>;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Options {
|
||||
pub data_dir: PathBuf,
|
||||
pub dev_root: String,
|
||||
pub virtual_dirs: Vec<String>,
|
||||
/// Stream port (tvheadend-compatible), if enabled.
|
||||
pub stream_port: Option<u16>,
|
||||
/// HTSP port, if enabled.
|
||||
pub htsp_port: Option<u16>,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, serde::Serialize)]
|
||||
pub struct EpgStatus {
|
||||
pub last_grab: Option<i64>,
|
||||
pub grabbing_mux: Option<i64>,
|
||||
pub last_xmltv: Option<i64>,
|
||||
pub xmltv_result: String,
|
||||
pub ota_events_written: u64,
|
||||
}
|
||||
|
||||
pub struct AppState {
|
||||
pub db: Db,
|
||||
pub settings: RwLock<Settings>,
|
||||
pub opts: Options,
|
||||
pub tuners: Arc<TunerManager>,
|
||||
pub hls: HlsManager,
|
||||
pub clients: Arc<Clients>,
|
||||
pub scan: ScanState,
|
||||
pub started: Instant,
|
||||
pub http: reqwest::Client,
|
||||
pub login_failures: Mutex<HashMap<IpAddr, (u32, Instant)>>,
|
||||
pub recordings_running: Mutex<HashMap<i64, Arc<AtomicBool>>>,
|
||||
pub epg_status: Mutex<EpgStatus>,
|
||||
pub epg_wakeup: Notify,
|
||||
pub xmltv_wakeup: Notify,
|
||||
pub rec_wakeup: Notify,
|
||||
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<crate::icons::IconJob>,
|
||||
/// `ffmpeg -version` first line, or None when ffmpeg is not available.
|
||||
pub ffmpeg: Mutex<Option<String>>,
|
||||
/// 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,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub async fn new(
|
||||
db: Db,
|
||||
opts: Options,
|
||||
) -> Result<(State, mpsc::UnboundedReceiver<(i64, Vec<EpgItem>)>)> {
|
||||
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<crate::ts::tables::Pmt>)>();
|
||||
*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::<Vec<_>>()
|
||||
.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);
|
||||
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(),
|
||||
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),
|
||||
});
|
||||
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.tuners
|
||||
.epg_enabled
|
||||
.store(s.epg_ota_enabled, Ordering::Relaxed);
|
||||
*self.tuners.linger.lock().unwrap() = Duration::from_secs(s.tuner_linger_seconds as u64);
|
||||
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.
|
||||
pub async fn refresh_adapters(&self) -> Result<Vec<AdapterInfo>> {
|
||||
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())
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user