//! Shared service handles. Blocking persistence is dispatched away from the UI and event actor. use std::{collections::{HashMap,HashSet},path::PathBuf,time::Instant,sync::{Arc,Mutex,MutexGuard,Weak,atomic::{AtomicBool,AtomicU64,Ordering}}}; use tokio::sync::{mpsc,oneshot,watch,Semaphore}; use serde_json::Value; use crate::{app::connections::{ConnectionError,SessionKey},media::{audio::engine::AudioHandle,stream::hub::StreamHub},platform::resources::{ActionPolicy,DirectoryGrant,PickRequest,Selection},services::{Result,ServiceError,profile::ProfileServices,connected::ConnectedServices,themes::ThemeService,privacy::{PhishingList,ApprovedLink},badges::BadgeCatalog,notifications::Notifications,keybinds::{KeybindRuntime,ChordRecorder,Action as KeyAction},secrets::SecretString,updates::UpdateService},ui::{shell::{Target,Entity,Form,Values,Operation},settings::{CommandDrafts,SettingsSnapshot}}}; use super::events::{ServiceEvent,Prompt,UiEffect}; pub type DirectoryKey=(String,u64,u64,u64); pub fn directory_key(key:&SessionKey,channel:u64)->DirectoryKey{(key.connection_id.clone(),key.session,key.generation,channel)} pub enum KeyCapture {Ptt,Binding{profile:String,binding:Option,action:KeyAction,target:String}} #[derive(Default)] pub struct KeyState { pub runtime:KeybindRuntime, pub recorder:ChordRecorder, pub capture:Option, pub chord:Option, #[cfg(not(any(target_os="android",target_os="ios")))] pub global:Option, } #[derive(Default)] pub struct TransmissionState { pub key:Option, pub revision:u64, pub ptt_holders:HashSet, // A normal PTT release stops its device lease, not the user's input selection. pub ptt_resume_input:bool, pub release_at:Option, pub deactivated:HashSet, pub whisper:crate::services::whisper::WhisperHold, pub whisper_resume_input:bool, pub configured:Option, } impl TransmissionState { /// A second release must not extend the tail or cancel another holder. pub(crate) fn release_ptt(&mut self, holder: &str, delay: Option) -> bool { if !self.ptt_holders.remove(holder) { return false; } if self.ptt_holders.is_empty() { self.release_at = delay.map(|d| Instant::now() + d); } self.revision = self.revision.wrapping_add(1); true } } pub(crate) fn ptt_release_delay(prefs: &Value) -> Option { let delay = &prefs["pttReleaseDelay"]; (delay["active"] == true).then(|| std::time::Duration::from_millis(delay["ms"].as_u64().unwrap_or(300))) } pub struct IdentityImprovement { pub uid:String, pub job:u64, pub ui_generation:u64, pub cancel:Arc, } pub struct RuntimeServices { pub root:PathBuf, /// The catalog loaded for this launch; saving a locale selects the next launch's catalog. pub catalog: crate::ui::i18n::Catalog, pub profile:Mutex, pub connected:Arc, pub audio:AudioHandle, pub streams:Arc, pub themes:Mutex, pub phishing:Arc, pub badges:Arc, pub notifications:Mutex, pub updates:UpdateService, pub keys:tokio::sync::Mutex, pub settings_drafts:Mutex, pub settings_status:Mutex, pub improvement:Mutex>, pub progress:Mutex>, pub directory_passwords:Mutex>, pub download_directory:Mutex>>, pub recording_directory:Mutex>>, pub file_workflows:tokio::sync::Mutex, pub chat_workflows:tokio::sync::Mutex, pub stream_workflows:tokio::sync::Mutex, pub local_workflows:Mutex, pub mobile_call:tokio::sync::Mutex>, #[cfg(target_os="ios")] pub apple_call:tokio::sync::Mutex>, #[cfg(target_os="android")] pub android_notifications:Mutex>, pub audio_input_active:AtomicBool, pub audio_defaults:Mutex<(bool,bool)>, pub audio_output_active:AtomicBool, pub applied_audio_selections:Mutex<(String,String)>, pub audio_configuration:tokio::sync::Mutex<()>, pub microphone_test_resume:Mutex,bool,bool)>>, pub transmission:Mutex, // Serializes saved receive-mode changes against pre-connect core initialization. pub(super) whisper_receive:tokio::sync::RwLock<()>, // Keep reconnect snapshots ordered with committed gain writes and their fanout. pub(super) volume_sync:tokio::sync::Mutex<()>, pub(super) notification_clock:super::notification_actions::NotificationClock, pub system_scheme:Mutex>, pub installed:bool, pub microphone_granted:AtomicBool, pub output_granted:AtomicBool, pub policy:ActionPolicy, pub network_enabled:bool, #[cfg(test)] pub(crate) fixture_channel_banners: Mutex)>>, #[cfg(all(test, windows))] pub(crate) fixture_live_channel_banners: AtomicBool, #[cfg(test)] pub(crate) fixture_channel_banner_completions: std::sync::atomic::AtomicUsize, pub version:&'static str, pub runtime:Weak, pub revision:AtomicU64, pub events:mpsc::Sender, pub cancelled:watch::Receiver, pub dialogs:Semaphore, pub prompt_counter:AtomicU64, #[cfg(all(test, windows, feature = "test-harness"))] pub(crate) channel_edit_gate:super::channel_edit_test_gate::Gate, } impl RuntimeServices { pub fn profile(&self)->Result> { self.profile.lock().map_err(|_|ServiceError::new("profile_unavailable","Profile service stopped after a failed operation")) } pub async fn mutate(self:&Arc,operation:impl FnOnce(&mut ProfileServices)->Result+Send+'static)->Result{ let owner=self.clone(); let result=tokio::task::spawn_blocking(move||{ let mut profile=owner.profile()?; let result=operation(&mut profile)?; owner.revision.fetch_add(1,Ordering::AcqRel); Ok::(result) }).await.map_err(|_|ServiceError::new("profile_worker_failed","Profile operation failed"))??; self.changed().await?;Ok(result) } pub async fn changed(&self)->Result<()>{self.events.send(ServiceEvent::Changed).await.map_err(|_|closed())} pub async fn effect(&self,effect:UiEffect)->Result<()>{self.events.send(ServiceEvent::Effect(effect)).await.map_err(|_|closed())} pub fn require_key(&self,key:&SessionKey,connected:bool)->Result<()> { let snapshot=self.connected.connections.snapshot(); let entry=snapshot.get(&key.connection_id).filter(|entry|entry.key==*key).ok_or_else(changed)?; if connected&&!entry.is_connected(){return Err(ServiceError::new("not_connected","Connect to the server first"));} Ok(()) } pub fn require_target(&self,target:&Target)->Result<()> { let Some(key)=&target.session else{return Ok(())};self.require_key(key,true)?; let snapshots=self.connected.connections.snapshot(); let snapshot=snapshots.get(&key.connection_id).and_then(|entry|entry.server.as_deref()).ok_or_else(changed)?; match &target.entity { Entity::Client{id,uid,..}|Entity::StreamViewer{client_id:id,uid,..}=>{ if !snapshot["clients"].as_array().is_some_and(|clients|clients.iter().any(|client|client["id"].as_u64()==Some(u64::from(*id))&&client["uid"].as_str()==Some(uid))){return Err(changed());} }, Entity::Channel{id}|Entity::File{channel_id:id,..}=>{ if !snapshot["channels"].as_array().is_some_and(|channels|channels.iter().any(|channel|channel["id"].as_u64()==Some(*id))){return Err(changed());} },_=>{} } Ok(()) } pub fn require_idle(&self)->Result<()> { if self.connected.connections.snapshot().any_active(){Err(ServiceError::new("connections_active","Disconnect all server sessions before this profile operation"))}else{Ok(())} } pub async fn request(&self,key:&SessionKey,command:teamspeach_core::protocol::Command)->Result{ self.require_key(key,false)?; if !self.network_enabled&&matches!(command,teamspeach_core::protocol::Command::Connect(_)) {return Err(ServiceError::new("network_disabled","Network connections are disabled in this isolated runtime"));} match self.connected.connections.request(key,command).await { Ok(value)=>Ok(value), Err(error)=>{ if let ConnectionError::Core(core)=&error{ // Notification delivery cannot replace the caller's original command error. let _=super::notification_actions::on_request_error(self,key,core).await; } Err(connection_error(error)) } } } pub async fn prompt(&self,mut form:Form)->Result{ if *self.cancelled.borrow(){return Err(closed());} let ui_generation=self.current_ui_generation()?; let mut cancelled=self.cancelled.clone(); let _lease=tokio::select!{lease=self.dialogs.acquire()=>lease.map_err(|_|closed())?,_ = cancelled.changed()=>return Err(closed())}; self.require_ui_generation(ui_generation)?; self.require_target(&form.target)?; let serial=self.prompt_counter.fetch_update(Ordering::AcqRel,Ordering::Acquire,|n|n.checked_add(1)).map_err(|_|closed())?; form.id=format!("service-prompt-{serial}"); let target=form.target.clone(); let(answer,reply)=oneshot::channel(); self.events.send(ServiceEvent::Prompt(Prompt{form,answer})).await.map_err(|_|closed())?; let response=tokio::select!{response=reply=>response.map_err(|_|closed())?,_ = cancelled.changed()=>return Err(closed())}; self.require_ui_generation(ui_generation)?;self.require_target(&target)?;response } pub async fn confirm(&self,target:Target,title:String,description:String,exact:Option)->Result{ let form=Form{id:String::new(),target,operation:Operation::ConfirmOverwrite,title,description,fields:Vec::new(),confirmation:exact,submit_label:"OK".into(),destructive:true,busy:false,error:String::new(),actions:Vec::new(),acknowledged_revision:0}; match self.prompt(form).await{Ok(_)=>Ok(true),Err(error)if error.code=="cancelled"=>Ok(false),Err(error)=>Err(error)} } pub async fn pick(&self,request:PickRequest)->Result>{ self.policy.check()?; let generation=self.current_ui_generation()?; let mut cancelled=self.cancelled.clone(); if *cancelled.borrow(){return Err(closed())} #[cfg(not(any(target_os="android",target_os="ios")))] let operation=crate::platform::desktop::pick(request,self.policy); #[cfg(target_os="android")] let operation=crate::platform::android::pick(request,self.policy); #[cfg(target_os="ios")] let operation=crate::platform::apple::pick(request,self.policy); let selection=tokio::select!{selection=operation=>selection?,_=cancelled.changed()=>return Err(closed())}; self.require_ui_generation(generation)?;Ok(selection) } pub async fn clipboard_write(&self,text:&str)->Result<()> { self.policy.check()?; #[cfg(not(any(target_os="android",target_os="ios")))] {crate::platform::desktop::clipboard_write(text,self.policy).await} #[cfg(target_os="android")] {crate::platform::android::clipboard_write(text,self.policy).await} #[cfg(target_os="ios")] {crate::platform::apple::clipboard_write(text,self.policy).await} } pub async fn open_approved(&self,link:&ApprovedLink)->Result<()> { self.policy.check()?; #[cfg(not(any(target_os="android",target_os="ios")))] {crate::platform::desktop::open_external(link,self.policy).await} #[cfg(target_os="android")] {crate::platform::android::open_external_url(link.url(),self.policy).await} #[cfg(target_os="ios")] {crate::platform::apple::open_external_url(link.url(),self.policy).await} } } pub fn connection_error(error:ConnectionError)->ServiceError { match error{ ConnectionError::Core(error) if error.ts_error.as_ref().is_some_and(|error|error.id==0x030d)=>ServiceError::new("channel_password_invalid",error.message), ConnectionError::Core(error)=>{ let code=serde_json::to_value(error.code).ok().and_then(|value|value.as_str().map(str::to_owned)).unwrap_or_else(||"server_error".into()); let message = match error.ts_error.filter(|ts| ts.id == 2568).and_then(|ts| ts.missing_permission) { Some(id) => format!("{} (permission ID: {id})", error.message), None => error.message, }; ServiceError::new(code,message) }, ConnectionError::TargetChanged|ConnectionError::Closed=>changed(), ConnectionError::NotConnected=>ServiceError::new("not_connected","Connect to the server first"), ConnectionError::TooManyConnections=>ServiceError::new("too_many_connections",format!("You can open up to {} server tabs. Close a tab before opening another.",crate::app::connections::MAX_CONNECTIONS)), other=>ServiceError::new("connection_failed",other.to_string()), } } pub fn changed()->ServiceError{ServiceError::new("target_changed","The captured server or client has changed")} pub fn closed()->ServiceError{ServiceError::new("closed","The application service is shutting down")} #[cfg(test)] #[test] fn permission_refusal_keeps_the_reported_id_without_inventing_one() { use teamspeach_core::protocol::{ErrorCode, ErrorObj, TsErrorInfo}; for (id, expected) in [(Some(86), "Denied (permission ID: 86)"), (None, "Denied")] { let error = ErrorObj::new(ErrorCode::ServerError, "Denied").with_ts(TsErrorInfo { id: 2568, name: "PermissionsClientInsufficient".into(), missing_permission: id, }); let shown = connection_error(ConnectionError::Core(error)); assert_eq!(shown.code, "server_error"); assert_eq!(shown.message, expected); } }