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    available: bool,
57    auth_failed: bool,
58    /// true if `cooldown_until_ms > now_ms` at snapshot time
59    cooling: bool,
60    disabled: bool,
61}
62
63impl Snap {
64    fn from_status(acc: &AccountStatus, now_ms: u64) -> Self {
65        Self {
66            available: acc.available,
67            auth_failed: acc.auth_failed,
68            cooling: acc.cooldown_until_ms > now_ms,
69            disabled: acc.disabled,
70        }
71    }
72}
73
74// ---------------------------------------------------------------------------
75// Thresholds
76// ---------------------------------------------------------------------------
77
78const POLL_INTERVAL: Duration = Duration::from_secs(10);
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    loop {
119        match fetch_local_status(&client, &local_url).await {
120            Ok(accounts) => {
121                let snapshot = RemoteSnapshot { accounts, ts_ms: now_ms() };
122                let data = serde_json::to_vec(&snapshot)?;
123                let payload = crate::sync::encrypt_bytes(&data, &code)?;
124
125                let push_url = format!("{relay_url}/watch/{code}");
126                match client
127                    .put(&push_url)
128                    .json(&serde_json::json!({ "payload": payload }))
129                    .send()
130                    .await
131                {
132                    Ok(r) if r.status().is_success() => {}
133                    Ok(r) => {
134                        let status = r.status();
135                        eprintln!("  {}  relay push failed: {status}", red("✗"));
136                    }
137                    Err(e) => eprintln!("  {}  relay unreachable: {e}", red("✗")),
138                }
139            }
140            Err(e) => eprintln!("  {}  local shunt unreachable: {e}", red("✗")),
141        }
142
143        tokio::time::sleep(POLL_INTERVAL).await;
144    }
145}
146
147// ---------------------------------------------------------------------------
148// Client mode
149// ---------------------------------------------------------------------------
150
151async fn run_client(code: String, relay_url: String) -> Result<()> {
152    crate::sync::validate_remote_code(&code)
153        .context("invalid remote code")?;
154
155    let client = reqwest::Client::builder()
156        .timeout(Duration::from_secs(10))
157        .pool_max_idle_per_host(0)
158        .build()?;
159
160    println!();
161    println!("  {}  {}  {}", bold("◆"), bold("shunt"), dim("remote  client"));
162    println!("  {}  {}", dim("·"), cyan(&relay_url));
163    println!("  {}  connecting…", dim("·"));
164    println!();
165
166    let mut prev: HashMap<String, Snap> = HashMap::new();
167    let mut first_poll = true;
168    let mut was_session_missing = false;
169
170    // Throttle state
171    let mut notified_cooldown: HashMap<String, u64> = HashMap::new();
172    let mut notified_auth_failed: HashSet<String> = HashSet::new();
173    let mut last_all_offline: Option<Instant> = None;
174    let mut was_all_offline = false;
175
176    loop {
177        let poll_url = format!("{relay_url}/watch/{code}");
178        match client.get(&poll_url).send().await {
179            Ok(resp) if resp.status() == reqwest::StatusCode::NOT_FOUND => {
180                if !was_session_missing {
181                    println!("  {}  session not found — waiting for host…", yellow("⏸"));
182                    was_session_missing = true;
183                }
184            }
185            Ok(resp) if resp.status().is_success() => {
186                if was_session_missing {
187                    println!("  {}  host connected", green("✓"));
188                    was_session_missing = false;
189                }
190
191                let body: serde_json::Value = match resp.json().await {
192                    Ok(v) => v,
193                    Err(e) => { eprintln!("  {}  bad relay response: {e}", red("✗")); continue; }
194                };
195
196                let payload = match body["payload"].as_str() {
197                    Some(p) => p.to_owned(),
198                    None => { eprintln!("  {}  relay response missing payload", red("✗")); continue; }
199                };
200
201                let data = match crate::sync::decrypt_bytes(&payload, &code) {
202                    Ok(d) => d,
203                    Err(e) => { eprintln!("  {}  decryption failed: {e}", red("✗")); continue; }
204                };
205
206                let snapshot: RemoteSnapshot = match serde_json::from_slice(&data) {
207                    Ok(s) => s,
208                    Err(e) => { eprintln!("  {}  snapshot parse error: {e}", red("✗")); continue; }
209                };
210
211                let now = now_ms();
212
213                if first_poll {
214                    print_initial_state(&snapshot.accounts, now);
215                    for acc in &snapshot.accounts {
216                        prev.insert(acc.name.clone(), Snap::from_status(acc, now));
217                    }
218                    first_poll = false;
219                } else {
220                    diff_and_notify(
221                        &snapshot.accounts,
222                        &prev,
223                        now,
224                        &mut notified_cooldown,
225                        &mut notified_auth_failed,
226                        &mut last_all_offline,
227                        &mut was_all_offline,
228                    );
229                    prev.clear();
230                    for acc in &snapshot.accounts {
231                        prev.insert(acc.name.clone(), Snap::from_status(acc, now));
232                    }
233                }
234            }
235            Ok(resp) => {
236                eprintln!("  {}  relay error: {}", red("✗"), resp.status());
237            }
238            Err(e) => {
239                eprintln!("  {}  cannot reach relay: {e}", red("✗"));
240            }
241        }
242
243        tokio::time::sleep(POLL_INTERVAL).await;
244    }
245}
246
247// ---------------------------------------------------------------------------
248// State diffing + notification dispatch
249// ---------------------------------------------------------------------------
250
251fn diff_and_notify(
252    accounts: &[AccountStatus],
253    prev: &HashMap<String, Snap>,
254    now_ms: u64,
255    notified_cooldown: &mut HashMap<String, u64>,
256    notified_auth_failed: &mut HashSet<String>,
257    last_all_offline: &mut Option<Instant>,
258    was_all_offline: &mut bool,
259) {
260    let all_unavailable = accounts.iter().all(|a| !a.available);
261
262    for acc in accounts {
263        let Some(p) = prev.get(&acc.name) else { continue };
264
265        // ── Reauth required (newly auth_failed) ─────────────────────────────
266        if acc.auth_failed && !p.auth_failed && !notified_auth_failed.contains(&acc.name) {
267            let msg = format!(
268                "Account '{}' needs re-authorization. Run `shunt add-account`.",
269                acc.name
270            );
271            println!("  {}  [{}]  reauth required", red("✗"), yellow(&acc.name));
272            crate::notify::notify("shunt: Reauth Required", &msg, "Basso");
273            notified_auth_failed.insert(acc.name.clone());
274        }
275        if !acc.auth_failed {
276            notified_auth_failed.remove(&acc.name);
277        }
278
279        // ── Entered cooldown (newly, long enough to matter) ──────────────────
280        let curr_cooling = acc.cooldown_until_ms > now_ms;
281        if curr_cooling && !p.cooling {
282            let remaining_ms = acc.cooldown_until_ms - now_ms;
283            let last_cdl = notified_cooldown.get(&acc.name).copied().unwrap_or(0);
284            if remaining_ms >= LONG_COOLDOWN_MS && acc.cooldown_until_ms != last_cdl {
285                let mins = remaining_ms / 60_000;
286                let msg = format!("Account '{}' hit quota limit — cooling {}m.", acc.name, mins);
287                println!(
288                    "  {}  [{}]  rate limited — cooling {}",
289                    yellow("⏸"), yellow(&acc.name), yellow(&fmt_duration_ms(remaining_ms)),
290                );
291                crate::notify::notify("shunt: Rate Limited", &msg, "Ping");
292                notified_cooldown.insert(acc.name.clone(), acc.cooldown_until_ms);
293            }
294        }
295
296        // ── Resumed from cooldown ────────────────────────────────────────────
297        if p.cooling && acc.available && !acc.auth_failed {
298            println!("  {}  [{}]  back online", green("✓"), green(&acc.name));
299            crate::notify::notify(
300                "shunt: Account Resumed",
301                &format!("Account '{}' is back online.", acc.name),
302                "Glass",
303            );
304            notified_cooldown.remove(&acc.name);
305        }
306
307        // ── Recovered from auth_failed / disabled ────────────────────────────
308        if (p.auth_failed || p.disabled) && acc.available {
309            println!("  {}  [{}]  recovered", green("✓"), green(&acc.name));
310            crate::notify::notify(
311                "shunt: Account Recovered",
312                &format!("Account '{}' is back online.", acc.name),
313                "Glass",
314            );
315        }
316    }
317
318    // ── All accounts offline ─────────────────────────────────────────────────
319    if all_unavailable && !*was_all_offline {
320        let should_notify = last_all_offline
321            .map(|t| t.elapsed() >= ALL_OFFLINE_NOTIFY_COOLDOWN)
322            .unwrap_or(true);
323        if should_notify {
324            println!("  {}  all accounts are offline", red("✗"));
325            crate::notify::notify(
326                "shunt: All Accounts Offline",
327                "All accounts are offline or on cooldown.",
328                "Basso",
329            );
330            *last_all_offline = Some(Instant::now());
331        }
332    }
333    if *was_all_offline && !all_unavailable {
334        println!("  {}  accounts back online", green("✓"));
335    }
336    *was_all_offline = all_unavailable;
337}
338
339// ---------------------------------------------------------------------------
340// Display helpers
341// ---------------------------------------------------------------------------
342
343fn print_initial_state(accounts: &[AccountStatus], now_ms: u64) {
344    println!("  {}  {} account(s)", green("✓"), accounts.len());
345    for acc in accounts {
346        let (sym, label) = if acc.auth_failed || acc.disabled {
347            (red("✗"), red(&acc.name))
348        } else if acc.cooldown_until_ms > now_ms {
349            let rem = fmt_duration_ms(acc.cooldown_until_ms - now_ms);
350            (yellow("⏸"), yellow(&format!("{}  cooling {}", acc.name, rem)))
351        } else {
352            (green("✓"), green(&acc.name))
353        };
354        println!("    {}  {}", sym, label);
355    }
356    println!();
357}
358
359// ---------------------------------------------------------------------------
360// HTTP helpers
361// ---------------------------------------------------------------------------
362
363async fn fetch_local_status(
364    client: &reqwest::Client,
365    local_url: &str,
366) -> Result<Vec<AccountStatus>> {
367    let url = format!("{}/status", local_url.trim_end_matches('/'));
368    let resp = client.get(&url).send().await?;
369    let body: serde_json::Value = resp.json().await?;
370    let accounts = serde_json::from_value(body["accounts"].clone())
371        .context("failed to parse accounts from /status")?;
372    Ok(accounts)
373}
374
375// ---------------------------------------------------------------------------
376// Time
377// ---------------------------------------------------------------------------
378
379fn now_ms() -> u64 {
380    std::time::SystemTime::now()
381        .duration_since(std::time::UNIX_EPOCH)
382        .unwrap_or_default()
383        .as_millis() as u64
384}