weirdnet_push/server/
apns.rs1use crate::error::{Error, Result};
2use crate::wake::Payload96;
3use serde::Deserialize;
4use std::path::PathBuf;
5use std::sync::Mutex;
6use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
7
8#[derive(Debug, Clone, Deserialize)]
10#[serde(deny_unknown_fields)]
11pub struct ApnsConfig {
12 pub key: PathBuf,
14 pub key_id: String,
16 pub team_id: String,
18 pub topics: Vec<String>,
20 #[serde(default)]
22 pub endpoint: Option<String>,
23 #[serde(default)]
25 pub sandbox_endpoint: Option<String>,
26}
27
28pub struct Apns {
30 config: ApnsConfig,
31 key: jsonwebtoken::EncodingKey,
32 http: reqwest::Client,
33 jwt: Mutex<Option<(String, Instant)>>,
34}
35
36impl std::fmt::Debug for Apns {
37 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38 f.debug_struct("Apns").field("key_id", &self.config.key_id).field("topics", &self.config.topics).finish()
39 }
40}
41
42#[derive(serde::Serialize)]
43struct Claims<'a> {
44 iss: &'a str,
45 iat: u64,
46}
47
48pub const PLACEHOLDER_TITLE: &str = "Weirdnet";
51pub const PLACEHOLDER_BODY: &str = "New activity";
53
54impl Apns {
55 pub fn new(config: &ApnsConfig) -> Result<Self> {
57 let pem = std::fs::read(&config.key)?;
58 let key = jsonwebtoken::EncodingKey::from_ec_pem(&pem).map_err(|e| Error::Invalid(format!("APNs key: {e}")))?;
59 let plain = |e: &Option<String>| e.as_deref().is_some_and(|u| u.starts_with("http://"));
60 let mut b = reqwest::Client::builder().timeout(Duration::from_secs(20)).pool_idle_timeout(Duration::from_secs(3000));
61 if plain(&config.endpoint) || plain(&config.sandbox_endpoint) {
62 b = b.http2_prior_knowledge(); }
64 Ok(Self { config: config.clone(), key, http: b.build()?, jwt: Mutex::new(None) })
65 }
66
67 pub(crate) fn allows_topic(&self, t: &str) -> bool {
68 self.config.topics.iter().any(|x| x == t)
69 }
70
71 fn token(&self) -> Result<String> {
72 let mut g = self.jwt.lock().unwrap();
73 if let Some((t, at)) = &*g
75 && at.elapsed() < Duration::from_secs(40 * 60)
76 {
77 return Ok(t.clone());
78 }
79 let mut h = jsonwebtoken::Header::new(jsonwebtoken::Algorithm::ES256);
80 h.kid = Some(self.config.key_id.clone());
81 let iat = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
82 let t = jsonwebtoken::encode(&h, &Claims { iss: &self.config.team_id, iat }, &self.key)
83 .map_err(|e| Error::Delivery(format!("APNs token: {e}")))?;
84 *g = Some((t.clone(), Instant::now()));
85 Ok(t)
86 }
87
88 pub(crate) async fn send(&self, device: &str, topic: &str, sandbox: bool, p: &Payload96) -> Result<()> {
89 let base = if sandbox {
90 self.config.sandbox_endpoint.as_deref().unwrap_or("https://api.sandbox.push.apple.com")
91 } else {
92 self.config.endpoint.as_deref().unwrap_or("https://api.push.apple.com")
93 };
94 let exp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() + 3600;
95 let body = serde_json::json!({
96 "aps": { "alert": { "title": PLACEHOLDER_TITLE, "body": PLACEHOLDER_BODY }, "mutable-content": 1 },
97 "wn": p.to_b64(),
98 });
99 let r = self
100 .http
101 .post(format!("{base}/3/device/{device}"))
102 .bearer_auth(self.token()?)
103 .header("apns-topic", topic)
104 .header("apns-push-type", "alert")
105 .header("apns-priority", "10")
106 .header("apns-expiration", exp.to_string())
107 .json(&body)
108 .send()
109 .await
110 .map_err(|e| Error::Delivery(format!("APNs: {e}")))?;
111 let status = r.status().as_u16();
112 if status == 200 {
113 return Ok(());
114 }
115 #[derive(Deserialize)]
116 struct Reason {
117 reason: String,
118 }
119 let reason = r.json::<Reason>().await.map(|r| r.reason).unwrap_or_default();
120 match (status, reason.as_str()) {
121 (410, _) | (400, "BadDeviceToken") | (400, "DeviceTokenNotForTopic") => Err(Error::Gone),
122 _ => Err(Error::Delivery(format!("APNs {status} {reason}"))),
123 }
124 }
125}