snapshot of https://github.com/tauri-apps/plugins-workspace.git (v2, 2026-09-23; blobs > 131072B omitted)
Some checks failed
integration tests / run-integration-tests (windows-latest) (push) Has been cancelled
Test Rust / test (push) Has been cancelled
test plugins e2e (mobile) / ios (push) Has been cancelled
test plugins e2e / test (map[name:Windows os:windows-latest]) (push) Has been cancelled
test plugins e2e / test (map[name:macOS os:macos-latest]) (push) Has been cancelled
integration tests / run-integration-tests (macos-latest) (push) Has been cancelled
version or publish / version-or-publish (push) Failing after 0s
integration tests / run-integration-tests (ubuntu-22.04) (push) Failing after 0s
Lint JavaScript / eslint (push) Failing after 0s
Sync / sync-to-mirrors (push) Failing after 0s
test plugins e2e (mobile) / android (push) Failing after 0s
test plugins e2e / test (map[name:Linux os:ubuntu-latest]) (push) Failing after 0s
Test Rust / changes (push) Failing after 0s
Lint Rust / changes (push) Failing after 0s
Lint Rust / clippy (push) Has been skipped
Audit Rust / audit-rust (push) Failing after 1s
Audit JavaScript / audit-js (push) Failing after 1s
Some checks failed
integration tests / run-integration-tests (windows-latest) (push) Has been cancelled
Test Rust / test (push) Has been cancelled
test plugins e2e (mobile) / ios (push) Has been cancelled
test plugins e2e / test (map[name:Windows os:windows-latest]) (push) Has been cancelled
test plugins e2e / test (map[name:macOS os:macos-latest]) (push) Has been cancelled
integration tests / run-integration-tests (macos-latest) (push) Has been cancelled
version or publish / version-or-publish (push) Failing after 0s
integration tests / run-integration-tests (ubuntu-22.04) (push) Failing after 0s
Lint JavaScript / eslint (push) Failing after 0s
Sync / sync-to-mirrors (push) Failing after 0s
test plugins e2e (mobile) / android (push) Failing after 0s
test plugins e2e / test (map[name:Linux os:ubuntu-latest]) (push) Failing after 0s
Test Rust / changes (push) Failing after 0s
Lint Rust / changes (push) Failing after 0s
Lint Rust / clippy (push) Has been skipped
Audit Rust / audit-rust (push) Failing after 1s
Audit JavaScript / audit-js (push) Failing after 1s
This commit is contained in:
165
plugins/notification/CHANGELOG.md
Normal file
165
plugins/notification/CHANGELOG.md
Normal file
@@ -0,0 +1,165 @@
|
||||
# Changelog
|
||||
|
||||
## [2.4.0]
|
||||
|
||||
- [`db9c5998`](https://github.com/tauri-apps/plugins-workspace/commit/db9c5998feff9384f9cbbefcbe0d45937c00a1fc) ([#3531](https://github.com/tauri-apps/plugins-workspace/pull/3531) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Fix missing `consumer-rules.pro` on Gradle v9.
|
||||
- [`304292d7`](https://github.com/tauri-apps/plugins-workspace/commit/304292d740a666d3903ab58329860fc0fdde2818) ([#2805](https://github.com/tauri-apps/plugins-workspace/pull/2805) by [@Innominus](https://github.com/tauri-apps/plugins-workspace/../../Innominus)) - Add Rust builders for mobile notification action types.
|
||||
- Fix Android action-group entries being stored under the action type ID instead of sequential indices, causing later actions to overwrite earlier ones.
|
||||
|
||||
## \[2.3.3]
|
||||
|
||||
- [`93426f85`](https://github.com/tauri-apps/plugins-workspace/commit/93426f85120f49beb9f40222bff45185a32d54a9) Fixed an issue that caused docs.rs builds to fail. No user facing changes.
|
||||
|
||||
## \[2.3.2]
|
||||
|
||||
- [`6c9b61fb`](https://github.com/tauri-apps/plugins-workspace/commit/6c9b61fb658145d13893626112fc489f7458aa17) ([#3039](https://github.com/tauri-apps/plugins-workspace/pull/3039) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) On Android, updated compileSdk to 36.
|
||||
|
||||
## \[2.3.1]
|
||||
|
||||
- [`8abb31ee`](https://github.com/tauri-apps/plugins-workspace/commit/8abb31ee59c68197102c0aa699d690b34646ec3c) ([#2905](https://github.com/tauri-apps/plugins-workspace/pull/2905) by [@ChristianPavilonis](https://github.com/tauri-apps/plugins-workspace/../../ChristianPavilonis)) Fix notification scheduling on iOS.
|
||||
- [`2d03e2ea`](https://github.com/tauri-apps/plugins-workspace/commit/2d03e2eac2c19ad997d81d23836ab6a219252ffb) ([#2678](https://github.com/tauri-apps/plugins-workspace/pull/2678) by [@Keerthi421](https://github.com/tauri-apps/plugins-workspace/../../Keerthi421)) Added sound support for desktop notifications which was previously only available on mobile platforms.
|
||||
|
||||
## \[2.3.0]
|
||||
|
||||
- [`f209b2f2`](https://github.com/tauri-apps/plugins-workspace/commit/f209b2f23cb29133c97ad5961fb46ef794dbe063) ([#2804](https://github.com/tauri-apps/plugins-workspace/pull/2804) by [@renovate](https://github.com/tauri-apps/plugins-workspace/../../renovate)) Updated tauri to 2.6
|
||||
|
||||
## \[2.2.3]
|
||||
|
||||
- [`f634e524`](https://github.com/tauri-apps/plugins-workspace/commit/f634e5248ebe428f8305a59f74c13fc15147fb8e) This is an "empty" release to update the plugins' source files on crates.io and docs.rs. This should fix docs.rs build failures for projects using tauri plugins as dependencies.
|
||||
|
||||
## \[2.2.2]
|
||||
|
||||
- [`a1b3fa27`](https://github.com/tauri-apps/plugins-workspace/commit/a1b3fa27f11022c9b6622b4fab12d93239eb05de) ([#2515](https://github.com/tauri-apps/plugins-workspace/pull/2515) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) Re-exported the `Geolocation`, `Haptics`, `Notification`, and `Os` structs so that they show up on docs.rs.
|
||||
|
||||
## \[2.2.1]
|
||||
|
||||
- [`da5c59e2`](https://github.com/tauri-apps/plugins-workspace/commit/da5c59e2fe879d177e3cfd52fcacce85440423cb) ([#2271](https://github.com/tauri-apps/plugins-workspace/pull/2271) by [@renovate](https://github.com/tauri-apps/plugins-workspace/../../renovate)) Updated `zbus` dependency to version 5. No API changes.
|
||||
|
||||
## \[2.2.0]
|
||||
|
||||
- [`3a79266b`](https://github.com/tauri-apps/plugins-workspace/commit/3a79266b8cf96a55b1ae6339d725567d45a44b1d) ([#2173](https://github.com/tauri-apps/plugins-workspace/pull/2173) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) Bumped all plugins to `v2.2.0`. From now, the versions for the Rust and JavaScript packages of each plugin will be in sync with each other.
|
||||
|
||||
## \[2.0.1]
|
||||
|
||||
- [`a1a82208`](https://github.com/tauri-apps/plugins-workspace/commit/a1a82208ed4ab87f83310be0dc95428aec9ab241) ([#1873](https://github.com/tauri-apps/plugins-workspace/pull/1873) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Downgrade MSRV to 1.77.2 to support Windows 7.
|
||||
|
||||
## \[2.0.0]
|
||||
|
||||
- [`e2c4dfb6`](https://github.com/tauri-apps/plugins-workspace/commit/e2c4dfb6af43e5dd8d9ceba232c315f5febd55c1) Update to tauri v2 stable release.
|
||||
|
||||
## \[2.0.0-rc.5]
|
||||
|
||||
- [`fb85e5dd`](https://github.com/tauri-apps/plugins-workspace/commit/fb85e5dd76688f3ae836890160f9bde843b70167) ([#1785](https://github.com/tauri-apps/plugins-workspace/pull/1785)) Update to tauri 2.0.0-rc.12.
|
||||
|
||||
## \[2.0.0-rc.4]
|
||||
|
||||
- [`3d301c65`](https://github.com/tauri-apps/plugins-workspace/commit/3d301c654e6f5e7f343e0e0cbb57648002e98f04) ([#1737](https://github.com/tauri-apps/plugins-workspace/pull/1737) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) The notification body is now optional on iOS to match the other platforms.
|
||||
|
||||
## \[2.0.0-rc.1]
|
||||
|
||||
- [`e2e97db5`](https://github.com/tauri-apps/plugins-workspace/commit/e2e97db51983267f5be84d4f6f0278d58834d1f5) ([#1701](https://github.com/tauri-apps/plugins-workspace/pull/1701) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Use `PermissionState` from the `tauri` crate, which now also includes a "prompt with rationale" variant for Android (returned when your app must explain to the user why it needs the permission).
|
||||
- [`e2e97db5`](https://github.com/tauri-apps/plugins-workspace/commit/e2e97db51983267f5be84d4f6f0278d58834d1f5) ([#1701](https://github.com/tauri-apps/plugins-workspace/pull/1701) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) **Breaking change**: The permission type when using the API is now `'granted' | 'denied' | 'prompt' | 'prompt-with-rationale'` instead of `'granted' | 'denied' | 'default'` for consistency with Rust types. When using the `window.Notification` API the type is unchanged to match the Web API type.
|
||||
- [`e2e97db5`](https://github.com/tauri-apps/plugins-workspace/commit/e2e97db51983267f5be84d4f6f0278d58834d1f5) ([#1701](https://github.com/tauri-apps/plugins-workspace/pull/1701) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Update to tauri 2.0.0-rc.8
|
||||
|
||||
## \[2.0.0-rc.2]
|
||||
|
||||
- [`b9147758`](https://github.com/tauri-apps/plugins-workspace/commit/b914775898c2bee7ceb20bd17ee595005cd17a64) ([#1679](https://github.com/tauri-apps/plugins-workspace/pull/1679) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Explicitly set a minimum macOS version for the Swift package.
|
||||
|
||||
## \[2.0.0-rc.1]
|
||||
|
||||
### changes
|
||||
|
||||
- [`6b079cfd`](https://github.com/tauri-apps/plugins-workspace/commit/6b079cfdd107c94abc2c7300f6af00bac3ff4040) ([#1649](https://github.com/tauri-apps/plugins-workspace/pull/1649) by [@ahqsoftwares](https://github.com/tauri-apps/plugins-workspace/../../ahqsoftwares)) Remove targetSdk from build.kts files as it is deprecated and will be removed from DSL v9.0
|
||||
|
||||
## \[2.0.0-rc.0]
|
||||
|
||||
- [`9887d1`](https://github.com/tauri-apps/plugins-workspace/commit/9887d14bd0e971c4c0f5c1188fc4005d3fc2e29e) Update to tauri RC.
|
||||
|
||||
## \[2.0.0-beta.8]
|
||||
|
||||
- [`99d6ac0f`](https://github.com/tauri-apps/plugins-workspace/commit/99d6ac0f9506a6a4a1aa59c728157190a7441af6) ([#1606](https://github.com/tauri-apps/plugins-workspace/pull/1606) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) The JS packages now specify the *minimum* `@tauri-apps/api` version instead of a single exact version.
|
||||
- [`6de87966`](https://github.com/tauri-apps/plugins-workspace/commit/6de87966ecc00ad9d91c25be452f1f46bd2b7e1f) ([#1597](https://github.com/tauri-apps/plugins-workspace/pull/1597) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Update to tauri beta.25.
|
||||
|
||||
## \[2.0.0-beta.11]
|
||||
|
||||
- [`725ff429`](https://github.com/tauri-apps/plugins-workspace/commit/725ff4295e56df9c30c099813bd64b96fe61b945) ([#1556](https://github.com/tauri-apps/plugins-workspace/pull/1556) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) Fixed an issue that caused the `notification` plugin's initialization script to cause the WebView on Windows to throw a `STATUS_ACCESS_VIOLATION` error on remote websites.
|
||||
|
||||
## \[2.0.0-beta.7]
|
||||
|
||||
- [`22a17980`](https://github.com/tauri-apps/plugins-workspace/commit/22a17980ff4f6f8c40adb1b8f4ffc6dae2fe7e30) ([#1537](https://github.com/tauri-apps/plugins-workspace/pull/1537) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Update to tauri beta.24.
|
||||
|
||||
## \[2.0.0-beta.6]
|
||||
|
||||
- [`76daee7a`](https://github.com/tauri-apps/plugins-workspace/commit/76daee7aafece34de3092c86e531cf9eb1138989) ([#1512](https://github.com/tauri-apps/plugins-workspace/pull/1512) by [@renovate](https://github.com/tauri-apps/plugins-workspace/../../renovate)) Update to tauri beta.23.
|
||||
|
||||
## \[2.0.0-beta.8]
|
||||
|
||||
- [`3779fb50`](https://github.com/tauri-apps/plugins-workspace/commit/3779fb50634fba4d7e7eb0bfecc2216349b9d64d) ([#1432](https://github.com/tauri-apps/plugins-workspace/pull/1432) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Use notify_rust from crates.io instead of local fork.
|
||||
|
||||
## \[2.0.0-beta.5]
|
||||
|
||||
- [`9013854f`](https://github.com/tauri-apps/plugins-workspace/commit/9013854f42a49a230b9dbb9d02774765528a923f)([#1382](https://github.com/tauri-apps/plugins-workspace/pull/1382)) Update to tauri beta.22.
|
||||
|
||||
## \[2.0.0-beta.4]
|
||||
|
||||
- [`430bd6f4`](https://github.com/tauri-apps/plugins-workspace/commit/430bd6f4f379bee5d232ae6b098ae131db7f178a)([#1363](https://github.com/tauri-apps/plugins-workspace/pull/1363)) Update to tauri beta.20.
|
||||
|
||||
## \[2.0.0-beta.3]
|
||||
|
||||
- [`bd1ed590`](https://github.com/tauri-apps/plugins-workspace/commit/bd1ed5903ffcce5500310dac1e59e8c67674ef1e)([#1237](https://github.com/tauri-apps/plugins-workspace/pull/1237)) Update to tauri beta.17.
|
||||
|
||||
## \[2.0.0-beta.4]
|
||||
|
||||
- [`326df688`](https://github.com/tauri-apps/plugins-workspace/commit/326df6883998d416fc0837583ed972854628bb52)([#1236](https://github.com/tauri-apps/plugins-workspace/pull/1236)) Fixes command argument parsing on iOS.
|
||||
|
||||
## \[2.0.0-beta.3]
|
||||
|
||||
- [`a04ea2f`](https://github.com/tauri-apps/plugins-workspace/commit/a04ea2f38294d5a3987578283badc8eec87a7752)([#1071](https://github.com/tauri-apps/plugins-workspace/pull/1071)) The global API script is now only added to the binary when the `withGlobalTauri` config is true.
|
||||
- [`62ce5df`](https://github.com/tauri-apps/plugins-workspace/commit/62ce5df52ca3c86786e711ef193a206e7b0dc0cf)([#1096](https://github.com/tauri-apps/plugins-workspace/pull/1096)) Fix development mode check to set the app ID on macOS.
|
||||
|
||||
## \[2.0.0-beta.2]
|
||||
|
||||
- [`99bea25`](https://github.com/tauri-apps/plugins-workspace/commit/99bea2559c2c0648c2519c50a18cd124dacef57b)([#1005](https://github.com/tauri-apps/plugins-workspace/pull/1005)) Update to tauri beta.8.
|
||||
|
||||
## \[2.0.0-beta.1]
|
||||
|
||||
- [`569defb`](https://github.com/tauri-apps/plugins-workspace/commit/569defbe9492e38938554bb7bdc1be9151456d21) Update to tauri beta.4.
|
||||
|
||||
## \[2.0.0-beta.0]
|
||||
|
||||
- [`d198c01`](https://github.com/tauri-apps/plugins-workspace/commit/d198c014863ee260cb0de88a14b7fc4356ef7474)([#862](https://github.com/tauri-apps/plugins-workspace/pull/862)) Update to tauri beta.
|
||||
- [`1b1d795`](https://github.com/tauri-apps/plugins-workspace/commit/1b1d795b5866e5524a9a9925f0fb7b2f8e3e3675)([#874](https://github.com/tauri-apps/plugins-workspace/pull/874)) Export the missing `Schedule` class.
|
||||
- [`8dea78a`](https://github.com/tauri-apps/plugins-workspace/commit/8dea78ac7dcb502159e66bad464094696aa257d4)([#909](https://github.com/tauri-apps/plugins-workspace/pull/909)) Fixes deserialization and implementation bugs with scheduled notifications on Android.
|
||||
|
||||
## \[2.0.0-alpha.5]
|
||||
|
||||
- [`387c2f9`](https://github.com/tauri-apps/plugins-workspace/commit/387c2f9e0ce4c75c07ffa3fd76391a25b58f5daf)([#802](https://github.com/tauri-apps/plugins-workspace/pull/802)) Update to @tauri-apps/api v2.0.0-alpha.13.
|
||||
|
||||
## \[2.0.0-alpha.4]
|
||||
|
||||
- [`387c2f9`](https://github.com/tauri-apps/plugins-workspace/commit/387c2f9e0ce4c75c07ffa3fd76391a25b58f5daf)([#802](https://github.com/tauri-apps/plugins-workspace/pull/802)) Update to @tauri-apps/api v2.0.0-alpha.12.
|
||||
|
||||
## \[2.0.0-alpha.3]
|
||||
|
||||
- [`e438e0a`](https://github.com/tauri-apps/plugins-workspace/commit/e438e0a62d4b430a5159f05f13ecd397dd891a0d)([#676](https://github.com/tauri-apps/plugins-workspace/pull/676)) Update to @tauri-apps/api v2.0.0-alpha.11.
|
||||
|
||||
## \[2.0.0-alpha.2]
|
||||
|
||||
- [`5c13736`](https://github.com/tauri-apps/plugins-workspace/commit/5c137365c60790e8d4037d449e8237aa3fffdab0)([#673](https://github.com/tauri-apps/plugins-workspace/pull/673)) Update to @tauri-apps/api v2.0.0-alpha.9.
|
||||
|
||||
## \[2.0.0-alpha.3]
|
||||
|
||||
- [`4e2cef9`](https://github.com/tauri-apps/plugins-workspace/commit/4e2cef9b702bbbb9cf4ee17de50791cb21f1b2a4)([#593](https://github.com/tauri-apps/plugins-workspace/pull/593)) Update to alpha.12.
|
||||
|
||||
## \[2.0.0-alpha.1]
|
||||
|
||||
- [`d74fc0a`](https://github.com/tauri-apps/plugins-workspace/commit/d74fc0a097996e90a37be8f57d50b7d1f6ca616f)([#555](https://github.com/tauri-apps/plugins-workspace/pull/555)) Update to alpha.11.
|
||||
|
||||
## \[2.0.0-alpha.1]
|
||||
|
||||
- [`d8b4aca`](https://github.com/tauri-apps/plugins-workspace/commit/d8b4aca69f628b170804ecb982e2c319d026ef47)([#414](https://github.com/tauri-apps/plugins-workspace/pull/414)) Use `window.__TAURI_INVOKE__` instead of `window.__TAURI__` in init.js, fixes usage in apps without `withGlobalTauri` enabled.
|
||||
- [`7d71ad4`](https://github.com/tauri-apps/plugins-workspace/commit/7d71ad4e587bcf47ea34645f5b226945e487b765) Play a default sound when showing a notification on Windows.
|
||||
|
||||
## \[2.0.0-alpha.0]
|
||||
|
||||
- [`717ae67`](https://github.com/tauri-apps/plugins-workspace/commit/717ae670978feb4492fac1f295998b93f2b9347f)([#371](https://github.com/tauri-apps/plugins-workspace/pull/371)) First v2 alpha release!
|
||||
58
plugins/notification/Cargo.toml
Normal file
58
plugins/notification/Cargo.toml
Normal file
@@ -0,0 +1,58 @@
|
||||
[package]
|
||||
name = "tauri-plugin-notification"
|
||||
version = "2.4.0"
|
||||
description = "Send desktop and mobile notifications on your Tauri application."
|
||||
edition = { workspace = true }
|
||||
authors = { workspace = true }
|
||||
license = { workspace = true }
|
||||
rust-version = { workspace = true }
|
||||
repository = { workspace = true }
|
||||
links = "tauri-plugin-notification"
|
||||
exclude = [
|
||||
"/banner.png",
|
||||
"/guest-js",
|
||||
"/package.json",
|
||||
"/rollup.config.js",
|
||||
"/test",
|
||||
"/tsconfig.json",
|
||||
]
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
targets = ["x86_64-unknown-linux-gnu", "x86_64-linux-android"]
|
||||
|
||||
[package.metadata.platforms.support]
|
||||
windows = { level = "full", notes = "Only works for installed apps. Shows powershell name & icon in development." }
|
||||
linux = { level = "full", notes = "" }
|
||||
macos = { level = "full", notes = "" }
|
||||
android = { level = "full", notes = "" }
|
||||
ios = { level = "full", notes = "" }
|
||||
|
||||
[build-dependencies]
|
||||
tauri-plugin = { workspace = true, features = ["build"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tauri = { workspace = true, features = ["wry"] }
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tauri = { workspace = true }
|
||||
log = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
rand = "0.9"
|
||||
time = { version = "0.3", features = ["serde", "parsing", "formatting"] }
|
||||
url = { version = "2", features = ["serde"] }
|
||||
serde_repr = "0.1"
|
||||
|
||||
[target.'cfg(target_os = "ios")'.dependencies]
|
||||
tauri = { workspace = true, features = ["wry"] }
|
||||
|
||||
[target."cfg(windows)".dependencies]
|
||||
win7-notifications = { version = "0.4.5", optional = true }
|
||||
windows-version = { version = "0.1", optional = true }
|
||||
|
||||
[target."cfg(any(target_os = \"macos\", windows, target_os = \"linux\", target_os = \"dragonfly\", target_os = \"freebsd\", target_os = \"openbsd\", target_os = \"netbsd\"))".dependencies]
|
||||
notify-rust = "4.11"
|
||||
|
||||
[features]
|
||||
windows7-compat = ["win7-notifications", "windows-version"]
|
||||
20
plugins/notification/LICENSE.spdx
Normal file
20
plugins/notification/LICENSE.spdx
Normal file
@@ -0,0 +1,20 @@
|
||||
SPDXVersion: SPDX-2.1
|
||||
DataLicense: CC0-1.0
|
||||
PackageName: tauri
|
||||
DataFormat: SPDXRef-1
|
||||
PackageSupplier: Organization: The Tauri Programme in the Commons Conservancy
|
||||
PackageHomePage: https://tauri.app
|
||||
PackageLicenseDeclared: Apache-2.0
|
||||
PackageLicenseDeclared: MIT
|
||||
PackageCopyrightText: 2019-2022, The Tauri Programme in the Commons Conservancy
|
||||
PackageSummary: <text>Tauri is a rust project that enables developers to make secure
|
||||
and small desktop applications using a web frontend.
|
||||
</text>
|
||||
PackageComment: <text>The package includes the following libraries; see
|
||||
Relationship information.
|
||||
</text>
|
||||
Created: 2019-05-20T09:00:00Z
|
||||
PackageDownloadLocation: git://github.com/tauri-apps/tauri
|
||||
PackageDownloadLocation: git+https://github.com/tauri-apps/tauri.git
|
||||
PackageDownloadLocation: git+ssh://github.com/tauri-apps/tauri.git
|
||||
Creator: Person: Daniel Thompson-Yvetot
|
||||
177
plugins/notification/LICENSE_APACHE-2.0
Normal file
177
plugins/notification/LICENSE_APACHE-2.0
Normal file
@@ -0,0 +1,177 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
21
plugins/notification/LICENSE_MIT
Normal file
21
plugins/notification/LICENSE_MIT
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017 - Present Tauri Apps Contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
161
plugins/notification/README.md
Normal file
161
plugins/notification/README.md
Normal file
@@ -0,0 +1,161 @@
|
||||

|
||||
|
||||
Send message notifications (brief auto-expiring OS window element) to your user. Can also be used with the Notification Web API.
|
||||
|
||||
| Platform | Supported |
|
||||
| -------- | --------- |
|
||||
| Linux | ✓ |
|
||||
| Windows | ✓ |
|
||||
| macOS | ✓ |
|
||||
| Android | ✓ |
|
||||
| iOS | ✓ |
|
||||
|
||||
## Install
|
||||
|
||||
_This plugin requires a Rust version of at least **1.77.2**_
|
||||
|
||||
There are three general methods of installation that we can recommend.
|
||||
|
||||
1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked)
|
||||
2. Pull sources directly from Github using git tags / revision hashes (most secure)
|
||||
3. Git submodule install this repo in your tauri project and then use file protocol to ingest the source (most secure, but inconvenient to use)
|
||||
|
||||
Install the Core plugin by adding the following to your `Cargo.toml` file:
|
||||
|
||||
`src-tauri/Cargo.toml`
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
tauri-plugin-notification = "2.0.0"
|
||||
# alternatively with Git:
|
||||
tauri-plugin-notification = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
|
||||
```
|
||||
|
||||
You can install the JavaScript Guest bindings using your preferred JavaScript package manager:
|
||||
|
||||
```sh
|
||||
pnpm add @tauri-apps/plugin-notification
|
||||
# or
|
||||
npm add @tauri-apps/plugin-notification
|
||||
# or
|
||||
yarn add @tauri-apps/plugin-notification
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
First you need to register the core plugin with Tauri:
|
||||
|
||||
`src-tauri/src/lib.rs`
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_notification::init())
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
||||
```
|
||||
|
||||
Then you need to add the permissions to your capabilities file:
|
||||
|
||||
`src-tauri/capabilities/main.json`
|
||||
|
||||
```json
|
||||
{
|
||||
...
|
||||
"permissions": [
|
||||
...
|
||||
"notification:default"
|
||||
],
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Afterwards all the plugin's APIs are available through the JavaScript guest bindings:
|
||||
|
||||
```javascript
|
||||
import {
|
||||
isPermissionGranted,
|
||||
requestPermission,
|
||||
sendNotification
|
||||
} from '@tauri-apps/plugin-notification'
|
||||
|
||||
async function checkPermission() {
|
||||
if (!(await isPermissionGranted())) {
|
||||
return (await requestPermission()) === 'granted'
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
export async function enqueueNotification(title, body) {
|
||||
if (!(await checkPermission())) {
|
||||
return
|
||||
}
|
||||
sendNotification({ title, body })
|
||||
}
|
||||
```
|
||||
|
||||
### Notification with Sound
|
||||
|
||||
You can add sound to your notifications on all platforms (desktop and mobile):
|
||||
|
||||
```javascript
|
||||
import { sendNotification } from '@tauri-apps/plugin-notification'
|
||||
import { platform } from '@tauri-apps/api/os'
|
||||
|
||||
// Basic notification with sound
|
||||
sendNotification({
|
||||
title: 'New Message',
|
||||
body: 'You have a new message',
|
||||
sound: 'notification.wav' // Path to sound file
|
||||
})
|
||||
|
||||
// Platform-specific sounds
|
||||
async function sendPlatformSpecificNotification() {
|
||||
const platformName = platform()
|
||||
|
||||
let soundPath
|
||||
if (platformName === 'darwin') {
|
||||
// On macOS: use system sounds or sound files in the app bundle
|
||||
soundPath = 'Ping' // macOS system sound
|
||||
} else if (platformName === 'linux') {
|
||||
// On Linux: use XDG theme sounds or file paths
|
||||
soundPath = 'message-new-instant' // XDG theme sound
|
||||
} else {
|
||||
// On Windows: use file paths
|
||||
soundPath = 'notification.wav'
|
||||
}
|
||||
|
||||
sendNotification({
|
||||
title: 'Platform-specific Notification',
|
||||
body: 'This notification uses platform-specific sound',
|
||||
sound: soundPath
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
PRs accepted. Please make sure to read the Contributing Guide before making a pull request.
|
||||
|
||||
## Partners
|
||||
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://crabnebula.dev" target="_blank">
|
||||
<img src="https://github.com/tauri-apps/plugins-workspace/raw/v2/.github/sponsors/crabnebula.svg" alt="CrabNebula" width="283">
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
For the complete list of sponsors please visit our [website](https://tauri.app#sponsors) and [Open Collective](https://opencollective.com/tauri).
|
||||
|
||||
## License
|
||||
|
||||
Code: (c) 2015 - Present - The Tauri Programme within The Commons Conservancy.
|
||||
|
||||
MIT or MIT/Apache 2.0 where applicable.
|
||||
23
plugins/notification/SECURITY.md
Normal file
23
plugins/notification/SECURITY.md
Normal file
@@ -0,0 +1,23 @@
|
||||
# Security Policy
|
||||
|
||||
**Do not report security vulnerabilities through public GitHub issues.**
|
||||
|
||||
**Please use the [Private Vulnerability Disclosure](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability) feature of GitHub.**
|
||||
|
||||
Include as much of the following information:
|
||||
|
||||
- Type of issue (e.g. improper input parsing, privilege escalation, etc.)
|
||||
- The location of the affected source code (tag/branch/commit or direct URL)
|
||||
- Any special configuration required to reproduce the issue
|
||||
- The distribution affected or used to help us with reproduction of the issue
|
||||
- Step-by-step instructions to reproduce the issue
|
||||
- Ideally a reproduction repository
|
||||
- Impact of the issue, including how an attacker might exploit the issue
|
||||
|
||||
We prefer to receive reports in English.
|
||||
|
||||
## Contact
|
||||
|
||||
Please disclose a vulnerability or security relevant issue here: [https://github.com/tauri-apps/plugins-workspace/security/advisories/new](https://github.com/tauri-apps/plugins-workspace/security/advisories/new).
|
||||
|
||||
Alternatively, you can also contact us by email via [security@tauri.app](mailto:security@tauri.app).
|
||||
2
plugins/notification/android/.gitignore
vendored
Normal file
2
plugins/notification/android/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
/build
|
||||
/.tauri
|
||||
36
plugins/notification/android/build.gradle.kts
Normal file
36
plugins/notification/android/build.gradle.kts
Normal file
@@ -0,0 +1,36 @@
|
||||
plugins {
|
||||
id("com.android.library")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "app.tauri.notification"
|
||||
compileSdk = 36
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 24
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
consumerProguardFiles("consumer-rules.pro")
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||
targetCompatibility = JavaVersion.VERSION_1_8
|
||||
}
|
||||
kotlinOptions {
|
||||
jvmTarget = "1.8"
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
|
||||
implementation("androidx.core:core-ktx:1.9.0")
|
||||
implementation("androidx.appcompat:appcompat:1.6.0")
|
||||
implementation("com.google.android.material:material:1.7.0")
|
||||
implementation("com.fasterxml.jackson.core:jackson-databind:2.15.3")
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
androidTestImplementation("androidx.test.ext:junit:1.1.5")
|
||||
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
|
||||
implementation(project(":tauri-android"))
|
||||
}
|
||||
21
plugins/notification/android/consumer-rules.pro
Normal file
21
plugins/notification/android/consumer-rules.pro
Normal file
@@ -0,0 +1,21 @@
|
||||
# Add project specific ProGuard rules here.
|
||||
# You can control the set of applied configuration files using the
|
||||
# proguardFiles setting in build.gradle.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
|
||||
# Uncomment this to preserve the line number information for
|
||||
# debugging stack traces.
|
||||
#-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
# If you keep the line number information, uncomment this to
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
||||
2
plugins/notification/android/settings.gradle
Normal file
2
plugins/notification/android/settings.gradle
Normal file
@@ -0,0 +1,2 @@
|
||||
include ':tauri-android'
|
||||
project(':tauri-android').projectDir = new File('./.tauri/tauri-api')
|
||||
@@ -0,0 +1,28 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.notification
|
||||
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
import org.junit.Assert.*
|
||||
|
||||
/**
|
||||
* Instrumented test, which will execute on an Android device.
|
||||
*
|
||||
* See [testing documentation](http://d.android.com/tools/testing).
|
||||
*/
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class ExampleInstrumentedTest {
|
||||
@Test
|
||||
fun useAppContext() {
|
||||
// Context of the app under test.
|
||||
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
assertEquals("app.tauri.notification", appContext.packageName)
|
||||
}
|
||||
}
|
||||
20
plugins/notification/android/src/main/AndroidManifest.xml
Normal file
20
plugins/notification/android/src/main/AndroidManifest.xml
Normal file
@@ -0,0 +1,20 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<application>
|
||||
<receiver android:name="app.tauri.notification.TimedNotificationPublisher" />
|
||||
<receiver android:name="app.tauri.notification.NotificationDismissReceiver" />
|
||||
<receiver
|
||||
android:name="app.tauri.notification.LocalNotificationRestoreReceiver"
|
||||
android:directBootAware="true"
|
||||
android:exported="false">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
|
||||
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
</application>
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
</manifest>
|
||||
29
plugins/notification/android/src/main/java/AssetUtils.kt
Normal file
29
plugins/notification/android/src/main/java/AssetUtils.kt
Normal file
@@ -0,0 +1,29 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.notification
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
|
||||
class AssetUtils {
|
||||
companion object {
|
||||
const val RESOURCE_ID_ZERO_VALUE = 0
|
||||
|
||||
@SuppressLint("DiscouragedApi")
|
||||
fun getResourceID(context: Context, resourceName: String?, dir: String?): Int {
|
||||
return context.resources.getIdentifier(resourceName, dir, context.packageName)
|
||||
}
|
||||
|
||||
fun getResourceBaseName(resPath: String?): String? {
|
||||
if (resPath == null) return null
|
||||
if (resPath.contains("/")) {
|
||||
return resPath.substring(resPath.lastIndexOf('/') + 1)
|
||||
}
|
||||
return if (resPath.contains(".")) {
|
||||
resPath.substring(0, resPath.lastIndexOf('.'))
|
||||
} else resPath
|
||||
}
|
||||
}
|
||||
}
|
||||
151
plugins/notification/android/src/main/java/ChannelManager.kt
Normal file
151
plugins/notification/android/src/main/java/ChannelManager.kt
Normal file
@@ -0,0 +1,151 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.notification
|
||||
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.graphics.Color
|
||||
import android.media.AudioAttributes
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import app.tauri.Logger
|
||||
import app.tauri.annotation.InvokeArg
|
||||
import app.tauri.plugin.Invoke
|
||||
import com.fasterxml.jackson.annotation.JsonValue
|
||||
|
||||
enum class Importance(@JsonValue val value: Int) {
|
||||
None(0),
|
||||
Min(1),
|
||||
Low(2),
|
||||
Default(3),
|
||||
High(4);
|
||||
}
|
||||
|
||||
enum class Visibility(@JsonValue val value: Int) {
|
||||
Secret(-1),
|
||||
Private(0),
|
||||
Public(1);
|
||||
}
|
||||
|
||||
@InvokeArg
|
||||
class Channel {
|
||||
lateinit var id: String
|
||||
lateinit var name: String
|
||||
var description: String? = null
|
||||
var sound: String? = null
|
||||
var lights: Boolean? = null
|
||||
var lightsColor: String? = null
|
||||
var vibration: Boolean? = null
|
||||
var importance: Importance? = null
|
||||
var visibility: Visibility? = null
|
||||
}
|
||||
|
||||
@InvokeArg
|
||||
class DeleteChannelArgs {
|
||||
lateinit var id: String
|
||||
}
|
||||
|
||||
class ChannelManager(private var context: Context) {
|
||||
private var notificationManager: NotificationManager? = null
|
||||
|
||||
init {
|
||||
notificationManager =
|
||||
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?
|
||||
}
|
||||
|
||||
fun createChannel(invoke: Invoke) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
val channel = invoke.parseArgs(Channel::class.java)
|
||||
createChannel(channel)
|
||||
invoke.resolve()
|
||||
} else {
|
||||
invoke.reject("channel not available")
|
||||
}
|
||||
}
|
||||
|
||||
private fun createChannel(channel: Channel) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
val notificationChannel = NotificationChannel(
|
||||
channel.id,
|
||||
channel.name,
|
||||
(channel.importance ?: Importance.Default).value
|
||||
)
|
||||
notificationChannel.description = channel.description
|
||||
notificationChannel.lockscreenVisibility = (channel.visibility ?: Visibility.Private).value
|
||||
notificationChannel.enableVibration(channel.vibration ?: false)
|
||||
notificationChannel.enableLights(channel.lights ?: false)
|
||||
val lightColor = channel.lightsColor ?: ""
|
||||
if (lightColor.isNotEmpty()) {
|
||||
try {
|
||||
notificationChannel.lightColor = Color.parseColor(lightColor)
|
||||
} catch (ex: IllegalArgumentException) {
|
||||
Logger.error(
|
||||
Logger.tags("NotificationChannel"),
|
||||
"Invalid color provided for light color.",
|
||||
null
|
||||
)
|
||||
}
|
||||
}
|
||||
var sound = channel.sound ?: ""
|
||||
if (sound.isNotEmpty()) {
|
||||
if (sound.contains(".")) {
|
||||
sound = sound.substring(0, sound.lastIndexOf('.'))
|
||||
}
|
||||
val audioAttributes = AudioAttributes.Builder()
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
|
||||
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
|
||||
.build()
|
||||
val soundUri =
|
||||
Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.packageName + "/raw/" + sound)
|
||||
notificationChannel.setSound(soundUri, audioAttributes)
|
||||
}
|
||||
notificationManager?.createNotificationChannel(notificationChannel)
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteChannel(invoke: Invoke) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
val args = invoke.parseArgs(DeleteChannelArgs::class.java)
|
||||
notificationManager?.deleteNotificationChannel(args.id)
|
||||
invoke.resolve()
|
||||
} else {
|
||||
invoke.reject("channel not available")
|
||||
}
|
||||
}
|
||||
|
||||
fun listChannels(invoke: Invoke) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
val notificationChannels: List<NotificationChannel> =
|
||||
notificationManager?.notificationChannels ?: listOf()
|
||||
|
||||
val channels = mutableListOf<Channel>()
|
||||
|
||||
for (notificationChannel in notificationChannels) {
|
||||
val channel = Channel()
|
||||
channel.id = notificationChannel.id
|
||||
channel.name = notificationChannel.name.toString()
|
||||
channel.description = notificationChannel.description
|
||||
channel.sound = notificationChannel.sound.toString()
|
||||
channel.lights = notificationChannel.shouldShowLights()
|
||||
String.format(
|
||||
"#%06X",
|
||||
0xFFFFFF and notificationChannel.lightColor
|
||||
)
|
||||
channel.vibration = notificationChannel.shouldVibrate()
|
||||
channel.importance = Importance.values().firstOrNull { it.value == notificationChannel.importance }
|
||||
channel.visibility = Visibility.values().firstOrNull { it.value == notificationChannel.lockscreenVisibility }
|
||||
|
||||
channels.add(channel)
|
||||
}
|
||||
|
||||
invoke.resolveObject(channels)
|
||||
|
||||
} else {
|
||||
invoke.reject("channel not available")
|
||||
}
|
||||
}
|
||||
}
|
||||
95
plugins/notification/android/src/main/java/Notification.kt
Normal file
95
plugins/notification/android/src/main/java/Notification.kt
Normal file
@@ -0,0 +1,95 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.notification
|
||||
|
||||
import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import app.tauri.annotation.InvokeArg
|
||||
import app.tauri.plugin.JSArray
|
||||
import app.tauri.plugin.JSObject
|
||||
import org.json.JSONException
|
||||
import org.json.JSONObject
|
||||
|
||||
@InvokeArg
|
||||
class Notification {
|
||||
var id: Int = 0
|
||||
var title: String? = null
|
||||
var body: String? = null
|
||||
var largeBody: String? = null
|
||||
var summary: String? = null
|
||||
var sound: String? = null
|
||||
var icon: String? = null
|
||||
var largeIcon: String? = null
|
||||
var iconColor: String? = null
|
||||
var actionTypeId: String? = null
|
||||
var group: String? = null
|
||||
var inboxLines: List<String>? = null
|
||||
var isGroupSummary = false
|
||||
var isOngoing = false
|
||||
var isAutoCancel = false
|
||||
var extra: JSObject? = null
|
||||
var attachments: List<NotificationAttachment>? = null
|
||||
var schedule: NotificationSchedule? = null
|
||||
var channelId: String? = null
|
||||
var sourceJson: String? = null
|
||||
var visibility: Int? = null
|
||||
var number: Int? = null
|
||||
|
||||
fun getSound(context: Context, defaultSound: Int): String? {
|
||||
var soundPath: String? = null
|
||||
var resId: Int = AssetUtils.RESOURCE_ID_ZERO_VALUE
|
||||
val name = AssetUtils.getResourceBaseName(sound)
|
||||
if (name != null) {
|
||||
resId = AssetUtils.getResourceID(context, name, "raw")
|
||||
}
|
||||
if (resId == AssetUtils.RESOURCE_ID_ZERO_VALUE) {
|
||||
resId = defaultSound
|
||||
}
|
||||
if (resId != AssetUtils.RESOURCE_ID_ZERO_VALUE) {
|
||||
soundPath =
|
||||
ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.packageName + "/" + resId
|
||||
}
|
||||
return soundPath
|
||||
}
|
||||
|
||||
fun getIconColor(globalColor: String): String {
|
||||
// use the one defined local before trying for a globally defined color
|
||||
return iconColor ?: globalColor
|
||||
}
|
||||
|
||||
fun getSmallIcon(context: Context, defaultIcon: Int): Int {
|
||||
var resId: Int = AssetUtils.RESOURCE_ID_ZERO_VALUE
|
||||
if (icon != null) {
|
||||
resId = AssetUtils.getResourceID(context, icon, "drawable")
|
||||
}
|
||||
if (resId == AssetUtils.RESOURCE_ID_ZERO_VALUE) {
|
||||
resId = defaultIcon
|
||||
}
|
||||
return resId
|
||||
}
|
||||
|
||||
fun getLargeIcon(context: Context): Bitmap? {
|
||||
if (largeIcon != null) {
|
||||
val resId: Int = AssetUtils.getResourceID(context, largeIcon, "drawable")
|
||||
return BitmapFactory.decodeResource(context.resources, resId)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun buildNotificationPendingList(notifications: List<Notification>): List<PendingNotification> {
|
||||
val pendingNotifications = mutableListOf<PendingNotification>()
|
||||
for (notification in notifications) {
|
||||
val pendingNotification = PendingNotification(notification.id, notification.title, notification.body, notification.schedule, notification.extra)
|
||||
pendingNotifications.add(pendingNotification)
|
||||
}
|
||||
return pendingNotifications
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class PendingNotification(val id: Int, val title: String?, val body: String?, val schedule: NotificationSchedule?, val extra: JSObject?)
|
||||
@@ -0,0 +1,52 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.notification
|
||||
|
||||
import app.tauri.plugin.JSObject
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONException
|
||||
import org.json.JSONObject
|
||||
|
||||
class NotificationAttachment {
|
||||
var id: String? = null
|
||||
var url: String? = null
|
||||
var options: JSONObject? = null
|
||||
|
||||
companion object {
|
||||
fun getAttachments(notification: JSObject): List<NotificationAttachment> {
|
||||
val attachmentsList: MutableList<NotificationAttachment> = ArrayList()
|
||||
var attachments: JSONArray? = null
|
||||
try {
|
||||
attachments = notification.getJSONArray("attachments")
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
if (attachments != null) {
|
||||
for (i in 0 until attachments.length()) {
|
||||
val newAttachment = NotificationAttachment()
|
||||
var jsonObject: JSONObject? = null
|
||||
try {
|
||||
jsonObject = attachments.getJSONObject(i)
|
||||
} catch (e: JSONException) {
|
||||
}
|
||||
if (jsonObject != null) {
|
||||
var jsObject: JSObject? = null
|
||||
try {
|
||||
jsObject = JSObject.fromJSONObject(jsonObject)
|
||||
} catch (_: JSONException) {
|
||||
}
|
||||
newAttachment.id = jsObject!!.getString("id")
|
||||
newAttachment.url = jsObject.getString("url")
|
||||
try {
|
||||
newAttachment.options = jsObject.getJSONObject("options")
|
||||
} catch (_: JSONException) {
|
||||
}
|
||||
attachmentsList.add(newAttachment)
|
||||
}
|
||||
}
|
||||
}
|
||||
return attachmentsList
|
||||
}
|
||||
}
|
||||
}
|
||||
286
plugins/notification/android/src/main/java/NotificationPlugin.kt
Normal file
286
plugins/notification/android/src/main/java/NotificationPlugin.kt
Normal file
@@ -0,0 +1,286 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.notification
|
||||
|
||||
import android.Manifest
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.Activity
|
||||
import android.app.NotificationManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.webkit.WebView
|
||||
import app.tauri.PermissionState
|
||||
import app.tauri.annotation.Command
|
||||
import app.tauri.annotation.InvokeArg
|
||||
import app.tauri.annotation.Permission
|
||||
import app.tauri.annotation.PermissionCallback
|
||||
import app.tauri.annotation.TauriPlugin
|
||||
import app.tauri.plugin.Invoke
|
||||
import app.tauri.plugin.JSArray
|
||||
import app.tauri.plugin.JSObject
|
||||
import app.tauri.plugin.Plugin
|
||||
|
||||
const val LOCAL_NOTIFICATIONS = "permissionState"
|
||||
|
||||
@InvokeArg
|
||||
class PluginConfig {
|
||||
var icon: String? = null
|
||||
var sound: String? = null
|
||||
var iconColor: String? = null
|
||||
}
|
||||
|
||||
@InvokeArg
|
||||
class BatchArgs {
|
||||
lateinit var notifications: List<Notification>
|
||||
}
|
||||
|
||||
@InvokeArg
|
||||
class CancelArgs {
|
||||
// `cancelAll()` sends no list: cancel every pending notification
|
||||
var notifications: List<Int>? = null
|
||||
}
|
||||
|
||||
@InvokeArg
|
||||
class NotificationAction {
|
||||
lateinit var id: String
|
||||
var title: String? = null
|
||||
var input: Boolean? = null
|
||||
}
|
||||
|
||||
@InvokeArg
|
||||
class ActionType {
|
||||
lateinit var id: String
|
||||
lateinit var actions: List<NotificationAction>
|
||||
}
|
||||
|
||||
@InvokeArg
|
||||
class RegisterActionTypesArgs {
|
||||
lateinit var types: List<ActionType>
|
||||
}
|
||||
|
||||
@InvokeArg
|
||||
class ActiveNotification {
|
||||
var id: Int = 0
|
||||
var tag: String? = null
|
||||
}
|
||||
|
||||
@InvokeArg
|
||||
class RemoveActiveArgs {
|
||||
var notifications: List<ActiveNotification> = listOf()
|
||||
}
|
||||
|
||||
@TauriPlugin(
|
||||
permissions = [
|
||||
Permission(strings = [Manifest.permission.POST_NOTIFICATIONS], alias = "permissionState")
|
||||
]
|
||||
)
|
||||
class NotificationPlugin(private val activity: Activity): Plugin(activity) {
|
||||
private var webView: WebView? = null
|
||||
private lateinit var manager: TauriNotificationManager
|
||||
private lateinit var notificationManager: NotificationManager
|
||||
private lateinit var notificationStorage: NotificationStorage
|
||||
private var channelManager = ChannelManager(activity)
|
||||
|
||||
companion object {
|
||||
var instance: NotificationPlugin? = null
|
||||
|
||||
fun triggerNotification(notification: Notification) {
|
||||
instance?.triggerObject("notification", notification)
|
||||
}
|
||||
}
|
||||
|
||||
override fun load(webView: WebView) {
|
||||
instance = this
|
||||
|
||||
super.load(webView)
|
||||
this.webView = webView
|
||||
notificationStorage = NotificationStorage(activity, jsonMapper())
|
||||
|
||||
val manager = TauriNotificationManager(
|
||||
notificationStorage,
|
||||
activity,
|
||||
activity,
|
||||
getConfig(PluginConfig::class.java)
|
||||
)
|
||||
manager.createNotificationChannel()
|
||||
|
||||
this.manager = manager
|
||||
|
||||
notificationManager = activity.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||
|
||||
val intent = activity.intent
|
||||
intent?.let {
|
||||
onIntent(it)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
onIntent(intent)
|
||||
}
|
||||
|
||||
fun onIntent(intent: Intent) {
|
||||
if (Intent.ACTION_MAIN != intent.action) {
|
||||
return
|
||||
}
|
||||
val dataJson = manager.handleNotificationActionPerformed(intent, notificationStorage)
|
||||
if (dataJson != null) {
|
||||
trigger("actionPerformed", dataJson)
|
||||
}
|
||||
}
|
||||
|
||||
@Command
|
||||
fun show(invoke: Invoke) {
|
||||
val notification = invoke.parseArgs(Notification::class.java)
|
||||
val id = manager.schedule(notification)
|
||||
|
||||
invoke.resolveObject(id)
|
||||
}
|
||||
|
||||
@Command
|
||||
fun batch(invoke: Invoke) {
|
||||
val args = invoke.parseArgs(BatchArgs::class.java)
|
||||
|
||||
val ids = manager.schedule(args.notifications)
|
||||
notificationStorage.appendNotifications(args.notifications)
|
||||
|
||||
invoke.resolveObject(ids)
|
||||
}
|
||||
|
||||
@Command
|
||||
fun cancel(invoke: Invoke) {
|
||||
val args = invoke.parseArgs(CancelArgs::class.java)
|
||||
manager.cancel(
|
||||
args.notifications ?: notificationStorage.getSavedNotificationIds().mapNotNull { it.toIntOrNull() }
|
||||
)
|
||||
invoke.resolve()
|
||||
}
|
||||
|
||||
@Command
|
||||
fun removeActive(invoke: Invoke) {
|
||||
val args = invoke.parseArgs(RemoveActiveArgs::class.java)
|
||||
|
||||
if (args.notifications.isEmpty()) {
|
||||
notificationManager.cancelAll()
|
||||
invoke.resolve()
|
||||
} else {
|
||||
for (notification in args.notifications) {
|
||||
if (notification.tag == null) {
|
||||
notificationManager.cancel(notification.id)
|
||||
} else {
|
||||
notificationManager.cancel(notification.tag, notification.id)
|
||||
}
|
||||
}
|
||||
invoke.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
@Command
|
||||
fun getPending(invoke: Invoke) {
|
||||
val notifications= notificationStorage.getSavedNotifications()
|
||||
val result = Notification.buildNotificationPendingList(notifications)
|
||||
invoke.resolveObject(result)
|
||||
}
|
||||
|
||||
@Command
|
||||
fun registerActionTypes(invoke: Invoke) {
|
||||
val args = invoke.parseArgs(RegisterActionTypesArgs::class.java)
|
||||
notificationStorage.writeActionGroup(args.types)
|
||||
invoke.resolve()
|
||||
}
|
||||
|
||||
@SuppressLint("ObsoleteSdkInt")
|
||||
@Command
|
||||
fun getActive(invoke: Invoke) {
|
||||
// plain lists and maps: until tauri serializes org.json values natively,
|
||||
// `resolveObject` turns a `JSArray` into `{ "values": [...] }`
|
||||
val notifications = mutableListOf<Map<String, Any?>>()
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
val activeNotifications = notificationManager.activeNotifications
|
||||
for (activeNotification in activeNotifications) {
|
||||
val jsNotification = mutableMapOf<String, Any?>(
|
||||
"id" to activeNotification.id,
|
||||
"tag" to activeNotification.tag
|
||||
)
|
||||
val notification = activeNotification.notification
|
||||
if (notification != null) {
|
||||
jsNotification["title"] = notification.extras.getCharSequence(android.app.Notification.EXTRA_TITLE)?.toString()
|
||||
jsNotification["body"] = notification.extras.getCharSequence(android.app.Notification.EXTRA_TEXT)?.toString()
|
||||
jsNotification["group"] = notification.group
|
||||
jsNotification["groupSummary"] =
|
||||
0 != notification.flags and android.app.Notification.FLAG_GROUP_SUMMARY
|
||||
val extras = mutableMapOf<String, String?>()
|
||||
for (key in notification.extras.keySet()) {
|
||||
extras[key] = notification.extras.getString(key)
|
||||
}
|
||||
jsNotification["data"] = extras
|
||||
}
|
||||
notifications.add(jsNotification)
|
||||
}
|
||||
}
|
||||
|
||||
invoke.resolveObject(notifications)
|
||||
}
|
||||
|
||||
@Command
|
||||
fun createChannel(invoke: Invoke) {
|
||||
channelManager.createChannel(invoke)
|
||||
}
|
||||
|
||||
@Command
|
||||
fun deleteChannel(invoke: Invoke) {
|
||||
channelManager.deleteChannel(invoke)
|
||||
}
|
||||
|
||||
@Command
|
||||
fun listChannels(invoke: Invoke) {
|
||||
channelManager.listChannels(invoke)
|
||||
}
|
||||
|
||||
@Command
|
||||
override fun checkPermissions(invoke: Invoke) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
|
||||
val permissionsResultJSON = JSObject()
|
||||
permissionsResultJSON.put("permissionState", getPermissionState())
|
||||
invoke.resolve(permissionsResultJSON)
|
||||
} else {
|
||||
super.checkPermissions(invoke)
|
||||
}
|
||||
}
|
||||
|
||||
@Command
|
||||
override fun requestPermissions(invoke: Invoke) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
|
||||
permissionState(invoke)
|
||||
} else {
|
||||
if (getPermissionState(LOCAL_NOTIFICATIONS) !== PermissionState.GRANTED) {
|
||||
requestPermissionForAlias(LOCAL_NOTIFICATIONS, invoke, "permissionsCallback")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Command
|
||||
fun permissionState(invoke: Invoke) {
|
||||
val permissionsResultJSON = JSObject()
|
||||
permissionsResultJSON.put("permissionState", getPermissionState())
|
||||
invoke.resolve(permissionsResultJSON)
|
||||
}
|
||||
|
||||
@PermissionCallback
|
||||
private fun permissionsCallback(invoke: Invoke) {
|
||||
val permissionsResultJSON = JSObject()
|
||||
permissionsResultJSON.put("permissionState", getPermissionState())
|
||||
invoke.resolve(permissionsResultJSON)
|
||||
}
|
||||
|
||||
private fun getPermissionState(): String {
|
||||
return if (manager.areNotificationsEnabled()) {
|
||||
"granted"
|
||||
} else {
|
||||
"denied"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.notification
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.text.format.DateUtils
|
||||
import com.fasterxml.jackson.annotation.JsonFormat
|
||||
import com.fasterxml.jackson.annotation.JsonProperty
|
||||
import com.fasterxml.jackson.core.JsonGenerator
|
||||
import com.fasterxml.jackson.core.JsonParser
|
||||
import com.fasterxml.jackson.core.JsonProcessingException
|
||||
import com.fasterxml.jackson.databind.DeserializationContext
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer
|
||||
import com.fasterxml.jackson.databind.JsonNode
|
||||
import com.fasterxml.jackson.databind.SerializerProvider
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize
|
||||
import com.fasterxml.jackson.databind.deser.std.StdDeserializer
|
||||
import com.fasterxml.jackson.databind.ser.std.StdSerializer
|
||||
import java.io.IOException
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Calendar
|
||||
import java.util.Date
|
||||
import java.util.TimeZone
|
||||
|
||||
const val JS_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
|
||||
|
||||
enum class NotificationInterval {
|
||||
@JsonProperty("year")
|
||||
Year,
|
||||
@JsonProperty("month")
|
||||
Month,
|
||||
@JsonProperty("twoWeeks")
|
||||
TwoWeeks,
|
||||
@JsonProperty("week")
|
||||
Week,
|
||||
@JsonProperty("day")
|
||||
Day,
|
||||
@JsonProperty("hour")
|
||||
Hour,
|
||||
@JsonProperty("minute")
|
||||
Minute,
|
||||
@JsonProperty("second")
|
||||
Second
|
||||
}
|
||||
|
||||
fun getIntervalTime(interval: NotificationInterval, count: Int): Long {
|
||||
return when (interval) {
|
||||
// This case is just approximation as not all years have the same number of days
|
||||
NotificationInterval.Year -> count * DateUtils.WEEK_IN_MILLIS * 52
|
||||
// This case is just approximation as months have different number of days
|
||||
NotificationInterval.Month -> count * 30 * DateUtils.DAY_IN_MILLIS
|
||||
NotificationInterval.TwoWeeks -> count * 2 * DateUtils.WEEK_IN_MILLIS
|
||||
NotificationInterval.Week -> count * DateUtils.WEEK_IN_MILLIS
|
||||
NotificationInterval.Day -> count * DateUtils.DAY_IN_MILLIS
|
||||
NotificationInterval.Hour -> count * DateUtils.HOUR_IN_MILLIS
|
||||
NotificationInterval.Minute -> count * DateUtils.MINUTE_IN_MILLIS
|
||||
NotificationInterval.Second -> count * DateUtils.SECOND_IN_MILLIS
|
||||
}
|
||||
}
|
||||
|
||||
@JsonDeserialize(using = NotificationScheduleDeserializer::class)
|
||||
@JsonSerialize(using = NotificationScheduleSerializer::class)
|
||||
sealed class NotificationSchedule {
|
||||
// At specific moment of time (with repeating option)
|
||||
@JsonDeserialize
|
||||
class At: NotificationSchedule() {
|
||||
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = JS_DATE_FORMAT)
|
||||
lateinit var date: Date
|
||||
var repeating: Boolean = false
|
||||
var allowWhileIdle: Boolean = false
|
||||
}
|
||||
@JsonDeserialize
|
||||
class Interval: NotificationSchedule() {
|
||||
lateinit var interval: DateMatch
|
||||
var allowWhileIdle: Boolean = false
|
||||
}
|
||||
@JsonDeserialize
|
||||
class Every: NotificationSchedule() {
|
||||
lateinit var interval: NotificationInterval
|
||||
var count: Int = 0
|
||||
var allowWhileIdle: Boolean = false
|
||||
}
|
||||
|
||||
fun isRemovable(): Boolean {
|
||||
return when (this) {
|
||||
is At -> !repeating
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
fun allowWhileIdle(): Boolean {
|
||||
return when (this) {
|
||||
is At -> allowWhileIdle
|
||||
is Interval -> allowWhileIdle
|
||||
is Every -> allowWhileIdle
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal class NotificationScheduleSerializer @JvmOverloads constructor(t: Class<NotificationSchedule>? = null) :
|
||||
StdSerializer<NotificationSchedule>(t) {
|
||||
@SuppressLint("SimpleDateFormat")
|
||||
@Throws(IOException::class, JsonProcessingException::class)
|
||||
override fun serialize(
|
||||
value: NotificationSchedule, jgen: JsonGenerator, provider: SerializerProvider
|
||||
) {
|
||||
jgen.writeStartObject()
|
||||
when (value) {
|
||||
is NotificationSchedule.At -> {
|
||||
jgen.writeObjectFieldStart("at")
|
||||
|
||||
val sdf = SimpleDateFormat(JS_DATE_FORMAT)
|
||||
sdf.timeZone = TimeZone.getTimeZone("UTC")
|
||||
jgen.writeStringField("date", sdf.format(value.date))
|
||||
jgen.writeBooleanField("repeating", value.repeating)
|
||||
|
||||
jgen.writeEndObject()
|
||||
}
|
||||
is NotificationSchedule.Interval -> {
|
||||
jgen.writeObjectFieldStart("interval")
|
||||
|
||||
jgen.writeObjectField("interval", value.interval)
|
||||
|
||||
jgen.writeEndObject()
|
||||
}
|
||||
is NotificationSchedule.Every -> {
|
||||
jgen.writeObjectFieldStart("every")
|
||||
|
||||
jgen.writeObjectField("interval", value.interval)
|
||||
jgen.writeNumberField("count", value.count)
|
||||
|
||||
jgen.writeEndObject()
|
||||
}
|
||||
}
|
||||
|
||||
jgen.writeEndObject()
|
||||
}
|
||||
}
|
||||
|
||||
internal class NotificationScheduleDeserializer: JsonDeserializer<NotificationSchedule>() {
|
||||
override fun deserialize(
|
||||
jsonParser: JsonParser,
|
||||
deserializationContext: DeserializationContext
|
||||
): NotificationSchedule {
|
||||
val node: JsonNode = jsonParser.codec.readTree(jsonParser)
|
||||
node.get("at")?.let {
|
||||
return jsonParser.codec.treeToValue(it, NotificationSchedule.At::class.java)
|
||||
}
|
||||
node.get("interval")?.let {
|
||||
return jsonParser.codec.treeToValue(it, NotificationSchedule.Interval::class.java)
|
||||
}
|
||||
node.get("every")?.let {
|
||||
return jsonParser.codec.treeToValue(it, NotificationSchedule.Every::class.java)
|
||||
}
|
||||
throw Error("unknown schedule kind $node")
|
||||
}
|
||||
}
|
||||
|
||||
class DateMatch {
|
||||
var year: Int? = null
|
||||
var month: Int? = null
|
||||
var day: Int? = null
|
||||
var weekday: Int? = null
|
||||
var hour: Int? = null
|
||||
var minute: Int? = null
|
||||
var second: Int? = null
|
||||
|
||||
// Unit used to save the last used unit for a trigger.
|
||||
// One of the Calendar constants values
|
||||
var unit: Int? = -1
|
||||
|
||||
/**
|
||||
* Gets a calendar instance pointing to the specified date.
|
||||
*
|
||||
* @param date The date to point.
|
||||
*/
|
||||
private fun buildCalendar(date: Date): Calendar {
|
||||
val cal: Calendar = Calendar.getInstance()
|
||||
cal.time = date
|
||||
cal.set(Calendar.MILLISECOND, 0)
|
||||
return cal
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates next trigger date for
|
||||
*
|
||||
* @param date base date used to calculate trigger
|
||||
* @return next trigger timestamp
|
||||
*/
|
||||
fun nextTrigger(date: Date): Long {
|
||||
val current: Calendar = buildCalendar(date)
|
||||
val next: Calendar = buildNextTriggerTime(date)
|
||||
return postponeTriggerIfNeeded(current, next)
|
||||
}
|
||||
|
||||
/**
|
||||
* Postpone trigger if first schedule matches the past
|
||||
*/
|
||||
private fun postponeTriggerIfNeeded(current: Calendar, next: Calendar): Long {
|
||||
if (next.timeInMillis <= current.timeInMillis && unit != -1) {
|
||||
var incrementUnit = -1
|
||||
if (unit == Calendar.YEAR || unit == Calendar.MONTH) {
|
||||
incrementUnit = Calendar.YEAR
|
||||
} else if (unit == Calendar.DAY_OF_MONTH) {
|
||||
incrementUnit = Calendar.MONTH
|
||||
} else if (unit == Calendar.DAY_OF_WEEK) {
|
||||
incrementUnit = Calendar.WEEK_OF_MONTH
|
||||
} else if (unit == Calendar.HOUR_OF_DAY) {
|
||||
incrementUnit = Calendar.DAY_OF_MONTH
|
||||
} else if (unit == Calendar.MINUTE) {
|
||||
incrementUnit = Calendar.HOUR_OF_DAY
|
||||
} else if (unit == Calendar.SECOND) {
|
||||
incrementUnit = Calendar.MINUTE
|
||||
}
|
||||
if (incrementUnit != -1) {
|
||||
next.set(incrementUnit, next.get(incrementUnit) + 1)
|
||||
}
|
||||
}
|
||||
return next.timeInMillis
|
||||
}
|
||||
|
||||
private fun buildNextTriggerTime(date: Date): Calendar {
|
||||
val next: Calendar = buildCalendar(date)
|
||||
if (year != null) {
|
||||
next.set(Calendar.YEAR, year ?: 0)
|
||||
if (unit == -1) unit = Calendar.YEAR
|
||||
}
|
||||
if (month != null) {
|
||||
next.set(Calendar.MONTH, month ?: 0)
|
||||
if (unit == -1) unit = Calendar.MONTH
|
||||
}
|
||||
if (day != null) {
|
||||
next.set(Calendar.DAY_OF_MONTH, day ?: 0)
|
||||
if (unit == -1) unit = Calendar.DAY_OF_MONTH
|
||||
}
|
||||
if (weekday != null) {
|
||||
next.set(Calendar.DAY_OF_WEEK, weekday ?: 0)
|
||||
if (unit == -1) unit = Calendar.DAY_OF_WEEK
|
||||
}
|
||||
if (hour != null) {
|
||||
next.set(Calendar.HOUR_OF_DAY, hour ?: 0)
|
||||
if (unit == -1) unit = Calendar.HOUR_OF_DAY
|
||||
}
|
||||
if (minute != null) {
|
||||
next.set(Calendar.MINUTE, minute ?: 0)
|
||||
if (unit == -1) unit = Calendar.MINUTE
|
||||
}
|
||||
if (second != null) {
|
||||
next.set(Calendar.SECOND, second ?: 0)
|
||||
if (unit == -1) unit = Calendar.SECOND
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
override fun toString(): String {
|
||||
return "DateMatch{" +
|
||||
"year=" +
|
||||
year +
|
||||
", month=" +
|
||||
month +
|
||||
", day=" +
|
||||
day +
|
||||
", weekday=" +
|
||||
weekday +
|
||||
", hour=" +
|
||||
hour +
|
||||
", minute=" +
|
||||
minute +
|
||||
", second=" +
|
||||
second +
|
||||
'}'
|
||||
}
|
||||
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (this === other) return true
|
||||
if (other == null || javaClass != other.javaClass) return false
|
||||
val dateMatch = other as DateMatch
|
||||
if (if (year != null) year != dateMatch.year else dateMatch.year != null) return false
|
||||
if (if (month != null) month != dateMatch.month else dateMatch.month != null) return false
|
||||
if (if (day != null) day != dateMatch.day else dateMatch.day != null) return false
|
||||
if (if (weekday != null) weekday != dateMatch.weekday else dateMatch.weekday != null) return false
|
||||
if (if (hour != null) hour != dateMatch.hour else dateMatch.hour != null) return false
|
||||
if (if (minute != null) minute != dateMatch.minute else dateMatch.minute != null) return false
|
||||
return if (second != null) second == dateMatch.second else dateMatch.second == null
|
||||
}
|
||||
|
||||
override fun hashCode(): Int {
|
||||
var result = if (year != null) year.hashCode() else 0
|
||||
result = 31 * result + if (month != null) month.hashCode() else 0
|
||||
result = 31 * result + if (day != null) day.hashCode() else 0
|
||||
result = 31 * result + if (weekday != null) weekday.hashCode() else 0
|
||||
result = 31 * result + if (hour != null) hour.hashCode() else 0
|
||||
result = 31 * result + if (minute != null) minute.hashCode() else 0
|
||||
result += 31 + if (second != null) second.hashCode() else 0
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform DateMatch object to CronString
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
fun toMatchString(): String {
|
||||
val matchString = year.toString() +
|
||||
separator +
|
||||
month +
|
||||
separator +
|
||||
day +
|
||||
separator +
|
||||
weekday +
|
||||
separator +
|
||||
hour +
|
||||
separator +
|
||||
minute +
|
||||
separator +
|
||||
second +
|
||||
separator +
|
||||
unit
|
||||
return matchString.replace("null", "*")
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val separator = " "
|
||||
|
||||
/**
|
||||
* Create DateMatch object from stored string
|
||||
*
|
||||
* @param matchString
|
||||
* @return
|
||||
*/
|
||||
fun fromMatchString(matchString: String): DateMatch {
|
||||
val date = DateMatch()
|
||||
val split = matchString.split(separator.toRegex()).dropLastWhile { it.isEmpty() }
|
||||
.toTypedArray()
|
||||
if (split.size == 7) {
|
||||
date.year = getValueFromCronElement(split[0])
|
||||
date.month = getValueFromCronElement(split[1])
|
||||
date.day = getValueFromCronElement(split[2])
|
||||
date.weekday = getValueFromCronElement(split[3])
|
||||
date.hour = getValueFromCronElement(split[4])
|
||||
date.minute = getValueFromCronElement(split[5])
|
||||
date.unit = getValueFromCronElement(split[6])
|
||||
}
|
||||
if (split.size == 8) {
|
||||
date.year = getValueFromCronElement(split[0])
|
||||
date.month = getValueFromCronElement(split[1])
|
||||
date.day = getValueFromCronElement(split[2])
|
||||
date.weekday = getValueFromCronElement(split[3])
|
||||
date.hour = getValueFromCronElement(split[4])
|
||||
date.minute = getValueFromCronElement(split[5])
|
||||
date.second = getValueFromCronElement(split[6])
|
||||
date.unit = getValueFromCronElement(split[7])
|
||||
}
|
||||
return date
|
||||
}
|
||||
|
||||
private fun getValueFromCronElement(token: String): Int? {
|
||||
return try {
|
||||
token.toInt()
|
||||
} catch (e: NumberFormatException) {
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.notification
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import com.fasterxml.jackson.databind.ObjectMapper
|
||||
import org.json.JSONException
|
||||
import java.lang.Exception
|
||||
|
||||
// Key for private preferences
|
||||
private const val NOTIFICATION_STORE_ID = "NOTIFICATION_STORE"
|
||||
// Key used to save action types
|
||||
private const val ACTION_TYPES_ID = "ACTION_TYPE_STORE"
|
||||
|
||||
class NotificationStorage(private val context: Context, private val jsonMapper: ObjectMapper) {
|
||||
fun appendNotifications(localNotifications: List<Notification>) {
|
||||
val storage = getStorage(NOTIFICATION_STORE_ID)
|
||||
val editor = storage.edit()
|
||||
for (request in localNotifications) {
|
||||
if (request.schedule != null) {
|
||||
val key: String = request.id.toString()
|
||||
editor.putString(key, request.sourceJson.toString())
|
||||
}
|
||||
}
|
||||
editor.apply()
|
||||
}
|
||||
|
||||
fun getSavedNotificationIds(): List<String> {
|
||||
val storage = getStorage(NOTIFICATION_STORE_ID)
|
||||
val all = storage.all
|
||||
return if (all != null) {
|
||||
ArrayList(all.keys)
|
||||
} else ArrayList()
|
||||
}
|
||||
|
||||
fun getSavedNotifications(): List<Notification> {
|
||||
val storage = getStorage(NOTIFICATION_STORE_ID)
|
||||
val all = storage.all
|
||||
if (all != null) {
|
||||
val notifications = ArrayList<Notification>()
|
||||
for (key in all.keys) {
|
||||
val notificationString = all[key] as String?
|
||||
try {
|
||||
val notification = jsonMapper.readValue(notificationString, Notification::class.java)
|
||||
notifications.add(notification)
|
||||
} catch (_: Exception) { }
|
||||
}
|
||||
return notifications
|
||||
}
|
||||
return ArrayList()
|
||||
}
|
||||
|
||||
fun getSavedNotification(key: String): Notification? {
|
||||
val storage = getStorage(NOTIFICATION_STORE_ID)
|
||||
val notificationString = try {
|
||||
storage.getString(key, null)
|
||||
} catch (ex: ClassCastException) {
|
||||
return null
|
||||
} ?: return null
|
||||
|
||||
return try {
|
||||
jsonMapper.readValue(notificationString, Notification::class.java)
|
||||
} catch (ex: JSONException) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteNotification(id: String?) {
|
||||
val editor = getStorage(NOTIFICATION_STORE_ID).edit()
|
||||
editor.remove(id)
|
||||
editor.apply()
|
||||
}
|
||||
|
||||
private fun getStorage(key: String): SharedPreferences {
|
||||
return context.getSharedPreferences(key, Context.MODE_PRIVATE)
|
||||
}
|
||||
|
||||
fun writeActionGroup(actions: List<ActionType>) {
|
||||
for (type in actions) {
|
||||
val editor = getStorage(ACTION_TYPES_ID + type.id).edit()
|
||||
editor.clear()
|
||||
editor.putInt("count", type.actions.size)
|
||||
for (i in 0 until type.actions.size) {
|
||||
val action = type.actions[i]
|
||||
editor.putString("id$i", action.id)
|
||||
editor.putString("title$i", action.title)
|
||||
editor.putBoolean("input$i", action.input ?: false)
|
||||
}
|
||||
editor.apply()
|
||||
}
|
||||
}
|
||||
|
||||
fun getActionGroup(forId: String): Array<NotificationAction?> {
|
||||
val storage = getStorage(ACTION_TYPES_ID + forId)
|
||||
val count = storage.getInt("count", 0)
|
||||
val actions: Array<NotificationAction?> = arrayOfNulls(count)
|
||||
for (i in 0 until count) {
|
||||
val id = storage.getString("id$i", "")
|
||||
val title = storage.getString("title$i", "")
|
||||
val input = storage.getBoolean("input$i", false)
|
||||
|
||||
val action = NotificationAction()
|
||||
action.id = id ?: ""
|
||||
action.title = title
|
||||
action.input = input
|
||||
actions[i] = action
|
||||
}
|
||||
return actions
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,581 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.notification
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.Activity
|
||||
import android.app.AlarmManager
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.Color
|
||||
import android.media.AudioAttributes
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Build.VERSION.SDK_INT
|
||||
import android.os.UserManager
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.app.RemoteInput
|
||||
import app.tauri.Logger
|
||||
import app.tauri.plugin.JSObject
|
||||
import app.tauri.plugin.PluginManager
|
||||
import com.fasterxml.jackson.databind.ObjectMapper
|
||||
import org.json.JSONException
|
||||
import org.json.JSONObject
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
|
||||
// Action constants
|
||||
const val NOTIFICATION_INTENT_KEY = "NotificationId"
|
||||
const val NOTIFICATION_OBJ_INTENT_KEY = "LocalNotficationObject"
|
||||
const val ACTION_INTENT_KEY = "NotificationUserAction"
|
||||
const val NOTIFICATION_IS_REMOVABLE_KEY = "NotificationRepeating"
|
||||
const val REMOTE_INPUT_KEY = "NotificationRemoteInput"
|
||||
const val DEFAULT_NOTIFICATION_CHANNEL_ID = "default"
|
||||
const val DEFAULT_PRESS_ACTION = "tap"
|
||||
|
||||
class TauriNotificationManager(
|
||||
private val storage: NotificationStorage,
|
||||
private val activity: Activity?,
|
||||
private val context: Context,
|
||||
private val config: PluginConfig?
|
||||
) {
|
||||
private var defaultSoundID: Int = AssetUtils.RESOURCE_ID_ZERO_VALUE
|
||||
private var defaultSmallIconID: Int = AssetUtils.RESOURCE_ID_ZERO_VALUE
|
||||
|
||||
fun handleNotificationActionPerformed(
|
||||
data: Intent,
|
||||
notificationStorage: NotificationStorage
|
||||
): JSObject? {
|
||||
Logger.debug(Logger.tags("Notification"), "Notification received: " + data.dataString)
|
||||
val notificationId =
|
||||
data.getIntExtra(NOTIFICATION_INTENT_KEY, Int.MIN_VALUE)
|
||||
if (notificationId == Int.MIN_VALUE) {
|
||||
Logger.debug(Logger.tags("Notification"), "Activity started without notification attached")
|
||||
return null
|
||||
}
|
||||
val isRemovable =
|
||||
data.getBooleanExtra(NOTIFICATION_IS_REMOVABLE_KEY, true)
|
||||
if (isRemovable) {
|
||||
notificationStorage.deleteNotification(notificationId.toString())
|
||||
}
|
||||
val dataJson = JSObject()
|
||||
val results = RemoteInput.getResultsFromIntent(data)
|
||||
val input = results?.getCharSequence(REMOTE_INPUT_KEY)
|
||||
dataJson.put("inputValue", input?.toString())
|
||||
val menuAction = data.getStringExtra(ACTION_INTENT_KEY)
|
||||
dismissVisibleNotification(notificationId)
|
||||
dataJson.put("actionId", menuAction)
|
||||
var request: JSONObject? = null
|
||||
try {
|
||||
val notificationJsonString =
|
||||
data.getStringExtra(NOTIFICATION_OBJ_INTENT_KEY)
|
||||
if (notificationJsonString != null) {
|
||||
request = JSObject(notificationJsonString)
|
||||
}
|
||||
} catch (_: JSONException) {
|
||||
}
|
||||
dataJson.put("notification", request)
|
||||
return dataJson
|
||||
}
|
||||
|
||||
/**
|
||||
* Create notification channel
|
||||
*/
|
||||
fun createNotificationChannel() {
|
||||
// Create the NotificationChannel, but only on API 26+ because
|
||||
// the NotificationChannel class is new and not in the support library
|
||||
if (SDK_INT >= Build.VERSION_CODES.O) {
|
||||
val name: CharSequence = "Default"
|
||||
val description = "Default"
|
||||
val importance = NotificationManager.IMPORTANCE_DEFAULT
|
||||
val channel = NotificationChannel(DEFAULT_NOTIFICATION_CHANNEL_ID, name, importance)
|
||||
channel.description = description
|
||||
val audioAttributes = AudioAttributes.Builder()
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
|
||||
.setUsage(AudioAttributes.USAGE_ALARM)
|
||||
.build()
|
||||
val soundUri = getDefaultSoundUrl(context)
|
||||
if (soundUri != null) {
|
||||
channel.setSound(soundUri, audioAttributes)
|
||||
}
|
||||
// Register the channel with the system; you can't change the importance
|
||||
// or other notification behaviors after this
|
||||
val notificationManager = context.getSystemService(
|
||||
NotificationManager::class.java
|
||||
)
|
||||
notificationManager.createNotificationChannel(channel)
|
||||
}
|
||||
}
|
||||
|
||||
private fun trigger(notificationManager: NotificationManagerCompat, notification: Notification): Int {
|
||||
dismissVisibleNotification(notification.id)
|
||||
cancelTimerForNotification(notification.id)
|
||||
buildNotification(notificationManager, notification)
|
||||
|
||||
return notification.id
|
||||
}
|
||||
|
||||
fun schedule(notification: Notification): Int {
|
||||
val notificationManager = NotificationManagerCompat.from(context)
|
||||
return trigger(notificationManager, notification)
|
||||
}
|
||||
|
||||
fun schedule(notifications: List<Notification>): List<Int> {
|
||||
val ids = mutableListOf<Int>()
|
||||
val notificationManager = NotificationManagerCompat.from(context)
|
||||
|
||||
for (notification in notifications) {
|
||||
val id = trigger(notificationManager, notification)
|
||||
ids.add(id)
|
||||
}
|
||||
|
||||
return ids
|
||||
}
|
||||
|
||||
// TODO Progressbar support
|
||||
// TODO System categories (DO_NOT_DISTURB etc.)
|
||||
// TODO use NotificationCompat.MessagingStyle for latest API
|
||||
// TODO expandable notification NotificationCompat.MessagingStyle
|
||||
// TODO media style notification support NotificationCompat.MediaStyle
|
||||
@SuppressLint("MissingPermission")
|
||||
private fun buildNotification(
|
||||
notificationManager: NotificationManagerCompat,
|
||||
notification: Notification,
|
||||
) {
|
||||
val channelId = notification.channelId ?: DEFAULT_NOTIFICATION_CHANNEL_ID
|
||||
val mBuilder = NotificationCompat.Builder(
|
||||
context, channelId
|
||||
)
|
||||
.setContentTitle(notification.title)
|
||||
.setContentText(notification.body)
|
||||
.setAutoCancel(notification.isAutoCancel)
|
||||
.setOngoing(notification.isOngoing)
|
||||
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
||||
.setGroupSummary(notification.isGroupSummary)
|
||||
if (notification.largeBody != null) {
|
||||
// support multiline text
|
||||
mBuilder.setStyle(
|
||||
NotificationCompat.BigTextStyle()
|
||||
.bigText(notification.largeBody)
|
||||
.setSummaryText(notification.summary)
|
||||
)
|
||||
} else if (notification.inboxLines != null) {
|
||||
val inboxStyle = NotificationCompat.InboxStyle()
|
||||
for (line in notification.inboxLines ?: listOf()) {
|
||||
inboxStyle.addLine(line)
|
||||
}
|
||||
inboxStyle.setBigContentTitle(notification.title)
|
||||
inboxStyle.setSummaryText(notification.summary)
|
||||
mBuilder.setStyle(inboxStyle)
|
||||
}
|
||||
val sound = notification.getSound(context, getDefaultSound(context))
|
||||
if (sound != null) {
|
||||
val soundUri = Uri.parse(sound)
|
||||
// Grant permission to use sound
|
||||
context.grantUriPermission(
|
||||
"com.android.systemui",
|
||||
soundUri,
|
||||
Intent.FLAG_GRANT_READ_URI_PERMISSION
|
||||
)
|
||||
mBuilder.setSound(soundUri)
|
||||
mBuilder.setDefaults(android.app.Notification.DEFAULT_VIBRATE or android.app.Notification.DEFAULT_LIGHTS)
|
||||
} else {
|
||||
mBuilder.setDefaults(android.app.Notification.DEFAULT_ALL)
|
||||
}
|
||||
val group = notification.group
|
||||
if (group != null) {
|
||||
mBuilder.setGroup(group)
|
||||
if (notification.isGroupSummary) {
|
||||
mBuilder.setSubText(notification.summary)
|
||||
}
|
||||
}
|
||||
mBuilder.setVisibility(notification.visibility ?: NotificationCompat.VISIBILITY_PRIVATE)
|
||||
mBuilder.setOnlyAlertOnce(true)
|
||||
mBuilder.setSmallIcon(notification.getSmallIcon(context, getDefaultSmallIcon(context)))
|
||||
mBuilder.setLargeIcon(notification.getLargeIcon(context))
|
||||
val iconColor = notification.getIconColor(config?.iconColor ?: "")
|
||||
if (iconColor.isNotEmpty()) {
|
||||
try {
|
||||
mBuilder.color = Color.parseColor(iconColor)
|
||||
} catch (ex: IllegalArgumentException) {
|
||||
throw Exception("Invalid color provided. Must be a hex string (ex: #ff0000")
|
||||
}
|
||||
}
|
||||
createActionIntents(notification, mBuilder)
|
||||
// notificationId is a unique int for each notification that you must define
|
||||
val buildNotification = mBuilder.build()
|
||||
if (notification.schedule != null) {
|
||||
triggerScheduledNotification(buildNotification, notification)
|
||||
} else {
|
||||
notificationManager.notify(notification.id, buildNotification)
|
||||
try {
|
||||
NotificationPlugin.triggerNotification(notification)
|
||||
} catch (_: JSONException) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create intents for open/dismiss actions
|
||||
private fun createActionIntents(
|
||||
notification: Notification,
|
||||
mBuilder: NotificationCompat.Builder
|
||||
) {
|
||||
// Open intent
|
||||
val intent = buildIntent(notification, DEFAULT_PRESS_ACTION)
|
||||
var flags = PendingIntent.FLAG_CANCEL_CURRENT
|
||||
if (SDK_INT >= Build.VERSION_CODES.S) {
|
||||
flags = flags or PendingIntent.FLAG_MUTABLE
|
||||
}
|
||||
val pendingIntent = PendingIntent.getActivity(context, notification.id, intent, flags)
|
||||
mBuilder.setContentIntent(pendingIntent)
|
||||
|
||||
// Build action types
|
||||
val actionTypeId = notification.actionTypeId
|
||||
if (actionTypeId != null) {
|
||||
val actionGroup = storage.getActionGroup(actionTypeId)
|
||||
for (notificationAction in actionGroup) {
|
||||
// TODO Add custom icons to actions
|
||||
val actionIntent = buildIntent(notification, notificationAction!!.id)
|
||||
val actionPendingIntent = PendingIntent.getActivity(
|
||||
context,
|
||||
(notification.id) + notificationAction.id.hashCode(),
|
||||
actionIntent,
|
||||
flags
|
||||
)
|
||||
val actionBuilder: NotificationCompat.Action.Builder = NotificationCompat.Action.Builder(
|
||||
R.drawable.ic_transparent,
|
||||
notificationAction.title,
|
||||
actionPendingIntent
|
||||
)
|
||||
if (notificationAction.input == true) {
|
||||
val remoteInput = RemoteInput.Builder(REMOTE_INPUT_KEY).setLabel(
|
||||
notificationAction.title
|
||||
).build()
|
||||
actionBuilder.addRemoteInput(remoteInput)
|
||||
}
|
||||
mBuilder.addAction(actionBuilder.build())
|
||||
}
|
||||
}
|
||||
|
||||
// Dismiss intent
|
||||
val dissmissIntent = Intent(
|
||||
context,
|
||||
NotificationDismissReceiver::class.java
|
||||
)
|
||||
dissmissIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
|
||||
dissmissIntent.putExtra(NOTIFICATION_INTENT_KEY, notification.id)
|
||||
dissmissIntent.putExtra(ACTION_INTENT_KEY, "dismiss")
|
||||
val schedule = notification.schedule
|
||||
dissmissIntent.putExtra(
|
||||
NOTIFICATION_IS_REMOVABLE_KEY,
|
||||
schedule == null || schedule.isRemovable()
|
||||
)
|
||||
flags = 0
|
||||
if (SDK_INT >= Build.VERSION_CODES.S) {
|
||||
flags = PendingIntent.FLAG_MUTABLE
|
||||
}
|
||||
val deleteIntent =
|
||||
PendingIntent.getBroadcast(context, notification.id, dissmissIntent, flags)
|
||||
mBuilder.setDeleteIntent(deleteIntent)
|
||||
}
|
||||
|
||||
private fun buildIntent(notification: Notification, action: String?): Intent {
|
||||
val intent = if (activity != null) {
|
||||
Intent(context, activity.javaClass)
|
||||
} else {
|
||||
val packageName = context.packageName
|
||||
context.packageManager.getLaunchIntentForPackage(packageName)!!
|
||||
}
|
||||
intent.action = Intent.ACTION_MAIN
|
||||
intent.addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
|
||||
intent.putExtra(NOTIFICATION_INTENT_KEY, notification.id)
|
||||
intent.putExtra(ACTION_INTENT_KEY, action)
|
||||
intent.putExtra(NOTIFICATION_OBJ_INTENT_KEY, notification.sourceJson)
|
||||
val schedule = notification.schedule
|
||||
intent.putExtra(NOTIFICATION_IS_REMOVABLE_KEY, schedule == null || schedule.isRemovable())
|
||||
return intent
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a notification trigger, such as triggering each N seconds, or
|
||||
* on a certain date "shape" (such as every first of the month)
|
||||
*/
|
||||
// TODO support different AlarmManager.RTC modes depending on priority
|
||||
@SuppressLint("SimpleDateFormat")
|
||||
private fun triggerScheduledNotification(notification: android.app.Notification, request: Notification) {
|
||||
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
|
||||
val schedule = request.schedule
|
||||
val notificationIntent = Intent(
|
||||
context,
|
||||
TimedNotificationPublisher::class.java
|
||||
)
|
||||
notificationIntent.putExtra(NOTIFICATION_INTENT_KEY, request.id)
|
||||
notificationIntent.putExtra(TimedNotificationPublisher.NOTIFICATION_KEY, notification)
|
||||
var flags = PendingIntent.FLAG_CANCEL_CURRENT
|
||||
if (SDK_INT >= Build.VERSION_CODES.S) {
|
||||
flags = flags or PendingIntent.FLAG_MUTABLE
|
||||
}
|
||||
var pendingIntent =
|
||||
PendingIntent.getBroadcast(context, request.id, notificationIntent, flags)
|
||||
|
||||
when (schedule) {
|
||||
is NotificationSchedule.At -> {
|
||||
if (schedule.date.time < Date().time) {
|
||||
Logger.error(Logger.tags("Notification"), "Scheduled time must be *after* current time", null)
|
||||
return
|
||||
}
|
||||
if (schedule.repeating) {
|
||||
val interval: Long = schedule.date.time - Date().time
|
||||
alarmManager.setRepeating(AlarmManager.RTC, schedule.date.time, interval, pendingIntent)
|
||||
} else {
|
||||
setExactIfPossible(alarmManager, schedule, schedule.date.time, pendingIntent)
|
||||
}
|
||||
}
|
||||
is NotificationSchedule.Interval -> {
|
||||
val trigger = schedule.interval.nextTrigger(Date())
|
||||
notificationIntent.putExtra(TimedNotificationPublisher.CRON_KEY, schedule.interval.toMatchString())
|
||||
pendingIntent =
|
||||
PendingIntent.getBroadcast(context, request.id, notificationIntent, flags)
|
||||
setExactIfPossible(alarmManager, schedule, trigger, pendingIntent)
|
||||
val sdf = SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
|
||||
Logger.debug(
|
||||
Logger.tags("Notification"),
|
||||
"notification " + request.id + " will next fire at " + sdf.format(Date(trigger))
|
||||
)
|
||||
}
|
||||
is NotificationSchedule.Every -> {
|
||||
val everyInterval = getIntervalTime(schedule.interval, schedule.count)
|
||||
val startTime: Long = Date().time + everyInterval
|
||||
alarmManager.setRepeating(AlarmManager.RTC, startTime, everyInterval, pendingIntent)
|
||||
}
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("ObsoleteSdkInt", "MissingPermission")
|
||||
private fun setExactIfPossible(
|
||||
alarmManager: AlarmManager,
|
||||
schedule: NotificationSchedule,
|
||||
trigger: Long,
|
||||
pendingIntent: PendingIntent
|
||||
) {
|
||||
if (SDK_INT >= Build.VERSION_CODES.S && !alarmManager.canScheduleExactAlarms()) {
|
||||
if (SDK_INT >= Build.VERSION_CODES.M && schedule.allowWhileIdle()) {
|
||||
alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, trigger, pendingIntent)
|
||||
} else {
|
||||
alarmManager[AlarmManager.RTC, trigger] = pendingIntent
|
||||
}
|
||||
} else {
|
||||
if (SDK_INT >= Build.VERSION_CODES.M && schedule.allowWhileIdle()) {
|
||||
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, trigger, pendingIntent)
|
||||
} else {
|
||||
alarmManager.setExact(AlarmManager.RTC, trigger, pendingIntent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun cancel(notifications: List<Int>) {
|
||||
for (id in notifications) {
|
||||
dismissVisibleNotification(id)
|
||||
cancelTimerForNotification(id)
|
||||
storage.deleteNotification(id.toString())
|
||||
}
|
||||
}
|
||||
|
||||
private fun cancelTimerForNotification(notificationId: Int) {
|
||||
val intent = Intent(context, TimedNotificationPublisher::class.java)
|
||||
var flags = 0
|
||||
if (SDK_INT >= Build.VERSION_CODES.S) {
|
||||
flags = PendingIntent.FLAG_MUTABLE
|
||||
}
|
||||
val pi = PendingIntent.getBroadcast(context, notificationId, intent, flags)
|
||||
if (pi != null) {
|
||||
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
|
||||
alarmManager.cancel(pi)
|
||||
}
|
||||
}
|
||||
|
||||
private fun dismissVisibleNotification(notificationId: Int) {
|
||||
val notificationManager = NotificationManagerCompat.from(
|
||||
context
|
||||
)
|
||||
notificationManager.cancel(notificationId)
|
||||
}
|
||||
|
||||
fun areNotificationsEnabled(): Boolean {
|
||||
val notificationManager = NotificationManagerCompat.from(context)
|
||||
return notificationManager.areNotificationsEnabled()
|
||||
}
|
||||
|
||||
private fun getDefaultSoundUrl(context: Context): Uri? {
|
||||
val soundId = getDefaultSound(context)
|
||||
return if (soundId != AssetUtils.RESOURCE_ID_ZERO_VALUE) {
|
||||
Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.packageName + "/" + soundId)
|
||||
} else null
|
||||
}
|
||||
|
||||
private fun getDefaultSound(context: Context): Int {
|
||||
if (defaultSoundID != AssetUtils.RESOURCE_ID_ZERO_VALUE) return defaultSoundID
|
||||
var resId: Int = AssetUtils.RESOURCE_ID_ZERO_VALUE
|
||||
val soundConfigResourceName = AssetUtils.getResourceBaseName(config?.sound)
|
||||
if (soundConfigResourceName != null) {
|
||||
resId = AssetUtils.getResourceID(context, soundConfigResourceName, "raw")
|
||||
}
|
||||
defaultSoundID = resId
|
||||
return resId
|
||||
}
|
||||
|
||||
private fun getDefaultSmallIcon(context: Context): Int {
|
||||
if (defaultSmallIconID != AssetUtils.RESOURCE_ID_ZERO_VALUE) return defaultSmallIconID
|
||||
var resId: Int = AssetUtils.RESOURCE_ID_ZERO_VALUE
|
||||
val smallIconConfigResourceName = AssetUtils.getResourceBaseName(config?.icon)
|
||||
if (smallIconConfigResourceName != null) {
|
||||
resId = AssetUtils.getResourceID(context, smallIconConfigResourceName, "drawable")
|
||||
}
|
||||
if (resId == AssetUtils.RESOURCE_ID_ZERO_VALUE) {
|
||||
resId = android.R.drawable.ic_dialog_info
|
||||
}
|
||||
defaultSmallIconID = resId
|
||||
return resId
|
||||
}
|
||||
}
|
||||
|
||||
class NotificationDismissReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
val intExtra =
|
||||
intent.getIntExtra(NOTIFICATION_INTENT_KEY, Int.MIN_VALUE)
|
||||
if (intExtra == Int.MIN_VALUE) {
|
||||
Logger.error(Logger.tags("Notification"), "Invalid notification dismiss operation", null)
|
||||
return
|
||||
}
|
||||
val isRemovable =
|
||||
intent.getBooleanExtra(NOTIFICATION_IS_REMOVABLE_KEY, true)
|
||||
if (isRemovable) {
|
||||
val notificationStorage = NotificationStorage(context, ObjectMapper())
|
||||
notificationStorage.deleteNotification(intExtra.toString())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class TimedNotificationPublisher : BroadcastReceiver() {
|
||||
/**
|
||||
* Restore and present notification
|
||||
*/
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
val notificationManager =
|
||||
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||
val notification = if (SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
intent.getParcelableExtra(
|
||||
NOTIFICATION_KEY,
|
||||
android.app.Notification::class.java
|
||||
)
|
||||
} else {
|
||||
getParcelableExtraLegacy(intent, NOTIFICATION_KEY)
|
||||
}
|
||||
notification?.`when` = System.currentTimeMillis()
|
||||
val id = intent.getIntExtra(NOTIFICATION_INTENT_KEY, Int.MIN_VALUE)
|
||||
if (id == Int.MIN_VALUE) {
|
||||
Logger.error(Logger.tags("Notification"), "No valid id supplied", null)
|
||||
}
|
||||
val storage = NotificationStorage(context, ObjectMapper())
|
||||
|
||||
val savedNotification = storage.getSavedNotification(id.toString())
|
||||
if (savedNotification != null) {
|
||||
NotificationPlugin.triggerNotification(savedNotification)
|
||||
}
|
||||
|
||||
notificationManager.notify(id, notification)
|
||||
if (!rescheduleNotificationIfNeeded(context, intent, id)) {
|
||||
storage.deleteNotification(id.toString())
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private fun getParcelableExtraLegacy(intent: Intent, string: String): android.app.Notification? {
|
||||
return intent.getParcelableExtra(string)
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission", "SimpleDateFormat")
|
||||
private fun rescheduleNotificationIfNeeded(context: Context, intent: Intent, id: Int): Boolean {
|
||||
val dateString = intent.getStringExtra(CRON_KEY)
|
||||
if (dateString != null) {
|
||||
val date = DateMatch.fromMatchString(dateString)
|
||||
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
|
||||
val trigger = date.nextTrigger(Date())
|
||||
val clone = intent.clone() as Intent
|
||||
var flags = PendingIntent.FLAG_CANCEL_CURRENT
|
||||
if (SDK_INT >= Build.VERSION_CODES.S) {
|
||||
flags = flags or PendingIntent.FLAG_MUTABLE
|
||||
}
|
||||
val pendingIntent = PendingIntent.getBroadcast(context, id, clone, flags)
|
||||
if (SDK_INT >= Build.VERSION_CODES.S && !alarmManager.canScheduleExactAlarms()) {
|
||||
alarmManager[AlarmManager.RTC, trigger] = pendingIntent
|
||||
} else {
|
||||
alarmManager.setExact(AlarmManager.RTC, trigger, pendingIntent)
|
||||
}
|
||||
val sdf = SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
|
||||
Logger.debug(
|
||||
Logger.tags("Notification"),
|
||||
"notification " + id + " will next fire at " + sdf.format(Date(trigger))
|
||||
)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
companion object {
|
||||
var NOTIFICATION_KEY = "NotificationPublisher.notification"
|
||||
var CRON_KEY = "NotificationPublisher.cron"
|
||||
}
|
||||
}
|
||||
|
||||
class LocalNotificationRestoreReceiver : BroadcastReceiver() {
|
||||
@SuppressLint("ObsoleteSdkInt")
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (SDK_INT >= Build.VERSION_CODES.N) {
|
||||
val um = context.getSystemService(
|
||||
UserManager::class.java
|
||||
)
|
||||
if (um == null || !um.isUserUnlocked) return
|
||||
}
|
||||
val storage = NotificationStorage(context, ObjectMapper())
|
||||
val ids = storage.getSavedNotificationIds()
|
||||
val notifications = mutableListOf<Notification>()
|
||||
val updatedNotifications = mutableListOf<Notification>()
|
||||
for (id in ids) {
|
||||
val notification = storage.getSavedNotification(id) ?: continue
|
||||
val schedule = notification.schedule
|
||||
if (schedule != null && schedule is NotificationSchedule.At) {
|
||||
val at: Date = schedule.date
|
||||
if (at.before(Date())) {
|
||||
// modify the scheduled date in order to show notifications that would have been delivered while device was off.
|
||||
val newDateTime = Date().time + 15 * 1000
|
||||
schedule.date = Date(newDateTime)
|
||||
updatedNotifications.add(notification)
|
||||
}
|
||||
}
|
||||
notifications.add(notification)
|
||||
}
|
||||
if (updatedNotifications.size > 0) {
|
||||
storage.appendNotifications(updatedNotifications)
|
||||
}
|
||||
|
||||
var config: PluginConfig? = null
|
||||
try {
|
||||
config = PluginManager.loadConfig(context, "notification", PluginConfig::class.java)
|
||||
} catch (ex: Exception) {
|
||||
ex.printStackTrace()
|
||||
}
|
||||
val notificationManager = TauriNotificationManager(storage, null, context, config)
|
||||
notificationManager.schedule(notifications)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="16dp"
|
||||
android:height="16dp"
|
||||
android:viewportHeight="108"
|
||||
android:viewportWidth="108">
|
||||
|
||||
<path
|
||||
android:width="1dp"
|
||||
android:color="@android:color/transparent" />
|
||||
|
||||
</vector>
|
||||
@@ -0,0 +1,21 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.notification
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
import org.junit.Assert.*
|
||||
|
||||
/**
|
||||
* Example local unit test, which will execute on the development machine (host).
|
||||
*
|
||||
* See [testing documentation](http://d.android.com/tools/testing).
|
||||
*/
|
||||
class ExampleUnitTest {
|
||||
@Test
|
||||
fun addition_isCorrect() {
|
||||
assertEquals(4, 2 + 2)
|
||||
}
|
||||
}
|
||||
1
plugins/notification/api-iife.js
Normal file
1
plugins/notification/api-iife.js
Normal file
@@ -0,0 +1 @@
|
||||
if("__TAURI__"in window){var __TAURI_PLUGIN_NOTIFICATION__=function(i,n){"use strict";var e,t,o;i.ScheduleEvery=void 0,(e=i.ScheduleEvery||(i.ScheduleEvery={})).Year="year",e.Month="month",e.TwoWeeks="twoWeeks",e.Week="week",e.Day="day",e.Hour="hour",e.Minute="minute",e.Second="second";return i.Importance=void 0,(t=i.Importance||(i.Importance={}))[t.None=0]="None",t[t.Min=1]="Min",t[t.Low=2]="Low",t[t.Default=3]="Default",t[t.High=4]="High",i.Visibility=void 0,(o=i.Visibility||(i.Visibility={}))[o.Secret=-1]="Secret",o[o.Private=0]="Private",o[o.Public=1]="Public",i.Schedule=class{static at(i,n=!1,e=!1){return{at:{date:i,repeating:n,allowWhileIdle:e},interval:void 0,every:void 0}}static interval(i,n=!1){return{at:void 0,interval:{interval:i,allowWhileIdle:n},every:void 0}}static every(i,n,e=!1){return{at:void 0,interval:void 0,every:{interval:i,count:n,allowWhileIdle:e}}}},i.active=async function(){return await n.invoke("plugin:notification|get_active")},i.cancel=async function(i){await n.invoke("plugin:notification|cancel",{notifications:i})},i.cancelAll=async function(){await n.invoke("plugin:notification|cancel")},i.channels=async function(){return await n.invoke("plugin:notification|list_channels")},i.createChannel=async function(i){await n.invoke("plugin:notification|create_channel",{...i})},i.isPermissionGranted=async function(){return"default"!==window.Notification.permission?await Promise.resolve("granted"===window.Notification.permission):await n.invoke("plugin:notification|is_permission_granted")},i.onAction=async function(i){return await n.addPluginListener("notification","actionPerformed",i)},i.onNotificationReceived=async function(i){return await n.addPluginListener("notification","notification",i)},i.pending=async function(){return await n.invoke("plugin:notification|get_pending")},i.registerActionTypes=async function(i){await n.invoke("plugin:notification|register_action_types",{types:i})},i.removeActive=async function(i){await n.invoke("plugin:notification|remove_active",{notifications:i})},i.removeAllActive=async function(){await n.invoke("plugin:notification|remove_active")},i.removeChannel=async function(i){await n.invoke("plugin:notification|delete_channel",{id:i})},i.requestPermission=async function(){return await window.Notification.requestPermission()},i.sendNotification=function(i){"string"==typeof i?new window.Notification(i):new window.Notification(i.title,i)},i}({},window.__TAURI__.core);Object.defineProperty(window.__TAURI__,"notification",{value:__TAURI_PLUGIN_NOTIFICATION__})}
|
||||
BIN
plugins/notification/banner.png
Normal file
BIN
plugins/notification/banner.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 59 KiB |
36
plugins/notification/build.rs
Normal file
36
plugins/notification/build.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
const COMMANDS: &[&str] = &[
|
||||
"notify",
|
||||
"request_permission",
|
||||
"is_permission_granted",
|
||||
"register_action_types",
|
||||
"register_listener",
|
||||
"remove_listener",
|
||||
"cancel",
|
||||
"get_pending",
|
||||
"remove_active",
|
||||
"get_active",
|
||||
"check_permissions",
|
||||
"show",
|
||||
"batch",
|
||||
"list_channels",
|
||||
"delete_channel",
|
||||
"create_channel",
|
||||
"permission_state",
|
||||
];
|
||||
|
||||
fn main() {
|
||||
let result = tauri_plugin::Builder::new(COMMANDS)
|
||||
.global_api_script_path("./api-iife.js")
|
||||
.android_path("android")
|
||||
.ios_path("ios")
|
||||
.try_build();
|
||||
|
||||
// when building documentation for Android the plugin build result is always Err() and is irrelevant to the crate documentation build
|
||||
if !(cfg!(docsrs) && std::env::var("TARGET").unwrap().contains("android")) {
|
||||
result.unwrap();
|
||||
}
|
||||
}
|
||||
967
plugins/notification/guest-js/index.ts
Normal file
967
plugins/notification/guest-js/index.ts
Normal file
@@ -0,0 +1,967 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/**
|
||||
* Send toast notifications (brief auto-expiring OS window element) to your user.
|
||||
* Can also be used with the Notification Web API.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import {
|
||||
invoke,
|
||||
type PluginListener,
|
||||
addPluginListener
|
||||
} from '@tauri-apps/api/core'
|
||||
|
||||
export type { PermissionState } from '@tauri-apps/api/core'
|
||||
|
||||
/**
|
||||
* Options to send a notification.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
interface Options {
|
||||
/**
|
||||
* The notification identifier to reference this object later. Must be a 32-bit integer.
|
||||
*/
|
||||
id?: number
|
||||
/**
|
||||
* Identifier of the {@link Channel} that deliveres this notification.
|
||||
*
|
||||
* If the channel does not exist, the notification won't fire.
|
||||
* Make sure the channel exists with {@link listChannels} and {@link createChannel}.
|
||||
*/
|
||||
channelId?: string
|
||||
/**
|
||||
* The title displayed on the notification.
|
||||
*/
|
||||
title: string
|
||||
/**
|
||||
* Optional notification body.
|
||||
* */
|
||||
body?: string
|
||||
/**
|
||||
* Schedule this notification to fire on a later time or a fixed interval.
|
||||
*/
|
||||
schedule?: Schedule
|
||||
/**
|
||||
* Multiline text.
|
||||
* Changes the notification style to big text.
|
||||
* Cannot be used with `inboxLines`.
|
||||
*/
|
||||
largeBody?: string
|
||||
/**
|
||||
* Detail text for the notification with `largeBody`, `inboxLines` or `groupSummary`.
|
||||
*/
|
||||
summary?: string
|
||||
/**
|
||||
* Defines an action type for this notification.
|
||||
*/
|
||||
actionTypeId?: string
|
||||
/**
|
||||
* Identifier used to group multiple notifications.
|
||||
*
|
||||
* https://developer.apple.com/documentation/usernotifications/unmutablenotificationcontent/1649872-threadidentifier
|
||||
*/
|
||||
group?: string
|
||||
/**
|
||||
* Instructs the system that this notification is the summary of a group on Android.
|
||||
*/
|
||||
groupSummary?: boolean
|
||||
/**
|
||||
* The sound resource name or file path for the notification.
|
||||
*
|
||||
* ## Platform-specific behavior:
|
||||
*
|
||||
* - On macOS: use system sounds (e.g., "Ping", "Blow") or sound files in the app bundle
|
||||
* - On Linux: use XDG theme sounds (e.g., "message-new-instant") or file paths
|
||||
* - On Windows: use file paths to sound files (.wav format)
|
||||
* - On Mobile: use resource names
|
||||
*/
|
||||
sound?: string
|
||||
/**
|
||||
* List of lines to add to the notification.
|
||||
* Changes the notification style to inbox.
|
||||
* Cannot be used with `largeBody`.
|
||||
*
|
||||
* Only supports up to 5 lines.
|
||||
*/
|
||||
inboxLines?: string[]
|
||||
/**
|
||||
* Notification icon.
|
||||
*
|
||||
* On Android the icon must be placed in the app's `res/drawable` folder.
|
||||
*/
|
||||
icon?: string
|
||||
/**
|
||||
* Notification large icon (Android).
|
||||
*
|
||||
* The icon must be placed in the app's `res/drawable` folder.
|
||||
*/
|
||||
largeIcon?: string
|
||||
/**
|
||||
* Icon color on Android.
|
||||
*/
|
||||
iconColor?: string
|
||||
/**
|
||||
* Notification attachments.
|
||||
*/
|
||||
attachments?: Attachment[]
|
||||
/**
|
||||
* Extra payload to store in the notification.
|
||||
*/
|
||||
extra?: Record<string, unknown>
|
||||
/**
|
||||
* If true, the notification cannot be dismissed by the user on Android.
|
||||
*
|
||||
* An application service must manage the dismissal of the notification.
|
||||
* It is typically used to indicate a background task that is pending (e.g. a file download)
|
||||
* or the user is engaged with (e.g. playing music).
|
||||
*/
|
||||
ongoing?: boolean
|
||||
/**
|
||||
* Automatically cancel the notification when the user clicks on it.
|
||||
*/
|
||||
autoCancel?: boolean
|
||||
/**
|
||||
* Changes the notification presentation to be silent on iOS (no badge, no sound, not listed).
|
||||
*/
|
||||
silent?: boolean
|
||||
/**
|
||||
* Notification visibility.
|
||||
*/
|
||||
visibility?: Visibility
|
||||
/**
|
||||
* Sets the number of items this notification represents on Android.
|
||||
*/
|
||||
number?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* The set of date fields a scheduled notification must match to be delivered.
|
||||
*
|
||||
* Fields that are not set match any value, so the notification fires on every date
|
||||
* whose remaining components match.
|
||||
*/
|
||||
interface ScheduleInterval {
|
||||
/**
|
||||
* The year the notification fires on.
|
||||
*/
|
||||
year?: number
|
||||
/**
|
||||
* The month of the year the notification fires on.
|
||||
*/
|
||||
month?: number
|
||||
/**
|
||||
* The day of the month the notification fires on.
|
||||
*/
|
||||
day?: number
|
||||
/**
|
||||
* The day of the week the notification fires on.
|
||||
*
|
||||
* 1 - Sunday
|
||||
* 2 - Monday
|
||||
* 3 - Tuesday
|
||||
* 4 - Wednesday
|
||||
* 5 - Thursday
|
||||
* 6 - Friday
|
||||
* 7 - Saturday
|
||||
*/
|
||||
weekday?: number
|
||||
/**
|
||||
* The hour of the day the notification fires on, in the 24-hour clock.
|
||||
*/
|
||||
hour?: number
|
||||
/**
|
||||
* The minute of the hour the notification fires on.
|
||||
*/
|
||||
minute?: number
|
||||
/**
|
||||
* The second of the minute the notification fires on.
|
||||
*/
|
||||
second?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* The unit of the repeating interval used by {@link Schedule.every}.
|
||||
*/
|
||||
enum ScheduleEvery {
|
||||
/**
|
||||
* The notification repeats every year.
|
||||
*
|
||||
* On Android a year is approximated as 52 weeks.
|
||||
*/
|
||||
Year = 'year',
|
||||
/**
|
||||
* The notification repeats every month.
|
||||
*
|
||||
* On Android a month is approximated as 30 days.
|
||||
*/
|
||||
Month = 'month',
|
||||
/**
|
||||
* The notification repeats every two weeks.
|
||||
*/
|
||||
TwoWeeks = 'twoWeeks',
|
||||
/**
|
||||
* The notification repeats every week.
|
||||
*/
|
||||
Week = 'week',
|
||||
/**
|
||||
* The notification repeats every day.
|
||||
*/
|
||||
Day = 'day',
|
||||
/**
|
||||
* The notification repeats every hour.
|
||||
*/
|
||||
Hour = 'hour',
|
||||
/**
|
||||
* The notification repeats every minute.
|
||||
*/
|
||||
Minute = 'minute',
|
||||
/**
|
||||
* The notification repeats every second.
|
||||
*
|
||||
* Not supported on iOS, where repeating triggers must be at least a minute apart.
|
||||
*/
|
||||
Second = 'second'
|
||||
}
|
||||
|
||||
/**
|
||||
* Defines when a scheduled notification is delivered.
|
||||
*
|
||||
* Build one with the static {@link Schedule.at}, {@link Schedule.interval} and
|
||||
* {@link Schedule.every} helpers, then pass it to the `schedule` option of a notification.
|
||||
* Scheduling is only supported on mobile; desktop notifications are always shown immediately.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
class Schedule {
|
||||
/**
|
||||
* Set when the notification fires at a fixed date and time.
|
||||
*/
|
||||
at:
|
||||
| {
|
||||
date: Date
|
||||
repeating: boolean
|
||||
allowWhileIdle: boolean
|
||||
}
|
||||
| undefined
|
||||
|
||||
/**
|
||||
* Set when the notification fires whenever the current date matches the given fields.
|
||||
*/
|
||||
interval:
|
||||
| {
|
||||
interval: ScheduleInterval
|
||||
allowWhileIdle: boolean
|
||||
}
|
||||
| undefined
|
||||
|
||||
/**
|
||||
* Set when the notification repeats on a fixed interval.
|
||||
*/
|
||||
every:
|
||||
| {
|
||||
interval: ScheduleEvery
|
||||
count: number
|
||||
allowWhileIdle: boolean
|
||||
}
|
||||
| undefined
|
||||
|
||||
/**
|
||||
* Creates a schedule that fires the notification at the given date and time.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Schedule, sendNotification } from '@tauri-apps/plugin-notification';
|
||||
* const schedule = Schedule.at(new Date(Date.now() + 60 * 1000));
|
||||
* sendNotification({ title: 'Tauri', body: 'One minute later', schedule });
|
||||
* ```
|
||||
*
|
||||
* @param date The date and time the notification fires at. It must be in the future.
|
||||
* @param repeating Whether the notification keeps repeating, using the duration between the moment it is scheduled and `date` as the interval. The interval must be at least one minute on iOS.
|
||||
* @param allowWhileIdle Whether the notification is allowed to fire while the device is in low-power idle (Doze) mode. Android only.
|
||||
*
|
||||
* @returns A schedule that can be assigned to the `schedule` option of a notification.
|
||||
*/
|
||||
static at(date: Date, repeating = false, allowWhileIdle = false): Schedule {
|
||||
return {
|
||||
at: { date, repeating, allowWhileIdle },
|
||||
interval: undefined,
|
||||
every: undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a schedule that fires the notification whenever the current date matches
|
||||
* every field set on the given interval.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Schedule, sendNotification } from '@tauri-apps/plugin-notification';
|
||||
* // fires every day at 9:00
|
||||
* const schedule = Schedule.interval({ hour: 9, minute: 0 });
|
||||
* sendNotification({ title: 'Tauri', body: 'Good morning', schedule });
|
||||
* ```
|
||||
*
|
||||
* @param interval The date fields the current date must match for the notification to fire.
|
||||
* @param allowWhileIdle Whether the notification is allowed to fire while the device is in low-power idle (Doze) mode. Android only.
|
||||
*
|
||||
* @returns A schedule that can be assigned to the `schedule` option of a notification.
|
||||
*/
|
||||
static interval(
|
||||
interval: ScheduleInterval,
|
||||
allowWhileIdle = false
|
||||
): Schedule {
|
||||
return {
|
||||
at: undefined,
|
||||
interval: { interval, allowWhileIdle },
|
||||
every: undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a schedule that repeatedly fires the notification, once every `count` interval units.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Schedule, ScheduleEvery, sendNotification } from '@tauri-apps/plugin-notification';
|
||||
* const schedule = Schedule.every(ScheduleEvery.Hour, 2);
|
||||
* sendNotification({ title: 'Tauri', body: 'Every two hours', schedule });
|
||||
* ```
|
||||
*
|
||||
* @param kind The unit of the repeating interval.
|
||||
* @param count How many interval units elapse between each notification.
|
||||
* @param allowWhileIdle Whether the notification is allowed to fire while the device is in low-power idle (Doze) mode. Android only.
|
||||
*
|
||||
* @returns A schedule that can be assigned to the `schedule` option of a notification.
|
||||
*/
|
||||
static every(
|
||||
kind: ScheduleEvery,
|
||||
count: number,
|
||||
allowWhileIdle = false
|
||||
): Schedule {
|
||||
return {
|
||||
at: undefined,
|
||||
interval: undefined,
|
||||
every: { interval: kind, count, allowWhileIdle }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attachment of a notification.
|
||||
*/
|
||||
interface Attachment {
|
||||
/** Attachment identifier. */
|
||||
id: string
|
||||
/** Attachment URL. Accepts the `asset` and `file` protocols. */
|
||||
url: string
|
||||
}
|
||||
|
||||
/**
|
||||
* A button the user can tap on a notification, belonging to an {@link ActionType}.
|
||||
*
|
||||
* Only used on mobile. On Android only the identifier, the title and the input flag are used.
|
||||
*/
|
||||
interface Action {
|
||||
/**
|
||||
* The identifier of this action, reported back when the user triggers it.
|
||||
*/
|
||||
id: string
|
||||
/**
|
||||
* The text displayed on the action button.
|
||||
*/
|
||||
title: string
|
||||
/**
|
||||
* Whether the device must be unlocked for the action to run. iOS only.
|
||||
*/
|
||||
requiresAuthentication?: boolean
|
||||
/**
|
||||
* Whether the app is brought to the foreground when the action is triggered. iOS only.
|
||||
*/
|
||||
foreground?: boolean
|
||||
/**
|
||||
* Whether the action is displayed as destructive, usually in red. iOS only.
|
||||
*/
|
||||
destructive?: boolean
|
||||
/**
|
||||
* Whether triggering the action lets the user type a text response.
|
||||
*/
|
||||
input?: boolean
|
||||
/**
|
||||
* The text displayed on the button that submits the text input. iOS only.
|
||||
*/
|
||||
inputButtonTitle?: string
|
||||
/**
|
||||
* The placeholder displayed on the empty text input field. iOS only.
|
||||
*/
|
||||
inputPlaceholder?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* A group of {@link Action}s a notification can display, referenced by the
|
||||
* `actionTypeId` option of a notification.
|
||||
*
|
||||
* Register it with {@link registerActionTypes} before sending a notification that uses it.
|
||||
* Only used on mobile.
|
||||
*/
|
||||
interface ActionType {
|
||||
/**
|
||||
* The identifier of this action type
|
||||
*/
|
||||
id: string
|
||||
/**
|
||||
* The list of associated actions
|
||||
*/
|
||||
actions: Action[]
|
||||
/**
|
||||
* The placeholder shown instead of the notification body when previews are hidden. iOS only.
|
||||
*/
|
||||
hiddenPreviewsBodyPlaceholder?: string
|
||||
/**
|
||||
* Whether the app is notified when the user dismisses the notification. iOS only.
|
||||
*/
|
||||
customDismissAction?: boolean
|
||||
/**
|
||||
* Whether the notification can be displayed in a CarPlay environment. iOS only.
|
||||
*/
|
||||
allowInCarPlay?: boolean
|
||||
/**
|
||||
* Whether the notification title is shown even when previews are hidden. iOS only.
|
||||
*/
|
||||
hiddenPreviewsShowTitle?: boolean
|
||||
/**
|
||||
* Whether the notification subtitle is shown even when previews are hidden. iOS only.
|
||||
*/
|
||||
hiddenPreviewsShowSubtitle?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* A notification that was scheduled and has not been delivered yet.
|
||||
*
|
||||
* Returned by {@link pending}, which is only supported on mobile.
|
||||
*/
|
||||
interface PendingNotification {
|
||||
/**
|
||||
* The identifier of the notification.
|
||||
*/
|
||||
id: number
|
||||
/**
|
||||
* The title of the notification, if it was set.
|
||||
*/
|
||||
title?: string
|
||||
/**
|
||||
* The body of the notification, if it was set.
|
||||
*/
|
||||
body?: string
|
||||
/**
|
||||
* The schedule that determines when the notification is delivered.
|
||||
*/
|
||||
schedule: Schedule
|
||||
}
|
||||
|
||||
/**
|
||||
* A notification that was delivered and is still visible in the notification center.
|
||||
*
|
||||
* Returned by {@link active}, which is only supported on mobile. Which fields are
|
||||
* populated depends on the platform, since Android and iOS expose different
|
||||
* information about delivered notifications.
|
||||
*/
|
||||
interface ActiveNotification {
|
||||
/**
|
||||
* The identifier of the notification.
|
||||
*/
|
||||
id: number
|
||||
/**
|
||||
* The tag the notification was posted with. Android only.
|
||||
*/
|
||||
tag?: string
|
||||
/**
|
||||
* The title of the notification, if it was set.
|
||||
*/
|
||||
title?: string
|
||||
/**
|
||||
* The body of the notification, if it was set.
|
||||
*/
|
||||
body?: string
|
||||
/**
|
||||
* The identifier of the group the notification belongs to. Android only.
|
||||
*/
|
||||
group?: string
|
||||
/**
|
||||
* Whether the notification is the summary of its group. Android only.
|
||||
*/
|
||||
groupSummary: boolean
|
||||
/**
|
||||
* The platform extras attached to the notification, as string values. Android only.
|
||||
*/
|
||||
data: Record<string, string>
|
||||
/**
|
||||
* The extra payload that was stored in the notification.
|
||||
*/
|
||||
extra: Record<string, unknown>
|
||||
/**
|
||||
* The attachments of the notification. iOS only.
|
||||
*/
|
||||
attachments: Attachment[]
|
||||
/**
|
||||
* The identifier of the action type the notification was registered with. iOS only.
|
||||
*/
|
||||
actionTypeId?: string
|
||||
/**
|
||||
* The schedule the notification was delivered with, if it was scheduled.
|
||||
*/
|
||||
schedule?: Schedule
|
||||
/**
|
||||
* The sound resource name of the notification. iOS only.
|
||||
*/
|
||||
sound?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* How much the notifications of a {@link Channel} interrupt the user.
|
||||
*
|
||||
* It maps to the Android `NotificationManager.IMPORTANCE_*` constants and is only used on Android.
|
||||
*/
|
||||
enum Importance {
|
||||
/**
|
||||
* The notifications are not shown.
|
||||
*/
|
||||
None = 0,
|
||||
/**
|
||||
* The notifications are only shown in the shade, below the fold, without a status bar icon.
|
||||
*/
|
||||
Min,
|
||||
/**
|
||||
* The notifications are shown without a sound.
|
||||
*/
|
||||
Low,
|
||||
/**
|
||||
* The notifications are shown and make a sound.
|
||||
*
|
||||
* This is the value used when the channel does not define an importance.
|
||||
*/
|
||||
Default,
|
||||
/**
|
||||
* The notifications are shown, make a sound and pop up as a heads-up notification.
|
||||
*/
|
||||
High
|
||||
}
|
||||
|
||||
/**
|
||||
* How much of a notification is shown on the lock screen.
|
||||
*
|
||||
* It maps to the Android `Notification.VISIBILITY_*` constants and is only used on Android.
|
||||
*/
|
||||
enum Visibility {
|
||||
/**
|
||||
* The notification is not shown on the lock screen at all.
|
||||
*/
|
||||
Secret = -1,
|
||||
/**
|
||||
* The notification is shown on the lock screen with its sensitive content hidden.
|
||||
*
|
||||
* This is the value used when the channel does not define a visibility.
|
||||
*/
|
||||
Private,
|
||||
/**
|
||||
* The notification is shown in full on the lock screen.
|
||||
*/
|
||||
Public
|
||||
}
|
||||
|
||||
/**
|
||||
* A notification channel, the category users configure notification behavior on.
|
||||
*
|
||||
* Notifications reference a channel through their `channelId` option and are not delivered
|
||||
* when the channel does not exist. Channels are only supported on Android.
|
||||
*/
|
||||
interface Channel {
|
||||
/**
|
||||
* The identifier of this channel.
|
||||
*/
|
||||
id: string
|
||||
/**
|
||||
* The user visible name of this channel.
|
||||
*/
|
||||
name: string
|
||||
/**
|
||||
* The user visible description of this channel.
|
||||
*/
|
||||
description?: string
|
||||
/**
|
||||
* The name of the sound resource played by the notifications of this channel.
|
||||
*
|
||||
* The resource must be placed in the app's `res/raw` folder.
|
||||
*/
|
||||
sound?: string
|
||||
/**
|
||||
* Whether the notifications of this channel blink the device light.
|
||||
*/
|
||||
lights?: boolean
|
||||
/**
|
||||
* The color of the device light, as a color string such as `#ff0000`.
|
||||
*/
|
||||
lightColor?: string
|
||||
/**
|
||||
* Whether the notifications of this channel vibrate the device.
|
||||
*/
|
||||
vibration?: boolean
|
||||
/**
|
||||
* How much the notifications of this channel interrupt the user.
|
||||
*/
|
||||
importance?: Importance
|
||||
/**
|
||||
* How much of the notifications of this channel is shown on the lock screen.
|
||||
*/
|
||||
visibility?: Visibility
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the permission to send notifications is granted.
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { isPermissionGranted } from '@tauri-apps/plugin-notification';
|
||||
* const permissionGranted = await isPermissionGranted();
|
||||
* ```
|
||||
*
|
||||
* @returns A promise resolving to whether the permission to send notifications is granted.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
async function isPermissionGranted(): Promise<boolean> {
|
||||
if (window.Notification.permission !== 'default') {
|
||||
return await Promise.resolve(window.Notification.permission === 'granted')
|
||||
}
|
||||
return await invoke('plugin:notification|is_permission_granted')
|
||||
}
|
||||
|
||||
/**
|
||||
* Requests the permission to send notifications.
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { isPermissionGranted, requestPermission } from '@tauri-apps/plugin-notification';
|
||||
* let permissionGranted = await isPermissionGranted();
|
||||
* if (!permissionGranted) {
|
||||
* const permission = await requestPermission();
|
||||
* permissionGranted = permission === 'granted';
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @returns A promise resolving to whether the user granted the permission or not.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
async function requestPermission(): Promise<NotificationPermission> {
|
||||
return await window.Notification.requestPermission()
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a notification to the user.
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { isPermissionGranted, requestPermission, sendNotification } from '@tauri-apps/plugin-notification';
|
||||
* let permissionGranted = await isPermissionGranted();
|
||||
* if (!permissionGranted) {
|
||||
* const permission = await requestPermission();
|
||||
* permissionGranted = permission === 'granted';
|
||||
* }
|
||||
* if (permissionGranted) {
|
||||
* sendNotification('Tauri is awesome!');
|
||||
* sendNotification({ title: 'TAURI', body: 'Tauri is awesome!' });
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param options The notification content, or the notification title when a string is given.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
function sendNotification(options: Options | string): void {
|
||||
if (typeof options === 'string') {
|
||||
new window.Notification(options)
|
||||
} else {
|
||||
new window.Notification(options.title, options)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register actions that are performed when the user clicks on the notification.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { registerActionTypes } from '@tauri-apps/plugin-notification';
|
||||
* await registerActionTypes([{
|
||||
* id: 'tauri',
|
||||
* actions: [{
|
||||
* id: 'my-action',
|
||||
* title: 'Settings'
|
||||
* }]
|
||||
* }])
|
||||
* ```
|
||||
*
|
||||
* @param types The action types to register.
|
||||
*
|
||||
* @returns A promise indicating the success or failure of the operation.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
async function registerActionTypes(types: ActionType[]): Promise<void> {
|
||||
await invoke('plugin:notification|register_action_types', { types })
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the list of pending notifications.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { pending } from '@tauri-apps/plugin-notification';
|
||||
* const pendingNotifications = await pending();
|
||||
* ```
|
||||
*
|
||||
* @returns A promise resolving to the list of pending notifications.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
async function pending(): Promise<PendingNotification[]> {
|
||||
return await invoke('plugin:notification|get_pending')
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancels the pending notifications with the given list of identifiers.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { cancel } from '@tauri-apps/plugin-notification';
|
||||
* await cancel([-34234, 23432, 4311]);
|
||||
* ```
|
||||
*
|
||||
* @param notifications The identifiers of the pending notifications to cancel.
|
||||
*
|
||||
* @returns A promise indicating the success or failure of the operation.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
async function cancel(notifications: number[]): Promise<void> {
|
||||
await invoke('plugin:notification|cancel', { notifications })
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancels all pending notifications.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { cancelAll } from '@tauri-apps/plugin-notification';
|
||||
* await cancelAll();
|
||||
* ```
|
||||
*
|
||||
* @returns A promise indicating the success or failure of the operation.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
async function cancelAll(): Promise<void> {
|
||||
await invoke('plugin:notification|cancel')
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the list of active notifications.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { active } from '@tauri-apps/plugin-notification';
|
||||
* const activeNotifications = await active();
|
||||
* ```
|
||||
*
|
||||
* @returns A promise resolving to the list of active notifications.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
async function active(): Promise<ActiveNotification[]> {
|
||||
return await invoke('plugin:notification|get_active')
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the active notifications with the given list of identifiers.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { removeActive } from '@tauri-apps/plugin-notification';
|
||||
* await removeActive([{ id: -34234 }, { id: 23432 }, { id: 4311 }])
|
||||
* ```
|
||||
*
|
||||
* @param notifications The active notifications to remove, identified by their id and, on Android, their optional tag.
|
||||
*
|
||||
* @returns A promise indicating the success or failure of the operation.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
async function removeActive(
|
||||
notifications: Array<{ id: number; tag?: string }>
|
||||
): Promise<void> {
|
||||
await invoke('plugin:notification|remove_active', { notifications })
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes all active notifications.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { removeAllActive } from '@tauri-apps/plugin-notification';
|
||||
* await removeAllActive()
|
||||
* ```
|
||||
*
|
||||
* @returns A promise indicating the success or failure of the operation.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
async function removeAllActive(): Promise<void> {
|
||||
await invoke('plugin:notification|remove_active')
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a notification channel.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { createChannel, Importance, Visibility } from '@tauri-apps/plugin-notification';
|
||||
* await createChannel({
|
||||
* id: 'new-messages',
|
||||
* name: 'New Messages',
|
||||
* lights: true,
|
||||
* vibration: true,
|
||||
* importance: Importance.Default,
|
||||
* visibility: Visibility.Private
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @param channel The channel to create.
|
||||
*
|
||||
* @returns A promise indicating the success or failure of the operation.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
async function createChannel(channel: Channel): Promise<void> {
|
||||
await invoke('plugin:notification|create_channel', { ...channel })
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the channel with the given identifier.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { removeChannel } from '@tauri-apps/plugin-notification';
|
||||
* await removeChannel('new-messages');
|
||||
* ```
|
||||
*
|
||||
* @param id The identifier of the channel to remove.
|
||||
*
|
||||
* @returns A promise indicating the success or failure of the operation.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
async function removeChannel(id: string): Promise<void> {
|
||||
await invoke('plugin:notification|delete_channel', { id })
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the list of notification channels.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { channels } from '@tauri-apps/plugin-notification';
|
||||
* const notificationChannels = await channels();
|
||||
* ```
|
||||
*
|
||||
* @returns A promise resolving to the list of notification channels.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
async function channels(): Promise<Channel[]> {
|
||||
return await invoke('plugin:notification|list_channels')
|
||||
}
|
||||
|
||||
/**
|
||||
* Listens to notifications that are delivered while the app is running.
|
||||
*
|
||||
* Only emitted on mobile.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { onNotificationReceived } from '@tauri-apps/plugin-notification';
|
||||
* const unlisten = await onNotificationReceived((notification) => {
|
||||
* console.log(`received notification: ${notification.title}`);
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @param cb The closure called with the notification that was delivered.
|
||||
*
|
||||
* @returns A promise resolving to a listener that can be used to stop listening for the event.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
async function onNotificationReceived(
|
||||
cb: (notification: Options) => void
|
||||
): Promise<PluginListener> {
|
||||
return await addPluginListener('notification', 'notification', cb)
|
||||
}
|
||||
|
||||
/**
|
||||
* Listens to the actions the user performs on a notification.
|
||||
*
|
||||
* Only emitted on mobile, for notifications that reference an action type
|
||||
* registered with {@link registerActionTypes}.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { onAction } from '@tauri-apps/plugin-notification';
|
||||
* const unlisten = await onAction((notification) => {
|
||||
* console.log(`user acted on notification: ${notification.title}`);
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @param cb The closure called with the notification the action was performed on.
|
||||
*
|
||||
* @returns A promise resolving to a listener that can be used to stop listening for the event.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
async function onAction(
|
||||
cb: (notification: Options) => void
|
||||
): Promise<PluginListener> {
|
||||
return await addPluginListener('notification', 'actionPerformed', cb)
|
||||
}
|
||||
|
||||
export type {
|
||||
Attachment,
|
||||
Options,
|
||||
Action,
|
||||
ActionType,
|
||||
PendingNotification,
|
||||
ActiveNotification,
|
||||
Channel,
|
||||
ScheduleInterval
|
||||
}
|
||||
|
||||
export {
|
||||
Importance,
|
||||
Visibility,
|
||||
sendNotification,
|
||||
requestPermission,
|
||||
isPermissionGranted,
|
||||
registerActionTypes,
|
||||
pending,
|
||||
cancel,
|
||||
cancelAll,
|
||||
active,
|
||||
removeActive,
|
||||
removeAllActive,
|
||||
createChannel,
|
||||
removeChannel,
|
||||
channels,
|
||||
onNotificationReceived,
|
||||
onAction,
|
||||
Schedule,
|
||||
ScheduleEvery
|
||||
}
|
||||
107
plugins/notification/guest-js/init.ts
Normal file
107
plugins/notification/guest-js/init.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/**
|
||||
* Webview script injected by the notification plugin.
|
||||
*
|
||||
* It replaces `window.Notification` with an implementation backed by the plugin, so the
|
||||
* standard Notification Web API sends OS notifications, and keeps
|
||||
* `window.Notification.permission` and `window.Notification.requestPermission` in sync
|
||||
* with the permission state reported by the plugin.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
import type { PermissionState } from '@tauri-apps/api/core'
|
||||
import type { Options } from './index'
|
||||
;(function () {
|
||||
let permissionSettable = false
|
||||
let permissionValue = 'default'
|
||||
|
||||
async function isPermissionGranted(): Promise<boolean> {
|
||||
if (window.Notification.permission !== 'default') {
|
||||
return await Promise.resolve(window.Notification.permission === 'granted')
|
||||
}
|
||||
// Windows always grants the permission, and asking the backend for it from
|
||||
// the init script makes the WebView throw a STATUS_ACCESS_VIOLATION on
|
||||
// remote websites, so answer it here instead of invoking.
|
||||
// @ts-expect-error __TEMPLATE_windows__ will be replaced in rust before it's injected.
|
||||
if (__TEMPLATE_windows__) {
|
||||
return true
|
||||
}
|
||||
return await invoke('plugin:notification|is_permission_granted')
|
||||
}
|
||||
|
||||
function setNotificationPermission(value: NotificationPermission): void {
|
||||
permissionSettable = true
|
||||
// @ts-expect-error we can actually set this value on the webview
|
||||
window.Notification.permission = value
|
||||
permissionSettable = false
|
||||
}
|
||||
|
||||
async function requestPermission(): Promise<PermissionState> {
|
||||
return await invoke<PermissionState>(
|
||||
'plugin:notification|request_permission'
|
||||
).then((permission) => {
|
||||
setNotificationPermission(
|
||||
permission === 'prompt' || permission === 'prompt-with-rationale'
|
||||
? 'default'
|
||||
: permission
|
||||
)
|
||||
return permission
|
||||
})
|
||||
}
|
||||
|
||||
async function sendNotification(options: string | Options): Promise<void> {
|
||||
if (typeof options === 'object') {
|
||||
Object.freeze(options)
|
||||
}
|
||||
|
||||
await invoke('plugin:notification|notify', {
|
||||
options:
|
||||
typeof options === 'string'
|
||||
? {
|
||||
title: options
|
||||
}
|
||||
: options
|
||||
})
|
||||
}
|
||||
|
||||
// @ts-expect-error unfortunately we can't implement the whole type, so we overwrite it with our own version
|
||||
window.Notification = function (title, options) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const opts = options || {}
|
||||
void sendNotification(
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
||||
Object.assign(opts, {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
title
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
// @ts-expect-error tauri does not have sync IPC :(
|
||||
window.Notification.requestPermission = requestPermission
|
||||
|
||||
Object.defineProperty(window.Notification, 'permission', {
|
||||
enumerable: true,
|
||||
get: () => permissionValue,
|
||||
set: (v) => {
|
||||
if (!permissionSettable) {
|
||||
throw new Error('Readonly property')
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
permissionValue = v
|
||||
}
|
||||
})
|
||||
|
||||
void isPermissionGranted().then(function (response) {
|
||||
if (response === null) {
|
||||
setNotificationPermission('default')
|
||||
} else {
|
||||
setNotificationPermission(response ? 'granted' : 'denied')
|
||||
}
|
||||
})
|
||||
})()
|
||||
10
plugins/notification/ios/.gitignore
vendored
Normal file
10
plugins/notification/ios/.gitignore
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
.DS_Store
|
||||
/.build
|
||||
/Packages
|
||||
/*.xcodeproj
|
||||
xcuserdata/
|
||||
DerivedData/
|
||||
.swiftpm/config/registries.json
|
||||
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
|
||||
.netrc
|
||||
Package.resolved
|
||||
34
plugins/notification/ios/Package.swift
Normal file
34
plugins/notification/ios/Package.swift
Normal file
@@ -0,0 +1,34 @@
|
||||
// swift-tools-version:5.5
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "tauri-plugin-notification",
|
||||
platforms: [
|
||||
.macOS(.v10_13),
|
||||
.iOS(.v13),
|
||||
],
|
||||
products: [
|
||||
// Products define the executables and libraries a package produces, and make them visible to other packages.
|
||||
.library(
|
||||
name: "tauri-plugin-notification",
|
||||
type: .static,
|
||||
targets: ["tauri-plugin-notification"])
|
||||
],
|
||||
dependencies: [
|
||||
.package(name: "Tauri", path: "../.tauri/tauri-api")
|
||||
],
|
||||
targets: [
|
||||
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
|
||||
// Targets can depend on other targets in this package, and on products in packages this package depends on.
|
||||
.target(
|
||||
name: "tauri-plugin-notification",
|
||||
dependencies: [
|
||||
.byName(name: "Tauri")
|
||||
],
|
||||
path: "Sources")
|
||||
]
|
||||
)
|
||||
3
plugins/notification/ios/README.md
Normal file
3
plugins/notification/ios/README.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# Tauri Plugin {{ plugin_name_original }}
|
||||
|
||||
A description of this package.
|
||||
286
plugins/notification/ios/Sources/Notification.swift
Normal file
286
plugins/notification/ios/Sources/Notification.swift
Normal file
@@ -0,0 +1,286 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Tauri
|
||||
import UserNotifications
|
||||
|
||||
enum NotificationError: LocalizedError {
|
||||
case triggerRepeatIntervalTooShort
|
||||
case attachmentFileNotFound(path: String)
|
||||
case attachmentUnableToCreate(String)
|
||||
case pastScheduledTime
|
||||
case invalidDate(String)
|
||||
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .triggerRepeatIntervalTooShort:
|
||||
return "Schedule interval too short, must be a least 1 minute"
|
||||
case .attachmentFileNotFound(let path):
|
||||
return "Unable to find file \(path) for attachment"
|
||||
case .attachmentUnableToCreate(let error):
|
||||
return "Failed to create attachment: \(error)"
|
||||
case .pastScheduledTime:
|
||||
return "Scheduled time must be *after* current time"
|
||||
case .invalidDate(let date):
|
||||
return "Could not parse date \(date)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func makeNotificationContent(_ notification: Notification) throws -> UNNotificationContent {
|
||||
let content = UNMutableNotificationContent()
|
||||
content.title = NSString.localizedUserNotificationString(
|
||||
forKey: notification.title, arguments: nil)
|
||||
if let body = notification.body {
|
||||
content.body = NSString.localizedUserNotificationString(
|
||||
forKey: body,
|
||||
arguments: nil)
|
||||
}
|
||||
|
||||
var userInfo: [String: Any] = [:]
|
||||
|
||||
if let extra = notification.extra {
|
||||
userInfo["__EXTRA__"] = extra
|
||||
}
|
||||
|
||||
if let schedule = notification.schedule {
|
||||
userInfo["__SCHEDULE__"] = scheduleToDictionary(schedule)
|
||||
}
|
||||
|
||||
content.userInfo = userInfo
|
||||
|
||||
if let actionTypeId = notification.actionTypeId {
|
||||
content.categoryIdentifier = actionTypeId
|
||||
}
|
||||
|
||||
if let threadIdentifier = notification.group {
|
||||
content.threadIdentifier = threadIdentifier
|
||||
}
|
||||
|
||||
if let summaryArgument = notification.summary {
|
||||
content.summaryArgument = summaryArgument
|
||||
}
|
||||
|
||||
if let sound = notification.sound {
|
||||
content.sound = UNNotificationSound(named: UNNotificationSoundName(sound))
|
||||
}
|
||||
|
||||
if let attachments = notification.attachments {
|
||||
content.attachments = try makeAttachments(attachments)
|
||||
}
|
||||
|
||||
return content
|
||||
}
|
||||
|
||||
func scheduleToDictionary(_ schedule: NotificationSchedule) -> [String: Any] {
|
||||
switch schedule {
|
||||
case .at(let date, let repeating):
|
||||
return [
|
||||
"type": "at",
|
||||
"date": date,
|
||||
"repeating": repeating
|
||||
]
|
||||
case .interval(let interval):
|
||||
return [
|
||||
"type": "interval",
|
||||
"interval": scheduleIntervalToDictionary(interval)
|
||||
]
|
||||
case .every(let interval, let count):
|
||||
return [
|
||||
"type": "every",
|
||||
"interval": interval.rawValue,
|
||||
"count": count
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
func scheduleIntervalToDictionary(_ interval: ScheduleInterval) -> [String: Any] {
|
||||
var dict: [String: Any] = [:]
|
||||
|
||||
if let year = interval.year {
|
||||
dict["year"] = year
|
||||
}
|
||||
if let month = interval.month {
|
||||
dict["month"] = month
|
||||
}
|
||||
if let day = interval.day {
|
||||
dict["day"] = day
|
||||
}
|
||||
if let weekday = interval.weekday {
|
||||
dict["weekday"] = weekday
|
||||
}
|
||||
if let hour = interval.hour {
|
||||
dict["hour"] = hour
|
||||
}
|
||||
if let minute = interval.minute {
|
||||
dict["minute"] = minute
|
||||
}
|
||||
if let second = interval.second {
|
||||
dict["second"] = second
|
||||
}
|
||||
|
||||
return dict
|
||||
}
|
||||
|
||||
func makeAttachments(_ attachments: [NotificationAttachment]) throws -> [UNNotificationAttachment] {
|
||||
var createdAttachments = [UNNotificationAttachment]()
|
||||
|
||||
for attachment in attachments {
|
||||
|
||||
guard let urlObject = makeAttachmentUrl(attachment.url) else {
|
||||
throw NotificationError.attachmentFileNotFound(path: attachment.url)
|
||||
}
|
||||
|
||||
let options = attachment.options != nil ? makeAttachmentOptions(attachment.options!) : nil
|
||||
|
||||
do {
|
||||
let newAttachment = try UNNotificationAttachment(
|
||||
identifier: attachment.id, url: urlObject, options: options)
|
||||
createdAttachments.append(newAttachment)
|
||||
} catch {
|
||||
throw NotificationError.attachmentUnableToCreate(error.localizedDescription)
|
||||
}
|
||||
}
|
||||
|
||||
return createdAttachments
|
||||
}
|
||||
|
||||
func makeAttachmentUrl(_ path: String) -> URL? {
|
||||
return URL(string: path)
|
||||
}
|
||||
|
||||
func makeAttachmentOptions(_ options: NotificationAttachmentOptions) -> [AnyHashable: Any] {
|
||||
var opts: [AnyHashable: Any] = [:]
|
||||
|
||||
if let value = options.iosUNNotificationAttachmentOptionsTypeHintKey {
|
||||
opts[UNNotificationAttachmentOptionsTypeHintKey] = value
|
||||
}
|
||||
if let value = options.iosUNNotificationAttachmentOptionsThumbnailHiddenKey {
|
||||
opts[UNNotificationAttachmentOptionsThumbnailHiddenKey] = value
|
||||
}
|
||||
if let value = options.iosUNNotificationAttachmentOptionsThumbnailClippingRectKey {
|
||||
opts[UNNotificationAttachmentOptionsThumbnailClippingRectKey] = value
|
||||
}
|
||||
if let value = options
|
||||
.iosUNNotificationAttachmentOptionsThumbnailTimeKey
|
||||
|
||||
{
|
||||
opts[UNNotificationAttachmentOptionsThumbnailTimeKey] = value
|
||||
}
|
||||
return opts
|
||||
}
|
||||
|
||||
func handleScheduledNotification(_ schedule: NotificationSchedule) throws
|
||||
-> UNNotificationTrigger?
|
||||
{
|
||||
switch schedule {
|
||||
case .at(let date, let repeating):
|
||||
let dateFormatter = DateFormatter()
|
||||
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
|
||||
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
|
||||
|
||||
if let at = dateFormatter.date(from: date) {
|
||||
let dateInfo = Calendar.current.dateComponents(in: TimeZone.current, from: at)
|
||||
|
||||
if dateInfo.date! < Date() {
|
||||
throw NotificationError.pastScheduledTime
|
||||
}
|
||||
|
||||
let dateInterval = DateInterval(start: Date(), end: dateInfo.date!)
|
||||
|
||||
// Notifications that repeat have to be at least a minute between each other
|
||||
if repeating && dateInterval.duration < 60 {
|
||||
throw NotificationError.triggerRepeatIntervalTooShort
|
||||
}
|
||||
|
||||
return UNTimeIntervalNotificationTrigger(
|
||||
timeInterval: dateInterval.duration, repeats: repeating)
|
||||
|
||||
} else {
|
||||
throw NotificationError.invalidDate(date)
|
||||
}
|
||||
case .interval(let interval):
|
||||
let dateComponents = getDateComponents(interval)
|
||||
return UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
|
||||
case .every(let interval, let count):
|
||||
if let repeatDateInterval = getRepeatDateInterval(interval, count) {
|
||||
// Notifications that repeat have to be at least a minute between each other
|
||||
if repeatDateInterval.duration < 60 {
|
||||
throw NotificationError.triggerRepeatIntervalTooShort
|
||||
}
|
||||
|
||||
return UNTimeIntervalNotificationTrigger(
|
||||
timeInterval: repeatDateInterval.duration, repeats: true)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Given our schedule format, return a DateComponents object
|
||||
/// that only contains the components passed in.
|
||||
|
||||
func getDateComponents(_ at: ScheduleInterval) -> DateComponents {
|
||||
// var dateInfo = Calendar.current.dateComponents(in: TimeZone.current, from: Date())
|
||||
// dateInfo.calendar = Calendar.current
|
||||
var dateInfo = DateComponents()
|
||||
|
||||
if let year = at.year {
|
||||
dateInfo.year = year
|
||||
}
|
||||
if let month = at.month {
|
||||
dateInfo.month = month
|
||||
}
|
||||
if let day = at.day {
|
||||
dateInfo.day = day
|
||||
}
|
||||
if let hour = at.hour {
|
||||
dateInfo.hour = hour
|
||||
}
|
||||
if let minute = at.minute {
|
||||
dateInfo.minute = minute
|
||||
}
|
||||
if let second = at.second {
|
||||
dateInfo.second = second
|
||||
}
|
||||
if let weekday = at.weekday {
|
||||
dateInfo.weekday = weekday
|
||||
}
|
||||
return dateInfo
|
||||
}
|
||||
|
||||
/// Compute the difference between the string representation of a date
|
||||
/// interval and today. For example, if every is "month", then we
|
||||
/// return the interval between today and a month from today.
|
||||
|
||||
func getRepeatDateInterval(_ every: ScheduleEveryKind, _ count: Int) -> DateInterval? {
|
||||
let cal = Calendar.current
|
||||
let now = Date()
|
||||
switch every {
|
||||
case .year:
|
||||
let newDate = cal.date(byAdding: .year, value: count, to: now)!
|
||||
return DateInterval(start: now, end: newDate)
|
||||
case .month:
|
||||
let newDate = cal.date(byAdding: .month, value: count, to: now)!
|
||||
return DateInterval(start: now, end: newDate)
|
||||
case .twoWeeks:
|
||||
let newDate = cal.date(byAdding: .weekOfYear, value: 2 * count, to: now)!
|
||||
return DateInterval(start: now, end: newDate)
|
||||
case .week:
|
||||
let newDate = cal.date(byAdding: .weekOfYear, value: count, to: now)!
|
||||
return DateInterval(start: now, end: newDate)
|
||||
case .day:
|
||||
let newDate = cal.date(byAdding: .day, value: count, to: now)!
|
||||
return DateInterval(start: now, end: newDate)
|
||||
case .hour:
|
||||
let newDate = cal.date(byAdding: .hour, value: count, to: now)!
|
||||
return DateInterval(start: now, end: newDate)
|
||||
case .minute:
|
||||
let newDate = cal.date(byAdding: .minute, value: count, to: now)!
|
||||
return DateInterval(start: now, end: newDate)
|
||||
case .second:
|
||||
let newDate = cal.date(byAdding: .second, value: count, to: now)!
|
||||
return DateInterval(start: now, end: newDate)
|
||||
}
|
||||
}
|
||||
97
plugins/notification/ios/Sources/NotificationCategory.swift
Normal file
97
plugins/notification/ios/Sources/NotificationCategory.swift
Normal file
@@ -0,0 +1,97 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Tauri
|
||||
import UserNotifications
|
||||
|
||||
internal func makeCategories(_ actionTypes: [ActionType]) {
|
||||
var createdCategories = [UNNotificationCategory]()
|
||||
|
||||
let generalCategory = UNNotificationCategory(
|
||||
identifier: "GENERAL",
|
||||
actions: [],
|
||||
intentIdentifiers: [],
|
||||
options: .customDismissAction)
|
||||
|
||||
createdCategories.append(generalCategory)
|
||||
for type in actionTypes {
|
||||
let newActions = makeActions(type.actions)
|
||||
|
||||
// Create the custom actions for the TIMER_EXPIRED category.
|
||||
var newCategory: UNNotificationCategory?
|
||||
|
||||
newCategory = UNNotificationCategory(
|
||||
identifier: type.id,
|
||||
actions: newActions,
|
||||
intentIdentifiers: [],
|
||||
hiddenPreviewsBodyPlaceholder: type.hiddenBodyPlaceholder ?? "",
|
||||
options: makeCategoryOptions(type))
|
||||
|
||||
createdCategories.append(newCategory!)
|
||||
}
|
||||
|
||||
let center = UNUserNotificationCenter.current()
|
||||
center.setNotificationCategories(Set(createdCategories))
|
||||
}
|
||||
|
||||
func makeActions(_ actions: [Action]) -> [UNNotificationAction] {
|
||||
var createdActions = [UNNotificationAction]()
|
||||
|
||||
for action in actions {
|
||||
var newAction: UNNotificationAction
|
||||
if action.input ?? false {
|
||||
if action.inputButtonTitle != nil {
|
||||
newAction = UNTextInputNotificationAction(
|
||||
identifier: action.id,
|
||||
title: action.title,
|
||||
options: makeActionOptions(action),
|
||||
textInputButtonTitle: action.inputButtonTitle ?? "",
|
||||
textInputPlaceholder: action.inputPlaceholder ?? "")
|
||||
} else {
|
||||
newAction = UNTextInputNotificationAction(
|
||||
identifier: action.id, title: action.title, options: makeActionOptions(action))
|
||||
}
|
||||
} else {
|
||||
// Create the custom actions for the TIMER_EXPIRED category.
|
||||
newAction = UNNotificationAction(
|
||||
identifier: action.id,
|
||||
title: action.title,
|
||||
options: makeActionOptions(action))
|
||||
}
|
||||
createdActions.append(newAction)
|
||||
}
|
||||
|
||||
return createdActions
|
||||
}
|
||||
|
||||
func makeActionOptions(_ action: Action) -> UNNotificationActionOptions {
|
||||
if action.foreground ?? false {
|
||||
return .foreground
|
||||
}
|
||||
if action.destructive ?? false {
|
||||
return .destructive
|
||||
}
|
||||
if action.requiresAuthentication ?? false {
|
||||
return .authenticationRequired
|
||||
}
|
||||
return UNNotificationActionOptions(rawValue: 0)
|
||||
}
|
||||
|
||||
func makeCategoryOptions(_ type: ActionType) -> UNNotificationCategoryOptions {
|
||||
if type.customDismissAction ?? false {
|
||||
return .customDismissAction
|
||||
}
|
||||
if type.allowInCarPlay ?? false {
|
||||
return .allowInCarPlay
|
||||
}
|
||||
|
||||
if type.hiddenPreviewsShowTitle ?? false {
|
||||
return .hiddenPreviewsShowTitle
|
||||
}
|
||||
if type.hiddenPreviewsShowSubtitle ?? false {
|
||||
return .hiddenPreviewsShowSubtitle
|
||||
}
|
||||
|
||||
return UNNotificationCategoryOptions(rawValue: 0)
|
||||
}
|
||||
118
plugins/notification/ios/Sources/NotificationHandler.swift
Normal file
118
plugins/notification/ios/Sources/NotificationHandler.swift
Normal file
@@ -0,0 +1,118 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Tauri
|
||||
import UserNotifications
|
||||
|
||||
public class NotificationHandler: NSObject, NotificationHandlerProtocol {
|
||||
|
||||
public weak var plugin: Plugin?
|
||||
|
||||
private var notificationsMap = [String: Notification]()
|
||||
|
||||
internal func saveNotification(_ key: String, _ notification: Notification) {
|
||||
notificationsMap.updateValue(notification, forKey: key)
|
||||
}
|
||||
|
||||
public func requestPermissions(with completion: ((Bool, Error?) -> Void)? = nil) {
|
||||
let center = UNUserNotificationCenter.current()
|
||||
center.requestAuthorization(options: [.badge, .alert, .sound]) { (granted, error) in
|
||||
completion?(granted, error)
|
||||
}
|
||||
}
|
||||
|
||||
public func checkPermissions(with completion: ((UNAuthorizationStatus) -> Void)? = nil) {
|
||||
let center = UNUserNotificationCenter.current()
|
||||
center.getNotificationSettings { settings in
|
||||
completion?(settings.authorizationStatus)
|
||||
}
|
||||
}
|
||||
|
||||
public func willPresent(notification: UNNotification) -> UNNotificationPresentationOptions {
|
||||
let notificationData = toActiveNotification(notification.request)
|
||||
try? self.plugin?.trigger("notification", data: notificationData)
|
||||
|
||||
if let options = notificationsMap[notification.request.identifier] {
|
||||
if options.silent ?? false {
|
||||
return UNNotificationPresentationOptions.init(rawValue: 0)
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
.badge,
|
||||
.sound,
|
||||
.alert,
|
||||
]
|
||||
}
|
||||
|
||||
public func didReceive(response: UNNotificationResponse) {
|
||||
let originalNotificationRequest = response.notification.request
|
||||
let actionId = response.actionIdentifier
|
||||
|
||||
var actionIdValue: String
|
||||
// We turn the two default actions (open/dismiss) into generic strings
|
||||
if actionId == UNNotificationDefaultActionIdentifier {
|
||||
actionIdValue = "tap"
|
||||
} else if actionId == UNNotificationDismissActionIdentifier {
|
||||
actionIdValue = "dismiss"
|
||||
} else {
|
||||
actionIdValue = actionId
|
||||
}
|
||||
|
||||
var inputValue: String? = nil
|
||||
// If the type of action was for an input type, get the value
|
||||
if let inputType = response as? UNTextInputNotificationResponse {
|
||||
inputValue = inputType.userText
|
||||
}
|
||||
|
||||
try? self.plugin?.trigger(
|
||||
"actionPerformed",
|
||||
data: ReceivedNotification(
|
||||
actionId: actionIdValue,
|
||||
inputValue: inputValue,
|
||||
notification: toActiveNotification(originalNotificationRequest)
|
||||
))
|
||||
}
|
||||
|
||||
func toActiveNotification(_ request: UNNotificationRequest) -> ActiveNotification {
|
||||
let notificationRequest = notificationsMap[request.identifier]!
|
||||
return ActiveNotification(
|
||||
id: Int(request.identifier) ?? -1,
|
||||
title: request.content.title,
|
||||
body: request.content.body,
|
||||
sound: notificationRequest.sound ?? "",
|
||||
actionTypeId: request.content.categoryIdentifier,
|
||||
attachments: notificationRequest.attachments
|
||||
)
|
||||
}
|
||||
|
||||
func toPendingNotification(_ request: UNNotificationRequest) -> PendingNotification {
|
||||
return PendingNotification(
|
||||
id: Int(request.identifier) ?? -1,
|
||||
title: request.content.title,
|
||||
body: request.content.body
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
struct PendingNotification: Encodable {
|
||||
let id: Int
|
||||
let title: String
|
||||
let body: String
|
||||
}
|
||||
|
||||
struct ActiveNotification: Encodable {
|
||||
let id: Int
|
||||
let title: String
|
||||
let body: String
|
||||
let sound: String
|
||||
let actionTypeId: String
|
||||
let attachments: [NotificationAttachment]?
|
||||
}
|
||||
|
||||
struct ReceivedNotification: Encodable {
|
||||
let actionId: String
|
||||
let inputValue: String?
|
||||
let notification: ActiveNotification
|
||||
}
|
||||
47
plugins/notification/ios/Sources/NotificationManager.swift
Normal file
47
plugins/notification/ios/Sources/NotificationManager.swift
Normal file
@@ -0,0 +1,47 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import UserNotifications
|
||||
|
||||
@objc public protocol NotificationHandlerProtocol {
|
||||
func willPresent(notification: UNNotification) -> UNNotificationPresentationOptions
|
||||
func didReceive(response: UNNotificationResponse)
|
||||
}
|
||||
|
||||
@objc public class NotificationManager: NSObject, UNUserNotificationCenterDelegate {
|
||||
public weak var notificationHandler: NotificationHandlerProtocol?
|
||||
|
||||
override init() {
|
||||
super.init()
|
||||
let center = UNUserNotificationCenter.current()
|
||||
center.delegate = self
|
||||
}
|
||||
|
||||
public func userNotificationCenter(
|
||||
_ center: UNUserNotificationCenter,
|
||||
willPresent notification: UNNotification,
|
||||
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
|
||||
) {
|
||||
var presentationOptions: UNNotificationPresentationOptions? = nil
|
||||
|
||||
if notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self) != true {
|
||||
presentationOptions = notificationHandler?.willPresent(notification: notification)
|
||||
}
|
||||
|
||||
completionHandler(presentationOptions ?? [])
|
||||
}
|
||||
|
||||
public func userNotificationCenter(
|
||||
_ center: UNUserNotificationCenter,
|
||||
didReceive response: UNNotificationResponse,
|
||||
withCompletionHandler completionHandler: @escaping () -> Void
|
||||
) {
|
||||
if response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self) != true {
|
||||
notificationHandler?.didReceive(response: response)
|
||||
}
|
||||
|
||||
completionHandler()
|
||||
}
|
||||
}
|
||||
290
plugins/notification/ios/Sources/NotificationPlugin.swift
Normal file
290
plugins/notification/ios/Sources/NotificationPlugin.swift
Normal file
@@ -0,0 +1,290 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftRs
|
||||
import Tauri
|
||||
import UIKit
|
||||
import UserNotifications
|
||||
import WebKit
|
||||
|
||||
enum ShowNotificationError: LocalizedError {
|
||||
case make(Error)
|
||||
case create(Error)
|
||||
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .make(let error):
|
||||
return "Unable to make notification: \(error)"
|
||||
case .create(let error):
|
||||
return "Unable to create notification: \(error)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum ScheduleEveryKind: String, Decodable {
|
||||
case year
|
||||
case month
|
||||
case twoWeeks
|
||||
case week
|
||||
case day
|
||||
case hour
|
||||
case minute
|
||||
case second
|
||||
}
|
||||
|
||||
struct ScheduleInterval: Decodable {
|
||||
var year: Int?
|
||||
var month: Int?
|
||||
var day: Int?
|
||||
var weekday: Int?
|
||||
var hour: Int?
|
||||
var minute: Int?
|
||||
var second: Int?
|
||||
}
|
||||
|
||||
enum NotificationSchedule: Decodable {
|
||||
case at(date: String, repeating: Bool)
|
||||
case interval(interval: ScheduleInterval)
|
||||
case every(interval: ScheduleEveryKind, count: Int)
|
||||
}
|
||||
|
||||
struct NotificationAttachmentOptions: Codable {
|
||||
let iosUNNotificationAttachmentOptionsTypeHintKey: String?
|
||||
let iosUNNotificationAttachmentOptionsThumbnailHiddenKey: String?
|
||||
let iosUNNotificationAttachmentOptionsThumbnailClippingRectKey: String?
|
||||
let iosUNNotificationAttachmentOptionsThumbnailTimeKey: String?
|
||||
}
|
||||
|
||||
struct NotificationAttachment: Codable {
|
||||
let id: String
|
||||
let url: String
|
||||
let options: NotificationAttachmentOptions?
|
||||
}
|
||||
|
||||
struct Notification: Decodable {
|
||||
let id: Int
|
||||
var title: String
|
||||
var body: String?
|
||||
var extra: [String: String]?
|
||||
var schedule: NotificationSchedule?
|
||||
var attachments: [NotificationAttachment]?
|
||||
var sound: String?
|
||||
var group: String?
|
||||
var actionTypeId: String?
|
||||
var summary: String?
|
||||
var silent: Bool?
|
||||
}
|
||||
|
||||
struct RemoveActiveNotification: Decodable {
|
||||
let id: Int
|
||||
}
|
||||
|
||||
struct RemoveActiveArgs: Decodable {
|
||||
let notifications: [RemoveActiveNotification]
|
||||
}
|
||||
|
||||
func showNotification(invoke: Invoke, notification: Notification)
|
||||
throws -> UNNotificationRequest
|
||||
{
|
||||
var content: UNNotificationContent
|
||||
do {
|
||||
content = try makeNotificationContent(notification)
|
||||
} catch {
|
||||
throw ShowNotificationError.make(error)
|
||||
}
|
||||
|
||||
var trigger: UNNotificationTrigger?
|
||||
|
||||
do {
|
||||
if let schedule = notification.schedule {
|
||||
try trigger = handleScheduledNotification(schedule)
|
||||
}
|
||||
} catch {
|
||||
throw ShowNotificationError.create(error)
|
||||
}
|
||||
|
||||
// Schedule the request.
|
||||
let request = UNNotificationRequest(
|
||||
identifier: "\(notification.id)", content: content, trigger: trigger
|
||||
)
|
||||
|
||||
let center = UNUserNotificationCenter.current()
|
||||
center.add(request) { (error: Error?) in
|
||||
if let theError = error {
|
||||
invoke.reject(theError.localizedDescription)
|
||||
}
|
||||
}
|
||||
|
||||
return request
|
||||
}
|
||||
|
||||
struct CancelArgs: Decodable {
|
||||
// `cancelAll()` sends no list: cancel every pending notification
|
||||
let notifications: [Int]?
|
||||
}
|
||||
|
||||
struct Action: Decodable {
|
||||
let id: String
|
||||
let title: String
|
||||
var requiresAuthentication: Bool?
|
||||
var foreground: Bool?
|
||||
var destructive: Bool?
|
||||
var input: Bool?
|
||||
var inputButtonTitle: String?
|
||||
var inputPlaceholder: String?
|
||||
}
|
||||
|
||||
struct ActionType: Decodable {
|
||||
let id: String
|
||||
let actions: [Action]
|
||||
var hiddenPreviewsBodyPlaceholder: String?
|
||||
var customDismissAction: Bool?
|
||||
var allowInCarPlay: Bool?
|
||||
var hiddenPreviewsShowTitle: Bool?
|
||||
var hiddenPreviewsShowSubtitle: Bool?
|
||||
var hiddenBodyPlaceholder: String?
|
||||
}
|
||||
|
||||
struct RegisterActionTypesArgs: Decodable {
|
||||
let types: [ActionType]
|
||||
}
|
||||
|
||||
struct BatchArgs: Decodable {
|
||||
let notifications: [Notification]
|
||||
}
|
||||
|
||||
class NotificationPlugin: Plugin {
|
||||
let notificationHandler = NotificationHandler()
|
||||
let notificationManager = NotificationManager()
|
||||
|
||||
override init() {
|
||||
super.init()
|
||||
notificationManager.notificationHandler = notificationHandler
|
||||
notificationHandler.plugin = self
|
||||
}
|
||||
|
||||
@objc public func show(_ invoke: Invoke) throws {
|
||||
let notification = try invoke.parseArgs(Notification.self)
|
||||
|
||||
let request = try showNotification(invoke: invoke, notification: notification)
|
||||
notificationHandler.saveNotification(request.identifier, notification)
|
||||
invoke.resolve(Int(request.identifier) ?? -1)
|
||||
}
|
||||
|
||||
@objc public func batch(_ invoke: Invoke) throws {
|
||||
let args = try invoke.parseArgs(BatchArgs.self)
|
||||
var ids = [Int]()
|
||||
|
||||
for notification in args.notifications {
|
||||
let request = try showNotification(invoke: invoke, notification: notification)
|
||||
notificationHandler.saveNotification(request.identifier, notification)
|
||||
ids.append(Int(request.identifier) ?? -1)
|
||||
}
|
||||
|
||||
invoke.resolve(ids)
|
||||
}
|
||||
|
||||
@objc public override func requestPermissions(_ invoke: Invoke) {
|
||||
notificationHandler.requestPermissions { granted, error in
|
||||
guard error == nil else {
|
||||
invoke.reject(error!.localizedDescription)
|
||||
return
|
||||
}
|
||||
invoke.resolve(["permissionState": granted ? "granted" : "denied"])
|
||||
}
|
||||
}
|
||||
|
||||
@objc public override func checkPermissions(_ invoke: Invoke) {
|
||||
notificationHandler.checkPermissions { status in
|
||||
let permission: String
|
||||
|
||||
switch status {
|
||||
case .authorized, .ephemeral, .provisional:
|
||||
permission = "granted"
|
||||
case .denied:
|
||||
permission = "denied"
|
||||
case .notDetermined:
|
||||
permission = "prompt"
|
||||
@unknown default:
|
||||
permission = "prompt"
|
||||
}
|
||||
|
||||
invoke.resolve(["permissionState": permission])
|
||||
}
|
||||
}
|
||||
|
||||
@objc func cancel(_ invoke: Invoke) throws {
|
||||
let args = try invoke.parseArgs(CancelArgs.self)
|
||||
|
||||
if let notifications = args.notifications {
|
||||
UNUserNotificationCenter.current().removePendingNotificationRequests(
|
||||
withIdentifiers: notifications.map { String($0) }
|
||||
)
|
||||
} else {
|
||||
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
|
||||
}
|
||||
invoke.resolve()
|
||||
}
|
||||
|
||||
@objc func getPending(_ invoke: Invoke) {
|
||||
UNUserNotificationCenter.current().getPendingNotificationRequests(completionHandler: {
|
||||
(notifications) in
|
||||
let ret = notifications.compactMap({ [weak self] (notification) -> PendingNotification? in
|
||||
return self?.notificationHandler.toPendingNotification(notification)
|
||||
})
|
||||
|
||||
invoke.resolve(ret)
|
||||
})
|
||||
}
|
||||
|
||||
@objc func registerActionTypes(_ invoke: Invoke) throws {
|
||||
let args = try invoke.parseArgs(RegisterActionTypesArgs.self)
|
||||
makeCategories(args.types)
|
||||
invoke.resolve()
|
||||
}
|
||||
|
||||
@objc func removeActive(_ invoke: Invoke) {
|
||||
do {
|
||||
let args = try invoke.parseArgs(RemoveActiveArgs.self)
|
||||
UNUserNotificationCenter.current().removeDeliveredNotifications(
|
||||
withIdentifiers: args.notifications.map { String($0.id) })
|
||||
invoke.resolve()
|
||||
} catch {
|
||||
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
|
||||
DispatchQueue.main.async(execute: {
|
||||
UIApplication.shared.applicationIconBadgeNumber = 0
|
||||
})
|
||||
invoke.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
@objc func getActive(_ invoke: Invoke) {
|
||||
UNUserNotificationCenter.current().getDeliveredNotifications(completionHandler: {
|
||||
(notifications) in
|
||||
let ret = notifications.map({ (notification) -> ActiveNotification in
|
||||
return self.notificationHandler.toActiveNotification(
|
||||
notification.request)
|
||||
})
|
||||
invoke.resolve(ret)
|
||||
})
|
||||
}
|
||||
|
||||
@objc func createChannel(_ invoke: Invoke) {
|
||||
invoke.reject("not implemented")
|
||||
}
|
||||
|
||||
@objc func deleteChannel(_ invoke: Invoke) {
|
||||
invoke.reject("not implemented")
|
||||
}
|
||||
|
||||
@objc func listChannels(_ invoke: Invoke) {
|
||||
invoke.reject("not implemented")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@_cdecl("init_plugin_notification")
|
||||
func initPlugin() -> Plugin {
|
||||
return NotificationPlugin()
|
||||
}
|
||||
12
plugins/notification/ios/Tests/PluginTests/PluginTests.swift
Normal file
12
plugins/notification/ios/Tests/PluginTests/PluginTests.swift
Normal file
@@ -0,0 +1,12 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import XCTest
|
||||
@testable import ExamplePlugin
|
||||
|
||||
final class ExamplePluginTests: XCTestCase {
|
||||
func testExample() throws {
|
||||
let plugin = ExamplePlugin()
|
||||
}
|
||||
}
|
||||
29
plugins/notification/package.json
Normal file
29
plugins/notification/package.json
Normal file
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "@tauri-apps/plugin-notification",
|
||||
"version": "2.4.0",
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"authors": [
|
||||
"Tauri Programme within The Commons Conservancy"
|
||||
],
|
||||
"repository": "https://github.com/tauri-apps/plugins-workspace",
|
||||
"type": "module",
|
||||
"types": "./dist-js/index.d.ts",
|
||||
"main": "./dist-js/index.cjs",
|
||||
"module": "./dist-js/index.js",
|
||||
"exports": {
|
||||
"types": "./dist-js/index.d.ts",
|
||||
"import": "./dist-js/index.js",
|
||||
"require": "./dist-js/index.cjs"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "rollup -c"
|
||||
},
|
||||
"files": [
|
||||
"dist-js",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2.11.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-batch"
|
||||
description = "Enables the batch command without any pre-configured scope."
|
||||
commands.allow = ["batch"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-batch"
|
||||
description = "Denies the batch command without any pre-configured scope."
|
||||
commands.deny = ["batch"]
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-cancel"
|
||||
description = "Enables the cancel command without any pre-configured scope."
|
||||
commands.allow = ["cancel"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-cancel"
|
||||
description = "Denies the cancel command without any pre-configured scope."
|
||||
commands.deny = ["cancel"]
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-check-permissions"
|
||||
description = "Enables the check_permissions command without any pre-configured scope."
|
||||
commands.allow = ["check_permissions"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-check-permissions"
|
||||
description = "Denies the check_permissions command without any pre-configured scope."
|
||||
commands.deny = ["check_permissions"]
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-create-channel"
|
||||
description = "Enables the create_channel command without any pre-configured scope."
|
||||
commands.allow = ["create_channel"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-create-channel"
|
||||
description = "Denies the create_channel command without any pre-configured scope."
|
||||
commands.deny = ["create_channel"]
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-delete-channel"
|
||||
description = "Enables the delete_channel command without any pre-configured scope."
|
||||
commands.allow = ["delete_channel"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-delete-channel"
|
||||
description = "Denies the delete_channel command without any pre-configured scope."
|
||||
commands.deny = ["delete_channel"]
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-get-active"
|
||||
description = "Enables the get_active command without any pre-configured scope."
|
||||
commands.allow = ["get_active"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-get-active"
|
||||
description = "Denies the get_active command without any pre-configured scope."
|
||||
commands.deny = ["get_active"]
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-get-pending"
|
||||
description = "Enables the get_pending command without any pre-configured scope."
|
||||
commands.allow = ["get_pending"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-get-pending"
|
||||
description = "Denies the get_pending command without any pre-configured scope."
|
||||
commands.deny = ["get_pending"]
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-is-permission-granted"
|
||||
description = "Enables the is_permission_granted command without any pre-configured scope."
|
||||
commands.allow = ["is_permission_granted"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-is-permission-granted"
|
||||
description = "Denies the is_permission_granted command without any pre-configured scope."
|
||||
commands.deny = ["is_permission_granted"]
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-list-channels"
|
||||
description = "Enables the list_channels command without any pre-configured scope."
|
||||
commands.allow = ["list_channels"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-list-channels"
|
||||
description = "Denies the list_channels command without any pre-configured scope."
|
||||
commands.deny = ["list_channels"]
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-notify"
|
||||
description = "Enables the notify command without any pre-configured scope."
|
||||
commands.allow = ["notify"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-notify"
|
||||
description = "Denies the notify command without any pre-configured scope."
|
||||
commands.deny = ["notify"]
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-permission-state"
|
||||
description = "Enables the permission_state command without any pre-configured scope."
|
||||
commands.allow = ["permission_state"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-permission-state"
|
||||
description = "Denies the permission_state command without any pre-configured scope."
|
||||
commands.deny = ["permission_state"]
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-register-action-types"
|
||||
description = "Enables the register_action_types command without any pre-configured scope."
|
||||
commands.allow = ["register_action_types"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-register-action-types"
|
||||
description = "Denies the register_action_types command without any pre-configured scope."
|
||||
commands.deny = ["register_action_types"]
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-register-listener"
|
||||
description = "Enables the register_listener command without any pre-configured scope."
|
||||
commands.allow = ["register_listener"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-register-listener"
|
||||
description = "Denies the register_listener command without any pre-configured scope."
|
||||
commands.deny = ["register_listener"]
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-remove-active"
|
||||
description = "Enables the remove_active command without any pre-configured scope."
|
||||
commands.allow = ["remove_active"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-remove-active"
|
||||
description = "Denies the remove_active command without any pre-configured scope."
|
||||
commands.deny = ["remove_active"]
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-remove-listener"
|
||||
description = "Enables the remove_listener command without any pre-configured scope."
|
||||
commands.allow = ["remove_listener"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-remove-listener"
|
||||
description = "Denies the remove_listener command without any pre-configured scope."
|
||||
commands.deny = ["remove_listener"]
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-request-permission"
|
||||
description = "Enables the request_permission command without any pre-configured scope."
|
||||
commands.allow = ["request_permission"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-request-permission"
|
||||
description = "Denies the request_permission command without any pre-configured scope."
|
||||
commands.deny = ["request_permission"]
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-show"
|
||||
description = "Enables the show command without any pre-configured scope."
|
||||
commands.allow = ["show"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-show"
|
||||
description = "Denies the show command without any pre-configured scope."
|
||||
commands.deny = ["show"]
|
||||
480
plugins/notification/permissions/autogenerated/reference.md
Normal file
480
plugins/notification/permissions/autogenerated/reference.md
Normal file
@@ -0,0 +1,480 @@
|
||||
## Default Permission
|
||||
|
||||
This permission set configures which
|
||||
notification features are by default exposed.
|
||||
|
||||
#### Granted Permissions
|
||||
|
||||
It allows all notification related features.
|
||||
|
||||
#### This default permission set includes the following:
|
||||
|
||||
- `allow-is-permission-granted`
|
||||
- `allow-request-permission`
|
||||
- `allow-notify`
|
||||
- `allow-register-action-types`
|
||||
- `allow-register-listener`
|
||||
- `allow-remove-listener`
|
||||
- `allow-cancel`
|
||||
- `allow-get-pending`
|
||||
- `allow-remove-active`
|
||||
- `allow-get-active`
|
||||
- `allow-check-permissions`
|
||||
- `allow-show`
|
||||
- `allow-batch`
|
||||
- `allow-list-channels`
|
||||
- `allow-delete-channel`
|
||||
- `allow-create-channel`
|
||||
- `allow-permission-state`
|
||||
|
||||
## Permission Table
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Identifier</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:allow-batch`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the batch command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:deny-batch`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the batch command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:allow-cancel`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the cancel command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:deny-cancel`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the cancel command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:allow-check-permissions`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the check_permissions command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:deny-check-permissions`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the check_permissions command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:allow-create-channel`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the create_channel command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:deny-create-channel`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the create_channel command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:allow-delete-channel`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the delete_channel command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:deny-delete-channel`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the delete_channel command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:allow-get-active`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the get_active command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:deny-get-active`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the get_active command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:allow-get-pending`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the get_pending command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:deny-get-pending`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the get_pending command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:allow-is-permission-granted`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the is_permission_granted command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:deny-is-permission-granted`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the is_permission_granted command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:allow-list-channels`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the list_channels command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:deny-list-channels`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the list_channels command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:allow-notify`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the notify command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:deny-notify`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the notify command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:allow-permission-state`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the permission_state command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:deny-permission-state`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the permission_state command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:allow-register-action-types`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the register_action_types command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:deny-register-action-types`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the register_action_types command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:allow-register-listener`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the register_listener command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:deny-register-listener`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the register_listener command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:allow-remove-active`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the remove_active command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:deny-remove-active`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the remove_active command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:allow-remove-listener`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the remove_listener command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:deny-remove-listener`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the remove_listener command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:allow-request-permission`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the request_permission command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:deny-request-permission`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the request_permission command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:allow-show`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the show command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`notification:deny-show`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the show command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
31
plugins/notification/permissions/default.toml
Normal file
31
plugins/notification/permissions/default.toml
Normal file
@@ -0,0 +1,31 @@
|
||||
"$schema" = "schemas/schema.json"
|
||||
[default]
|
||||
description = """
|
||||
This permission set configures which
|
||||
notification features are by default exposed.
|
||||
|
||||
#### Granted Permissions
|
||||
|
||||
It allows all notification related features.
|
||||
|
||||
"""
|
||||
|
||||
permissions = [
|
||||
"allow-is-permission-granted",
|
||||
"allow-request-permission",
|
||||
"allow-notify",
|
||||
"allow-register-action-types",
|
||||
"allow-register-listener",
|
||||
"allow-remove-listener",
|
||||
"allow-cancel",
|
||||
"allow-get-pending",
|
||||
"allow-remove-active",
|
||||
"allow-get-active",
|
||||
"allow-check-permissions",
|
||||
"allow-show",
|
||||
"allow-batch",
|
||||
"allow-list-channels",
|
||||
"allow-delete-channel",
|
||||
"allow-create-channel",
|
||||
"allow-permission-state",
|
||||
]
|
||||
510
plugins/notification/permissions/schemas/schema.json
Normal file
510
plugins/notification/permissions/schemas/schema.json
Normal file
@@ -0,0 +1,510 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "PermissionFile",
|
||||
"description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"default": {
|
||||
"description": "The default permission set for the plugin",
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/DefaultPermission"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"set": {
|
||||
"description": "A list of permissions sets defined",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/PermissionSet"
|
||||
}
|
||||
},
|
||||
"permission": {
|
||||
"description": "A list of inlined permissions",
|
||||
"default": [],
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Permission"
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"DefaultPermission": {
|
||||
"description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"permissions"
|
||||
],
|
||||
"properties": {
|
||||
"version": {
|
||||
"description": "The version of the permission.",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint64",
|
||||
"minimum": 1.0
|
||||
},
|
||||
"description": {
|
||||
"description": "Human-readable description of what the permission does. Tauri convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"permissions": {
|
||||
"description": "All permissions this set contains.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"PermissionSet": {
|
||||
"description": "A set of direct permissions grouped together under a new name.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"description",
|
||||
"identifier",
|
||||
"permissions"
|
||||
],
|
||||
"properties": {
|
||||
"identifier": {
|
||||
"description": "A unique identifier for the permission.",
|
||||
"type": "string"
|
||||
},
|
||||
"description": {
|
||||
"description": "Human-readable description of what the permission does.",
|
||||
"type": "string"
|
||||
},
|
||||
"permissions": {
|
||||
"description": "All permissions this set contains.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/PermissionKind"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Permission": {
|
||||
"description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"identifier"
|
||||
],
|
||||
"properties": {
|
||||
"version": {
|
||||
"description": "The version of the permission.",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint64",
|
||||
"minimum": 1.0
|
||||
},
|
||||
"identifier": {
|
||||
"description": "A unique identifier for the permission.",
|
||||
"type": "string"
|
||||
},
|
||||
"description": {
|
||||
"description": "Human-readable description of what the permission does. Tauri internal convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"commands": {
|
||||
"description": "Allowed or denied commands when using this permission.",
|
||||
"default": {
|
||||
"allow": [],
|
||||
"deny": []
|
||||
},
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Commands"
|
||||
}
|
||||
]
|
||||
},
|
||||
"scope": {
|
||||
"description": "Allowed or denied scoped when using this permission.",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Scopes"
|
||||
}
|
||||
]
|
||||
},
|
||||
"platforms": {
|
||||
"description": "Target platforms this permission applies. By default all platforms are affected by this permission.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
],
|
||||
"items": {
|
||||
"$ref": "#/definitions/Target"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Commands": {
|
||||
"description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"allow": {
|
||||
"description": "Allowed command.",
|
||||
"default": [],
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"deny": {
|
||||
"description": "Denied command, which takes priority.",
|
||||
"default": [],
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Scopes": {
|
||||
"description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"allow": {
|
||||
"description": "Data that defines what is allowed by the scope.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
],
|
||||
"items": {
|
||||
"$ref": "#/definitions/Value"
|
||||
}
|
||||
},
|
||||
"deny": {
|
||||
"description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
],
|
||||
"items": {
|
||||
"$ref": "#/definitions/Value"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Value": {
|
||||
"description": "All supported ACL values.",
|
||||
"anyOf": [
|
||||
{
|
||||
"description": "Represents a null JSON value.",
|
||||
"type": "null"
|
||||
},
|
||||
{
|
||||
"description": "Represents a [`bool`].",
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"description": "Represents a valid ACL [`Number`].",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Number"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Represents a [`String`].",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"description": "Represents a list of other [`Value`]s.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Value"
|
||||
}
|
||||
},
|
||||
{
|
||||
"description": "Represents a map of [`String`] keys to [`Value`]s.",
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"$ref": "#/definitions/Value"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"Number": {
|
||||
"description": "A valid ACL number.",
|
||||
"anyOf": [
|
||||
{
|
||||
"description": "Represents an [`i64`].",
|
||||
"type": "integer",
|
||||
"format": "int64"
|
||||
},
|
||||
{
|
||||
"description": "Represents a [`f64`].",
|
||||
"type": "number",
|
||||
"format": "double"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Target": {
|
||||
"description": "Platform target.",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "MacOS.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"macOS"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Windows.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"windows"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Linux.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"linux"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Android.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"android"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "iOS.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"iOS"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"PermissionKind": {
|
||||
"type": "string",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "Enables the batch command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-batch",
|
||||
"markdownDescription": "Enables the batch command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the batch command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-batch",
|
||||
"markdownDescription": "Denies the batch command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the cancel command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-cancel",
|
||||
"markdownDescription": "Enables the cancel command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the cancel command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-cancel",
|
||||
"markdownDescription": "Denies the cancel command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the check_permissions command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-check-permissions",
|
||||
"markdownDescription": "Enables the check_permissions command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the check_permissions command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-check-permissions",
|
||||
"markdownDescription": "Denies the check_permissions command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the create_channel command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-create-channel",
|
||||
"markdownDescription": "Enables the create_channel command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the create_channel command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-create-channel",
|
||||
"markdownDescription": "Denies the create_channel command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the delete_channel command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-delete-channel",
|
||||
"markdownDescription": "Enables the delete_channel command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the delete_channel command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-delete-channel",
|
||||
"markdownDescription": "Denies the delete_channel command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the get_active command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-get-active",
|
||||
"markdownDescription": "Enables the get_active command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the get_active command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-get-active",
|
||||
"markdownDescription": "Denies the get_active command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the get_pending command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-get-pending",
|
||||
"markdownDescription": "Enables the get_pending command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the get_pending command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-get-pending",
|
||||
"markdownDescription": "Denies the get_pending command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the is_permission_granted command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-is-permission-granted",
|
||||
"markdownDescription": "Enables the is_permission_granted command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the is_permission_granted command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-is-permission-granted",
|
||||
"markdownDescription": "Denies the is_permission_granted command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the list_channels command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-list-channels",
|
||||
"markdownDescription": "Enables the list_channels command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the list_channels command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-list-channels",
|
||||
"markdownDescription": "Denies the list_channels command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the notify command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-notify",
|
||||
"markdownDescription": "Enables the notify command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the notify command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-notify",
|
||||
"markdownDescription": "Denies the notify command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the permission_state command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-permission-state",
|
||||
"markdownDescription": "Enables the permission_state command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the permission_state command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-permission-state",
|
||||
"markdownDescription": "Denies the permission_state command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the register_action_types command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-register-action-types",
|
||||
"markdownDescription": "Enables the register_action_types command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the register_action_types command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-register-action-types",
|
||||
"markdownDescription": "Denies the register_action_types command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the register_listener command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-register-listener",
|
||||
"markdownDescription": "Enables the register_listener command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the register_listener command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-register-listener",
|
||||
"markdownDescription": "Denies the register_listener command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the remove_active command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-remove-active",
|
||||
"markdownDescription": "Enables the remove_active command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the remove_active command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-remove-active",
|
||||
"markdownDescription": "Denies the remove_active command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the remove_listener command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-remove-listener",
|
||||
"markdownDescription": "Enables the remove_listener command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the remove_listener command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-remove-listener",
|
||||
"markdownDescription": "Denies the remove_listener command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the request_permission command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-request-permission",
|
||||
"markdownDescription": "Enables the request_permission command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the request_permission command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-request-permission",
|
||||
"markdownDescription": "Denies the request_permission command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the show command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-show",
|
||||
"markdownDescription": "Enables the show command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the show command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-show",
|
||||
"markdownDescription": "Denies the show command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "This permission set configures which\nnotification features are by default exposed.\n\n#### Granted Permissions\n\nIt allows all notification related features.\n\n\n#### This default permission set includes:\n\n- `allow-is-permission-granted`\n- `allow-request-permission`\n- `allow-notify`\n- `allow-register-action-types`\n- `allow-register-listener`\n- `allow-remove-listener`\n- `allow-cancel`\n- `allow-get-pending`\n- `allow-remove-active`\n- `allow-get-active`\n- `allow-check-permissions`\n- `allow-show`\n- `allow-batch`\n- `allow-list-channels`\n- `allow-delete-channel`\n- `allow-create-channel`\n- `allow-permission-state`",
|
||||
"type": "string",
|
||||
"const": "default",
|
||||
"markdownDescription": "This permission set configures which\nnotification features are by default exposed.\n\n#### Granted Permissions\n\nIt allows all notification related features.\n\n\n#### This default permission set includes:\n\n- `allow-is-permission-granted`\n- `allow-request-permission`\n- `allow-notify`\n- `allow-register-action-types`\n- `allow-register-listener`\n- `allow-remove-listener`\n- `allow-cancel`\n- `allow-get-pending`\n- `allow-remove-active`\n- `allow-get-active`\n- `allow-check-permissions`\n- `allow-show`\n- `allow-batch`\n- `allow-list-channels`\n- `allow-delete-channel`\n- `allow-create-channel`\n- `allow-permission-state`"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
22
plugins/notification/rollup.config.js
Normal file
22
plugins/notification/rollup.config.js
Normal file
@@ -0,0 +1,22 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import { createConfig } from '../../shared/rollup.config.js'
|
||||
import { nodeResolve } from '@rollup/plugin-node-resolve'
|
||||
import typescript from '@rollup/plugin-typescript'
|
||||
import terser from '@rollup/plugin-terser'
|
||||
|
||||
export default createConfig({
|
||||
additionalConfigs: {
|
||||
input: 'guest-js/init.ts',
|
||||
output: {
|
||||
file: 'src/init-iife.js',
|
||||
format: 'iife'
|
||||
},
|
||||
plugins: [typescript(), terser(), nodeResolve()],
|
||||
onwarn: (warning) => {
|
||||
throw Object.assign(new Error(), warning)
|
||||
}
|
||||
}
|
||||
})
|
||||
39
plugins/notification/src/commands.rs
Normal file
39
plugins/notification/src/commands.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use tauri::{command, plugin::PermissionState, AppHandle, Runtime, State};
|
||||
|
||||
use crate::{Notification, NotificationData, Result};
|
||||
|
||||
#[command]
|
||||
pub(crate) async fn is_permission_granted<R: Runtime>(
|
||||
_app: AppHandle<R>,
|
||||
notification: State<'_, Notification<R>>,
|
||||
) -> Result<Option<bool>> {
|
||||
let state = notification.permission_state()?;
|
||||
match state {
|
||||
PermissionState::Granted => Ok(Some(true)),
|
||||
PermissionState::Denied => Ok(Some(false)),
|
||||
PermissionState::Prompt | PermissionState::PromptWithRationale => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub(crate) async fn request_permission<R: Runtime>(
|
||||
_app: AppHandle<R>,
|
||||
notification: State<'_, Notification<R>>,
|
||||
) -> Result<PermissionState> {
|
||||
notification.request_permission()
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub(crate) async fn notify<R: Runtime>(
|
||||
_app: AppHandle<R>,
|
||||
notification: State<'_, Notification<R>>,
|
||||
options: NotificationData,
|
||||
) -> Result<()> {
|
||||
let mut builder = notification.builder();
|
||||
builder.data = options;
|
||||
builder.show()
|
||||
}
|
||||
330
plugins/notification/src/desktop.rs
Normal file
330
plugins/notification/src/desktop.rs
Normal file
@@ -0,0 +1,330 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use serde::de::DeserializeOwned;
|
||||
use tauri::{
|
||||
plugin::{PermissionState, PluginApi},
|
||||
AppHandle, Runtime,
|
||||
};
|
||||
|
||||
use crate::NotificationBuilder;
|
||||
|
||||
/// Initializes the desktop implementation of the notification APIs.
|
||||
pub fn init<R: Runtime, C: DeserializeOwned>(
|
||||
app: &AppHandle<R>,
|
||||
_api: PluginApi<R, C>,
|
||||
) -> crate::Result<Notification<R>> {
|
||||
Ok(Notification(app.clone()))
|
||||
}
|
||||
|
||||
/// Access to the notification APIs.
|
||||
///
|
||||
/// You can get an instance of this type via [`NotificationExt`](crate::NotificationExt)
|
||||
pub struct Notification<R: Runtime>(AppHandle<R>);
|
||||
|
||||
impl<R: Runtime> crate::NotificationBuilder<R> {
|
||||
/// Shows the notification.
|
||||
///
|
||||
/// When no title was set with [`Self::title`], the `productName` from the Tauri configuration is used instead.
|
||||
/// Only the title, body, icon and sound of the notification are used on desktop;
|
||||
/// the scheduling, grouping and action related options are ignored.
|
||||
///
|
||||
/// The notification is dispatched on a background task, so this returns as soon as the payload is prepared.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error when the notification could not be prepared,
|
||||
/// e.g. when the path of the running executable cannot be resolved on Windows.
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// - **Windows**: Not supported on Windows 7 unless the `windows7-compat` Cargo feature is enabled.
|
||||
pub fn show(self) -> crate::Result<()> {
|
||||
let mut notification = imp::Notification::new(self.app.config().identifier.clone());
|
||||
|
||||
if let Some(title) = self
|
||||
.data
|
||||
.title
|
||||
.or_else(|| self.app.config().product_name.clone())
|
||||
{
|
||||
notification = notification.title(title);
|
||||
}
|
||||
if let Some(body) = self.data.body {
|
||||
notification = notification.body(body);
|
||||
}
|
||||
if let Some(icon) = self.data.icon {
|
||||
notification = notification.icon(icon);
|
||||
}
|
||||
if let Some(sound) = self.data.sound {
|
||||
notification = notification.sound(sound);
|
||||
}
|
||||
#[cfg(feature = "windows7-compat")]
|
||||
{
|
||||
notification.notify(&self.app)?;
|
||||
}
|
||||
#[cfg(not(feature = "windows7-compat"))]
|
||||
notification.show()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: Runtime> Notification<R> {
|
||||
/// Creates a new builder for a notification.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```no_run
|
||||
/// use tauri_plugin_notification::NotificationExt;
|
||||
///
|
||||
/// fn notify<R: tauri::Runtime>(app: &tauri::AppHandle<R>) {
|
||||
/// app.notification()
|
||||
/// .builder()
|
||||
/// .title("Tauri")
|
||||
/// .body("Tauri is awesome!")
|
||||
/// .show()
|
||||
/// .unwrap();
|
||||
/// }
|
||||
/// ```
|
||||
pub fn builder(&self) -> NotificationBuilder<R> {
|
||||
NotificationBuilder::new(self.0.clone())
|
||||
}
|
||||
|
||||
/// Requests the permission to send notifications.
|
||||
///
|
||||
/// Desktop applications do not need to ask for this permission,
|
||||
/// so this always resolves to [`PermissionState::Granted`] without prompting the user.
|
||||
pub fn request_permission(&self) -> crate::Result<PermissionState> {
|
||||
Ok(PermissionState::Granted)
|
||||
}
|
||||
|
||||
/// Checks whether the permission to send notifications was granted.
|
||||
///
|
||||
/// Desktop applications do not need to ask for this permission,
|
||||
/// so this always resolves to [`PermissionState::Granted`].
|
||||
pub fn permission_state(&self) -> crate::Result<PermissionState> {
|
||||
Ok(PermissionState::Granted)
|
||||
}
|
||||
}
|
||||
|
||||
mod imp {
|
||||
//! Types and functions related to desktop notifications.
|
||||
|
||||
#[cfg(windows)]
|
||||
use std::path::MAIN_SEPARATOR as SEP;
|
||||
|
||||
/// The desktop notification definition.
|
||||
///
|
||||
/// Allows you to construct a Notification data and send it.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```rust,no_run
|
||||
/// use tauri_plugin_notification::NotificationExt;
|
||||
/// // first we build the application to access the Tauri configuration
|
||||
/// let app = tauri::Builder::default()
|
||||
/// // on an actual app, remove the string argument
|
||||
/// .build(tauri::generate_context!("test/tauri.conf.json"))
|
||||
/// .expect("error while building tauri application");
|
||||
///
|
||||
/// // shows a notification with the given title and body
|
||||
/// app.notification()
|
||||
/// .builder()
|
||||
/// .title("New message")
|
||||
/// .body("You've got a new message.")
|
||||
/// .show();
|
||||
///
|
||||
/// // run the app
|
||||
/// app.run(|_app_handle, _event| {});
|
||||
/// ```
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Notification {
|
||||
/// The notification body.
|
||||
body: Option<String>,
|
||||
/// The notification title.
|
||||
title: Option<String>,
|
||||
/// The notification icon.
|
||||
icon: Option<String>,
|
||||
/// The notification sound.
|
||||
sound: Option<String>,
|
||||
/// The notification identifier
|
||||
identifier: String,
|
||||
}
|
||||
|
||||
impl Notification {
|
||||
/// Initializes a instance of a Notification.
|
||||
pub fn new(identifier: impl Into<String>) -> Self {
|
||||
Self {
|
||||
identifier: identifier.into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the notification body.
|
||||
#[must_use]
|
||||
pub fn body(mut self, body: impl Into<String>) -> Self {
|
||||
self.body = Some(body.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the notification title.
|
||||
#[must_use]
|
||||
pub fn title(mut self, title: impl Into<String>) -> Self {
|
||||
self.title = Some(title.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the notification icon.
|
||||
#[must_use]
|
||||
pub fn icon(mut self, icon: impl Into<String>) -> Self {
|
||||
self.icon = Some(icon.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the notification sound file.
|
||||
#[must_use]
|
||||
pub fn sound(mut self, sound: impl Into<String>) -> Self {
|
||||
self.sound = Some(sound.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Shows the notification.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```no_run
|
||||
/// use tauri_plugin_notification::NotificationExt;
|
||||
///
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(|app| {
|
||||
/// app.notification()
|
||||
/// .builder()
|
||||
/// .title("Tauri")
|
||||
/// .body("Tauri is awesome!")
|
||||
/// .show()
|
||||
/// .unwrap();
|
||||
/// Ok(())
|
||||
/// })
|
||||
/// .run(tauri::generate_context!("test/tauri.conf.json"))
|
||||
/// .expect("error while running tauri application");
|
||||
/// ```
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// - **Windows**: Not supported on Windows 7. If your app targets it, enable the `windows7-compat` feature and use [`Self::notify`].
|
||||
#[cfg_attr(
|
||||
all(not(docsrs), feature = "windows7-compat"),
|
||||
deprecated = "This function does not work on Windows 7. Use `Self::notify` instead."
|
||||
)]
|
||||
pub fn show(self) -> crate::Result<()> {
|
||||
let mut notification = notify_rust::Notification::new();
|
||||
if let Some(body) = self.body {
|
||||
notification.body(&body);
|
||||
}
|
||||
if let Some(title) = self.title {
|
||||
notification.summary(&title);
|
||||
}
|
||||
if let Some(icon) = self.icon {
|
||||
notification.icon(&icon);
|
||||
} else {
|
||||
notification.auto_icon();
|
||||
}
|
||||
if let Some(sound) = self.sound {
|
||||
notification.sound_name(&sound);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let exe = tauri::utils::platform::current_exe()?;
|
||||
let exe_dir = exe.parent().expect("failed to get exe directory");
|
||||
let curr_dir = exe_dir.display().to_string();
|
||||
// set the notification's System.AppUserModel.ID only when running the installed app
|
||||
if !(curr_dir.ends_with(format!("{SEP}target{SEP}debug").as_str())
|
||||
|| curr_dir.ends_with(format!("{SEP}target{SEP}release").as_str()))
|
||||
{
|
||||
notification.app_id(&self.identifier);
|
||||
}
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let _ = notify_rust::set_application(if tauri::is_dev() {
|
||||
"com.apple.Terminal"
|
||||
} else {
|
||||
&self.identifier
|
||||
});
|
||||
}
|
||||
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let _ = notification.show();
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Shows the notification. This API is similar to [`Self::show`], but it also works on Windows 7.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```no_run
|
||||
/// use tauri_plugin_notification::NotificationExt;
|
||||
///
|
||||
/// tauri::Builder::default()
|
||||
/// .setup(move |app| {
|
||||
/// app.notification().builder()
|
||||
/// .title("Tauri")
|
||||
/// .body("Tauri is awesome!")
|
||||
/// .show()
|
||||
/// .unwrap();
|
||||
/// Ok(())
|
||||
/// })
|
||||
/// .run(tauri::generate_context!("test/tauri.conf.json"))
|
||||
/// .expect("error while running tauri application");
|
||||
/// ```
|
||||
#[cfg(feature = "windows7-compat")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "windows7-compat")))]
|
||||
#[allow(unused_variables)]
|
||||
pub fn notify<R: tauri::Runtime>(self, app: &tauri::AppHandle<R>) -> crate::Result<()> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
fn is_windows_7() -> bool {
|
||||
let v = windows_version::OsVersion::current();
|
||||
// windows 7 is 6.1
|
||||
v.major == 6 && v.minor == 1
|
||||
}
|
||||
|
||||
if is_windows_7() {
|
||||
self.notify_win7(app)
|
||||
} else {
|
||||
#[allow(deprecated)]
|
||||
self.show()
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
#[allow(deprecated)]
|
||||
self.show()
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the notification on Windows 7.
|
||||
#[cfg(all(windows, feature = "windows7-compat"))]
|
||||
fn notify_win7<R: tauri::Runtime>(self, app: &tauri::AppHandle<R>) -> crate::Result<()> {
|
||||
let app_ = app.clone();
|
||||
let _ = app.clone().run_on_main_thread(move || {
|
||||
let mut notification = win7_notifications::Notification::new();
|
||||
if let Some(body) = self.body {
|
||||
notification.body(&body);
|
||||
}
|
||||
if let Some(title) = self.title {
|
||||
notification.summary(&title);
|
||||
}
|
||||
if let Some(icon) = app_.default_window_icon() {
|
||||
notification.icon(icon.rgba().to_vec(), icon.width(), icon.height());
|
||||
}
|
||||
let _ = notification.show();
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
33
plugins/notification/src/error.rs
Normal file
33
plugins/notification/src/error.rs
Normal file
@@ -0,0 +1,33 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use serde::{ser::Serializer, Serialize};
|
||||
|
||||
/// Alias for a [`std::result::Result`] with the error type set to [`Error`].
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// Errors returned by the notification plugin.
|
||||
///
|
||||
/// The error is serialized to its [`Display`](std::fmt::Display) string when it crosses the IPC boundary.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
/// An I/O operation failed, e.g. resolving the path of the running executable on Windows.
|
||||
#[error(transparent)]
|
||||
Io(#[from] std::io::Error),
|
||||
/// Failed to run a command on the mobile plugin implementation (Kotlin on Android, Swift on iOS).
|
||||
///
|
||||
/// Only available on mobile.
|
||||
#[cfg(mobile)]
|
||||
#[error(transparent)]
|
||||
PluginInvoke(#[from] tauri::plugin::mobile::PluginInvokeError),
|
||||
}
|
||||
|
||||
impl Serialize for Error {
|
||||
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(self.to_string().as_ref())
|
||||
}
|
||||
}
|
||||
1
plugins/notification/src/init-iife.js
Normal file
1
plugins/notification/src/init-iife.js
Normal file
@@ -0,0 +1 @@
|
||||
!function(){"use strict";async function i(i,n={},t){return window.__TAURI_INTERNALS__.invoke(i,n,t)}"function"==typeof SuppressedError&&SuppressedError,function(){let n=!1,t="default";function o(i){n=!0,window.Notification.permission=i,n=!1}window.Notification=function(n,t){const o=t||{};!async function(n){"object"==typeof n&&Object.freeze(n),await i("plugin:notification|notify",{options:"string"==typeof n?{title:n}:n})}(Object.assign(o,{title:n}))},window.Notification.requestPermission=async function(){return await i("plugin:notification|request_permission").then(i=>(o("prompt"===i||"prompt-with-rationale"===i?"default":i),i))},Object.defineProperty(window.Notification,"permission",{enumerable:!0,get:()=>t,set:i=>{if(!n)throw new Error("Readonly property");t=i}}),async function(){return"default"!==window.Notification.permission?await Promise.resolve("granted"===window.Notification.permission):!!__TEMPLATE_windows__||await i("plugin:notification|is_permission_granted")}().then(function(i){o(null===i?"default":i?"granted":"denied")})}()}();
|
||||
265
plugins/notification/src/lib.rs
Normal file
265
plugins/notification/src/lib.rs
Normal file
@@ -0,0 +1,265 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//! Send message notifications (brief auto-expiring OS window element) to your user. Can also be used with the Notification Web API.
|
||||
//!
|
||||
//! ## Cargo features
|
||||
//!
|
||||
//! - **windows7-compat**: Adds support for the legacy Windows 7 notification implementation and Windows-version detection.
|
||||
|
||||
#![doc(
|
||||
html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png",
|
||||
html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png"
|
||||
)]
|
||||
|
||||
use serde::Serialize;
|
||||
#[cfg(mobile)]
|
||||
use tauri::plugin::PluginHandle;
|
||||
#[cfg(desktop)]
|
||||
use tauri::AppHandle;
|
||||
use tauri::{
|
||||
plugin::{Builder, TauriPlugin},
|
||||
Manager, Runtime,
|
||||
};
|
||||
|
||||
pub use models::*;
|
||||
pub use tauri::plugin::PermissionState;
|
||||
|
||||
#[cfg(desktop)]
|
||||
mod desktop;
|
||||
#[cfg(mobile)]
|
||||
mod mobile;
|
||||
|
||||
mod commands;
|
||||
mod error;
|
||||
mod models;
|
||||
|
||||
pub use error::{Error, Result};
|
||||
|
||||
#[cfg(desktop)]
|
||||
pub use desktop::Notification;
|
||||
#[cfg(mobile)]
|
||||
pub use mobile::Notification;
|
||||
|
||||
/// The notification builder.
|
||||
#[derive(Debug)]
|
||||
pub struct NotificationBuilder<R: Runtime> {
|
||||
#[cfg(desktop)]
|
||||
app: AppHandle<R>,
|
||||
#[cfg(mobile)]
|
||||
handle: PluginHandle<R>,
|
||||
pub(crate) data: NotificationData,
|
||||
}
|
||||
|
||||
impl<R: Runtime> NotificationBuilder<R> {
|
||||
#[cfg(desktop)]
|
||||
fn new(app: AppHandle<R>) -> Self {
|
||||
Self {
|
||||
app,
|
||||
data: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(mobile)]
|
||||
fn new(handle: PluginHandle<R>) -> Self {
|
||||
Self {
|
||||
handle,
|
||||
data: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the notification identifier.
|
||||
pub fn id(mut self, id: i32) -> Self {
|
||||
self.data.id = id;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the identifier of the notification channel that delivers this notification.
|
||||
///
|
||||
/// If the channel does not exist, the notification won't fire.
|
||||
/// Make sure the channel exists with `Notification::list_channels` and
|
||||
/// `Notification::create_channel`.
|
||||
///
|
||||
/// Only used on Android.
|
||||
pub fn channel_id(mut self, id: impl Into<String>) -> Self {
|
||||
self.data.channel_id.replace(id.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the notification title.
|
||||
pub fn title(mut self, title: impl Into<String>) -> Self {
|
||||
self.data.title.replace(title.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the notification body.
|
||||
pub fn body(mut self, body: impl Into<String>) -> Self {
|
||||
self.data.body.replace(body.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Schedule this notification to fire on a later time or a fixed interval.
|
||||
pub fn schedule(mut self, schedule: Schedule) -> Self {
|
||||
self.data.schedule.replace(schedule);
|
||||
self
|
||||
}
|
||||
|
||||
/// Multiline text.
|
||||
/// Changes the notification style to big text.
|
||||
/// Cannot be used with `inboxLines`.
|
||||
pub fn large_body(mut self, large_body: impl Into<String>) -> Self {
|
||||
self.data.large_body.replace(large_body.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Detail text for the notification with `largeBody`, `inboxLines` or `groupSummary`.
|
||||
pub fn summary(mut self, summary: impl Into<String>) -> Self {
|
||||
self.data.summary.replace(summary.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Defines an action type for this notification.
|
||||
pub fn action_type_id(mut self, action_type_id: impl Into<String>) -> Self {
|
||||
self.data.action_type_id.replace(action_type_id.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Identifier used to group multiple notifications.
|
||||
///
|
||||
/// <https://developer.apple.com/documentation/usernotifications/unmutablenotificationcontent/1649872-threadidentifier>
|
||||
pub fn group(mut self, group: impl Into<String>) -> Self {
|
||||
self.data.group.replace(group.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Instructs the system that this notification is the summary of a group on Android.
|
||||
pub fn group_summary(mut self) -> Self {
|
||||
self.data.group_summary = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// The sound resource name for the notification.
|
||||
pub fn sound(mut self, sound: impl Into<String>) -> Self {
|
||||
self.data.sound.replace(sound.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Append an inbox line to the notification.
|
||||
/// Changes the notification style to inbox.
|
||||
/// Cannot be used with `largeBody`.
|
||||
///
|
||||
/// Only supports up to 5 lines.
|
||||
pub fn inbox_line(mut self, line: impl Into<String>) -> Self {
|
||||
self.data.inbox_lines.push(line.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Notification icon.
|
||||
///
|
||||
/// On Android the icon must be placed in the app's `res/drawable` folder.
|
||||
pub fn icon(mut self, icon: impl Into<String>) -> Self {
|
||||
self.data.icon.replace(icon.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Notification large icon (Android).
|
||||
///
|
||||
/// The icon must be placed in the app's `res/drawable` folder.
|
||||
pub fn large_icon(mut self, large_icon: impl Into<String>) -> Self {
|
||||
self.data.large_icon.replace(large_icon.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Icon color on Android.
|
||||
pub fn icon_color(mut self, icon_color: impl Into<String>) -> Self {
|
||||
self.data.icon_color.replace(icon_color.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Append an attachment to the notification.
|
||||
pub fn attachment(mut self, attachment: Attachment) -> Self {
|
||||
self.data.attachments.push(attachment);
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds an extra payload to store in the notification.
|
||||
pub fn extra(mut self, key: impl Into<String>, value: impl Serialize) -> Self {
|
||||
self.data
|
||||
.extra
|
||||
.insert(key.into(), serde_json::to_value(value).unwrap());
|
||||
self
|
||||
}
|
||||
|
||||
/// If true, the notification cannot be dismissed by the user on Android.
|
||||
///
|
||||
/// An application service must manage the dismissal of the notification.
|
||||
/// It is typically used to indicate a background task that is pending (e.g. a file download)
|
||||
/// or the user is engaged with (e.g. playing music).
|
||||
pub fn ongoing(mut self) -> Self {
|
||||
self.data.ongoing = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// Automatically cancel the notification when the user clicks on it.
|
||||
pub fn auto_cancel(mut self) -> Self {
|
||||
self.data.auto_cancel = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// Changes the notification presentation to be silent on iOS (no badge, no sound, not listed).
|
||||
pub fn silent(mut self) -> Self {
|
||||
self.data.silent = true;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Extensions to [`tauri::App`], [`tauri::AppHandle`], [`tauri::WebviewWindow`], [`tauri::Webview`] and [`tauri::Window`] to access the notification APIs.
|
||||
pub trait NotificationExt<R: Runtime> {
|
||||
/// Returns the notification APIs managed by the plugin.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```no_run
|
||||
/// use tauri_plugin_notification::NotificationExt;
|
||||
///
|
||||
/// fn notify<R: tauri::Runtime>(app: &tauri::AppHandle<R>) {
|
||||
/// app.notification()
|
||||
/// .builder()
|
||||
/// .title("Tauri")
|
||||
/// .body("Tauri is awesome!")
|
||||
/// .show()
|
||||
/// .unwrap();
|
||||
/// }
|
||||
/// ```
|
||||
fn notification(&self) -> &Notification<R>;
|
||||
}
|
||||
|
||||
impl<R: Runtime, T: Manager<R>> crate::NotificationExt<R> for T {
|
||||
fn notification(&self) -> &Notification<R> {
|
||||
self.state::<Notification<R>>().inner()
|
||||
}
|
||||
}
|
||||
|
||||
/// Initializes the plugin.
|
||||
pub fn init<R: Runtime>() -> TauriPlugin<R> {
|
||||
Builder::new("notification")
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
commands::notify,
|
||||
commands::request_permission,
|
||||
commands::is_permission_granted
|
||||
])
|
||||
.js_init_script(include_str!("init-iife.js").replace(
|
||||
"__TEMPLATE_windows__",
|
||||
if cfg!(windows) { "true" } else { "false" },
|
||||
))
|
||||
.setup(|app, api| {
|
||||
#[cfg(mobile)]
|
||||
let notification = mobile::init(app, api)?;
|
||||
#[cfg(desktop)]
|
||||
let notification = desktop::init(app, api)?;
|
||||
app.manage(notification);
|
||||
Ok(())
|
||||
})
|
||||
.build()
|
||||
}
|
||||
202
plugins/notification/src/mobile.rs
Normal file
202
plugins/notification/src/mobile.rs
Normal file
@@ -0,0 +1,202 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use serde::{de::DeserializeOwned, Deserialize};
|
||||
use tauri::{
|
||||
plugin::{PermissionState, PluginApi, PluginHandle},
|
||||
AppHandle, Runtime,
|
||||
};
|
||||
|
||||
use crate::models::*;
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
const PLUGIN_IDENTIFIER: &str = "app.tauri.notification";
|
||||
|
||||
#[cfg(target_os = "ios")]
|
||||
tauri::ios_plugin_binding!(init_plugin_notification);
|
||||
|
||||
/// Initializes the mobile implementation of the notification APIs by registering
|
||||
/// the Kotlin (Android) or Swift (iOS) plugin class.
|
||||
pub fn init<R: Runtime, C: DeserializeOwned>(
|
||||
_app: &AppHandle<R>,
|
||||
api: PluginApi<R, C>,
|
||||
) -> crate::Result<Notification<R>> {
|
||||
#[cfg(target_os = "android")]
|
||||
let handle = api.register_android_plugin(PLUGIN_IDENTIFIER, "NotificationPlugin")?;
|
||||
#[cfg(target_os = "ios")]
|
||||
let handle = api.register_ios_plugin(init_plugin_notification)?;
|
||||
Ok(Notification(handle))
|
||||
}
|
||||
|
||||
impl<R: Runtime> crate::NotificationBuilder<R> {
|
||||
/// Shows the notification, or schedules it when [`Self::schedule`] was called.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::PluginInvoke`](crate::Error::PluginInvoke) when the mobile plugin
|
||||
/// rejects the notification, e.g. when the scheduled date is in the past.
|
||||
pub fn show(self) -> crate::Result<()> {
|
||||
self.handle
|
||||
.run_mobile_plugin::<i32>("show", self.data)
|
||||
.map(|_| ())
|
||||
.map_err(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
/// Access to the notification APIs.
|
||||
///
|
||||
/// You can get an instance of this type via [`NotificationExt`](crate::NotificationExt)
|
||||
pub struct Notification<R: Runtime>(PluginHandle<R>);
|
||||
|
||||
impl<R: Runtime> Notification<R> {
|
||||
/// Creates a new builder for a notification.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```no_run
|
||||
/// use tauri_plugin_notification::NotificationExt;
|
||||
///
|
||||
/// fn notify<R: tauri::Runtime>(app: &tauri::AppHandle<R>) {
|
||||
/// app.notification()
|
||||
/// .builder()
|
||||
/// .title("Tauri")
|
||||
/// .body("Tauri is awesome!")
|
||||
/// .show()
|
||||
/// .unwrap();
|
||||
/// }
|
||||
/// ```
|
||||
pub fn builder(&self) -> crate::NotificationBuilder<R> {
|
||||
crate::NotificationBuilder::new(self.0.clone())
|
||||
}
|
||||
|
||||
/// Requests the permission to send notifications, prompting the user when it was not decided yet.
|
||||
///
|
||||
/// On Android this requests the `POST_NOTIFICATIONS` runtime permission.
|
||||
pub fn request_permission(&self) -> crate::Result<PermissionState> {
|
||||
self.0
|
||||
.run_mobile_plugin::<PermissionResponse>("requestPermissions", ())
|
||||
.map(|r| r.permission_state)
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Checks the current state of the permission to send notifications without prompting the user.
|
||||
pub fn permission_state(&self) -> crate::Result<PermissionState> {
|
||||
self.0
|
||||
.run_mobile_plugin::<PermissionResponse>("checkPermissions", ())
|
||||
.map(|r| r.permission_state)
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Registers the action types a notification can reference
|
||||
/// through [`NotificationBuilder::action_type_id`](crate::NotificationBuilder::action_type_id).
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// - **Android**: only the identifier, title and input flag of each [`Action`] are used.
|
||||
/// - **iOS**: each action type is registered as a `UNNotificationCategory`.
|
||||
pub fn register_action_types(&self, types: Vec<ActionType>) -> crate::Result<()> {
|
||||
let mut args = HashMap::new();
|
||||
args.insert("types", types);
|
||||
self.0
|
||||
.run_mobile_plugin("registerActionTypes", args)
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Removes the delivered notifications with the given identifiers from the notification center.
|
||||
///
|
||||
/// Use [`Self::remove_all_active`] to remove every delivered notification.
|
||||
pub fn remove_active(&self, notifications: Vec<i32>) -> crate::Result<()> {
|
||||
let mut args = HashMap::new();
|
||||
args.insert(
|
||||
"notifications",
|
||||
notifications
|
||||
.into_iter()
|
||||
.map(|id| {
|
||||
let mut notification = HashMap::new();
|
||||
notification.insert("id", id);
|
||||
notification
|
||||
})
|
||||
.collect::<Vec<HashMap<&str, i32>>>(),
|
||||
);
|
||||
self.0
|
||||
.run_mobile_plugin("removeActive", args)
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Lists the notifications that were delivered and are still visible in the notification center.
|
||||
pub fn active(&self) -> crate::Result<Vec<ActiveNotification>> {
|
||||
self.0
|
||||
.run_mobile_plugin("getActive", ())
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Removes all delivered notifications from the notification center.
|
||||
pub fn remove_all_active(&self) -> crate::Result<()> {
|
||||
self.0
|
||||
.run_mobile_plugin("removeActive", ())
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Lists the scheduled notifications that have not been delivered yet.
|
||||
pub fn pending(&self) -> crate::Result<Vec<PendingNotification>> {
|
||||
self.0
|
||||
.run_mobile_plugin("getPending", ())
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Cancel pending notifications.
|
||||
pub fn cancel(&self, notifications: Vec<i32>) -> crate::Result<()> {
|
||||
let mut args = HashMap::new();
|
||||
args.insert("notifications", notifications);
|
||||
self.0.run_mobile_plugin("cancel", args).map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Cancel all pending notifications.
|
||||
pub fn cancel_all(&self) -> crate::Result<()> {
|
||||
self.0.run_mobile_plugin("cancel", ()).map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Creates a notification channel, which notifications can target
|
||||
/// through [`NotificationBuilder::channel_id`](crate::NotificationBuilder::channel_id).
|
||||
///
|
||||
/// Notifications that reference a channel that does not exist are not delivered.
|
||||
///
|
||||
/// Only available on Android.
|
||||
#[cfg(target_os = "android")]
|
||||
pub fn create_channel(&self, channel: Channel) -> crate::Result<()> {
|
||||
self.0
|
||||
.run_mobile_plugin("createChannel", channel)
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Deletes the notification channel with the given identifier.
|
||||
///
|
||||
/// Only available on Android.
|
||||
#[cfg(target_os = "android")]
|
||||
pub fn delete_channel(&self, id: impl Into<String>) -> crate::Result<()> {
|
||||
let mut args = HashMap::new();
|
||||
args.insert("id", id.into());
|
||||
self.0
|
||||
.run_mobile_plugin("deleteChannel", args)
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Lists the notification channels that are currently registered for the app.
|
||||
///
|
||||
/// Only available on Android.
|
||||
#[cfg(target_os = "android")]
|
||||
pub fn list_channels(&self) -> crate::Result<Vec<Channel>> {
|
||||
self.0
|
||||
.run_mobile_plugin("listChannels", ())
|
||||
.map_err(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct PermissionResponse {
|
||||
permission_state: PermissionState,
|
||||
}
|
||||
914
plugins/notification/src/models.rs
Normal file
914
plugins/notification/src/models.rs
Normal file
@@ -0,0 +1,914 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::{collections::HashMap, fmt::Display};
|
||||
|
||||
use serde::{de::Error as DeError, Deserialize, Deserializer, Serialize, Serializer};
|
||||
|
||||
use url::Url;
|
||||
|
||||
/// A media file attached to a notification.
|
||||
///
|
||||
/// Attachments are only used on mobile; desktop notifications ignore them.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Attachment {
|
||||
id: String,
|
||||
url: Url,
|
||||
}
|
||||
|
||||
impl Attachment {
|
||||
/// Creates a new attachment with the given identifier and URL.
|
||||
///
|
||||
/// The URL accepts the `asset` and `file` protocols.
|
||||
pub fn new(id: impl Into<String>, url: Url) -> Self {
|
||||
Self { id: id.into(), url }
|
||||
}
|
||||
}
|
||||
|
||||
/// The set of date fields a notification must match to be delivered.
|
||||
///
|
||||
/// Fields left as [`None`] match any value, so the notification fires on every date
|
||||
/// whose remaining components match. Used by [`Schedule::Interval`].
|
||||
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ScheduleInterval {
|
||||
/// The year the notification fires on.
|
||||
pub year: Option<u8>,
|
||||
/// The month of the year the notification fires on.
|
||||
pub month: Option<u8>,
|
||||
/// The day of the month the notification fires on.
|
||||
pub day: Option<u8>,
|
||||
/// The day of the week the notification fires on.
|
||||
///
|
||||
/// 1 - Sunday, 2 - Monday, 3 - Tuesday, 4 - Wednesday, 5 - Thursday, 6 - Friday, 7 - Saturday.
|
||||
pub weekday: Option<u8>,
|
||||
/// The hour of the day the notification fires on, in the 24-hour clock.
|
||||
pub hour: Option<u8>,
|
||||
/// The minute of the hour the notification fires on.
|
||||
pub minute: Option<u8>,
|
||||
/// The second of the minute the notification fires on.
|
||||
pub second: Option<u8>,
|
||||
}
|
||||
|
||||
/// The unit of the repeating interval used by [`Schedule::Every`].
|
||||
///
|
||||
/// It is serialized as its lowercase camelCase name, e.g. `twoWeeks`.
|
||||
#[derive(Debug)]
|
||||
pub enum ScheduleEvery {
|
||||
/// Repeats every year.
|
||||
///
|
||||
/// On Android a year is approximated as 52 weeks.
|
||||
Year,
|
||||
/// Repeats every month.
|
||||
///
|
||||
/// On Android a month is approximated as 30 days.
|
||||
Month,
|
||||
/// Repeats every two weeks.
|
||||
TwoWeeks,
|
||||
/// Repeats every week.
|
||||
Week,
|
||||
/// Repeats every day.
|
||||
Day,
|
||||
/// Repeats every hour.
|
||||
Hour,
|
||||
/// Repeats every minute.
|
||||
Minute,
|
||||
/// Repeats every second.
|
||||
///
|
||||
/// Not supported on iOS, where repeating triggers must be at least a minute apart.
|
||||
Second,
|
||||
}
|
||||
|
||||
impl Display for ScheduleEvery {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"{}",
|
||||
match self {
|
||||
Self::Year => "year",
|
||||
Self::Month => "month",
|
||||
Self::TwoWeeks => "twoWeeks",
|
||||
Self::Week => "week",
|
||||
Self::Day => "day",
|
||||
Self::Hour => "hour",
|
||||
Self::Minute => "minute",
|
||||
Self::Second => "second",
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for ScheduleEvery {
|
||||
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(self.to_string().as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for ScheduleEvery {
|
||||
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let s = String::deserialize(deserializer)?;
|
||||
match s.to_lowercase().as_str() {
|
||||
"year" => Ok(Self::Year),
|
||||
"month" => Ok(Self::Month),
|
||||
"twoweeks" => Ok(Self::TwoWeeks),
|
||||
"week" => Ok(Self::Week),
|
||||
"day" => Ok(Self::Day),
|
||||
"hour" => Ok(Self::Hour),
|
||||
"minute" => Ok(Self::Minute),
|
||||
"second" => Ok(Self::Second),
|
||||
_ => Err(DeError::custom(format!("unknown every kind '{s}'"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Defines when a notification is delivered.
|
||||
///
|
||||
/// Scheduling is only implemented on mobile; the desktop implementation delivers the
|
||||
/// notification immediately and ignores the schedule.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Schedule {
|
||||
/// Fires at a specific date and time, which must be in the future.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
At {
|
||||
/// The date and time the notification fires at, serialized as an ISO-8601 string.
|
||||
#[serde(
|
||||
serialize_with = "iso8601::serialize",
|
||||
deserialize_with = "time::serde::iso8601::deserialize"
|
||||
)]
|
||||
date: time::OffsetDateTime,
|
||||
/// Whether the notification keeps repeating, using the duration between the moment it is
|
||||
/// scheduled and `date` as the interval. Defaults to `false`.
|
||||
///
|
||||
/// The interval must be at least one minute on iOS.
|
||||
#[serde(default)]
|
||||
repeating: bool,
|
||||
/// Whether the notification is allowed to fire while the device is in low-power idle
|
||||
/// (Doze) mode. Defaults to `false`.
|
||||
///
|
||||
/// Only used on Android.
|
||||
#[serde(default)]
|
||||
allow_while_idle: bool,
|
||||
},
|
||||
/// Fires whenever the current date matches every field set on the given interval.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
Interval {
|
||||
/// The date fields the current date must match for the notification to fire.
|
||||
interval: ScheduleInterval,
|
||||
/// Whether the notification is allowed to fire while the device is in low-power idle
|
||||
/// (Doze) mode. Defaults to `false`.
|
||||
///
|
||||
/// Only used on Android.
|
||||
#[serde(default)]
|
||||
allow_while_idle: bool,
|
||||
},
|
||||
/// Fires repeatedly, once every `count` times the given interval unit.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
Every {
|
||||
/// The unit of the repeating interval.
|
||||
interval: ScheduleEvery,
|
||||
/// How many interval units elapse between each notification.
|
||||
count: u8,
|
||||
/// Whether the notification is allowed to fire while the device is in low-power idle
|
||||
/// (Doze) mode. Defaults to `false`.
|
||||
///
|
||||
/// Only used on Android.
|
||||
#[serde(default)]
|
||||
allow_while_idle: bool,
|
||||
},
|
||||
}
|
||||
|
||||
// custom ISO-8601 serialization that does not use 6 digits for years.
|
||||
mod iso8601 {
|
||||
use serde::{ser::Error as _, Serialize, Serializer};
|
||||
use time::{
|
||||
format_description::well_known::iso8601::{Config, EncodedConfig},
|
||||
format_description::well_known::Iso8601,
|
||||
OffsetDateTime,
|
||||
};
|
||||
|
||||
const SERDE_CONFIG: EncodedConfig = Config::DEFAULT.encode();
|
||||
|
||||
pub fn serialize<S: Serializer>(
|
||||
datetime: &OffsetDateTime,
|
||||
serializer: S,
|
||||
) -> Result<S::Ok, S::Error> {
|
||||
datetime
|
||||
.format(&Iso8601::<SERDE_CONFIG>)
|
||||
.map_err(S::Error::custom)?
|
||||
.serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
/// The payload of a notification, as sent to the platform implementation.
|
||||
///
|
||||
/// Build it with [`NotificationBuilder`](crate::NotificationBuilder) rather than constructing it directly.
|
||||
/// The identifier defaults to a random 32-bit integer when it is not provided.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NotificationData {
|
||||
#[serde(default = "default_id")]
|
||||
pub(crate) id: i32,
|
||||
pub(crate) channel_id: Option<String>,
|
||||
pub(crate) title: Option<String>,
|
||||
pub(crate) body: Option<String>,
|
||||
pub(crate) schedule: Option<Schedule>,
|
||||
pub(crate) large_body: Option<String>,
|
||||
pub(crate) summary: Option<String>,
|
||||
pub(crate) action_type_id: Option<String>,
|
||||
pub(crate) group: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(crate) group_summary: bool,
|
||||
pub(crate) sound: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(crate) inbox_lines: Vec<String>,
|
||||
pub(crate) icon: Option<String>,
|
||||
pub(crate) large_icon: Option<String>,
|
||||
pub(crate) icon_color: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(crate) attachments: Vec<Attachment>,
|
||||
#[serde(default)]
|
||||
pub(crate) extra: HashMap<String, serde_json::Value>,
|
||||
#[serde(default)]
|
||||
pub(crate) ongoing: bool,
|
||||
#[serde(default)]
|
||||
pub(crate) auto_cancel: bool,
|
||||
#[serde(default)]
|
||||
pub(crate) silent: bool,
|
||||
}
|
||||
|
||||
fn default_id() -> i32 {
|
||||
rand::random()
|
||||
}
|
||||
|
||||
impl Default for NotificationData {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
id: default_id(),
|
||||
channel_id: None,
|
||||
title: None,
|
||||
body: None,
|
||||
schedule: None,
|
||||
large_body: None,
|
||||
summary: None,
|
||||
action_type_id: None,
|
||||
group: None,
|
||||
group_summary: false,
|
||||
sound: None,
|
||||
inbox_lines: Vec::new(),
|
||||
icon: None,
|
||||
large_icon: None,
|
||||
icon_color: None,
|
||||
attachments: Vec::new(),
|
||||
extra: Default::default(),
|
||||
ongoing: false,
|
||||
auto_cancel: false,
|
||||
silent: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A notification that was scheduled and has not been delivered yet.
|
||||
///
|
||||
/// Returned by `Notification::pending`, which is only available on mobile.
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PendingNotification {
|
||||
id: i32,
|
||||
title: Option<String>,
|
||||
body: Option<String>,
|
||||
schedule: Schedule,
|
||||
}
|
||||
|
||||
impl PendingNotification {
|
||||
/// The notification identifier.
|
||||
pub fn id(&self) -> i32 {
|
||||
self.id
|
||||
}
|
||||
|
||||
/// The notification title, if it was set.
|
||||
pub fn title(&self) -> Option<&str> {
|
||||
self.title.as_deref()
|
||||
}
|
||||
|
||||
/// The notification body, if it was set.
|
||||
pub fn body(&self) -> Option<&str> {
|
||||
self.body.as_deref()
|
||||
}
|
||||
|
||||
/// The schedule that determines when the notification is delivered.
|
||||
pub fn schedule(&self) -> &Schedule {
|
||||
&self.schedule
|
||||
}
|
||||
}
|
||||
|
||||
/// A notification that was delivered and is still visible in the notification center.
|
||||
///
|
||||
/// Returned by `Notification::active`, which is only available on mobile.
|
||||
/// Which fields are populated depends on the platform, since Android and iOS expose
|
||||
/// different information about delivered notifications.
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ActiveNotification {
|
||||
id: i32,
|
||||
tag: Option<String>,
|
||||
title: Option<String>,
|
||||
body: Option<String>,
|
||||
group: Option<String>,
|
||||
#[serde(default)]
|
||||
group_summary: bool,
|
||||
#[serde(default)]
|
||||
data: HashMap<String, String>,
|
||||
#[serde(default)]
|
||||
extra: HashMap<String, serde_json::Value>,
|
||||
#[serde(default)]
|
||||
attachments: Vec<Attachment>,
|
||||
action_type_id: Option<String>,
|
||||
schedule: Option<Schedule>,
|
||||
sound: Option<String>,
|
||||
}
|
||||
|
||||
impl ActiveNotification {
|
||||
/// The notification identifier.
|
||||
pub fn id(&self) -> i32 {
|
||||
self.id
|
||||
}
|
||||
|
||||
/// The tag the notification was posted with.
|
||||
///
|
||||
/// Only set on Android.
|
||||
pub fn tag(&self) -> Option<&str> {
|
||||
self.tag.as_deref()
|
||||
}
|
||||
|
||||
/// The notification title, if it was set.
|
||||
pub fn title(&self) -> Option<&str> {
|
||||
self.title.as_deref()
|
||||
}
|
||||
|
||||
/// The notification body, if it was set.
|
||||
pub fn body(&self) -> Option<&str> {
|
||||
self.body.as_deref()
|
||||
}
|
||||
|
||||
/// The identifier of the group the notification belongs to.
|
||||
///
|
||||
/// Only set on Android.
|
||||
pub fn group(&self) -> Option<&str> {
|
||||
self.group.as_deref()
|
||||
}
|
||||
|
||||
/// Whether the notification is the summary of its group.
|
||||
///
|
||||
/// Only set on Android. Defaults to `false`.
|
||||
pub fn group_summary(&self) -> bool {
|
||||
self.group_summary
|
||||
}
|
||||
|
||||
/// The platform extras attached to the notification, as string values.
|
||||
///
|
||||
/// Only set on Android, where it holds the `android.app.Notification` extras bundle.
|
||||
pub fn data(&self) -> &HashMap<String, String> {
|
||||
&self.data
|
||||
}
|
||||
|
||||
/// The extra payload that was stored in the notification.
|
||||
pub fn extra(&self) -> &HashMap<String, serde_json::Value> {
|
||||
&self.extra
|
||||
}
|
||||
|
||||
/// The attachments of the notification.
|
||||
///
|
||||
/// Only set on iOS.
|
||||
pub fn attachments(&self) -> &[Attachment] {
|
||||
&self.attachments
|
||||
}
|
||||
|
||||
/// The identifier of the action type the notification was registered with.
|
||||
///
|
||||
/// Only set on iOS.
|
||||
pub fn action_type_id(&self) -> Option<&str> {
|
||||
self.action_type_id.as_deref()
|
||||
}
|
||||
|
||||
/// The schedule the notification was delivered with, if it was scheduled.
|
||||
pub fn schedule(&self) -> Option<&Schedule> {
|
||||
self.schedule.as_ref()
|
||||
}
|
||||
|
||||
/// The sound resource name of the notification.
|
||||
///
|
||||
/// Only set on iOS.
|
||||
pub fn sound(&self) -> Option<&str> {
|
||||
self.sound.as_deref()
|
||||
}
|
||||
}
|
||||
|
||||
/// A group of [`Action`]s a notification can display, referenced by
|
||||
/// [`NotificationBuilder::action_type_id`](crate::NotificationBuilder::action_type_id).
|
||||
///
|
||||
/// Register it with `Notification::register_action_types` before sending a notification that uses it.
|
||||
/// It maps to a `UNNotificationCategory` on iOS and to an action group on Android.
|
||||
///
|
||||
/// Only available on mobile. Use [`ActionType::builder`] to construct one.
|
||||
#[cfg(mobile)]
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ActionType {
|
||||
id: String,
|
||||
actions: Vec<Action>,
|
||||
hidden_previews_body_placeholder: Option<String>,
|
||||
custom_dismiss_action: bool,
|
||||
allow_in_car_play: bool,
|
||||
hidden_previews_show_title: bool,
|
||||
hidden_previews_show_subtitle: bool,
|
||||
}
|
||||
|
||||
/// Builder for an [`ActionType`], created with [`ActionType::builder`].
|
||||
///
|
||||
/// Only available on mobile.
|
||||
#[cfg(mobile)]
|
||||
#[derive(Debug)]
|
||||
pub struct ActionTypeBuilder(ActionType);
|
||||
|
||||
#[cfg(mobile)]
|
||||
impl ActionType {
|
||||
/// Creates a builder for an action type with the given identifier.
|
||||
///
|
||||
/// All the optional settings default to `false` or [`None`];
|
||||
/// call [`ActionTypeBuilder::build`] to get the [`ActionType`].
|
||||
pub fn builder(id: impl Into<String>) -> ActionTypeBuilder {
|
||||
ActionTypeBuilder(Self {
|
||||
id: id.into(),
|
||||
actions: Vec::new(),
|
||||
hidden_previews_body_placeholder: None,
|
||||
custom_dismiss_action: false,
|
||||
allow_in_car_play: false,
|
||||
hidden_previews_show_title: false,
|
||||
hidden_previews_show_subtitle: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// The identifier of this action type.
|
||||
pub fn id(&self) -> &str {
|
||||
&self.id
|
||||
}
|
||||
|
||||
/// The actions associated with this action type.
|
||||
pub fn actions(&self) -> &[Action] {
|
||||
&self.actions
|
||||
}
|
||||
|
||||
/// The placeholder shown instead of the notification body when previews are hidden.
|
||||
///
|
||||
/// Only used on iOS.
|
||||
pub fn hidden_previews_body_placeholder(&self) -> Option<&str> {
|
||||
self.hidden_previews_body_placeholder.as_deref()
|
||||
}
|
||||
|
||||
/// Whether the app is notified when the user dismisses the notification.
|
||||
///
|
||||
/// Only used on iOS.
|
||||
pub fn custom_dismiss_action(&self) -> bool {
|
||||
self.custom_dismiss_action
|
||||
}
|
||||
|
||||
/// Whether the notification can be displayed in a CarPlay environment.
|
||||
///
|
||||
/// Only used on iOS.
|
||||
pub fn allow_in_car_play(&self) -> bool {
|
||||
self.allow_in_car_play
|
||||
}
|
||||
|
||||
/// Whether the notification title is shown even when previews are hidden.
|
||||
///
|
||||
/// Only used on iOS.
|
||||
pub fn hidden_previews_show_title(&self) -> bool {
|
||||
self.hidden_previews_show_title
|
||||
}
|
||||
|
||||
/// Whether the notification subtitle is shown even when previews are hidden.
|
||||
///
|
||||
/// Only used on iOS.
|
||||
pub fn hidden_previews_show_subtitle(&self) -> bool {
|
||||
self.hidden_previews_show_subtitle
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(mobile)]
|
||||
impl ActionTypeBuilder {
|
||||
/// Sets the actions associated with this action type.
|
||||
pub fn actions(mut self, actions: Vec<Action>) -> Self {
|
||||
self.0.actions = actions;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the placeholder shown instead of the notification body when previews are hidden.
|
||||
///
|
||||
/// Only used on iOS.
|
||||
pub fn hidden_previews_body_placeholder(
|
||||
mut self,
|
||||
hidden_previews_body_placeholder: impl Into<String>,
|
||||
) -> Self {
|
||||
self.0
|
||||
.hidden_previews_body_placeholder
|
||||
.replace(hidden_previews_body_placeholder.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether the app is notified when the user dismisses the notification.
|
||||
///
|
||||
/// Only used on iOS.
|
||||
pub fn custom_dismiss_action(mut self, custom_dismiss_action: bool) -> Self {
|
||||
self.0.custom_dismiss_action = custom_dismiss_action;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether the notification can be displayed in a CarPlay environment.
|
||||
///
|
||||
/// Only used on iOS.
|
||||
pub fn allow_in_car_play(mut self, allow_in_car_play: bool) -> Self {
|
||||
self.0.allow_in_car_play = allow_in_car_play;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether the notification title is shown even when previews are hidden.
|
||||
///
|
||||
/// Only used on iOS.
|
||||
pub fn hidden_previews_show_title(mut self, hidden_previews_show_title: bool) -> Self {
|
||||
self.0.hidden_previews_show_title = hidden_previews_show_title;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether the notification subtitle is shown even when previews are hidden.
|
||||
///
|
||||
/// Only used on iOS.
|
||||
pub fn hidden_previews_show_subtitle(mut self, hidden_previews_show_subtitle: bool) -> Self {
|
||||
self.0.hidden_previews_show_subtitle = hidden_previews_show_subtitle;
|
||||
self
|
||||
}
|
||||
|
||||
/// Builds the [`ActionType`].
|
||||
pub fn build(self) -> ActionType {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// A button the user can tap on a notification, belonging to an [`ActionType`].
|
||||
///
|
||||
/// It maps to a `UNNotificationAction` on iOS. On Android only the identifier, the title
|
||||
/// and the input flag are used.
|
||||
///
|
||||
/// Only available on mobile. Use [`Action::builder`] to construct one.
|
||||
#[cfg(mobile)]
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Action {
|
||||
id: String,
|
||||
title: String,
|
||||
requires_authentication: bool,
|
||||
foreground: bool,
|
||||
destructive: bool,
|
||||
input: bool,
|
||||
input_button_title: Option<String>,
|
||||
input_placeholder: Option<String>,
|
||||
}
|
||||
|
||||
/// Builder for an [`Action`], created with [`Action::builder`].
|
||||
///
|
||||
/// Only available on mobile.
|
||||
#[cfg(mobile)]
|
||||
#[derive(Debug)]
|
||||
pub struct ActionBuilder(Action);
|
||||
|
||||
#[cfg(mobile)]
|
||||
impl Action {
|
||||
/// Creates a builder for an action with the given identifier and button title.
|
||||
///
|
||||
/// All the optional settings default to `false` or [`None`];
|
||||
/// call [`ActionBuilder::build`] to get the [`Action`].
|
||||
pub fn builder(id: impl Into<String>, title: impl Into<String>) -> ActionBuilder {
|
||||
ActionBuilder(Self {
|
||||
id: id.into(),
|
||||
title: title.into(),
|
||||
requires_authentication: false,
|
||||
foreground: false,
|
||||
destructive: false,
|
||||
input: false,
|
||||
input_button_title: None,
|
||||
input_placeholder: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The identifier of this action, reported back when the user triggers it.
|
||||
pub fn id(&self) -> &str {
|
||||
&self.id
|
||||
}
|
||||
|
||||
/// The text displayed on the action button.
|
||||
pub fn title(&self) -> &str {
|
||||
&self.title
|
||||
}
|
||||
|
||||
/// Whether the device must be unlocked for the action to run.
|
||||
///
|
||||
/// Only used on iOS.
|
||||
pub fn requires_authentication(&self) -> bool {
|
||||
self.requires_authentication
|
||||
}
|
||||
|
||||
/// Whether the app is brought to the foreground when the action is triggered.
|
||||
///
|
||||
/// Only used on iOS.
|
||||
pub fn foreground(&self) -> bool {
|
||||
self.foreground
|
||||
}
|
||||
|
||||
/// Whether the action is displayed as destructive, usually in red.
|
||||
///
|
||||
/// Only used on iOS.
|
||||
pub fn destructive(&self) -> bool {
|
||||
self.destructive
|
||||
}
|
||||
|
||||
/// Whether triggering the action lets the user type a text response.
|
||||
pub fn input(&self) -> bool {
|
||||
self.input
|
||||
}
|
||||
|
||||
/// The text displayed on the button that submits the text input.
|
||||
///
|
||||
/// Only used on iOS.
|
||||
pub fn input_button_title(&self) -> Option<&str> {
|
||||
self.input_button_title.as_deref()
|
||||
}
|
||||
|
||||
/// The placeholder displayed on the empty text input field.
|
||||
///
|
||||
/// Only used on iOS.
|
||||
pub fn input_placeholder(&self) -> Option<&str> {
|
||||
self.input_placeholder.as_deref()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(mobile)]
|
||||
impl ActionBuilder {
|
||||
/// Sets whether the device must be unlocked for the action to run.
|
||||
///
|
||||
/// Only used on iOS.
|
||||
pub fn requires_authentication(mut self, requires_authentication: bool) -> Self {
|
||||
self.0.requires_authentication = requires_authentication;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether the app is brought to the foreground when the action is triggered.
|
||||
///
|
||||
/// Only used on iOS.
|
||||
pub fn foreground(mut self, foreground: bool) -> Self {
|
||||
self.0.foreground = foreground;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether the action is displayed as destructive, usually in red.
|
||||
///
|
||||
/// Only used on iOS.
|
||||
pub fn destructive(mut self, destructive: bool) -> Self {
|
||||
self.0.destructive = destructive;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether triggering the action lets the user type a text response.
|
||||
pub fn input(mut self, input: bool) -> Self {
|
||||
self.0.input = input;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the text displayed on the button that submits the text input.
|
||||
///
|
||||
/// Only used on iOS.
|
||||
pub fn input_button_title(mut self, input_button_title: impl Into<String>) -> Self {
|
||||
self.0.input_button_title.replace(input_button_title.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the placeholder displayed on the empty text input field.
|
||||
///
|
||||
/// Only used on iOS.
|
||||
pub fn input_placeholder(mut self, input_placeholder: impl Into<String>) -> Self {
|
||||
self.0.input_placeholder.replace(input_placeholder.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Builds the [`Action`].
|
||||
pub fn build(self) -> Action {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
pub use android::*;
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
mod android {
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_repr::{Deserialize_repr, Serialize_repr};
|
||||
|
||||
/// How much the notifications of a [`Channel`] interrupt the user.
|
||||
///
|
||||
/// It maps to the `NotificationManager.IMPORTANCE_*` constants and is serialized as its
|
||||
/// integer value. Only available on Android.
|
||||
#[derive(Debug, Clone, Copy, Serialize_repr, Deserialize_repr)]
|
||||
#[repr(u8)]
|
||||
pub enum Importance {
|
||||
/// The notifications are not shown.
|
||||
None = 0,
|
||||
/// The notifications are only shown in the shade, below the fold, without a status bar icon.
|
||||
Min = 1,
|
||||
/// The notifications are shown without a sound.
|
||||
Low = 2,
|
||||
/// The notifications are shown and make a sound.
|
||||
///
|
||||
/// This is the value used when the channel does not define an importance.
|
||||
Default = 3,
|
||||
/// The notifications are shown, make a sound and pop up as a heads-up notification.
|
||||
High = 4,
|
||||
}
|
||||
|
||||
impl Default for Importance {
|
||||
fn default() -> Self {
|
||||
Self::Default
|
||||
}
|
||||
}
|
||||
|
||||
/// How much of a notification is shown on the lock screen.
|
||||
///
|
||||
/// It maps to the `Notification.VISIBILITY_*` constants and is serialized as its
|
||||
/// integer value. Only available on Android.
|
||||
#[derive(Debug, Clone, Copy, Serialize_repr, Deserialize_repr)]
|
||||
#[repr(i8)]
|
||||
pub enum Visibility {
|
||||
/// The notification is not shown on the lock screen at all.
|
||||
Secret = -1,
|
||||
/// The notification is shown on the lock screen with its sensitive content hidden.
|
||||
///
|
||||
/// This is the value used when the channel does not define a visibility.
|
||||
Private = 0,
|
||||
/// The notification is shown in full on the lock screen.
|
||||
Public = 1,
|
||||
}
|
||||
|
||||
/// A notification channel, the category users configure notification behavior on.
|
||||
///
|
||||
/// Notifications reference a channel through
|
||||
/// [`NotificationBuilder::channel_id`](crate::NotificationBuilder::channel_id) and are not
|
||||
/// delivered when the channel does not exist. Only available on Android.
|
||||
/// Use [`Channel::builder`] to construct one.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Channel {
|
||||
id: String,
|
||||
name: String,
|
||||
description: Option<String>,
|
||||
sound: Option<String>,
|
||||
lights: bool,
|
||||
light_color: Option<String>,
|
||||
vibration: bool,
|
||||
importance: Importance,
|
||||
visibility: Option<Visibility>,
|
||||
}
|
||||
|
||||
/// Builder for a [`Channel`], created with [`Channel::builder`].
|
||||
///
|
||||
/// Only available on Android.
|
||||
#[derive(Debug)]
|
||||
pub struct ChannelBuilder(Channel);
|
||||
|
||||
impl Channel {
|
||||
/// Creates a builder for a channel with the given identifier and user visible name.
|
||||
///
|
||||
/// Lights and vibration are disabled, the importance defaults to [`Importance::Default`]
|
||||
/// and the remaining settings default to [`None`];
|
||||
/// call [`ChannelBuilder::build`] to get the [`Channel`].
|
||||
pub fn builder(id: impl Into<String>, name: impl Into<String>) -> ChannelBuilder {
|
||||
ChannelBuilder(Self {
|
||||
id: id.into(),
|
||||
name: name.into(),
|
||||
description: None,
|
||||
sound: None,
|
||||
lights: false,
|
||||
light_color: None,
|
||||
vibration: false,
|
||||
importance: Default::default(),
|
||||
visibility: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The identifier of this channel.
|
||||
pub fn id(&self) -> &str {
|
||||
&self.id
|
||||
}
|
||||
|
||||
/// The user visible name of this channel.
|
||||
pub fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
/// The user visible description of this channel.
|
||||
pub fn description(&self) -> Option<&str> {
|
||||
self.description.as_deref()
|
||||
}
|
||||
|
||||
/// The name of the sound resource played by the notifications of this channel.
|
||||
///
|
||||
/// The resource must be placed in the app's `res/raw` folder.
|
||||
pub fn sound(&self) -> Option<&str> {
|
||||
self.sound.as_deref()
|
||||
}
|
||||
|
||||
/// Whether the notifications of this channel blink the device light.
|
||||
pub fn lights(&self) -> bool {
|
||||
self.lights
|
||||
}
|
||||
|
||||
/// The color of the device light, as a color string such as `#ff0000`.
|
||||
pub fn light_color(&self) -> Option<&str> {
|
||||
self.light_color.as_deref()
|
||||
}
|
||||
|
||||
/// Whether the notifications of this channel vibrate the device.
|
||||
pub fn vibration(&self) -> bool {
|
||||
self.vibration
|
||||
}
|
||||
|
||||
/// How much the notifications of this channel interrupt the user.
|
||||
pub fn importance(&self) -> Importance {
|
||||
self.importance
|
||||
}
|
||||
|
||||
/// How much of the notifications of this channel is shown on the lock screen.
|
||||
///
|
||||
/// [`Visibility::Private`] is used when this is [`None`].
|
||||
pub fn visibility(&self) -> Option<Visibility> {
|
||||
self.visibility
|
||||
}
|
||||
}
|
||||
|
||||
impl ChannelBuilder {
|
||||
/// Sets the user visible description of the channel.
|
||||
pub fn description(mut self, description: impl Into<String>) -> Self {
|
||||
self.0.description.replace(description.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the name of the sound resource played by the notifications of this channel.
|
||||
///
|
||||
/// The resource must be placed in the app's `res/raw` folder.
|
||||
pub fn sound(mut self, sound: impl Into<String>) -> Self {
|
||||
self.0.sound.replace(sound.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether the notifications of this channel blink the device light.
|
||||
pub fn lights(mut self, lights: bool) -> Self {
|
||||
self.0.lights = lights;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the color of the device light, as a color string such as `#ff0000`.
|
||||
pub fn light_color(mut self, color: impl Into<String>) -> Self {
|
||||
self.0.light_color.replace(color.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether the notifications of this channel vibrate the device.
|
||||
pub fn vibration(mut self, vibration: bool) -> Self {
|
||||
self.0.vibration = vibration;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets how much the notifications of this channel interrupt the user.
|
||||
pub fn importance(mut self, importance: Importance) -> Self {
|
||||
self.0.importance = importance;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets how much of the notifications of this channel is shown on the lock screen.
|
||||
pub fn visibility(mut self, visibility: Visibility) -> Self {
|
||||
self.0.visibility.replace(visibility);
|
||||
self
|
||||
}
|
||||
|
||||
/// Builds the [`Channel`].
|
||||
pub fn build(self) -> Channel {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
}
|
||||
21
plugins/notification/test/tauri.conf.json
Normal file
21
plugins/notification/test/tauri.conf.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"identifier": "app.tauri.example",
|
||||
"build": {
|
||||
"frontendDist": ".",
|
||||
"devUrl": "http://localhost:4000"
|
||||
},
|
||||
"app": {
|
||||
"windows": [
|
||||
{
|
||||
"title": "Tauri App"
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": "default-src blob: data: filesystem: ws: wss: http: https: tauri: http://tauri.localhost 'unsafe-eval' 'unsafe-inline' 'self'"
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"icon": ["../../../examples/api/src-tauri/icons/icon.png"]
|
||||
}
|
||||
}
|
||||
7
plugins/notification/tsconfig.json
Normal file
7
plugins/notification/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "guest-js"
|
||||
},
|
||||
"include": ["guest-js/*.ts"]
|
||||
}
|
||||
Reference in New Issue
Block a user