Skip to main content

g3_native_plugins/
deep_links.rs

1use serde_json::{Value, json};
2/// Declared for its side effect: this is what tells `dx` to build and bundle
3/// the Kotlin module. The calls go through [`crate::android_bridge`] instead,
4/// because the macro's own bindings resolve classes against the calling
5/// thread's loader and Dioxus does not call from a thread that has one.
6#[cfg(all(feature = "deep-links", target_os = "android"))]
7#[manganis::ffi("src/android/deep_links")]
8unsafe extern "Kotlin" {
9    pub type DeepLinksPlugin;
10}
11#[cfg(all(feature = "deep-links", target_os = "android"))]
12const DEEP_LINKS_CLASS: &str = "dev.dioxus.g3_native_plugins.deep_links.DeepLinksPlugin";
13#[cfg(all(feature = "deep-links", target_os = "android"))]
14type DeepLinksHandle = crate::android_bridge::AndroidPlugin;
15#[cfg(all(feature = "deep-links", target_os = "ios"))]
16type DeepLinksHandle = DeepLinksPlugin;
17#[cfg(all(feature = "deep-links", target_os = "ios"))]
18#[allow(missing_docs)]
19#[manganis::ffi("src/ios")]
20unsafe extern "Swift" {
21    /// Native iOS deep-link queue bridge.
22    pub type DeepLinksPlugin;
23    /// Installs the native app-delegate hooks.
24    pub fn prepareFromRust(this: &DeepLinksPlugin);
25    /// Removes and returns the oldest queued link.
26    pub fn takeLinkFromRust(this: &DeepLinksPlugin) -> Option<String>;
27}
28/// The URLs a universal link, App Link, or custom scheme opened the app with.
29///
30/// This is the receiving half of deep linking. Declaring the links is already
31/// handled elsewhere: the Dioxus CLI writes the `Info.plist` and manifest
32/// entries from `[deep_links]` in `Dioxus.toml`, and the builders in this
33/// module generate the `apple-app-site-association` and `assetlinks.json` files
34/// the two platforms fetch to verify the claim. What neither covers is the URL
35/// itself once the app is open, which is what this does.
36///
37/// Links are queued and polled rather than pushed at a listener. A link can
38/// arrive before the app has rendered anything able to receive it — a cold
39/// start is the normal case, not the edge case — and unlike a back gesture it
40/// is a value that must not be dropped. Drain it wherever routing decisions are
41/// made:
42///
43/// ```rust,ignore
44/// let mut plugins = use_context::<NativePlugins>();
45/// let navigator = use_navigator();
46///
47/// use_future(move || async move {
48///     loop {
49///         while let Ok(Some(url)) = plugins.deep_links.write().take_link() {
50///             // Route on the URL however the app wants to.
51///         }
52///         gloo_timers::future::TimeoutFuture::new(200).await;
53///     }
54/// });
55/// ```
56///
57/// [`prepare`](DeepLinks::prepare) is worth calling as early as the app can
58/// manage, because on iOS a cold-start link is read from the launch options and
59/// they are only observable before launching finishes. [`DeepLinks::new`] is
60/// public so that can happen ahead of the plugin provider, and the queue lives
61/// on the native side rather than in this struct, so a link is never stranded
62/// on an instance that has since been dropped.
63///
64/// On the web the browser hands the app its URL directly and the router already
65/// routes it, and macOS has no equivalent delivery, so both are inert and
66/// callers need no cfg of their own.
67#[cfg(all(feature = "deep-links", any(target_os = "android", target_os = "ios")))]
68pub struct DeepLinks {
69    plugin: Option<DeepLinksHandle>,
70}
71/// The inert deep-link facade: see the native [`DeepLinks`] for the contract.
72#[cfg(all(
73    feature = "deep-links",
74    any(target_arch = "wasm32", target_os = "macos")
75))]
76pub struct DeepLinks;
77#[cfg(all(feature = "deep-links", any(target_os = "android", target_os = "ios")))]
78impl DeepLinks {
79    /// Create an unprepared deep-link receiver.
80    ///
81    /// Public, unlike most plugins here, so an app can prepare the native side
82    /// before [`crate::NativePluginsProvider`] exists. The queue is shared
83    /// across instances, so an early instance and the provider's own see the
84    /// same links.
85    pub fn new() -> Self {
86        Self { plugin: None }
87    }
88    fn get_plugin(&mut self) -> Result<&DeepLinksHandle, String> {
89        if self.plugin.is_none() {
90            #[cfg(target_os = "android")]
91            let created = DeepLinksHandle::new(DEEP_LINKS_CLASS)?;
92            #[cfg(target_os = "ios")]
93            let created = DeepLinksPlugin::new()
94                .map_err(|error| format!("Failed to create DeepLinksPlugin: {error:?}"))?;
95            self.plugin = Some(created);
96        }
97        Ok(self.plugin.as_ref().unwrap())
98    }
99    /// Start collecting links.
100    ///
101    /// Call this as early as the app can. On iOS a link that started the app is
102    /// only readable from the launch options, so preparing after launch has
103    /// finished can miss a cold-start link; on Android the launch Intent stays
104    /// readable and timing does not matter. Calling it more than once is
105    /// harmless and does not re-deliver a link already queued.
106    pub fn prepare(&mut self) -> Result<(), String> {
107        let plugin = self.get_plugin()?;
108        #[cfg(target_os = "android")]
109        plugin.call_unit("prepareFromRust")?;
110        #[cfg(target_os = "ios")]
111        prepareFromRust(plugin)?;
112        Ok(())
113    }
114    /// Take the oldest link not yet handled, or `None` when none are waiting.
115    ///
116    /// Preparation happens on the platform's main thread while this is called
117    /// from a Dioxus effect thread, so a link queued at launch may need a poll
118    /// or two to appear. Drain in a loop until this returns `None`.
119    pub fn take_link(&mut self) -> Result<Option<String>, String> {
120        let plugin = self.get_plugin()?;
121        #[cfg(target_os = "android")]
122        return plugin.call_string("takeLinkFromRust");
123        #[cfg(target_os = "ios")]
124        return Ok(takeLinkFromRust(plugin)?);
125    }
126}
127#[cfg(all(
128    feature = "deep-links",
129    any(target_arch = "wasm32", target_os = "macos")
130))]
131impl DeepLinks {
132    /// Create the inert deep-link facade used where nothing delivers links.
133    pub fn new() -> Self {
134        Self
135    }
136    /// No-op: the browser routes its own URL, and macOS delivers no links here.
137    pub fn prepare(&mut self) -> Result<(), String> {
138        Ok(())
139    }
140    /// Always `None`: nothing on these targets queues a link.
141    pub fn take_link(&mut self) -> Result<Option<String>, String> {
142        Ok(None)
143    }
144}
145#[cfg(all(
146    feature = "deep-links",
147    any(
148        target_arch = "wasm32",
149        target_os = "android",
150        target_os = "ios",
151        target_os = "macos"
152    )
153))]
154impl Default for DeepLinks {
155    fn default() -> Self {
156        Self::new()
157    }
158}
159/// The contents of an `apple-app-site-association` file, which iOS fetches
160/// from `https://<host>/.well-known/apple-app-site-association` to decide
161/// which URLs open in the app instead of Safari.
162#[derive(Debug, Clone, PartialEq, Eq)]
163pub struct AppleAppSiteAssociation {
164    /// The Apple Developer Team ID that prefixes the app identifier.
165    pub team_id: String,
166    /// The app's bundle identifier, e.g. `com.G3Tech.GreensidePartee`.
167    pub bundle_id: String,
168    /// URL paths claimed by the app. Supports Apple's wildcard syntax, so
169    /// `/games/*/join` matches any game id.
170    pub paths: Vec<String>,
171}
172impl AppleAppSiteAssociation {
173    /// Build an association for one app and the paths it claims.
174    pub fn new(
175        team_id: impl Into<String>,
176        bundle_id: impl Into<String>,
177        paths: impl IntoIterator<Item = impl Into<String>>,
178    ) -> Self {
179        Self {
180            team_id: team_id.into(),
181            bundle_id: bundle_id.into(),
182            paths: paths.into_iter().map(Into::into).collect(),
183        }
184    }
185    /// The fully qualified app identifier Apple expects: `<team_id>.<bundle_id>`.
186    pub fn app_id(&self) -> String {
187        format!("{}.{}", self.team_id, self.bundle_id)
188    }
189    /// Render the association as the JSON body to serve at the well-known path.
190    pub fn to_json(&self) -> Value {
191        json!(
192            { "applinks" : { "apps" : [], "details" : [{ "appID" : self.app_id(), "paths"
193            : self.paths }] } }
194        )
195    }
196}
197/// The contents of an `assetlinks.json` file, which Android fetches from
198/// `https://<host>/.well-known/assetlinks.json` to verify an App Link and
199/// open matching URLs in the app without a disambiguation dialog.
200#[derive(Debug, Clone, PartialEq, Eq)]
201pub struct AndroidAssetLinks {
202    /// The application id of the Android app, e.g. `com.G3Tech.GreensidePartee`.
203    pub package_name: String,
204    /// SHA-256 fingerprints of the signing certificates. Include both the
205    /// upload and Play-managed app-signing keys when Play App Signing is on,
206    /// or verification fails for store builds.
207    pub sha256_cert_fingerprints: Vec<String>,
208}
209impl AndroidAssetLinks {
210    /// Build an asset-links statement for one app and its signing fingerprints.
211    pub fn new(
212        package_name: impl Into<String>,
213        sha256_cert_fingerprints: impl IntoIterator<Item = impl Into<String>>,
214    ) -> Self {
215        Self {
216            package_name: package_name.into(),
217            sha256_cert_fingerprints: sha256_cert_fingerprints
218                .into_iter()
219                .map(Into::into)
220                .collect(),
221        }
222    }
223    /// Render the statement list as the JSON body to serve at the well-known path.
224    pub fn to_json(&self) -> Value {
225        json!(
226            [{ "relation" : ["delegate_permission/common.handle_all_urls"], "target" : {
227            "namespace" : "android_app", "package_name" : self.package_name,
228            "sha256_cert_fingerprints" : self.sha256_cert_fingerprints } }]
229        )
230    }
231}
232/// Shorthand for [`AppleAppSiteAssociation::new`] followed by
233/// [`AppleAppSiteAssociation::to_json`].
234pub fn apple_app_site_association(
235    team_id: impl Into<String>,
236    bundle_id: impl Into<String>,
237    paths: impl IntoIterator<Item = impl Into<String>>,
238) -> Value {
239    AppleAppSiteAssociation::new(team_id, bundle_id, paths).to_json()
240}
241/// Shorthand for [`AndroidAssetLinks::new`] followed by
242/// [`AndroidAssetLinks::to_json`].
243pub fn android_asset_links(
244    package_name: impl Into<String>,
245    sha256_cert_fingerprints: impl IntoIterator<Item = impl Into<String>>,
246) -> Value {
247    AndroidAssetLinks::new(package_name, sha256_cert_fingerprints).to_json()
248}
249/// Define the server route that serves the `apple-app-site-association`
250/// file, so iOS universal links resolve for the given team, bundle, and
251/// paths.
252///
253/// Expands to a `#[get]` handler; call it once in a server module.
254#[macro_export]
255macro_rules! ios_app_site_association_route {
256    (
257        team_id : $team_id:expr, bundle_id : $bundle_id:expr, paths : [$($path:expr),*
258        $(,)?] $(,)?
259    ) => {
260        #[dioxus::prelude::get("/.well-known/apple-app-site-association")] async fn
261        get_apple_app_site_association() -> dioxus::prelude::Result <
262        dioxus_fullstack::Json < serde_json::Value >, dioxus::prelude::StatusCode > {
263        Ok(dioxus_fullstack::Json($crate::deep_links::apple_app_site_association($team_id,
264        $bundle_id, [$($path),*]))) }
265    };
266}
267/// Define the server route that serves `assetlinks.json`, so Android App
268/// Links resolve for the given package and signing fingerprints.
269///
270/// Expands to a `#[get]` handler; call it once in a server module.
271#[macro_export]
272macro_rules! android_asset_links_route {
273    (
274        package_name : $package_name:expr, sha256_cert_fingerprints :
275        [$($fingerprint:expr),* $(,)?] $(,)?
276    ) => {
277        #[dioxus::prelude::get("/.well-known/assetlinks.json")] async fn
278        get_android_asset_links() -> dioxus::prelude::Result < dioxus_fullstack::Json <
279        serde_json::Value >, dioxus::prelude::StatusCode > {
280        Ok(dioxus_fullstack::Json($crate::deep_links::android_asset_links($package_name,
281        [$($fingerprint),*]))) }
282    };
283}
284#[cfg(test)]
285mod tests {
286    use super::*;
287    fn production_source() -> &'static str {
288        include_str!("deep_links.rs")
289            .split("#[cfg(test)]")
290            .next()
291            .expect("source should split before tests")
292    }
293    #[test]
294    fn generates_apple_app_site_association() {
295        let association = AppleAppSiteAssociation::new(
296            "TEAM123456",
297            "com.example.App",
298            ["/account", "/games/*/join"],
299        );
300        assert_eq!(association.app_id(), "TEAM123456.com.example.App");
301        assert_eq!(
302            association.to_json(),
303            json!(
304                { "applinks" : { "apps" : [], "details" : [{ "appID" :
305                "TEAM123456.com.example.App", "paths" : ["/account", "/games/*/join"] }]
306                } }
307            ),
308        );
309    }
310    #[test]
311    fn generates_android_asset_links() {
312        assert_eq!(
313            android_asset_links("com.example.App", ["AA:BB", "CC:DD"]),
314            json!(
315                [{ "relation" : ["delegate_permission/common.handle_all_urls"], "target"
316                : { "namespace" : "android_app", "package_name" : "com.example.App",
317                "sha256_cert_fingerprints" : ["AA:BB", "CC:DD"] } }]
318            ),
319        );
320    }
321    #[test]
322    fn exports_ios_and_android_route_macros() {
323        let source = production_source();
324        assert!(source.contains("macro_rules! ios_app_site_association_route"));
325        assert!(source.contains("macro_rules! android_asset_links_route"));
326        assert!(
327            source
328                .contains("#[dioxus::prelude::get(\"/.well-known/apple-app-site-association\")]",),
329        );
330        assert!(source.contains("#[dioxus::prelude::get(\"/.well-known/assetlinks.json\")]"),);
331        assert!(source.contains("dioxus_fullstack::Json"));
332    }
333}