#[cfg(any(target_os = "android", target_os = "ios", test))]
use serde::Deserialize;
use serde::Serialize;
#[cfg(target_os = "android")]
#[manganis::ffi("src/android/push_notifications")]
unsafe extern "Kotlin" {
pub type PushNotificationsPlugin;
}
#[cfg(target_os = "android")]
const PUSH_NOTIFICATIONS_CLASS: &str =
"dev.dioxus.g3_native_plugins.push_notifications.PushNotificationsPlugin";
#[cfg(target_os = "android")]
type PushNotificationsHandle = crate::android_bridge::AndroidPlugin;
#[cfg(target_os = "ios")]
type PushNotificationsHandle = PushNotificationsPlugin;
#[cfg(target_os = "ios")]
#[manganis::ffi("src/ios")]
unsafe extern "Swift" {
pub type PushNotificationsPlugin;
pub fn prepareFromRust(this: &PushNotificationsPlugin);
pub fn registerFromRust(this: &PushNotificationsPlugin, configJson: String) -> Option<String>;
pub fn unregisterFromRust(this: &PushNotificationsPlugin) -> Option<String>;
pub fn tokenFromRust(this: &PushNotificationsPlugin) -> Option<String>;
pub fn takeEventFromRust(this: &PushNotificationsPlugin) -> Option<String>;
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FirebaseOptions {
pub application_id: String,
pub api_key: String,
pub project_id: String,
pub sender_id: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum PushService {
Apns,
Fcm,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, serde::Deserialize)]
pub struct PushToken {
pub service: PushService,
pub token: String,
}
#[derive(Debug, Clone, PartialEq)]
pub enum PushEvent {
Token(PushToken),
RegistrationFailed(String),
Message {
data: serde_json::Map<String, serde_json::Value>,
title: Option<String>,
body: Option<String>,
},
Opened {
action_id: String,
data: serde_json::Map<String, serde_json::Value>,
},
}
#[cfg(any(target_os = "android", target_os = "ios", test))]
#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
enum WireEvent {
Token {
token: String,
},
RegistrationFailed {
error: String,
},
Message {
#[serde(default)]
data: serde_json::Map<String, serde_json::Value>,
#[serde(default)]
title: Option<String>,
#[serde(default)]
body: Option<String>,
},
#[serde(rename_all = "camelCase")]
Opened {
#[serde(default = "tap")]
action_id: String,
#[serde(default)]
data: serde_json::Map<String, serde_json::Value>,
},
}
#[cfg(any(target_os = "android", target_os = "ios", test))]
fn tap() -> String {
crate::notifications::TAP_ACTION.to_string()
}
#[cfg(any(target_os = "android", target_os = "ios", test))]
impl WireEvent {
fn into_event(self, service: PushService) -> PushEvent {
match self {
WireEvent::Token { token } => PushEvent::Token(PushToken { service, token }),
WireEvent::RegistrationFailed { error } => PushEvent::RegistrationFailed(error),
WireEvent::Message { data, title, body } => PushEvent::Message { data, title, body },
WireEvent::Opened { action_id, data } => PushEvent::Opened { action_id, data },
}
}
}
#[cfg(any(target_os = "android", target_os = "ios"))]
pub struct PushNotifications {
plugin: Option<PushNotificationsHandle>,
}
#[cfg(any(target_arch = "wasm32", target_os = "macos"))]
pub struct PushNotifications;
#[cfg(target_os = "android")]
const SERVICE: PushService = PushService::Fcm;
#[cfg(target_os = "ios")]
const SERVICE: PushService = PushService::Apns;
#[cfg(any(target_os = "android", target_os = "ios"))]
fn check(reported: Option<String>) -> Result<(), String> {
let Some(raw) = reported else {
return Ok(());
};
match serde_json::from_str::<serde_json::Value>(&raw) {
Ok(value) => match value.get("error").and_then(|error| error.as_str()) {
Some(error) => Err(error.to_string()),
None => Ok(()),
},
Err(_) => Ok(()),
}
}
#[cfg(any(target_os = "android", target_os = "ios"))]
impl PushNotifications {
pub fn new() -> Self {
Self { plugin: None }
}
fn get_plugin(&mut self) -> Result<&PushNotificationsHandle, String> {
if self.plugin.is_none() {
#[cfg(target_os = "android")]
let created = PushNotificationsHandle::new(PUSH_NOTIFICATIONS_CLASS)?;
#[cfg(target_os = "ios")]
let created = PushNotificationsPlugin::new()
.map_err(|error| format!("Failed to create PushNotificationsPlugin: {error:?}"))?;
self.plugin = Some(created);
}
Ok(self.plugin.as_ref().unwrap())
}
pub fn prepare(&mut self) -> Result<(), String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
plugin.call_unit("prepareFromRust")?;
#[cfg(target_os = "ios")]
prepareFromRust(plugin)?;
Ok(())
}
pub fn register(&mut self, firebase: Option<&FirebaseOptions>) -> Result<(), String> {
let config = serde_json::json!({ "firebase": firebase }).to_string();
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
return check(plugin.call_string_str("registerFromRust", &config)?);
#[cfg(target_os = "ios")]
return check(registerFromRust(plugin, config)?);
}
pub fn unregister(&mut self) -> Result<(), String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
return check(plugin.call_string("unregisterFromRust")?);
#[cfg(target_os = "ios")]
return check(unregisterFromRust(plugin)?);
}
pub fn token(&mut self) -> Result<Option<PushToken>, String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
let token = plugin.call_string("tokenFromRust")?;
#[cfg(target_os = "ios")]
let token = tokenFromRust(plugin)?;
Ok(token.map(|token| PushToken {
service: SERVICE,
token,
}))
}
pub fn take_event(&mut self) -> Result<Option<PushEvent>, String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
let reported = plugin.call_string("takeEventFromRust")?;
#[cfg(target_os = "ios")]
let reported = takeEventFromRust(plugin)?;
let Some(raw) = reported else {
return Ok(None);
};
let wire: WireEvent = serde_json::from_str(&raw)
.map_err(|error| format!("Failed to read a push event: {error}"))?;
Ok(Some(wire.into_event(SERVICE)))
}
}
#[cfg(any(target_arch = "wasm32", target_os = "macos"))]
impl PushNotifications {
pub fn new() -> Self {
Self
}
pub fn prepare(&mut self) -> Result<(), String> {
Ok(())
}
pub fn register(&mut self, _firebase: Option<&FirebaseOptions>) -> Result<(), String> {
Ok(())
}
pub fn unregister(&mut self) -> Result<(), String> {
Ok(())
}
pub fn token(&mut self) -> Result<Option<PushToken>, String> {
Ok(None)
}
pub fn take_event(&mut self) -> Result<Option<PushEvent>, String> {
Ok(None)
}
}
#[cfg(any(
target_arch = "wasm32",
target_os = "android",
target_os = "ios",
target_os = "macos"
))]
impl Default for PushNotifications {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn event(json: &str, service: PushService) -> PushEvent {
serde_json::from_str::<WireEvent>(json)
.expect("wire event should parse")
.into_event(service)
}
#[test]
fn events_from_either_platform_parse_into_the_public_shape() {
assert_eq!(
event(r#"{"type":"token","token":"abc"}"#, PushService::Fcm),
PushEvent::Token(PushToken {
service: PushService::Fcm,
token: "abc".to_string(),
})
);
let PushEvent::Message { data, title, .. } = event(
r#"{"type":"message","messageId":"1","title":"Hi","body":null,"data":{"game":"7"}}"#,
PushService::Fcm,
) else {
panic!("a message");
};
assert_eq!(title.as_deref(), Some("Hi"));
assert_eq!(data["game"], "7");
assert_eq!(
event(r#"{"type":"opened","data":{}}"#, PushService::Apns),
PushEvent::Opened {
action_id: "tap".to_string(),
data: serde_json::Map::new(),
}
);
assert_eq!(
event(
r#"{"type":"registrationFailed","error":"no entitlement"}"#,
PushService::Apns
),
PushEvent::RegistrationFailed("no entitlement".to_string())
);
}
#[test]
fn firebase_options_reach_kotlin_under_the_names_it_reads() {
let options = FirebaseOptions {
application_id: "1:2:android:3".to_string(),
api_key: "key".to_string(),
project_id: "project".to_string(),
sender_id: "2".to_string(),
};
let config = serde_json::json!({ "firebase": options });
for key in ["applicationId", "apiKey", "projectId", "senderId"] {
assert!(config["firebase"].get(key).is_some(), "{key}");
}
}
}