fcm_service/
lib.rs

1use gcp_auth::CustomServiceAccount;
2use gcp_auth::TokenProvider;
3use reqwest::Client;
4use serde::{Deserialize, Serialize};
5use serde_json::json;
6use serde_json::Value;
7use std::error::Error;
8use std::fs;
9use std::io;
10use std::path::PathBuf;
11mod domain;
12pub use domain::AndroidConfig;
13pub use domain::ApnsConfig;
14pub use domain::FcmMessage;
15pub use domain::FcmNotification;
16pub use domain::FcmOptions;
17pub use domain::Target;
18pub use domain::WebpushConfig;
19
20/// Wrapper struct for FCM payload, required by the FCM v1 API.
21#[derive(Serialize, Deserialize)]
22pub struct FcmPayload {
23    pub message: FcmMessage,
24}
25
26pub struct FcmService {
27    pub credential_file: String,
28}
29
30impl FcmService {
31    pub fn new(credential_file: impl Into<String>) -> Self {
32        Self {
33            credential_file: credential_file.into(),
34        }
35    }
36}
37
38/// Service for sending Firebase Cloud Messaging (FCM) notifications using the v1 API.
39///
40/// This service uses a Google Cloud service account credential file to authenticate
41/// and send notifications to FCM.
42///
43/// # Examples
44/// ```rust,no_run
45/// use fcm_service::{FcmService, FcmMessage, FcmNotification, Target};
46///
47/// #[tokio::main]
48/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
49///     let service = FcmService::new("path/to/service-account.json");
50///
51///     let mut message = FcmMessage::new();
52///     let mut notification = FcmNotification::new();
53///     notification.set_title("Hello".to_string());
54///     notification.set_body("World".to_string());
55///     notification.set_image(None);
56///     message.set_notification(Some(notification));
57///     message.set_target(Target::Token("device-token".to_string()));
58///
59///     service.send_notification(message).await?;
60///     Ok(())
61/// }
62/// ```
63impl FcmService {
64    /// Extracts the project ID from the service account credential file.
65    fn get_project_id(&self) -> Result<String, Box<dyn Error>> {
66        let content = fs::read_to_string(&self.credential_file)?;
67        let json: Value = serde_json::from_str(&content)?;
68
69        json.get("project_id")
70            .and_then(|v| v.as_str())
71            .map(|s| s.to_string())
72            .ok_or_else(|| {
73                io::Error::new(io::ErrorKind::InvalidData, "project_id not found").into()
74            })
75    }
76    /// Sends an FCM notification asynchronously.
77    ///
78    /// # Errors
79    /// Returns an error if:
80    /// - The credential file cannot be read or parsed
81    /// - Authentication with GCP fails
82    /// - The HTTP request to FCM fails
83    /// - The FCM API returns an unsuccessful status
84    pub async fn send_notification(&self, message: FcmMessage) -> Result<(), Box<dyn Error>> {
85        let project_id = self.get_project_id()?;
86        let client = Client::new();
87        let credentials_path = PathBuf::from(&self.credential_file);
88        // let service_account = CustomServiceAccount::from_file(credentials_path)?;
89        let service_account = CustomServiceAccount::from_file(credentials_path)?;
90        let scopes = &["https://www.googleapis.com/auth/firebase.messaging"];
91        let token = service_account.token(scopes).await?;
92        let url = format!(
93            "https://fcm.googleapis.com/v1/projects/{}/messages:send",
94            project_id
95        );
96
97        let payload = FcmPayload { message };
98
99        let response = client
100            .post(&url)
101            .bearer_auth(token.as_str())
102            .json(&payload)
103            .send()
104            .await?;
105
106        if response.status().is_success() {
107            let response_text = response.text().await?;
108
109            Ok(())
110        } else {
111            let error_text = response.text().await?;
112            Err(format!("Failed to send notification: {:#?}", error_text).into())
113        }
114    }
115}
116#[cfg(test)]
117mod tests {
118    use super::*;
119    use std::fs::File;
120    use std::io::Write;
121    use tempfile;
122
123    fn setup_dummy_credentials(temp_dir: &tempfile::TempDir) -> String {
124        let credential_path = temp_dir.path().join("service-account.json");
125        let mut file = File::create(&credential_path).unwrap();
126        writeln!(
127            file,
128            r#"{{"project_id": "test-project", "client_email": "test@example.com"}}"#
129        )
130        .unwrap();
131        credential_path.to_str().unwrap().to_string()
132    }
133
134    #[test]
135    fn test_new_service() {
136        let service = FcmService::new("dummy.json");
137        assert_eq!(service.credential_file, "dummy.json");
138    }
139
140    #[test]
141    fn test_get_project_id_success() {
142        let temp_dir = tempfile::tempdir().unwrap();
143        let credential_file = setup_dummy_credentials(&temp_dir);
144        let service = FcmService::new(credential_file);
145        let project_id = service.get_project_id().unwrap();
146        assert_eq!(project_id, "test-project");
147    }
148
149    #[test]
150    fn test_get_project_id_missing_file() {
151        let service = FcmService::new("nonexistent.json");
152        let result = service.get_project_id();
153        assert!(result.is_err());
154        assert!(matches!(
155            result.unwrap_err().downcast_ref::<io::Error>(),
156            Some(err) if err.kind() == io::ErrorKind::NotFound
157        ));
158    }
159
160    #[test]
161    fn test_get_project_id_invalid_json() {
162        let temp_dir = tempfile::tempdir().unwrap();
163        let credential_path = temp_dir.path().join("service-account.json");
164        let mut file = File::create(&credential_path).unwrap();
165        writeln!(file, "invalid json").unwrap();
166        let service = FcmService::new(credential_path.to_str().unwrap());
167        let result = service.get_project_id();
168        assert!(result.is_err());
169    }
170}