Skip to main content

weirdnet_push/server/
fcm.rs

1use crate::error::{Error, Result};
2use crate::wake::Payload96;
3use serde::Deserialize;
4use std::path::PathBuf;
5use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
6
7/// FCM HTTP v1 with a service account.
8#[derive(Debug, Clone, Deserialize)]
9#[serde(deny_unknown_fields)]
10pub struct FcmConfig {
11    /// The service account JSON key file.
12    pub service_account: PathBuf,
13    /// Override the FCM endpoint (tests).
14    #[serde(default)]
15    pub endpoint: Option<String>,
16}
17
18#[derive(Deserialize)]
19struct ServiceAccount {
20    project_id: String,
21    client_email: String,
22    private_key: String,
23    token_uri: String,
24}
25
26/// An FCM sender.
27pub struct Fcm {
28    sa: ServiceAccount,
29    key: jsonwebtoken::EncodingKey,
30    endpoint: String,
31    http: reqwest::Client,
32    access: tokio::sync::Mutex<Option<(String, Instant)>>,
33}
34
35impl std::fmt::Debug for Fcm {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        f.debug_struct("Fcm").field("project", &self.sa.project_id).finish()
38    }
39}
40
41#[derive(serde::Serialize)]
42struct Claims<'a> {
43    iss: &'a str,
44    scope: &'a str,
45    aud: &'a str,
46    iat: u64,
47    exp: u64,
48}
49
50const SCOPE: &str = "https://www.googleapis.com/auth/firebase.messaging";
51
52impl Fcm {
53    /// Loads the service account.
54    pub fn new(config: &FcmConfig) -> Result<Self> {
55        let sa: ServiceAccount =
56            serde_json::from_slice(&std::fs::read(&config.service_account)?).map_err(|e| Error::Invalid(format!("FCM service account: {e}")))?;
57        let key = jsonwebtoken::EncodingKey::from_rsa_pem(sa.private_key.as_bytes()).map_err(|e| Error::Invalid(format!("FCM key: {e}")))?;
58        let endpoint = config.endpoint.clone().unwrap_or_else(|| "https://fcm.googleapis.com".into()).trim_end_matches('/').to_string();
59        let http = reqwest::Client::builder().timeout(Duration::from_secs(20)).build()?;
60        Ok(Self { sa, key, endpoint, http, access: tokio::sync::Mutex::new(None) })
61    }
62
63    async fn access_token(&self) -> Result<String> {
64        let mut g = self.access.lock().await;
65        if let Some((t, until)) = &*g
66            && Instant::now() < *until
67        {
68            return Ok(t.clone());
69        }
70        let iat = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
71        let claims = Claims { iss: &self.sa.client_email, scope: SCOPE, aud: &self.sa.token_uri, iat, exp: iat + 3600 };
72        let jwt = jsonwebtoken::encode(&jsonwebtoken::Header::new(jsonwebtoken::Algorithm::RS256), &claims, &self.key)
73            .map_err(|e| Error::Delivery(format!("FCM token: {e}")))?;
74        let body = format!("grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion={jwt}");
75        let r = self
76            .http
77            .post(&self.sa.token_uri)
78            .header("content-type", "application/x-www-form-urlencoded")
79            .body(body)
80            .send()
81            .await
82            .map_err(|e| Error::Delivery(format!("FCM token: {e}")))?;
83        if !r.status().is_success() {
84            return Err(Error::Delivery(format!("FCM token: {}", r.status())));
85        }
86        #[derive(Deserialize)]
87        struct Tok {
88            access_token: String,
89            expires_in: u64,
90        }
91        let t: Tok = r.json().await.map_err(|e| Error::Delivery(format!("FCM token: {e}")))?;
92        let until = Instant::now() + Duration::from_secs(t.expires_in.saturating_sub(120).max(60));
93        *g = Some((t.access_token.clone(), until));
94        Ok(t.access_token)
95    }
96
97    pub(crate) async fn send(&self, device: &str, p: &Payload96) -> Result<()> {
98        let body = serde_json::json!({
99            "message": {
100                "token": device,
101                "data": { "wn": p.to_b64() },
102                "android": { "priority": "HIGH", "ttl": "3600s" },
103            }
104        });
105        let r = self
106            .http
107            .post(format!("{}/v1/projects/{}/messages:send", self.endpoint, self.sa.project_id))
108            .bearer_auth(self.access_token().await?)
109            .json(&body)
110            .send()
111            .await
112            .map_err(|e| Error::Delivery(format!("FCM: {e}")))?;
113        let status = r.status().as_u16();
114        if (200..300).contains(&status) {
115            return Ok(());
116        }
117        if status == 401 {
118            *self.access.lock().await = None;
119        }
120        let text = r.text().await.unwrap_or_default();
121        if status == 404 || text.contains("UNREGISTERED") {
122            return Err(Error::Gone);
123        }
124        Err(Error::Delivery(format!("FCM {status}")))
125    }
126}