Skip to main content

tauri_plugin_notification/
lib.rs

1// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2// SPDX-License-Identifier: Apache-2.0
3// SPDX-License-Identifier: MIT
4
5//! Send message notifications (brief auto-expiring OS window element) to your user. Can also be used with the Notification Web API.
6//!
7//! ## Cargo features
8//!
9//! - **windows7-compat**: Adds support for the legacy Windows 7 notification implementation and Windows-version detection.
10
11#![doc(
12    html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png",
13    html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png"
14)]
15
16use serde::Serialize;
17#[cfg(mobile)]
18use tauri::plugin::PluginHandle;
19#[cfg(desktop)]
20use tauri::AppHandle;
21use tauri::{
22    plugin::{Builder, TauriPlugin},
23    Manager, Runtime,
24};
25
26pub use models::*;
27pub use tauri::plugin::PermissionState;
28
29#[cfg(desktop)]
30mod desktop;
31#[cfg(mobile)]
32mod mobile;
33
34mod commands;
35mod error;
36mod models;
37
38pub use error::{Error, Result};
39
40#[cfg(desktop)]
41pub use desktop::Notification;
42#[cfg(mobile)]
43pub use mobile::Notification;
44
45/// The notification builder.
46#[derive(Debug)]
47pub struct NotificationBuilder<R: Runtime> {
48    #[cfg(desktop)]
49    app: AppHandle<R>,
50    #[cfg(mobile)]
51    handle: PluginHandle<R>,
52    pub(crate) data: NotificationData,
53}
54
55impl<R: Runtime> NotificationBuilder<R> {
56    #[cfg(desktop)]
57    fn new(app: AppHandle<R>) -> Self {
58        Self {
59            app,
60            data: Default::default(),
61        }
62    }
63
64    #[cfg(mobile)]
65    fn new(handle: PluginHandle<R>) -> Self {
66        Self {
67            handle,
68            data: Default::default(),
69        }
70    }
71
72    /// Sets the notification identifier.
73    pub fn id(mut self, id: i32) -> Self {
74        self.data.id = id;
75        self
76    }
77
78    /// Identifier of the {@link Channel} that deliveres this notification.
79    ///
80    /// If the channel does not exist, the notification won't fire.
81    /// Make sure the channel exists with {@link listChannels} and {@link createChannel}.
82    pub fn channel_id(mut self, id: impl Into<String>) -> Self {
83        self.data.channel_id.replace(id.into());
84        self
85    }
86
87    /// Sets the notification title.
88    pub fn title(mut self, title: impl Into<String>) -> Self {
89        self.data.title.replace(title.into());
90        self
91    }
92
93    /// Sets the notification body.
94    pub fn body(mut self, body: impl Into<String>) -> Self {
95        self.data.body.replace(body.into());
96        self
97    }
98
99    /// Schedule this notification to fire on a later time or a fixed interval.
100    pub fn schedule(mut self, schedule: Schedule) -> Self {
101        self.data.schedule.replace(schedule);
102        self
103    }
104
105    /// Multiline text.
106    /// Changes the notification style to big text.
107    /// Cannot be used with `inboxLines`.
108    pub fn large_body(mut self, large_body: impl Into<String>) -> Self {
109        self.data.large_body.replace(large_body.into());
110        self
111    }
112
113    /// Detail text for the notification with `largeBody`, `inboxLines` or `groupSummary`.
114    pub fn summary(mut self, summary: impl Into<String>) -> Self {
115        self.data.summary.replace(summary.into());
116        self
117    }
118
119    /// Defines an action type for this notification.
120    pub fn action_type_id(mut self, action_type_id: impl Into<String>) -> Self {
121        self.data.action_type_id.replace(action_type_id.into());
122        self
123    }
124
125    /// Identifier used to group multiple notifications.
126    ///
127    /// <https://developer.apple.com/documentation/usernotifications/unmutablenotificationcontent/1649872-threadidentifier>
128    pub fn group(mut self, group: impl Into<String>) -> Self {
129        self.data.group.replace(group.into());
130        self
131    }
132
133    /// Instructs the system that this notification is the summary of a group on Android.
134    pub fn group_summary(mut self) -> Self {
135        self.data.group_summary = true;
136        self
137    }
138
139    /// The sound resource name for the notification.
140    pub fn sound(mut self, sound: impl Into<String>) -> Self {
141        self.data.sound.replace(sound.into());
142        self
143    }
144
145    /// Append an inbox line to the notification.
146    /// Changes the notification style to inbox.
147    /// Cannot be used with `largeBody`.
148    ///
149    /// Only supports up to 5 lines.
150    pub fn inbox_line(mut self, line: impl Into<String>) -> Self {
151        self.data.inbox_lines.push(line.into());
152        self
153    }
154
155    /// Notification icon.
156    ///
157    /// On Android the icon must be placed in the app's `res/drawable` folder.
158    pub fn icon(mut self, icon: impl Into<String>) -> Self {
159        self.data.icon.replace(icon.into());
160        self
161    }
162
163    /// Notification large icon (Android).
164    ///
165    /// The icon must be placed in the app's `res/drawable` folder.
166    pub fn large_icon(mut self, large_icon: impl Into<String>) -> Self {
167        self.data.large_icon.replace(large_icon.into());
168        self
169    }
170
171    /// Icon color on Android.
172    pub fn icon_color(mut self, icon_color: impl Into<String>) -> Self {
173        self.data.icon_color.replace(icon_color.into());
174        self
175    }
176
177    /// Append an attachment to the notification.
178    pub fn attachment(mut self, attachment: Attachment) -> Self {
179        self.data.attachments.push(attachment);
180        self
181    }
182
183    /// Adds an extra payload to store in the notification.
184    pub fn extra(mut self, key: impl Into<String>, value: impl Serialize) -> Self {
185        self.data
186            .extra
187            .insert(key.into(), serde_json::to_value(value).unwrap());
188        self
189    }
190
191    /// If true, the notification cannot be dismissed by the user on Android.
192    ///
193    /// An application service must manage the dismissal of the notification.
194    /// It is typically used to indicate a background task that is pending (e.g. a file download)
195    /// or the user is engaged with (e.g. playing music).
196    pub fn ongoing(mut self) -> Self {
197        self.data.ongoing = true;
198        self
199    }
200
201    /// Automatically cancel the notification when the user clicks on it.
202    pub fn auto_cancel(mut self) -> Self {
203        self.data.auto_cancel = true;
204        self
205    }
206
207    /// Changes the notification presentation to be silent on iOS (no badge, no sound, not listed).
208    pub fn silent(mut self) -> Self {
209        self.data.silent = true;
210        self
211    }
212}
213
214/// Extensions to [`tauri::App`], [`tauri::AppHandle`], [`tauri::WebviewWindow`], [`tauri::Webview`] and [`tauri::Window`] to access the notification APIs.
215pub trait NotificationExt<R: Runtime> {
216    fn notification(&self) -> &Notification<R>;
217}
218
219impl<R: Runtime, T: Manager<R>> crate::NotificationExt<R> for T {
220    fn notification(&self) -> &Notification<R> {
221        self.state::<Notification<R>>().inner()
222    }
223}
224
225/// Initializes the plugin.
226pub fn init<R: Runtime>() -> TauriPlugin<R> {
227    Builder::new("notification")
228        .invoke_handler(tauri::generate_handler![
229            commands::notify,
230            commands::request_permission,
231            commands::is_permission_granted
232        ])
233        .js_init_script(include_str!("init-iife.js").replace(
234            "__TEMPLATE_windows__",
235            if cfg!(windows) { "true" } else { "false" },
236        ))
237        .setup(|app, api| {
238            #[cfg(mobile)]
239            let notification = mobile::init(app, api)?;
240            #[cfg(desktop)]
241            let notification = desktop::init(app, api)?;
242            app.manage(notification);
243            Ok(())
244        })
245        .build()
246}