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