//! DIAL glue: apps with a `[dial]` section in their manifest (YouTube) can be //! started from a phone. Store apps may do it too (the `dial` permission the //! user approved); an official app with the same DIAL name wins. use std::sync::Arc; use anyhow::{Context, Result}; use sf_dial::{AppState, Config, Handler, LaunchParams}; use sf_ipc::{AppManifest, Origin}; use crate::apps::Core; struct Dial(Arc); impl Dial { fn app_for(&self, dial_name: &str) -> Option { pick(self.0.apps(), dial_name) } } /// The app that answers to `dial_name`: official apps first, then store apps /// (in the app list's order). fn pick(apps: Vec, dial_name: &str) -> Option { let mut found: Vec = apps.into_iter().filter(|a| a.dial.as_ref().is_some_and(|d| d.name == dial_name)).collect(); found.sort_by_key(|a| a.origin == Origin::Store); found.into_iter().next().map(|a| a.id) } #[cfg(test)] mod tests { use super::*; #[test] fn official_dial_app_wins() { let app = |id: &str, origin| { let mut a: AppManifest = toml::from_str(&format!("id = '{id}'\nname = 'x'\nkind = 'web'\nurl = 'https://x'\n[dial]\nname = 'YouTube'\n")).unwrap(); a.origin = origin; a }; assert_eq!(pick(vec![app("io.x.tube", Origin::Store), app("youtube", Origin::Official)], "YouTube").as_deref(), Some("youtube")); assert_eq!(pick(vec![app("io.x.tube", Origin::Store)], "YouTube").as_deref(), Some("io.x.tube")); assert_eq!(pick(vec![app("io.x.tube", Origin::Store)], "Netflix"), None); } } impl Handler for Dial { fn state(&self, name: &str) -> Option { let id = self.app_for(name)?; Some(if self.0.is_running(&id) { AppState::Running } else { AppState::Stopped }) } fn launch(&self, name: &str, params: LaunchParams) -> Result<()> { let id = self.app_for(name).context("unknown app")?; log::info!("dial: {name} -> {id} from {}", params.peer); let core = self.0.clone(); let query = params.query(); tokio::spawn(async move { if let Err(e) = core.launch(&id, Some(query), true).await { log::error!("dial launch {id}: {e:#}"); } }); Ok(()) } fn stop(&self, name: &str) -> bool { match self.app_for(name) { Some(id) => self.0.stop(&id), None => false, } } } pub async fn run(core: Arc, port: u16) -> Result<()> { let settings = sf_ipc::Settings::load(&sf_ipc::paths::settings_file()).unwrap_or_default(); let mut config = Config { http_port: port, ..Default::default() }; if let Some(name) = settings.get("device_name").filter(|n| !n.trim().is_empty()) { config.friendly_name = name.trim().to_string(); } if let Ok(id) = std::fs::read_to_string("/etc/machine-id") { config.uuid = sf_dial::uuid_from_machine_id(&id); } log::info!("dial: \"{}\" uuid:{}", config.friendly_name, config.uuid); sf_dial::run(config, Dial(core)).await }