Skip to main content

weirdnet_push/
client.rs

1//! A client for the push service: devices register, rotate and revoke handles; senders
2//! (relays and peers) wake devices; relays follow announcements.
3
4use crate::api::{Announcement, Control, ErrorBody, Register, Registered, Transport, WakeRequest};
5use crate::error::{Error, Result};
6use crate::handle::{ControlSecret, WakeCard, WakeHandle};
7use crate::wake::{Payload96, Reason};
8
9/// A push service client.
10#[derive(Debug, Clone)]
11pub struct PushClient {
12    base: String,
13    http: reqwest::Client,
14}
15
16async fn check(r: reqwest::Response) -> Result<reqwest::Response> {
17    let s = r.status();
18    if s.is_success() {
19        return Ok(r);
20    }
21    if s.as_u16() == 410 {
22        return Err(Error::Gone);
23    }
24    if s.as_u16() == 401 || s.as_u16() == 403 {
25        return Err(Error::Unauthorized);
26    }
27    let message = r.json::<ErrorBody>().await.map(|b| b.error).unwrap_or_default();
28    Err(Error::Server { status: s.as_u16(), message })
29}
30
31impl PushClient {
32    /// A client for the service at `base` (such as `https://push.weirdbrains.com`).
33    pub fn new(base: impl Into<String>) -> Self {
34        Self::with_client(base, reqwest::Client::builder().timeout(std::time::Duration::from_secs(20)).build().expect("HTTP client"))
35    }
36
37    /// With your own HTTP client.
38    pub fn with_client(base: impl Into<String>, http: reqwest::Client) -> Self {
39        Self { base: base.into().trim_end_matches('/').to_string(), http }
40    }
41
42    /// The service base URL.
43    pub fn base(&self) -> &str {
44        &self.base
45    }
46
47    fn url(&self, p: &str) -> String {
48        format!("{}{p}", self.base)
49    }
50
51    /// Registers a device and gets a new handle.
52    pub async fn register(&self, transport: Transport) -> Result<Registered> {
53        Ok(check(self.http.post(self.url("/v1/register")).json(&Register { transport }).send().await?).await?.json().await?)
54    }
55
56    /// Replaces a handle with a new one (and optionally a new transport); the old one stops
57    /// working at once. Tell the home relay and trusted peers the new handle.
58    pub async fn rotate(&self, handle: &WakeHandle, control: &ControlSecret, transport: Option<Transport>) -> Result<Registered> {
59        let body = Control { handle: handle.clone(), control: control.clone(), transport };
60        Ok(check(self.http.post(self.url("/v1/rotate")).json(&body).send().await?).await?.json().await?)
61    }
62
63    /// Revokes a handle and forgets the device token (the per-device off switch).
64    pub async fn unregister(&self, handle: &WakeHandle, control: &ControlSecret) -> Result<()> {
65        let body = Control { handle: handle.clone(), control: control.clone(), transport: None };
66        check(self.http.post(self.url("/v1/unregister")).json(&body).send().await?).await?;
67        Ok(())
68    }
69
70    /// Sends a sealed payload. [`Error::Gone`] means the handle was revoked: forget it.
71    pub async fn wake(&self, handle: &WakeHandle, payload: Payload96) -> Result<()> {
72        check(self.http.post(self.url("/v1/wake")).json(&WakeRequest { handle: handle.clone(), payload }).send().await?).await?;
73        Ok(())
74    }
75
76    /// Seals and sends a wake for a card.
77    pub async fn wake_card(&self, card: &WakeCard, reason: Reason) -> Result<()> {
78        self.wake(&card.handle, card.seal(reason)?).await
79    }
80
81    /// Follows wake announcements (relays). Calls `f` for each until the stream ends or `f`
82    /// returns false.
83    pub async fn announcements(&self, relay_token: &str, mut f: impl FnMut(Announcement) -> bool) -> Result<()> {
84        let mut r = check(
85            self.http
86                .get(self.url("/v1/relay/announcements"))
87                .bearer_auth(relay_token)
88                .timeout(std::time::Duration::from_secs(365 * 86400))
89                .send()
90                .await?,
91        )
92        .await?;
93        let mut buf = Vec::new();
94        while let Some(chunk) = r.chunk().await? {
95            buf.extend_from_slice(&chunk);
96            while let Some(i) = buf.iter().position(|&b| b == b'\n') {
97                let line: Vec<u8> = buf.drain(..=i).collect();
98                let line = &line[..line.len() - 1];
99                if line.is_empty() {
100                    continue; // keepalive
101                }
102                if let Ok(a) = serde_json::from_slice::<Announcement>(line)
103                    && !f(a)
104                {
105                    return Ok(());
106                }
107            }
108            if buf.len() > 64 << 10 {
109                return Err(Error::Invalid("announcement line too long".into()));
110            }
111        }
112        Ok(())
113    }
114}