Skip to main content

day_core/
urls.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3//! Raw external URL delivery; application handlers may consume data links before routing.
4//! Text shared to the app from the system share sheet arrives here too: a web link in it goes
5//! the URL way, other text to [`on_shared_text`].
6use std::{cell::RefCell, collections::VecDeque, rc::Rc, sync::Mutex};
7static PENDING: Mutex<VecDeque<String>> = Mutex::new(VecDeque::new());
8/// Shared text with no web link in it, waiting for a handler.
9static SHARED: Mutex<VecDeque<String>> = Mutex::new(VecDeque::new());
10day_reactive::tls_slots! {
11    urls;
12    static HANDLERS: RefCell<Vec<Rc<dyn Fn(&str) -> bool>>> = const { RefCell::new(Vec::new()) };
13    static SHARED_HANDLERS: RefCell<Vec<Rc<dyn Fn(&str)>>> = const { RefCell::new(Vec::new()) };
14}
15/// Register on the UI thread. Return true to consume a URL; false retains normal deep-link
16/// routing. Delivery never performs a privileged action.
17///
18/// Handlers stack: the newest registration is asked first, and a URL it declines goes to the
19/// ones before it, so a part that awaits a callback URL (a sign-in's redirect) can register
20/// for the duration of its scope without displacing the application's own handler. Each
21/// registration leaves the stack when the scope it was made in is disposed.
22pub fn on_open_url(handler: impl Fn(&str) -> bool + 'static) {
23    let handler: Rc<dyn Fn(&str) -> bool> = Rc::new(handler);
24    HANDLERS.with(|h| h.borrow_mut().push(handler.clone()));
25    day_reactive::Scope::current().on_cleanup(move || {
26        let _ = HANDLERS.try_with(|h| {
27            h.borrow_mut()
28                .retain(|current| !Rc::ptr_eq(current, &handler));
29        });
30    });
31    if day_reactive::has_main_poster() {
32        day_reactive::on_main(drain);
33    }
34}
35/// Platform intake. Keeps the original URL, including its scheme, query and escaping.
36pub fn request_open_url(url: &str) {
37    if url.is_empty() {
38        return;
39    }
40    PENDING
41        .lock()
42        .unwrap_or_else(std::sync::PoisonError::into_inner)
43        .push_back(url.into());
44    if day_reactive::has_main_poster() {
45        day_reactive::on_main(drain);
46    }
47}
48pub(crate) fn drain() {
49    drain_queue(&PENDING);
50}
51
52/// Receive text the user shares to the app from another app's share sheet, on the UI thread
53/// (Day.toml `share_target`, docs/deep-links.md "Receiving shared links").
54///
55/// Shared text that holds a web link never arrives here: its first `http`/`https` URL goes to
56/// [`on_open_url`] instead, exactly as if the link had been opened with the app, which is what
57/// a browser or a reader wants from "Share → App". This receives the rest: a search term, a
58/// note, a quote. Text shared before any handler exists waits for the first registration.
59///
60/// The newest registration receives the text; it leaves when the scope it was made in is
61/// disposed, and the one before it receives again.
62pub fn on_shared_text(handler: impl Fn(&str) + 'static) {
63    let handler: Rc<dyn Fn(&str)> = Rc::new(handler);
64    SHARED_HANDLERS.with(|h| h.borrow_mut().push(handler.clone()));
65    day_reactive::Scope::current().on_cleanup(move || {
66        let _ = SHARED_HANDLERS.try_with(|h| {
67            h.borrow_mut()
68                .retain(|current| !Rc::ptr_eq(current, &handler));
69        });
70    });
71    if day_reactive::has_main_poster() {
72        day_reactive::on_main(drain_shared);
73    }
74}
75
76/// Platform intake for the share sheet: the shared `text` and the `subject` that came with it
77/// (a page title, a mail subject). The first web link in the text, else in the subject, goes to
78/// [`request_open_url`]; otherwise the text (the subject when the text is empty) goes to
79/// [`on_shared_text`].
80pub fn request_shared_text(text: &str, subject: Option<&str>) {
81    if let Some(url) = web_link_in(text).or_else(|| subject.and_then(web_link_in)) {
82        request_open_url(url);
83        return;
84    }
85    let text = if text.trim().is_empty() {
86        subject.unwrap_or_default()
87    } else {
88        text
89    };
90    if text.trim().is_empty() {
91        return;
92    }
93    SHARED
94        .lock()
95        .unwrap_or_else(std::sync::PoisonError::into_inner)
96        .push_back(text.into());
97    if day_reactive::has_main_poster() {
98        day_reactive::on_main(drain_shared);
99    }
100}
101
102fn drain_shared() {
103    drain_shared_queue(&SHARED);
104}
105
106fn drain_shared_queue(queue: &Mutex<VecDeque<String>>) {
107    loop {
108        // Text waits in the queue until someone registers to receive it.
109        let Some(handler) = SHARED_HANDLERS.with(|h| h.borrow().last().cloned()) else {
110            return;
111        };
112        let next = queue
113            .lock()
114            .unwrap_or_else(std::sync::PoisonError::into_inner)
115            .pop_front();
116        let Some(text) = next else { return };
117        handler(&text);
118    }
119}
120
121/// The first `http`/`https` link in shared text. Share sheets hand links over in every shape:
122/// Chrome sends the bare URL, other apps "Title https://… via App", a mail client `<https://…>`.
123/// The link ends at whitespace or a character URLs never contain, and loses the sentence
124/// punctuation after it, and a closing bracket it did not open.
125fn web_link_in(text: &str) -> Option<&str> {
126    // ASCII lowercasing keeps every byte offset, so positions found here index `text`.
127    let lower = text.to_ascii_lowercase();
128    let mut from = 0;
129    while let Some(found) = lower[from..].find("http") {
130        let start = from + found;
131        from = start + 4;
132        let rest = &lower[start..];
133        let scheme = if rest.starts_with("https://") {
134            8
135        } else if rest.starts_with("http://") {
136            7
137        } else {
138            continue;
139        };
140        // Not the tail of a longer word ("xhttp://").
141        if text[..start]
142            .chars()
143            .next_back()
144            .is_some_and(|c| c.is_ascii_alphanumeric())
145        {
146            continue;
147        }
148        let len = text[start..]
149            .find(|c: char| c.is_whitespace() || matches!(c, '<' | '>' | '"' | '`' | '\u{1f}'))
150            .unwrap_or(text.len() - start);
151        let mut link = &text[start..start + len];
152        loop {
153            let trimmed = link.trim_end_matches(['.', ',', ';', ':', '!', '?', '\'', '*']);
154            let unbalanced = |open: char, close: char| {
155                trimmed.ends_with(close)
156                    && trimmed.matches(close).count() > trimmed.matches(open).count()
157            };
158            let trimmed = if unbalanced('(', ')') || unbalanced('[', ']') {
159                &trimmed[..trimmed.len() - 1]
160            } else {
161                trimmed
162            };
163            if trimmed.len() == link.len() {
164                break;
165            }
166            link = trimmed;
167        }
168        // A host, at least: "https://" alone, or "https:///x", is not a link.
169        if link.len() > scheme && !link[scheme..].starts_with('/') {
170            return Some(link);
171        }
172    }
173    None
174}
175fn drain_queue(queue: &Mutex<VecDeque<String>>) {
176    loop {
177        let next = queue
178            .lock()
179            .unwrap_or_else(std::sync::PoisonError::into_inner)
180            .pop_front();
181        let Some(url) = next else { break };
182        // Newest first; a snapshot, so a handler may register or unregister another.
183        let handlers: Vec<_> = HANDLERS.with(|h| h.borrow().iter().rev().cloned().collect());
184        let consumed = handlers.iter().any(|h| h(&url));
185        if !consumed {
186            crate::request_route(&day_spec::route_of_url(&url));
187        }
188    }
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194
195    #[test]
196    fn shared_text_finds_the_web_link_in_it() {
197        let cases = [
198            (
199                "https://example.org/a?b=c#d",
200                Some("https://example.org/a?b=c#d"),
201            ),
202            ("  https://example.org\n", Some("https://example.org")),
203            (
204                "Read this: \"Title\" https://example.org/post. Via App",
205                Some("https://example.org/post"),
206            ),
207            ("<HTTP://Example.org/x>", Some("HTTP://Example.org/x")),
208            (
209                "(see https://example.org/a_(b))",
210                Some("https://example.org/a_(b)"),
211            ),
212            (
213                "(see https://example.org/a)!",
214                Some("https://example.org/a"),
215            ),
216            (
217                "first http://a.example then https://b.example",
218                Some("http://a.example"),
219            ),
220            (
221                "xhttp://not.a.link https://yes.example",
222                Some("https://yes.example"),
223            ),
224            ("ftp://example.org", None),
225            ("https:// nothing", None),
226            ("a quote with no link", None),
227            ("http and https words", None),
228        ];
229        for (text, want) in cases {
230            assert_eq!(web_link_in(text), want, "{text:?}");
231        }
232    }
233
234    #[test]
235    fn shared_text_waits_for_the_newest_handler() {
236        let queue = Mutex::new(VecDeque::from(["early".to_string()]));
237        // Nothing registered: the text stays.
238        drain_shared_queue(&queue);
239        assert_eq!(queue.lock().unwrap().len(), 1);
240        let first = Rc::new(RefCell::new(Vec::new()));
241        let second = Rc::new(RefCell::new(Vec::new()));
242        let app = day_reactive::Scope::child();
243        let seen = first.clone();
244        app.enter(|| on_shared_text(move |t| seen.borrow_mut().push(t.to_owned())));
245        drain_shared_queue(&queue);
246        assert_eq!(*first.borrow(), ["early"]);
247        let page = day_reactive::Scope::child();
248        let seen = second.clone();
249        page.enter(|| on_shared_text(move |t| seen.borrow_mut().push(t.to_owned())));
250        queue.lock().unwrap().push_back("later".into());
251        drain_shared_queue(&queue);
252        assert_eq!(*second.borrow(), ["later"]);
253        page.dispose();
254        queue.lock().unwrap().push_back("last".into());
255        drain_shared_queue(&queue);
256        assert_eq!(*first.borrow(), ["early", "last"]);
257        app.dispose();
258        assert!(SHARED_HANDLERS.with(|h| h.borrow().is_empty()));
259    }
260    #[test]
261    fn original_urls_are_queued_reentrant_and_scoped() {
262        let seen = Rc::new(RefCell::new(Vec::new()));
263        // No main poster exists in this unit test: cold data survives until the root installs.
264        let queue = std::sync::Arc::new(Mutex::new(VecDeque::from([
265            "feed:https://fixture.example/rss?q=a%26b".into(),
266        ])));
267        let again = queue.clone();
268        let scope = day_reactive::Scope::child();
269        let received = seen.clone();
270        scope.enter(|| {
271            on_open_url(move |url| {
272                received.borrow_mut().push(url.to_owned());
273                if url.starts_with("feed:") {
274                    again
275                        .lock()
276                        .unwrap()
277                        .push_back("atom:https://fixture.example/atom".into());
278                }
279                true
280            });
281        });
282        drain_queue(&queue);
283        queue
284            .lock()
285            .unwrap()
286            .push_back("rss://fixture.example/rss".into());
287        drain_queue(&queue);
288        assert_eq!(
289            *seen.borrow(),
290            [
291                "feed:https://fixture.example/rss?q=a%26b",
292                "atom:https://fixture.example/atom",
293                "rss://fixture.example/rss"
294            ]
295        );
296        scope.dispose();
297        assert!(HANDLERS.with(|h| h.borrow().is_empty()));
298    }
299
300    /// A later registration is asked first and may decline, which hands the URL on to the
301    /// earlier one; disposing its scope removes only its own entry.
302    #[test]
303    fn handlers_stack_newest_first_and_leave_with_their_scope() {
304        let app_seen = Rc::new(RefCell::new(Vec::new()));
305        let part_seen = Rc::new(RefCell::new(Vec::new()));
306        let queue = std::sync::Arc::new(Mutex::new(VecDeque::new()));
307        let app_scope = day_reactive::Scope::child();
308        let received = app_seen.clone();
309        app_scope.enter(|| {
310            on_open_url(move |url| {
311                received.borrow_mut().push(url.to_owned());
312                true
313            });
314        });
315        let part_scope = day_reactive::Scope::child();
316        let received = part_seen.clone();
317        part_scope.enter(|| {
318            on_open_url(move |url| {
319                let mine = url.starts_with("myapp://auth");
320                if mine {
321                    received.borrow_mut().push(url.to_owned());
322                }
323                mine
324            });
325        });
326        queue.lock().unwrap().extend([
327            "myapp://auth?code=1".to_string(),
328            "myapp://inbox".to_string(),
329        ]);
330        drain_queue(&queue);
331        assert_eq!(*part_seen.borrow(), ["myapp://auth?code=1"]);
332        assert_eq!(*app_seen.borrow(), ["myapp://inbox"]);
333        part_scope.dispose();
334        assert_eq!(HANDLERS.with(|h| h.borrow().len()), 1);
335        queue
336            .lock()
337            .unwrap()
338            .push_back("myapp://auth?code=2".into());
339        drain_queue(&queue);
340        assert_eq!(*app_seen.borrow(), ["myapp://inbox", "myapp://auth?code=2"]);
341        app_scope.dispose();
342        assert!(HANDLERS.with(|h| h.borrow().is_empty()));
343    }
344}