toolblox_lib/
auto_rejoin.rs1use std::collections::HashMap;
4use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
5
6use tauri::{AppHandle, Manager};
7use tauri_plugin_notification::NotificationExt;
8
9use crate::app_commands::Runtime;
10use crate::models::PresenceState;
11
12const POLL_INTERVAL: Duration = Duration::from_secs(10);
14const LAUNCH_POLL_INTERVAL: Duration = Duration::from_secs(3);
16const LAUNCH_WINDOW: Duration = Duration::from_secs(60);
18const REJOIN_GRACE: Duration = Duration::from_secs(45);
20
21const CLOSE_GRACE: Duration = Duration::from_secs(120);
23
24static CLOSED_ALL_AT: std::sync::Mutex<Option<Instant>> = std::sync::Mutex::new(None);
26
27pub fn note_closed_all() {
29 *CLOSED_ALL_AT
30 .lock()
31 .unwrap_or_else(|error| error.into_inner()) = Some(Instant::now());
32}
33
34fn closed_all_recently() -> bool {
35 CLOSED_ALL_AT
36 .lock()
37 .unwrap_or_else(|error| error.into_inner())
38 .is_some_and(|closed| closed.elapsed() < CLOSE_GRACE)
39}
40
41#[derive(Default)]
43struct Entry {
44 was_in_game: bool,
46 last_rejoin: Option<Instant>,
47 suspended: bool,
49 last_played_at: Option<f64>,
50}
51
52pub async fn run(app: AppHandle) {
56 let mut entries: HashMap<u64, Entry> = HashMap::new();
57 let mut interval = POLL_INTERVAL;
58 let mut presence_failing = false;
59 loop {
60 tokio::time::sleep(interval).await;
61 interval = POLL_INTERVAL;
62 let runtime = app.state::<Runtime>();
63 let Ok(settings) = runtime.storage.load_settings() else {
64 continue;
65 };
66 if !settings.auto_rejoin && !settings.notify_on_drop {
67 entries.clear();
68 continue;
69 }
70 let Ok(accounts) = runtime.storage.load_accounts() else {
71 continue;
72 };
73 let now = SystemTime::now()
74 .duration_since(UNIX_EPOCH)
75 .map_or(0.0, |elapsed| elapsed.as_secs_f64());
76 let launched = accounts
77 .iter()
78 .any(|account| launched_recently(now, account.last_played_at))
79 || entries.values().any(|entry| {
80 entry
81 .last_rejoin
82 .is_some_and(|last| last.elapsed() < LAUNCH_WINDOW)
83 });
84 if launched {
85 interval = LAUNCH_POLL_INTERVAL;
86 }
87 let ids: Vec<_> = accounts.iter().map(|account| account.id).collect();
88 let mut states = None;
89 let mut failure = None;
90 for account in &accounts {
91 let Ok(secret) = runtime.session(account.id) else {
92 continue;
93 };
94 let result = crate::roblox::fetch_presence(&runtime.client, &secret, &ids).await;
95 runtime.note_session(account.id, &result);
96 match result {
97 Ok(found) => {
98 states = Some(found);
99 break;
100 }
101 Err(error @ crate::roblox::RobloxError::Rejected(_)) => {
102 failure = Some(error.to_string());
103 }
104 Err(error) => {
105 failure = Some(error.to_string());
106 break;
107 }
108 }
109 }
110 let Some(states) = states else {
111 if !presence_failing && !accounts.is_empty() {
112 log::warn!(
113 "Presence checks for auto-rejoin are failing: {}",
114 failure
115 .as_deref()
116 .unwrap_or("no account has a readable session")
117 );
118 }
119 presence_failing = true;
120 continue;
121 };
122 if presence_failing {
123 log::info!("Presence checks for auto-rejoin recovered");
124 presence_failing = false;
125 }
126 entries.retain(|id, _| states.contains_key(id));
127 for (id, presence) in states {
128 let entry = entries.entry(id).or_default();
129 let last_played_at = accounts
130 .iter()
131 .find(|account| account.id == id)
132 .and_then(|account| account.last_played_at);
133 if entry.last_played_at.is_some() && entry.last_played_at != last_played_at {
134 entry.suspended = false;
135 entry.last_rejoin = None;
136 }
137 entry.last_played_at = last_played_at;
138 match presence {
139 PresenceState::InGame | PresenceState::InStudio => entry.was_in_game = true,
140 PresenceState::Offline | PresenceState::Online if entry.was_in_game => {
141 entry.was_in_game = false;
142 if closed_all_recently() {
143 continue;
144 }
145 let name = accounts
146 .iter()
147 .find(|account| account.id == id)
148 .map(|account| account.display_name.clone())
149 .unwrap_or_default();
150 let notify = |title: String, body: &str| {
151 if settings.notify_on_drop {
152 let _ = app.notification().builder().title(title).body(body).show();
153 }
154 };
155 log::info!("Account {id} left its game");
156 if !settings.auto_rejoin {
157 notify(format!("{name} disconnected"), "Open Toolblox to rejoin.");
158 continue;
159 }
160 if entry.suspended {
161 continue;
162 }
163 if entry
164 .last_rejoin
165 .is_some_and(|last| last.elapsed() < REJOIN_GRACE)
166 {
167 entry.suspended = true;
168 log::warn!(
169 "Auto-rejoin paused for account {id}: it left again within {} seconds",
170 REJOIN_GRACE.as_secs()
171 );
172 notify(
173 format!("Auto-rejoin paused for {name}"),
174 "It disconnected again shortly after rejoining. Join manually to resume.",
175 );
176 continue;
177 }
178 notify(format!("{name} disconnected"), "Rejoining automatically.");
179 match crate::app_commands::join_account_ids(&runtime, &[id], false, None, None)
180 .await
181 {
182 Ok(_) => {
183 log::info!("Auto-rejoined account {id}");
184 entry.last_rejoin = Some(Instant::now());
185 }
186 Err(error) => log::warn!("Auto-rejoin for account {id} failed: {error}"),
187 }
188 }
189 PresenceState::Offline | PresenceState::Online | PresenceState::Unknown => {}
190 }
191 }
192 }
193}
194
195fn launched_recently(now: f64, last_played_at: Option<f64>) -> bool {
197 last_played_at
198 .is_some_and(|played| (0.0..LAUNCH_WINDOW.as_secs_f64()).contains(&(now - played)))
199}
200
201#[cfg(test)]
202mod tests {
203 use super::*;
204
205 #[test]
206 fn polls_faster_only_in_the_first_minute() {
207 assert!(launched_recently(100.0, Some(100.0)));
208 assert!(launched_recently(100.0, Some(41.0)));
209 assert!(!launched_recently(100.0, Some(40.0)));
210 assert!(!launched_recently(100.0, Some(200.0)));
211 assert!(!launched_recently(100.0, None));
212 }
213}