#[cfg(any(
target_arch = "wasm32",
target_os = "android",
target_os = "ios",
target_os = "macos"
))]
use crate::permissions::PermissionState;
use serde::{Deserialize, Serialize};
#[cfg(target_os = "android")]
#[manganis::ffi("src/android/notifications")]
unsafe extern "Kotlin" {
pub type NotificationsPlugin;
}
#[cfg(target_os = "android")]
const NOTIFICATIONS_CLASS: &str = "dev.dioxus.g3_native_plugins.notifications.NotificationsPlugin";
#[cfg(target_os = "android")]
type NotificationsHandle = crate::android_bridge::AndroidPlugin;
#[cfg(target_os = "ios")]
type NotificationsHandle = NotificationsPlugin;
#[cfg(target_os = "ios")]
#[manganis::ffi("src/ios")]
unsafe extern "Swift" {
pub type NotificationsPlugin;
pub fn prepareFromRust(this: &NotificationsPlugin);
pub fn checkPermissionsFromRust(this: &NotificationsPlugin) -> Option<String>;
pub fn requestPermissionsFromRust(this: &NotificationsPlugin);
pub fn openSettingsFromRust(this: &NotificationsPlugin);
pub fn showFromRust(this: &NotificationsPlugin, notificationJson: String) -> Option<String>;
pub fn pendingFromRust(this: &NotificationsPlugin) -> Option<String>;
pub fn cancelFromRust(this: &NotificationsPlugin, idsJson: String) -> Option<String>;
pub fn cancelAllFromRust(this: &NotificationsPlugin) -> Option<String>;
pub fn activeFromRust(this: &NotificationsPlugin) -> Option<String>;
pub fn removeActiveFromRust(this: &NotificationsPlugin, idsJson: String) -> Option<String>;
pub fn removeAllActiveFromRust(this: &NotificationsPlugin) -> Option<String>;
pub fn createChannelFromRust(this: &NotificationsPlugin, channelJson: String)
-> Option<String>;
pub fn deleteChannelFromRust(this: &NotificationsPlugin, id: String) -> Option<String>;
pub fn channelsFromRust(this: &NotificationsPlugin) -> Option<String>;
pub fn registerActionTypesFromRust(
this: &NotificationsPlugin,
typesJson: String,
) -> Option<String>;
pub fn takeEventFromRust(this: &NotificationsPlugin) -> Option<String>;
}
pub const TAP_ACTION: &str = "tap";
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Notification {
pub id: i32,
pub title: String,
pub body: Option<String>,
pub channel_id: Option<String>,
pub group: Option<String>,
pub action_type_id: Option<String>,
pub sound: Option<String>,
pub silent: bool,
pub badge: Option<u32>,
pub icon: Option<String>,
pub extra: serde_json::Map<String, serde_json::Value>,
pub schedule: Option<Schedule>,
}
impl Notification {
pub fn new(id: i32, title: impl Into<String>) -> Self {
Self {
id,
title: title.into(),
..Self::default()
}
}
pub fn body(mut self, body: impl Into<String>) -> Self {
self.body = Some(body.into());
self
}
pub fn schedule(mut self, schedule: Schedule) -> Self {
self.schedule = Some(schedule);
self
}
pub fn channel(mut self, channel_id: impl Into<String>) -> Self {
self.channel_id = Some(channel_id.into());
self
}
pub fn action_type(mut self, action_type_id: impl Into<String>) -> Self {
self.action_type_id = Some(action_type_id.into());
self
}
pub fn extra(mut self, key: impl Into<String>, value: impl Into<serde_json::Value>) -> Self {
self.extra.insert(key.into(), value.into());
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum Schedule {
#[serde(rename_all = "camelCase")]
At {
at_ms: i64,
allow_while_idle: bool,
},
#[serde(rename_all = "camelCase")]
Every {
interval: ScheduleInterval,
count: u32,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ScheduleInterval {
Minute,
Hour,
Day,
Week,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PendingNotification {
pub id: i32,
pub title: String,
pub body: Option<String>,
pub schedule: Option<Schedule>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct DeliveredNotification {
pub id: i32,
pub title: String,
pub body: Option<String>,
pub group: Option<String>,
pub action_type_id: Option<String>,
pub extra: serde_json::Map<String, serde_json::Value>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum NotificationEvent {
Received {
notification: DeliveredNotification,
},
#[serde(rename_all = "camelCase")]
Action {
action_id: String,
input: Option<String>,
notification: DeliveredNotification,
},
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Importance {
None,
Min,
Low,
#[default]
Default,
High,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Visibility {
#[default]
Private,
Public,
Secret,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct Channel {
pub id: String,
pub name: String,
pub description: Option<String>,
pub importance: Importance,
pub visibility: Visibility,
pub vibration: bool,
pub sound: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActionType {
pub id: String,
pub actions: Vec<Action>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct Action {
pub id: String,
pub title: String,
pub foreground: bool,
pub destructive: bool,
pub requires_authentication: bool,
pub input: bool,
pub input_placeholder: Option<String>,
pub input_button_title: Option<String>,
}
#[cfg(any(target_os = "android", target_os = "ios"))]
pub struct Notifications {
plugin: Option<NotificationsHandle>,
}
#[cfg(any(target_arch = "wasm32", target_os = "macos"))]
pub struct Notifications;
#[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"))]
fn parse<T: serde::de::DeserializeOwned>(
reported: Option<String>,
what: &str,
) -> Result<T, String> {
let raw = reported.ok_or_else(|| format!("The platform did not report {what}"))?;
let value: serde_json::Value =
serde_json::from_str(&raw).map_err(|error| format!("Failed to read {what}: {error}"))?;
if let Some(error) = value.get("error").and_then(|error| error.as_str()) {
return Err(error.to_string());
}
serde_json::from_value(value).map_err(|error| format!("Failed to read {what}: {error}"))
}
#[cfg(any(target_os = "android", target_os = "ios"))]
fn encode<T: Serialize>(value: &T, what: &str) -> Result<String, String> {
serde_json::to_string(value).map_err(|error| format!("Failed to encode {what}: {error}"))
}
#[cfg(any(target_os = "android", target_os = "ios"))]
impl Notifications {
pub fn new() -> Self {
Self { plugin: None }
}
fn get_plugin(&mut self) -> Result<&NotificationsHandle, String> {
if self.plugin.is_none() {
#[cfg(target_os = "android")]
let created = NotificationsHandle::new(NOTIFICATIONS_CLASS)?;
#[cfg(target_os = "ios")]
let created = NotificationsPlugin::new()
.map_err(|error| format!("Failed to create NotificationsPlugin: {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 check_permissions(&mut self) -> Result<PermissionState, String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
let reported = plugin.call_string("checkPermissionsFromRust")?;
#[cfg(target_os = "ios")]
let reported = checkPermissionsFromRust(plugin)?;
let state = reported.ok_or("Notification permission was not reported")?;
serde_json::from_value(serde_json::Value::String(state))
.map_err(|error| format!("Failed to read notification permission: {error}"))
}
pub fn request_permissions(&mut self) -> Result<(), String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
plugin.call_unit("requestPermissionsFromRust")?;
#[cfg(target_os = "ios")]
requestPermissionsFromRust(plugin)?;
Ok(())
}
pub fn open_settings(&mut self) -> Result<(), String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
plugin.call_unit("openSettingsFromRust")?;
#[cfg(target_os = "ios")]
openSettingsFromRust(plugin)?;
Ok(())
}
pub fn show(&mut self, notification: &Notification) -> Result<(), String> {
if let Some(Schedule::Every { count: 0, .. }) = notification.schedule {
return Err("A repeating schedule needs a count of at least one".to_string());
}
let json = encode(notification, "the notification")?;
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
return check(plugin.call_string_str("showFromRust", &json)?);
#[cfg(target_os = "ios")]
return check(showFromRust(plugin, json)?);
}
pub fn pending(&mut self) -> Result<Vec<PendingNotification>, String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
let reported = plugin.call_string("pendingFromRust")?;
#[cfg(target_os = "ios")]
let reported = pendingFromRust(plugin)?;
parse(reported, "pending notifications")
}
pub fn cancel(&mut self, ids: &[i32]) -> Result<(), String> {
let json = encode(&ids, "notification ids")?;
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
return check(plugin.call_string_str("cancelFromRust", &json)?);
#[cfg(target_os = "ios")]
return check(cancelFromRust(plugin, json)?);
}
pub fn cancel_all(&mut self) -> Result<(), String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
return check(plugin.call_string("cancelAllFromRust")?);
#[cfg(target_os = "ios")]
return check(cancelAllFromRust(plugin)?);
}
pub fn active(&mut self) -> Result<Vec<DeliveredNotification>, String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
let reported = plugin.call_string("activeFromRust")?;
#[cfg(target_os = "ios")]
let reported = activeFromRust(plugin)?;
parse(reported, "active notifications")
}
pub fn remove_active(&mut self, ids: &[i32]) -> Result<(), String> {
let json = encode(&ids, "notification ids")?;
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
return check(plugin.call_string_str("removeActiveFromRust", &json)?);
#[cfg(target_os = "ios")]
return check(removeActiveFromRust(plugin, json)?);
}
pub fn remove_all_active(&mut self) -> Result<(), String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
return check(plugin.call_string("removeAllActiveFromRust")?);
#[cfg(target_os = "ios")]
return check(removeAllActiveFromRust(plugin)?);
}
pub fn create_channel(&mut self, channel: &Channel) -> Result<(), String> {
let json = encode(channel, "the channel")?;
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
return check(plugin.call_string_str("createChannelFromRust", &json)?);
#[cfg(target_os = "ios")]
return check(createChannelFromRust(plugin, json)?);
}
pub fn delete_channel(&mut self, id: &str) -> Result<(), String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
return check(plugin.call_string_str("deleteChannelFromRust", id)?);
#[cfg(target_os = "ios")]
return check(deleteChannelFromRust(plugin, id.to_string())?);
}
pub fn channels(&mut self) -> Result<Vec<Channel>, String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
let reported = plugin.call_string("channelsFromRust")?;
#[cfg(target_os = "ios")]
let reported = channelsFromRust(plugin)?;
parse(reported, "notification channels")
}
pub fn register_action_types(&mut self, types: &[ActionType]) -> Result<(), String> {
let json = encode(&types, "the action types")?;
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
return check(plugin.call_string_str("registerActionTypesFromRust", &json)?);
#[cfg(target_os = "ios")]
return check(registerActionTypesFromRust(plugin, json)?);
}
pub fn take_event(&mut self) -> Result<Option<NotificationEvent>, String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
let reported = plugin.call_string("takeEventFromRust")?;
#[cfg(target_os = "ios")]
let reported = takeEventFromRust(plugin)?;
match reported {
None => Ok(None),
Some(_) => parse(reported, "a notification event").map(Some),
}
}
}
#[cfg(any(target_arch = "wasm32", target_os = "macos"))]
impl Notifications {
pub fn new() -> Self {
Self
}
pub fn prepare(&mut self) -> Result<(), String> {
Ok(())
}
pub fn check_permissions(&mut self) -> Result<PermissionState, String> {
Ok(PermissionState::Prompt)
}
pub fn request_permissions(&mut self) -> Result<(), String> {
Ok(())
}
pub fn open_settings(&mut self) -> Result<(), String> {
Ok(())
}
pub fn show(&mut self, _notification: &Notification) -> Result<(), String> {
Ok(())
}
pub fn pending(&mut self) -> Result<Vec<PendingNotification>, String> {
Ok(Vec::new())
}
pub fn cancel(&mut self, _ids: &[i32]) -> Result<(), String> {
Ok(())
}
pub fn cancel_all(&mut self) -> Result<(), String> {
Ok(())
}
pub fn active(&mut self) -> Result<Vec<DeliveredNotification>, String> {
Ok(Vec::new())
}
pub fn remove_active(&mut self, _ids: &[i32]) -> Result<(), String> {
Ok(())
}
pub fn remove_all_active(&mut self) -> Result<(), String> {
Ok(())
}
pub fn create_channel(&mut self, _channel: &Channel) -> Result<(), String> {
Ok(())
}
pub fn delete_channel(&mut self, _id: &str) -> Result<(), String> {
Ok(())
}
pub fn channels(&mut self) -> Result<Vec<Channel>, String> {
Ok(Vec::new())
}
pub fn register_action_types(&mut self, _types: &[ActionType]) -> Result<(), String> {
Ok(())
}
pub fn take_event(&mut self) -> Result<Option<NotificationEvent>, String> {
Ok(None)
}
}
#[cfg(any(
target_arch = "wasm32",
target_os = "android",
target_os = "ios",
target_os = "macos"
))]
impl Default for Notifications {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn notifications_cross_the_bridge_in_the_shape_both_platforms_read() {
let notification = Notification::new(7, "Tee time")
.body("Hole 1")
.action_type("reply")
.extra("route", "/games/7")
.schedule(Schedule::At {
at_ms: 1_800_000_000_000,
allow_while_idle: true,
});
let json = serde_json::to_value(¬ification).unwrap();
assert_eq!(json["actionTypeId"], "reply");
assert_eq!(json["extra"]["route"], "/games/7");
assert_eq!(json["schedule"]["kind"], "at");
assert_eq!(json["schedule"]["atMs"], 1_800_000_000_000_i64);
assert_eq!(json["schedule"]["allowWhileIdle"], true);
let every = serde_json::to_value(Schedule::Every {
interval: ScheduleInterval::Day,
count: 2,
})
.unwrap();
assert_eq!(
every,
serde_json::json!({ "kind": "every", "interval": "day", "count": 2 })
);
}
#[test]
fn events_from_either_platform_parse() {
let tap: NotificationEvent = serde_json::from_str(
r#"{"type":"action","actionId":"tap","input":null,
"notification":{"id":7,"title":"Tee time","body":"Hole 1","extra":{"route":"/games/7"}}}"#,
)
.unwrap();
let NotificationEvent::Action {
action_id,
notification,
..
} = tap
else {
panic!("a tap is an action");
};
assert_eq!(action_id, TAP_ACTION);
assert_eq!(notification.extra["route"], "/games/7");
let received: NotificationEvent =
serde_json::from_str(r#"{"type":"received","notification":{"id":1,"title":"Hi"}}"#)
.unwrap();
assert!(matches!(received, NotificationEvent::Received { .. }));
}
}