Skip to main content

shunt/
remote.rs

1/// `shunt remote` — relay-based remote account event watcher.
2///
3/// **Host mode** (`shunt remote`):
4///   - Generates a one-time watch code (`RM-…`)
5///   - Polls the local shunt `/status` every 10 s
6///   - Encrypts the snapshot and pushes it to the relay
7///   - Prints the code so the user can enter it on another device
8///
9/// **Client mode** (`shunt remote RM-…`):
10///   - Polls the relay for the latest encrypted snapshot
11///   - Decrypts and diffs against the previous poll
12///   - Fires local system notifications on account events
13use std::collections::{HashMap, HashSet};
14use std::time::{Duration, Instant};
15
16use anyhow::{Context, Result};
17use serde::{Deserialize, Serialize};
18
19use crate::term::{bold, cyan, dim, fmt_duration_ms, green, red, yellow};
20
21// ---------------------------------------------------------------------------
22// Relay URL default
23// ---------------------------------------------------------------------------
24
25const DEFAULT_RELAY: &str = "https://relay.ramcharan.shop";
26
27// ---------------------------------------------------------------------------
28// Snapshot types (serialized + encrypted over the relay)
29// ---------------------------------------------------------------------------
30
31#[derive(Debug, Serialize, Deserialize, Clone)]
32pub struct AccountStatus {
33    pub name: String,
34    #[serde(default)]
35    pub available: bool,
36    #[serde(default)]
37    pub disabled: bool,
38    #[serde(default)]
39    pub auth_failed: bool,
40    #[serde(default)]
41    pub cooldown_until_ms: u64,
42}
43
44#[derive(Debug, Serialize, Deserialize)]
45struct RemoteSnapshot {
46    accounts: Vec<AccountStatus>,
47    ts_ms: u64,
48}
49
50// ---------------------------------------------------------------------------
51// State snapshot for diffing (client side)
52// ---------------------------------------------------------------------------
53
54#[derive(Debug, Clone)]
55struct Snap {
56    auth_failed: bool,
57    /// true if `cooldown_until_ms > now_ms` at snapshot time
58    cooling: bool,
59    disabled: bool,
60}
61
62impl Snap {
63    fn from_status(acc: &AccountStatus, now_ms: u64) -> Self {
64        Self {
65            auth_failed: acc.auth_failed,
66            cooling: acc.cooldown_until_ms > now_ms,
67            disabled: acc.disabled,
68        }
69    }
70}
71
72// ---------------------------------------------------------------------------
73// Thresholds
74// ---------------------------------------------------------------------------
75
76const POLL_INTERVAL: Duration = Duration::from_secs(10);
77/// How often the host pushes to the relay even if nothing changed (keeps session alive).
78const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5 * 60);
79/// Cooldowns shorter than this are transient — skip notification.
80const LONG_COOLDOWN_MS: u64 = 5 * 60_000;
81/// Minimum gap between "all accounts offline" notifications.
82const ALL_OFFLINE_NOTIFY_COOLDOWN: Duration = Duration::from_secs(3_600);
83
84// ---------------------------------------------------------------------------
85// Entry point — dispatches host vs client
86// ---------------------------------------------------------------------------
87
88pub async fn run_remote(code: Option<String>, relay_url: Option<String>, local_url: String) -> Result<()> {
89    let relay = relay_url.unwrap_or_else(|| DEFAULT_RELAY.to_string());
90    match code {
91        None        => run_host(relay, local_url).await,
92        Some(code)  => run_client(code, relay).await,
93    }
94}
95
96// ---------------------------------------------------------------------------
97// Host mode
98// ---------------------------------------------------------------------------
99
100async fn run_host(relay_url: String, local_url: String) -> Result<()> {
101    let code = crate::sync::generate_remote_code();
102
103    let client = reqwest::Client::builder()
104        .timeout(Duration::from_secs(10))
105        .pool_max_idle_per_host(0)
106        .build()?;
107
108    println!();
109    println!("  {}  {}  {}", bold("◆"), bold("shunt"), dim("remote  host"));
110    println!();
111    println!("  {}  {}", dim("code"), cyan(&code));
112    println!("  {}  on another device run:", dim("·"));
113    println!("  {}  {}", dim("·"), bold(&format!("shunt remote {code}")));
114    println!();
115    println!("  {}  watching local accounts — Ctrl-C to stop", dim("·"));
116    println!();
117
118    let mut last_push: Option<Instant> = None;
119    let mut last_accounts_json: Option<String> = None;
120
121    loop {
122        match fetch_local_status(&client, &local_url).await {
123            Ok(accounts) => {
124                let accounts_json = serde_json::to_string(&accounts).unwrap_or_default();
125                let changed = last_accounts_json.as_deref() != Some(accounts_json.as_str());
126                let heartbeat_due = last_push
127                    .map(|t| t.elapsed() >= HEARTBEAT_INTERVAL)
128                    .unwrap_or(true);
129
130                if changed || heartbeat_due {
131                    let snapshot = RemoteSnapshot { accounts, ts_ms: now_ms() };
132                    let data = serde_json::to_vec(&snapshot)?;
133                    let payload = crate::sync::encrypt_bytes(&data, &code)?;
134
135                    let push_url = format!("{relay_url}/watch/{code}");
136                    match client
137                        .put(&push_url)
138                        .json(&serde_json::json!({ "payload": payload }))
139                        .send()
140                        .await
141                    {
142                        Ok(r) if r.status().is_success() => {
143                            last_push = Some(Instant::now());
144                            last_accounts_json = Some(accounts_json);
145                        }
146                        Ok(r) => {
147                            let status = r.status();
148                            eprintln!("  {}  relay push failed: {status}", red("✗"));
149                        }
150                        Err(e) => eprintln!("  {}  relay unreachable: {e}", red("✗")),
151                    }
152                }
153            }
154            Err(e) => eprintln!("  {}  local shunt unreachable: {e}", red("✗")),
155        }
156
157        tokio::time::sleep(POLL_INTERVAL).await;
158    }
159}
160
161// ---------------------------------------------------------------------------
162// Client mode
163// ---------------------------------------------------------------------------
164
165async fn run_client(code: String, relay_url: String) -> Result<()> {
166    crate::sync::validate_remote_code(&code)
167        .context("invalid remote code")?;
168
169    let client = reqwest::Client::builder()
170        .timeout(Duration::from_secs(10))
171        .pool_max_idle_per_host(0)
172        .build()?;
173
174    println!();
175    println!("  {}  {}  {}", bold("◆"), bold("shunt"), dim("remote  client"));
176    println!("  {}  {}", dim("·"), cyan(&relay_url));
177    println!("  {}  connecting…", dim("·"));
178    println!();
179
180    let mut prev: HashMap<String, Snap> = HashMap::new();
181    let mut first_poll = true;
182    let mut was_session_missing = false;
183
184    // Throttle state
185    let mut notified_cooldown: HashMap<String, u64> = HashMap::new();
186    let mut notified_auth_failed: HashSet<String> = HashSet::new();
187    let mut last_all_offline: Option<Instant> = None;
188    let mut was_all_offline = false;
189
190    loop {
191        let poll_url = format!("{relay_url}/watch/{code}");
192        match client.get(&poll_url).send().await {
193            Ok(resp) if resp.status() == reqwest::StatusCode::NOT_FOUND => {
194                if !was_session_missing {
195                    println!("  {}  session not found — waiting for host…", yellow("⏸"));
196                    was_session_missing = true;
197                }
198            }
199            Ok(resp) if resp.status().is_success() => {
200                if was_session_missing {
201                    println!("  {}  host connected", green("✓"));
202                    was_session_missing = false;
203                }
204
205                let body: serde_json::Value = match resp.json().await {
206                    Ok(v) => v,
207                    Err(e) => { eprintln!("  {}  bad relay response: {e}", red("✗")); continue; }
208                };
209
210                let payload = match body["payload"].as_str() {
211                    Some(p) => p.to_owned(),
212                    None => { eprintln!("  {}  relay response missing payload", red("✗")); continue; }
213                };
214
215                let data = match crate::sync::decrypt_bytes(&payload, &code) {
216                    Ok(d) => d,
217                    Err(e) => { eprintln!("  {}  decryption failed: {e}", red("✗")); continue; }
218                };
219
220                let snapshot: RemoteSnapshot = match serde_json::from_slice(&data) {
221                    Ok(s) => s,
222                    Err(e) => { eprintln!("  {}  snapshot parse error: {e}", red("✗")); continue; }
223                };
224
225                let now = now_ms();
226
227                if first_poll {
228                    print_initial_state(&snapshot.accounts, now);
229                    for acc in &snapshot.accounts {
230                        prev.insert(acc.name.clone(), Snap::from_status(acc, now));
231                    }
232                    first_poll = false;
233                } else {
234                    diff_and_notify(
235                        &snapshot.accounts,
236                        &prev,
237                        now,
238                        &mut notified_cooldown,
239                        &mut notified_auth_failed,
240                        &mut last_all_offline,
241                        &mut was_all_offline,
242                    );
243                    prev.clear();
244                    for acc in &snapshot.accounts {
245                        prev.insert(acc.name.clone(), Snap::from_status(acc, now));
246                    }
247                }
248            }
249            Ok(resp) => {
250                eprintln!("  {}  relay error: {}", red("✗"), resp.status());
251            }
252            Err(e) => {
253                eprintln!("  {}  cannot reach relay: {e}", red("✗"));
254            }
255        }
256
257        tokio::time::sleep(POLL_INTERVAL).await;
258    }
259}
260
261// ---------------------------------------------------------------------------
262// State diffing + notification dispatch
263// ---------------------------------------------------------------------------
264
265fn diff_and_notify(
266    accounts: &[AccountStatus],
267    prev: &HashMap<String, Snap>,
268    now_ms: u64,
269    notified_cooldown: &mut HashMap<String, u64>,
270    notified_auth_failed: &mut HashSet<String>,
271    last_all_offline: &mut Option<Instant>,
272    was_all_offline: &mut bool,
273) {
274    let all_unavailable = accounts.iter().all(|a| !a.available);
275
276    for acc in accounts {
277        let Some(p) = prev.get(&acc.name) else { continue };
278
279        // ── Reauth required (newly auth_failed) ─────────────────────────────
280        if acc.auth_failed && !p.auth_failed && !notified_auth_failed.contains(&acc.name) {
281            let msg = format!(
282                "Account '{}' needs re-authorization. Run `shunt add-account`.",
283                acc.name
284            );
285            println!("  {}  [{}]  reauth required", red("✗"), yellow(&acc.name));
286            crate::notify::notify("shunt: Reauth Required", &msg, "Basso");
287            notified_auth_failed.insert(acc.name.clone());
288        }
289        if !acc.auth_failed {
290            notified_auth_failed.remove(&acc.name);
291        }
292
293        // ── Entered cooldown (newly, long enough to matter) ──────────────────
294        let curr_cooling = acc.cooldown_until_ms > now_ms;
295        if curr_cooling && !p.cooling {
296            let remaining_ms = acc.cooldown_until_ms - now_ms;
297            let last_cdl = notified_cooldown.get(&acc.name).copied().unwrap_or(0);
298            if remaining_ms >= LONG_COOLDOWN_MS && acc.cooldown_until_ms != last_cdl {
299                let mins = remaining_ms / 60_000;
300                let msg = format!("Account '{}' hit quota limit — cooling {}m.", acc.name, mins);
301                println!(
302                    "  {}  [{}]  rate limited — cooling {}",
303                    yellow("⏸"), yellow(&acc.name), yellow(&fmt_duration_ms(remaining_ms)),
304                );
305                crate::notify::notify("shunt: Rate Limited", &msg, "Ping");
306                notified_cooldown.insert(acc.name.clone(), acc.cooldown_until_ms);
307            }
308        }
309
310        // ── Resumed from cooldown ────────────────────────────────────────────
311        if p.cooling && acc.available && !acc.auth_failed {
312            println!("  {}  [{}]  back online", green("✓"), green(&acc.name));
313            crate::notify::notify(
314                "shunt: Account Resumed",
315                &format!("Account '{}' is back online.", acc.name),
316                "Glass",
317            );
318            notified_cooldown.remove(&acc.name);
319        }
320
321        // ── Recovered from auth_failed / disabled ────────────────────────────
322        if (p.auth_failed || p.disabled) && acc.available {
323            println!("  {}  [{}]  recovered", green("✓"), green(&acc.name));
324            crate::notify::notify(
325                "shunt: Account Recovered",
326                &format!("Account '{}' is back online.", acc.name),
327                "Glass",
328            );
329        }
330    }
331
332    // ── All accounts offline ─────────────────────────────────────────────────
333    if all_unavailable && !*was_all_offline {
334        let should_notify = last_all_offline
335            .map(|t| t.elapsed() >= ALL_OFFLINE_NOTIFY_COOLDOWN)
336            .unwrap_or(true);
337        if should_notify {
338            println!("  {}  all accounts are offline", red("✗"));
339            crate::notify::notify(
340                "shunt: All Accounts Offline",
341                "All accounts are offline or on cooldown.",
342                "Basso",
343            );
344            *last_all_offline = Some(Instant::now());
345        }
346    }
347    if *was_all_offline && !all_unavailable {
348        println!("  {}  accounts back online", green("✓"));
349    }
350    *was_all_offline = all_unavailable;
351}
352
353// ---------------------------------------------------------------------------
354// Display helpers
355// ---------------------------------------------------------------------------
356
357fn print_initial_state(accounts: &[AccountStatus], now_ms: u64) {
358    println!("  {}  {} account(s)", green("✓"), accounts.len());
359    for acc in accounts {
360        let (sym, label) = if acc.auth_failed || acc.disabled {
361            (red("✗"), red(&acc.name))
362        } else if acc.cooldown_until_ms > now_ms {
363            let rem = fmt_duration_ms(acc.cooldown_until_ms - now_ms);
364            (yellow("⏸"), yellow(&format!("{}  cooling {}", acc.name, rem)))
365        } else {
366            (green("✓"), green(&acc.name))
367        };
368        println!("    {}  {}", sym, label);
369    }
370    println!();
371}
372
373// ---------------------------------------------------------------------------
374// HTTP helpers
375// ---------------------------------------------------------------------------
376
377async fn fetch_local_status(
378    client: &reqwest::Client,
379    local_url: &str,
380) -> Result<Vec<AccountStatus>> {
381    let url = format!("{}/status", local_url.trim_end_matches('/'));
382    let resp = client.get(&url).send().await?;
383    let body: serde_json::Value = resp.json().await?;
384    let accounts = serde_json::from_value(body["accounts"].clone())
385        .context("failed to parse accounts from /status")?;
386    Ok(accounts)
387}
388
389// ---------------------------------------------------------------------------
390// Time
391// ---------------------------------------------------------------------------
392
393fn now_ms() -> u64 {
394    std::time::SystemTime::now()
395        .duration_since(std::time::UNIX_EPOCH)
396        .unwrap_or_default()
397        .as_millis() as u64
398}