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