1use 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#[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 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 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 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 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 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 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 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 pub async fn wake_card(&self, card: &WakeCard, reason: Reason) -> Result<()> {
78 self.wake(&card.handle, card.seal(reason)?).await
79 }
80
81 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; }
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}