Skip to main content

tauri_plugin_notification/
mobile.rs

1// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2// SPDX-License-Identifier: Apache-2.0
3// SPDX-License-Identifier: MIT
4
5use serde::{Deserialize, de::DeserializeOwned};
6use tauri::{
7    AppHandle, Runtime,
8    plugin::{PermissionState, PluginApi, PluginHandle},
9};
10
11use crate::models::*;
12
13use std::collections::HashMap;
14
15#[cfg(target_os = "android")]
16const PLUGIN_IDENTIFIER: &str = "app.tauri.notification";
17
18#[cfg(target_os = "ios")]
19tauri::ios_plugin_binding!(init_plugin_notification);
20
21/// Initializes the mobile implementation of the notification APIs by registering
22/// the Kotlin (Android) or Swift (iOS) plugin class.
23pub fn init<R: Runtime, C: DeserializeOwned>(
24    _app: &AppHandle<R>,
25    api: PluginApi<R, C>,
26) -> crate::Result<Notification<R>> {
27    #[cfg(target_os = "android")]
28    let handle = api.register_android_plugin(PLUGIN_IDENTIFIER, "NotificationPlugin")?;
29    #[cfg(target_os = "ios")]
30    let handle = api.register_ios_plugin(init_plugin_notification)?;
31    Ok(Notification(handle))
32}
33
34impl<R: Runtime> crate::NotificationBuilder<R> {
35    /// Shows the notification, or schedules it when [`Self::schedule`] was called.
36    ///
37    /// # Errors
38    ///
39    /// Returns [`Error::PluginInvoke`](crate::Error::PluginInvoke) when the mobile plugin
40    /// rejects the notification, e.g. when the scheduled date is in the past.
41    pub fn show(self) -> crate::Result<()> {
42        self.handle
43            .run_mobile_plugin::<i32>("show", self.data)
44            .map(|_| ())
45            .map_err(Into::into)
46    }
47}
48
49/// Access to the notification APIs.
50///
51/// You can get an instance of this type via [`NotificationExt`](crate::NotificationExt)
52pub struct Notification<R: Runtime>(PluginHandle<R>);
53
54impl<R: Runtime> Notification<R> {
55    /// Creates a new builder for a notification.
56    ///
57    /// # Examples
58    ///
59    /// ```no_run
60    /// use tauri_plugin_notification::NotificationExt;
61    ///
62    /// fn notify<R: tauri::Runtime>(app: &tauri::AppHandle<R>) {
63    ///   app.notification()
64    ///     .builder()
65    ///     .title("Tauri")
66    ///     .body("Tauri is awesome!")
67    ///     .show()
68    ///     .unwrap();
69    /// }
70    /// ```
71    pub fn builder(&self) -> crate::NotificationBuilder<R> {
72        crate::NotificationBuilder::new(self.0.clone())
73    }
74
75    /// Requests the permission to send notifications, prompting the user when it was not decided yet.
76    ///
77    /// On Android this requests the `POST_NOTIFICATIONS` runtime permission.
78    pub fn request_permission(&self) -> crate::Result<PermissionState> {
79        self.0
80            .run_mobile_plugin::<PermissionResponse>("requestPermissions", ())
81            .map(|r| r.permission_state)
82            .map_err(Into::into)
83    }
84
85    /// Checks the current state of the permission to send notifications without prompting the user.
86    pub fn permission_state(&self) -> crate::Result<PermissionState> {
87        self.0
88            .run_mobile_plugin::<PermissionResponse>("checkPermissions", ())
89            .map(|r| r.permission_state)
90            .map_err(Into::into)
91    }
92
93    /// Registers the action types a notification can reference
94    /// through [`NotificationBuilder::action_type_id`](crate::NotificationBuilder::action_type_id).
95    ///
96    /// ## Platform-specific
97    ///
98    /// - **Android**: only the identifier, title and input flag of each [`Action`] are used.
99    /// - **iOS**: each action type is registered as a `UNNotificationCategory`.
100    pub fn register_action_types(&self, types: Vec<ActionType>) -> crate::Result<()> {
101        let mut args = HashMap::new();
102        args.insert("types", types);
103        self.0
104            .run_mobile_plugin("registerActionTypes", args)
105            .map_err(Into::into)
106    }
107
108    /// Removes the delivered notifications with the given identifiers from the notification center.
109    ///
110    /// Use [`Self::remove_all_active`] to remove every delivered notification.
111    pub fn remove_active(&self, notifications: Vec<i32>) -> crate::Result<()> {
112        let mut args = HashMap::new();
113        args.insert(
114            "notifications",
115            notifications
116                .into_iter()
117                .map(|id| {
118                    let mut notification = HashMap::new();
119                    notification.insert("id", id);
120                    notification
121                })
122                .collect::<Vec<HashMap<&str, i32>>>(),
123        );
124        self.0
125            .run_mobile_plugin("removeActive", args)
126            .map_err(Into::into)
127    }
128
129    /// Lists the notifications that were delivered and are still visible in the notification center.
130    pub fn active(&self) -> crate::Result<Vec<ActiveNotification>> {
131        self.0
132            .run_mobile_plugin("getActive", ())
133            .map_err(Into::into)
134    }
135
136    /// Removes all delivered notifications from the notification center.
137    pub fn remove_all_active(&self) -> crate::Result<()> {
138        self.0
139            .run_mobile_plugin("removeActive", ())
140            .map_err(Into::into)
141    }
142
143    /// Lists the scheduled notifications that have not been delivered yet.
144    pub fn pending(&self) -> crate::Result<Vec<PendingNotification>> {
145        self.0
146            .run_mobile_plugin("getPending", ())
147            .map_err(Into::into)
148    }
149
150    /// Cancel pending notifications.
151    pub fn cancel(&self, notifications: Vec<i32>) -> crate::Result<()> {
152        let mut args = HashMap::new();
153        args.insert("notifications", notifications);
154        self.0.run_mobile_plugin("cancel", args).map_err(Into::into)
155    }
156
157    /// Cancel all pending notifications.
158    pub fn cancel_all(&self) -> crate::Result<()> {
159        self.0.run_mobile_plugin("cancel", ()).map_err(Into::into)
160    }
161
162    /// Creates a notification channel, which notifications can target
163    /// through [`NotificationBuilder::channel_id`](crate::NotificationBuilder::channel_id).
164    ///
165    /// Notifications that reference a channel that does not exist are not delivered.
166    ///
167    /// Only available on Android.
168    #[cfg(target_os = "android")]
169    pub fn create_channel(&self, channel: Channel) -> crate::Result<()> {
170        self.0
171            .run_mobile_plugin("createChannel", channel)
172            .map_err(Into::into)
173    }
174
175    /// Deletes the notification channel with the given identifier.
176    ///
177    /// Only available on Android.
178    #[cfg(target_os = "android")]
179    pub fn delete_channel(&self, id: impl Into<String>) -> crate::Result<()> {
180        let mut args = HashMap::new();
181        args.insert("id", id.into());
182        self.0
183            .run_mobile_plugin("deleteChannel", args)
184            .map_err(Into::into)
185    }
186
187    /// Lists the notification channels that are currently registered for the app.
188    ///
189    /// Only available on Android.
190    #[cfg(target_os = "android")]
191    pub fn list_channels(&self) -> crate::Result<Vec<Channel>> {
192        self.0
193            .run_mobile_plugin("listChannels", ())
194            .map_err(Into::into)
195    }
196}
197
198#[derive(Deserialize)]
199#[serde(rename_all = "camelCase")]
200struct PermissionResponse {
201    permission_state: PermissionState,
202}