Files
client/native/src/app/runtime/context.rs
T
omar 87cfa59252 test: verify live beta14 channel banner fetch
Reject zero channel IDs at the fetch_banner command boundary. Verify exact classic download bytes and rendered Slint row pixels, permission refusal, missing-file fallback and stale-reference rejection on disposable loopback beta14.
2026-11-28 10:04:25 +03:00

255 lines
14 KiB
Rust

//! 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<String>,action:KeyAction,target:String}}
#[derive(Default)]
pub struct KeyState {
pub runtime:KeybindRuntime,
pub recorder:ChordRecorder,
pub capture:Option<KeyCapture>,
pub chord:Option<crate::services::keybinds::Chord>,
#[cfg(not(any(target_os="android",target_os="ios")))]
pub global:Option<crate::platform::desktop::hotkeys::Hotkeys>,
}
#[derive(Default)]
pub struct TransmissionState {
pub key:Option<SessionKey>,
pub revision:u64,
pub ptt_holders:HashSet<String>,
// A normal PTT release stops its device lease, not the user's input selection.
pub ptt_resume_input:bool,
pub release_at:Option<Instant>,
pub deactivated:HashSet<String>,
pub whisper:crate::services::whisper::WhisperHold,
pub whisper_resume_input:bool,
pub configured:Option<crate::app::connections::InputConfiguration>,
}
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<std::time::Duration>) -> 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<std::time::Duration> {
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<AtomicBool>,
}
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<ProfileServices>,
pub connected:Arc<ConnectedServices>,
pub audio:AudioHandle,
pub streams:Arc<StreamHub>,
pub themes:Mutex<ThemeService>,
pub phishing:Arc<PhishingList>,
pub badges:Arc<BadgeCatalog>,
pub notifications:Mutex<Notifications>,
pub updates:UpdateService,
pub keys:tokio::sync::Mutex<KeyState>,
pub settings_drafts:Mutex<CommandDrafts>,
pub settings_status:Mutex<SettingsSnapshot>,
pub improvement:Mutex<Option<IdentityImprovement>>,
pub progress:Mutex<HashMap<String,Value>>,
pub directory_passwords:Mutex<HashMap<DirectoryKey,SecretString>>,
pub download_directory:Mutex<Option<Arc<dyn DirectoryGrant>>>,
pub recording_directory:Mutex<Option<Arc<dyn DirectoryGrant>>>,
pub file_workflows:tokio::sync::Mutex<super::file_actions::FileWorkflows>,
pub chat_workflows:tokio::sync::Mutex<super::chat_actions::ChatWorkflows>,
pub stream_workflows:tokio::sync::Mutex<super::stream_actions::StreamWorkflows>,
pub local_workflows:Mutex<super::local_actions::LocalWorkflows>,
pub mobile_call:tokio::sync::Mutex<Option<(SessionKey,bool)>>,
#[cfg(target_os="ios")]
pub apple_call:tokio::sync::Mutex<Option<crate::platform::apple::CallLease>>,
#[cfg(target_os="android")]
pub android_notifications:Mutex<std::collections::VecDeque<crate::platform::android::NotificationLease>>,
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<Option<(Option<SessionKey>,bool,bool)>>,
pub transmission:Mutex<TransmissionState>,
// 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<Option<crate::services::themes::ColorScheme>>,
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<Vec<(super::channel_banners::Source, oneshot::Receiver<Value>)>>,
#[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<crate::AppRuntime>,
pub revision:AtomicU64,
pub events:mpsc::Sender<ServiceEvent>,
pub cancelled:watch::Receiver<bool>,
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<MutexGuard<'_,ProfileServices>> {
self.profile.lock().map_err(|_|ServiceError::new("profile_unavailable","Profile service stopped after a failed operation"))
}
pub async fn mutate<T:Send+'static>(self:&Arc<Self>,operation:impl FnOnce(&mut ProfileServices)->Result<T>+Send+'static)->Result<T>{
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::<T,ServiceError>(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<Value>{
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<Values>{
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<String>)->Result<bool>{
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<Option<Selection>>{
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);
}
}