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(|e| e.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(|e| e.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.lock().unwrap_or_else(|e| e.into_inner()).pop_front();
113        let Some(text) = next else { return };
114        handler(&text);
115    }
116}
117
118/// The first `http`/`https` link in shared text. Share sheets hand links over in every shape:
119/// Chrome sends the bare URL, other apps "Title https://… via App", a mail client `<https://…>`.
120/// The link ends at whitespace or a character URLs never contain, and loses the sentence
121/// punctuation after it, and a closing bracket it did not open.
122fn web_link_in(text: &str) -> Option<&str> {
123    // ASCII lowercasing keeps every byte offset, so positions found here index `text`.
124    let lower = text.to_ascii_lowercase();
125    let mut from = 0;
126    while let Some(found) = lower[from..].find("http") {
127        let start = from + found;
128        from = start + 4;
129        let rest = &lower[start..];
130        let scheme = if rest.starts_with("https://") {
131            8
132        } else if rest.starts_with("http://") {
133            7
134        } else {
135            continue;
136        };
137        // Not the tail of a longer word ("xhttp://").
138        if text[..start]
139            .chars()
140            .next_back()
141            .is_some_and(|c| c.is_ascii_alphanumeric())
142        {
143            continue;
144        }
145        let len = text[start..]
146            .find(|c: char| c.is_whitespace() || matches!(c, '<' | '>' | '"' | '`' | '\u{1f}'))
147            .unwrap_or(text.len() - start);
148        let mut link = &text[start..start + len];
149        loop {
150            let trimmed = link.trim_end_matches(['.', ',', ';', ':', '!', '?', '\'', '*']);
151            let unbalanced = |open: char, close: char| {
152                trimmed.ends_with(close)
153                    && trimmed.matches(close).count() > trimmed.matches(open).count()
154            };
155            let trimmed = if unbalanced('(', ')') || unbalanced('[', ']') {
156                &trimmed[..trimmed.len() - 1]
157            } else {
158                trimmed
159            };
160            if trimmed.len() == link.len() {
161                break;
162            }
163            link = trimmed;
164        }
165        // A host, at least: "https://" alone, or "https:///x", is not a link.
166        if link.len() > scheme && !link[scheme..].starts_with('/') {
167            return Some(link);
168        }
169    }
170    None
171}
172fn drain_queue(queue: &Mutex<VecDeque<String>>) {
173    loop {
174        let next = queue.lock().unwrap_or_else(|e| e.into_inner()).pop_front();
175        let Some(url) = next else { break };
176        // Newest first; a snapshot, so a handler may register or unregister another.
177        let handlers: Vec<_> = HANDLERS.with(|h| h.borrow().iter().rev().cloned().collect());
178        let consumed = handlers.iter().any(|h| h(&url));
179        if !consumed {
180            crate::request_route(&day_spec::route_of_url(&url));
181        }
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188
189    #[test]
190    fn shared_text_finds_the_web_link_in_it() {
191        let cases = [
192            (
193                "https://example.org/a?b=c#d",
194                Some("https://example.org/a?b=c#d"),
195            ),
196            ("  https://example.org\n", Some("https://example.org")),
197            (
198                "Read this: \"Title\" https://example.org/post. Via App",
199                Some("https://example.org/post"),
200            ),
201            ("<HTTP://Example.org/x>", Some("HTTP://Example.org/x")),
202            (
203                "(see https://example.org/a_(b))",
204                Some("https://example.org/a_(b)"),
205            ),
206            (
207                "(see https://example.org/a)!",
208                Some("https://example.org/a"),
209            ),
210            (
211                "first http://a.example then https://b.example",
212                Some("http://a.example"),
213            ),
214            (
215                "xhttp://not.a.link https://yes.example",
216                Some("https://yes.example"),
217            ),
218            ("ftp://example.org", None),
219            ("https:// nothing", None),
220            ("a quote with no link", None),
221            ("http and https words", None),
222        ];
223        for (text, want) in cases {
224            assert_eq!(web_link_in(text), want, "{text:?}");
225        }
226    }
227
228    #[test]
229    fn shared_text_waits_for_the_newest_handler() {
230        let queue = Mutex::new(VecDeque::from(["early".to_string()]));
231        // Nothing registered: the text stays.
232        drain_shared_queue(&queue);
233        assert_eq!(queue.lock().unwrap().len(), 1);
234        let first = Rc::new(RefCell::new(Vec::new()));
235        let second = Rc::new(RefCell::new(Vec::new()));
236        let app = day_reactive::Scope::child();
237        let seen = first.clone();
238        app.enter(|| on_shared_text(move |t| seen.borrow_mut().push(t.to_owned())));
239        drain_shared_queue(&queue);
240        assert_eq!(*first.borrow(), ["early"]);
241        let page = day_reactive::Scope::child();
242        let seen = second.clone();
243        page.enter(|| on_shared_text(move |t| seen.borrow_mut().push(t.to_owned())));
244        queue.lock().unwrap().push_back("later".into());
245        drain_shared_queue(&queue);
246        assert_eq!(*second.borrow(), ["later"]);
247        page.dispose();
248        queue.lock().unwrap().push_back("last".into());
249        drain_shared_queue(&queue);
250        assert_eq!(*first.borrow(), ["early", "last"]);
251        app.dispose();
252        assert!(SHARED_HANDLERS.with(|h| h.borrow().is_empty()));
253    }
254    #[test]
255    fn original_urls_are_queued_reentrant_and_scoped() {
256        let seen = Rc::new(RefCell::new(Vec::new()));
257        // No main poster exists in this unit test: cold data survives until the root installs.
258        let queue = std::sync::Arc::new(Mutex::new(VecDeque::from([
259            "feed:https://fixture.example/rss?q=a%26b".into(),
260        ])));
261        let again = queue.clone();
262        let scope = day_reactive::Scope::child();
263        let received = seen.clone();
264        scope.enter(|| {
265            on_open_url(move |url| {
266                received.borrow_mut().push(url.to_owned());
267                if url.starts_with("feed:") {
268                    again
269                        .lock()
270                        .unwrap()
271                        .push_back("atom:https://fixture.example/atom".into());
272                }
273                true
274            })
275        });
276        drain_queue(&queue);
277        queue
278            .lock()
279            .unwrap()
280            .push_back("rss://fixture.example/rss".into());
281        drain_queue(&queue);
282        assert_eq!(
283            *seen.borrow(),
284            [
285                "feed:https://fixture.example/rss?q=a%26b",
286                "atom:https://fixture.example/atom",
287                "rss://fixture.example/rss"
288            ]
289        );
290        scope.dispose();
291        assert!(HANDLERS.with(|h| h.borrow().is_empty()));
292    }
293
294    /// A later registration is asked first and may decline, which hands the URL on to the
295    /// earlier one; disposing its scope removes only its own entry.
296    #[test]
297    fn handlers_stack_newest_first_and_leave_with_their_scope() {
298        let app_seen = Rc::new(RefCell::new(Vec::new()));
299        let part_seen = Rc::new(RefCell::new(Vec::new()));
300        let queue = std::sync::Arc::new(Mutex::new(VecDeque::new()));
301        let app_scope = day_reactive::Scope::child();
302        let received = app_seen.clone();
303        app_scope.enter(|| {
304            on_open_url(move |url| {
305                received.borrow_mut().push(url.to_owned());
306                true
307            })
308        });
309        let part_scope = day_reactive::Scope::child();
310        let received = part_seen.clone();
311        part_scope.enter(|| {
312            on_open_url(move |url| {
313                let mine = url.starts_with("myapp://auth");
314                if mine {
315                    received.borrow_mut().push(url.to_owned());
316                }
317                mine
318            })
319        });
320        queue.lock().unwrap().extend([
321            "myapp://auth?code=1".to_string(),
322            "myapp://inbox".to_string(),
323        ]);
324        drain_queue(&queue);
325        assert_eq!(*part_seen.borrow(), ["myapp://auth?code=1"]);
326        assert_eq!(*app_seen.borrow(), ["myapp://inbox"]);
327        part_scope.dispose();
328        assert_eq!(HANDLERS.with(|h| h.borrow().len()), 1);
329        queue
330            .lock()
331            .unwrap()
332            .push_back("myapp://auth?code=2".into());
333        drain_queue(&queue);
334        assert_eq!(*app_seen.borrow(), ["myapp://inbox", "myapp://auth?code=2"]);
335        app_scope.dispose();
336        assert!(HANDLERS.with(|h| h.borrow().is_empty()));
337    }
338}