Skip to content

XP event5x XPListening, games, ratings, comments and chat earn five times the XP

leftLeaderboard

juicewrld-desktopsrc-taurisrcnotices.rs

1.4.2Released Nov 21, 2026

notices.rs

411 lines17.3 KBRust
//! Windows notifications for what the site would push to a browser (the owner, 2026-11-20: "yes i want that built")://! new messages and message requests, replies and the bell's other notes, and the site's alerts (new leaks, snippets,//! group buys, the owner's own posts). The app's WebView2 can't show a website's notifications (the site treats it as//! a browser without them: src/lib/push-client.ts support()), so the page works out what's new//! (src/components/desktop-alerts.tsx) and asks the app (`notify`, site.js's window.juicewrldNotifications).//!//! The toast is the app's own, through WinRT (the windows crate's ToastNotification) under the app's AppUserModelID,//! which the installer's shortcuts carry. tauri-plugin-notification's toast (the like shortcut's notice) says nothing of//! a click once it has left the screen; this one is a protocol launch, juicewrld://notification?n=<token>, so a click on//! the screen or later in the Action Center opens the link with the app (a second launch hands it to this one, as a//! sign-in link is), which brings its window forward and opens the page the token names in the site webview. A token//! is random, known only to this process and kept a day: a juicewrld:// link a web page made can't name one, so it's//! ignored like any other stray link, and a closed app opened by an old toast just opens.//!//! Guarded like the like shortcut's notice: only the site's own webview on https://juicewrld.io may ask, only a page on//! the site can be opened, the words are one clipped line each, and at most BURST toasts go up a minute.use serde::Serialize;use std::collections::VecDeque;use std::sync::{Mutex, MutexGuard};use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};use tauri::{AppHandle, Manager, Webview};use url::Url;/// A notification's page is kept this long, as its toast is (its expiry in the Action Center).const KEEP: Duration = Duration::from_secs(24 * 3600);/// Pages kept at most: past it the oldest go.const PAGES_MAX: usize = 200;/// Toasts shown at most in WINDOW: a page gone wrong can't bury the screen in them.const BURST: usize = 8;const WINDOW: Duration = Duration::from_secs(60);pub const TITLE_MAX: usize = 120;pub const BODY_MAX: usize = 300;const TAG_MAX: usize = 64;const SITE: &str = "https://juicewrld.io";/// Windows' own AppUserModelID for PowerShell: a build run from target\ (no shortcut of its own) shows its toasts under/// it, as tauri-plugin-notification does, since Windows drops toasts from an ID no shortcut names.const DEV_APP_ID: &str = "{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe";#[derive(Default)]pub struct Notices(Mutex<State>);#[derive(Default)]struct State {    /// The pages notifications open, by token, oldest first.    pages: VecDeque<(String, Url, Instant)>,    /// When the last toasts went up.    shown: VecDeque<Instant>,}fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {    m.lock().unwrap_or_else(|e| e.into_inner())}impl State {    /// One more toast may go up now (and counts), or BURST already went up in the last WINDOW.    fn allow(&mut self, now: Instant) -> bool {        while self.shown.front().is_some_and(|t| now.duration_since(*t) >= WINDOW) {            self.shown.pop_front();        }        if self.shown.len() >= BURST {            return false;        }        self.shown.push_back(now);        true    }    /// Keeps the page a notification opens; its token.    fn remember(&mut self, page: Url, now: Instant) -> String {        self.forget_old(now);        while self.pages.len() >= PAGES_MAX {            self.pages.pop_front();        }        let token = random_token();        self.pages.push_back((token.clone(), page, now));        token    }    /// The page a token names, while it's kept. A toast clicked twice (on the screen, then in the Action Center) opens    /// its page twice, which is all a token can do.    fn page(&mut self, token: &str, now: Instant) -> Option<Url> {        self.forget_old(now);        self.pages.iter().find(|(t, _, _)| t == token).map(|(_, url, _)| url.clone())    }    fn forget_old(&mut self, now: Instant) {        while self.pages.front().is_some_and(|(_, _, at)| now.duration_since(*at) >= KEEP) {            self.pages.pop_front();        }    }}impl Notices {    /// The page a clicked notification's token names (juicewrld://notification?n=), while this process keeps it.    pub fn page(&self, token: &str) -> Option<Url> {        lock(&self.0).page(token, Instant::now())    }}fn random_token() -> String {    use base64::engine::general_purpose::URL_SAFE_NO_PAD;    use base64::Engine;    let mut bytes = [0u8; 32];    getrandom::fill(&mut bytes).expect("the system's random source");    URL_SAFE_NO_PAD.encode(bytes)}/// 43 base64url characters (32 bytes).fn is_token(s: &str) -> bool {    s.len() == 43 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')}/// What a notification's click launches.fn launch_link(token: &str) -> String {    format!("juicewrld://notification?n={token}")}/// The token in a juicewrld://notification?n= link, when it is one.pub fn link_token(link: &Url) -> Option<String> {    if link.scheme() != "juicewrld" || link.host_str() != Some("notification") {        return None;    }    link.query_pairs().find(|(k, _)| k == "n").map(|(_, v)| v.into_owned()).filter(|t| is_token(t))}/// A page on juicewrld.io from what the site gives: a path ("/messages/12") or an address on the site; nothing else/// (another host, http, a scheme of a script's making, a protocol-relative or backslashed path).pub fn page(raw: &str) -> Option<Url> {    let raw = raw.trim();    if raw.is_empty() || raw.len() > 1000 || raw.contains('\\') || raw.chars().any(char::is_control) || raw.starts_with("//") {        return None;    }    let base = Url::parse(SITE).expect("site url");    let url = if raw.starts_with('/') { base.join(raw).ok()? } else { Url::parse(raw).ok()? };    let ours = url.scheme() == "https" && url.host_str() == Some("juicewrld.io") && url.port().is_none() && url.username().is_empty() && url.password().is_none();    ours.then_some(url)}/// One line of at most `max` characters: control characters and runs of spaces as one space, trimmed, an ellipsis/// where it's cut.pub fn clean(s: &str, max: usize) -> String {    // Direction marks and overrides (a name holding U+202E would turn "Message request from X" round) and the    // zero-width space go; the zero-width joiners stay, since emoji are built with them.    let s: String = s.chars().filter(|c| !matches!(*c, '\u{200B}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')).collect();    let flat = s.split(|c: char| c.is_whitespace() || c.is_control()).filter(|w| !w.is_empty()).collect::<Vec<_>>().join(" ");    if flat.chars().count() <= max {        return flat;    }    let mut out: String = flat.chars().take(max.saturating_sub(1)).collect::<String>().trim_end().to_string();    out.push('…');    out}/// A tag Windows takes (64 characters at most) from the site's ("dm:12", "reply:812"): letters, digits and `:_-.`/// alone, else none.fn clean_tag(tag: Option<&str>) -> Option<String> {    let t = tag?.trim();    let ok = !t.is_empty() && t.len() <= TAG_MAX && t.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b':' | b'_' | b'-' | b'.'));    ok.then(|| t.to_string())}fn unix_ms() -> i64 {    SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0)}/// A Windows time (100 ns ticks since 1601), from milliseconds since 1970.fn windows_time(unix_ms: i64) -> i64 {    (unix_ms + 11_644_473_600_000) * 10_000}/// The AppUserModelID the toasts go under: the app's identifier, which the installer's shortcuts carry, or/// PowerShell's for a build run from target\.fn app_id(app: &AppHandle) -> String {    let dev = std::env::current_exe().ok().and_then(|exe| exe.parent().map(|d| d.to_path_buf())).is_some_and(|dir| {        let d = dir.to_string_lossy().to_lowercase().replace('/', "\\");        d.ends_with("\\target\\debug") || d.ends_with("\\target\\release")    });    if dev { DEV_APP_ID.to_string() } else { app.config().identifier.clone() }}/// What `notify` answers: whether a toast went up, and why not ("focused": the app's window was in front and the page/// asked for quiet then; "off": Windows has the app's notifications off; "busy": BURST went up in the last minute).#[derive(Serialize, Debug, PartialEq)]pub struct Shown {    shown: bool,    #[serde(skip_serializing_if = "Option::is_none")]    why: Option<&'static str>,}impl Shown {    fn yes() -> Self {        Shown { shown: true, why: None }    }    fn not(why: &'static str) -> Self {        Shown { shown: false, why: Some(why) }    }}/// A Windows notification for the site: its title and words (one line each), the page a click opens (a path on/// juicewrld.io or an address on it), a tag (one toast per tag: a newer one with the same tag takes the older's place,/// as a conversation's messages do), and `quietIfFocused`: nothing while the app's window is the one in front (the/// site's alerts, a message in the conversation on the screen). Answers whether it went up, and why not.#[tauri::command]pub async fn notify(    app: AppHandle,    webview: Webview,    title: String,    body: String,    url: String,    tag: Option<String>,    quiet_if_focused: Option<bool>,) -> Result<Shown, String> {    crate::from_site(&webview)?;    let page = page(&url).ok_or("That isn't a page on juicewrld.io")?;    let title = clean(&title, TITLE_MAX);    if title.is_empty() {        return Err("A notification needs a title".into());    }    let body = clean(&body, BODY_MAX);    if quiet_if_focused.unwrap_or(false) && webview.window().is_focused().unwrap_or(false) {        return Ok(Shown::not("focused"));    }    let token = {        let notices = app.state::<Notices>();        let mut state = lock(&notices.0);        let now = Instant::now();        if !state.allow(now) {            return Ok(Shown::not("busy"));        }        state.remember(page, now)    };    let expires = unix_ms() + KEEP.as_millis() as i64;    match toast::show(&app_id(&app), &title, &body, &launch_link(&token), clean_tag(tag.as_deref()).as_deref(), windows_time(expires)) {        Ok(()) => Ok(Shown::yes()),        Err(toast::Error::Off) => Ok(Shown::not("off")),        Err(toast::Error::Failed(e)) => {            eprintln!("[notify] the toast didn't go up ({e})");            Err("Windows didn't show the notification".into())        }    }}#[cfg(windows)]mod toast {    use windows::core::{h, Interface, HSTRING};    use windows::Data::Xml::Dom::XmlDocument;    use windows::Foundation::{DateTime, IReference, PropertyValue};    use windows::UI::Notifications::{NotificationSetting, ToastNotification, ToastNotificationManager};    pub enum Error {        /// Windows has the app's notifications off (Settings, System, Notifications), or a policy does.        Off,        Failed(String),    }    impl From<windows::core::Error> for Error {        fn from(e: windows::core::Error) -> Self {            Error::Failed(e.message())        }    }    /// One toast: the title and the words, a click launching `launch` (a protocol activation, so it works from the    /// Action Center too), replacing an earlier one of the same `tag`, gone from the Action Center at `expires` (a    /// Windows time). The XML is built element by element, so no word of the site's is ever read as markup.    pub fn show(app_id: &str, title: &str, body: &str, launch: &str, tag: Option<&str>, expires: i64) -> Result<(), Error> {        let notifier = ToastNotificationManager::CreateToastNotifierWithId(&HSTRING::from(app_id))?;        // Windows says whether it would show them; an ID it can't place answers an error, and the toast is tried anyway.        if let Ok(setting) = notifier.Setting() {            if setting != NotificationSetting::Enabled {                return Err(Error::Off);            }        }        let doc = XmlDocument::new()?;        let toast = doc.CreateElement(h!("toast"))?;        toast.SetAttribute(h!("launch"), &HSTRING::from(launch))?;        toast.SetAttribute(h!("activationType"), h!("protocol"))?;        let visual = doc.CreateElement(h!("visual"))?;        let binding = doc.CreateElement(h!("binding"))?;        binding.SetAttribute(h!("template"), h!("ToastGeneric"))?;        for line in [title, body] {            if line.is_empty() {                continue;            }            let text = doc.CreateElement(h!("text"))?;            text.SetInnerText(&HSTRING::from(line))?;            binding.AppendChild(&text)?;        }        visual.AppendChild(&binding)?;        toast.AppendChild(&visual)?;        doc.AppendChild(&toast)?;        let n = ToastNotification::CreateToastNotification(&doc)?;        if let Some(tag) = tag {            n.SetTag(&HSTRING::from(tag))?;            n.SetGroup(h!("juicewrld"))?;        }        let expiry: IReference<DateTime> = PropertyValue::CreateDateTime(DateTime { UniversalTime: expires })?.cast()?;        n.SetExpirationTime(&expiry)?;        notifier.Show(&n)?;        Ok(())    }}#[cfg(not(windows))]mod toast {    pub enum Error {        #[allow(dead_code)]        Off,        Failed(String),    }    pub fn show(_app_id: &str, _title: &str, _body: &str, _launch: &str, _tag: Option<&str>, _expires: i64) -> Result<(), Error> {        Err(Error::Failed("toasts are Windows' own".into()))    }}#[cfg(test)]mod tests {    use super::*;    #[test]    fn only_pages_on_the_site_open() {        assert_eq!(page("/messages/12").unwrap().as_str(), "https://juicewrld.io/messages/12");        assert_eq!(page("/song/robbery?push=1#comments").unwrap().as_str(), "https://juicewrld.io/song/robbery?push=1#comments");        assert_eq!(page("https://juicewrld.io/updates").unwrap().as_str(), "https://juicewrld.io/updates");        for other in [            "",            "//evil.example/x",            "/\\evil.example",            "http://juicewrld.io/",            "https://juicewrld.io.evil.example/",            "https://www.juicewrld.io/",            "https://juicewrld.io:8443/",            "https://user:[email protected]/",            "https://discord.com/login",            "javascript:alert(1)",            "data:text/html,hi",            "file:///C:/Windows/win.ini",            "juicewrld://signin?code=x",            "/a\nb",        ] {            assert!(page(other).is_none(), "{other}");        }    }    #[test]    fn words_are_one_clipped_line() {        assert_eq!(clean("  strives\n replied\t\tto  your comment ", 120), "strives replied to your comment");        assert_eq!(clean("a\u{0007}b", 10), "a b");        assert_eq!(clean("abcdefghij", 5), "abcd…");        assert_eq!(clean(&"é".repeat(400), BODY_MAX).chars().count(), BODY_MAX);        assert_eq!(clean("", 10), "");    }    #[test]    fn tags_are_short_and_plain() {        assert_eq!(clean_tag(Some("dm:12")).as_deref(), Some("dm:12"));        assert_eq!(clean_tag(Some("edit:3.likes")).as_deref(), Some("edit:3.likes"));        assert_eq!(clean_tag(Some("alert-55")).as_deref(), Some("alert-55"));        assert_eq!(clean_tag(Some("<toast>")), None);        assert_eq!(clean_tag(Some(&"x".repeat(65))), None);        assert_eq!(clean_tag(Some("")), None);        assert_eq!(clean_tag(None), None);    }    #[test]    fn a_click_opens_only_a_page_this_process_kept() {        let mut s = State::default();        let now = Instant::now();        let token = s.remember(page("/messages/7").unwrap(), now);        let link = Url::parse(&launch_link(&token)).unwrap();        assert_eq!(link_token(&link).as_deref(), Some(token.as_str()));        assert_eq!(s.page(&token, now).unwrap().as_str(), "https://juicewrld.io/messages/7");        assert_eq!(s.page(&token, now).unwrap().as_str(), "https://juicewrld.io/messages/7", "clicked twice, opened twice");        // A token nobody kept, a malformed one, another kind of link: nothing.        assert!(s.page(&random_token(), now).is_none());        for other in ["juicewrld://notification?n=short", "juicewrld://signin?code=x", "https://juicewrld.io/?n=x", "juicewrld://other?n=x"] {            assert!(link_token(&Url::parse(other).unwrap()).is_none(), "{other}");        }        // Kept a day, then gone.        assert!(s.page(&token, now + KEEP + Duration::from_secs(1)).is_none());    }    #[test]    fn the_oldest_pages_go_past_the_cap() {        let mut s = State::default();        let now = Instant::now();        let first = s.remember(page("/a").unwrap(), now);        for i in 0..PAGES_MAX {            s.remember(page(&format!("/p/{i}")).unwrap(), now);        }        assert_eq!(s.pages.len(), PAGES_MAX);        assert!(s.page(&first, now).is_none());    }    #[test]    fn at_most_a_burst_a_minute() {        let mut s = State::default();        let now = Instant::now();        for _ in 0..BURST {            assert!(s.allow(now));        }        assert!(!s.allow(now));        assert!(s.allow(now + WINDOW), "a minute on, room again");    }    #[test]    fn expiry_is_a_windows_time() {        // 1970-01-01 in Windows' clock, and a day after it.        assert_eq!(windows_time(0), 116_444_736_000_000_000);        assert_eq!(windows_time(86_400_000) - windows_time(0), 864_000_000_000);    }}