juicewrld-desktopsrc-taurisrcpresence.rs
1.4.2Released Nov 21, 2026
presence.rs
482 lines18.8 KBRust//! Discord Rich Presence: "Listening to <song>" with the artist, the cover, a progress bar and a button to//! the song's page, while something plays on juicewrld.io: in this window, or in another browser of the member's//! account while this window plays nothing (the owner, 2026-11-20: "my rpc discord status should still show the song//! im playin if im playin through web as long as the app is open"). The site webview reports what's playing//! (site.js → `presence`), and what the account's other browsers play (site.js asks /api/me/now-playing while its own//! page is quiet → `presence` with source "web"); this window's own playback always wins. A worker thread keeps//! Discord in step over its local IPC pipe. Discord not running, closing or restarting is normal: the worker retries//! quietly and never shows anything.use discord_rich_presence::activity::{Activity, ActivityType, Assets, Button, StatusDisplayType, Timestamps};use discord_rich_presence::{DiscordIpc, DiscordIpcClient};use serde::{Deserialize, Serialize};use std::collections::VecDeque;use std::panic::{catch_unwind, AssertUnwindSafe};use std::sync::{Arc, Condvar, Mutex, MutexGuard};use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};use url::Url;/// The site's Discord application (public).const APP_ID: &str = "1562418221972324372";const SITE: &str = "https://juicewrld.io/";/// The cover when a song has none, and the small badge on every cover.const ICON: &str = "https://juicewrld.io/brand/icon-512.png";const BADGE: &str = "https://juicewrld.io/brand/icon-192.png";/// Discord takes at most 5 activity updates in 20 seconds.const BURST: usize = 5;const WINDOW: Duration = Duration::from_secs(20);/// While something plays, a dropped pipe (Discord restarted) is noticed by re-sending this often.const KEEPALIVE: Duration = Duration::from_secs(30);/// How long to wait before looking for Discord again.const RETRY: Duration = Duration::from_secs(15);/// At quit, how long the app waits for the worker to clear the status (it looks once a second, or at once when idle).const STOP_WAIT: Duration = Duration::from_millis(1500);/// Another browser's song goes when site.js hasn't said it again for this long: it asks every 15 s (about once a/// minute while the window has been hidden a while, as a hidden page's timers go), and says "none" itself once the/// site does, so this only catches a page that went quiet.const WEB_FRESH: Duration = Duration::from_secs(150);/// ...or once the song would have ended this long ago: that browser moved on without a word reaching us.const WEB_ENDED_MS: i64 = 15_000;/// The same song said again with its clock this close to where it was is the same moment (site.js's rule for a seek).const SAME_MOMENT_MS: i64 = 2_500;/// What the site reports (site.js `snapshot`): `state` is "playing", "paused" or "none".pub struct Update { pub state: String, pub title: String, pub artist: String, pub album: String, pub artwork: String, pub position: f64, pub duration: f64, pub url: String,}/// What the title bar shows.pub struct Now { pub state: String, pub title: String, pub artist: String, pub url: String,}/// A song as Discord shows it, cleaned and checked.struct Song { title: String, artist: String, album: String, artwork: String, url: String, start: i64, end: Option<i64>,}struct Wanted { /// What this window's page plays, while it plays. local: Option<Song>, /// What another browser of the account plays (site.js, from /api/me/now-playing), and when it was last said. web: Option<(Song, Instant)>, quit: bool, /// The worker has cleared Discord's status and let go of the pipe (after `quit`). done: bool,}impl Wanted { /// What Discord shows: this window's song while it plays, else another browser's while that's fresh (said again /// within WEB_FRESH and not past its end). fn song(&self, now: Instant, wall_ms: i64) -> Option<Song> { if let Some(s) = &self.local { return Some(s.clone()); } let (s, at) = self.web.as_ref()?; let ended = s.end.is_some_and(|end| wall_ms > end + WEB_ENDED_MS); (now.duration_since(*at) < WEB_FRESH && !ended).then(|| s.clone()) }}/// The same song, its clock within SAME_MOMENT_MS of where it was: said again, not changed.fn same_moment(a: &Song, b: &Song) -> bool { let near = |x: i64, y: i64| (x - y).abs() <= SAME_MOMENT_MS; let ends = match (a.end, b.end) { (Some(x), Some(y)) => near(x, y), (None, None) => true, _ => false, }; a.title == b.title && a.artist == b.artist && a.album == b.album && a.artwork == b.artwork && a.url == b.url && near(a.start, b.start) && ends}pub struct Presence { wanted: Arc<(Mutex<Wanted>, Condvar)>, now: Mutex<Now>,}fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> { m.lock().unwrap_or_else(|e| e.into_inner())}impl Presence { /// Starts the worker; it connects to Discord only once there is something to show. pub fn start() -> Self { let wanted = Arc::new((Mutex::new(Wanted::default()), Condvar::new())); let w = wanted.clone(); let _ = std::thread::Builder::new().name("discord".into()).spawn(move || loop { // A panic in the worker costs the presence a few seconds, never the app. if catch_unwind(AssertUnwindSafe(|| worker(&w))).is_ok() { break; } std::thread::sleep(RETRY); }); Presence { wanted, now: Mutex::new(Now::default()) } } /// Takes a report from the site about this window's own playback. Returns the title bar's new line when it changed. pub fn update(&self, u: Update) -> Option<Now> { let song = (u.state == "playing").then(|| song(&u)); { let (m, cv) = &*self.wanted; let mut w = lock(m); if w.local != song { w.local = song; cv.notify_one(); } } let now = if u.state == "playing" || u.state == "paused" { Now { state: u.state, title: clip(&u.title, 200), artist: clip(&u.artist, 200), url: song_url(&u.url) } } else { Now::default() }; let mut cur = lock(&self.now); (*cur != now).then(|| { *cur = now.clone(); now }) } /// Takes what another browser of the account plays (site.js asks the site while this window plays nothing; "none" /// when nothing plays there). Discord shows it only while this window plays nothing; the title bar never does, it /// shows this window's own. The same moment said again only keeps it fresh. True when it changed what's wanted. pub fn update_web(&self, u: Update) -> bool { let next = (u.state == "playing").then(|| song(&u)); let (m, cv) = &*self.wanted; let mut w = lock(m); let changed = match (next, &mut w.web) { (None, web) => web.take().is_some(), (Some(s), Some((held, at))) if same_moment(held, &s) => { *at = Instant::now(); false } (Some(s), web) => { *web = Some((s, Instant::now())); true } }; if changed { cv.notify_one(); } changed } /// The page went away (a reload, or off to sign in): nothing plays until it says so again, here or elsewhere. pub fn clear(&self) -> Option<Now> { self.update_web(Update::default()); self.update(Update { state: "none".into(), ..Default::default() }) } pub fn now(&self) -> Now { lock(&self.now).clone() } pub fn stop(&self) { let (m, cv) = &*self.wanted; let mut w = lock(m); w.quit = true; cv.notify_all(); // Waits (a moment at most) for the worker to clear the status, so the app's Quit leaves nothing showing on // Discord, rather than leaving it to Discord to notice the pipe closed. let _ = cv.wait_timeout_while(w, STOP_WAIT, |w| !w.done); }}fn unix_ms() -> i64 { SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0)}/// At most `max` characters, trimmed, with an ellipsis when cut.fn clip(s: &str, max: usize) -> String { let s = s.trim(); if s.chars().count() <= max { return s.to_string(); } let mut out: String = s.chars().take(max - 1).collect(); out.push('…'); out}/// Discord wants 2 to 128 characters in its text fields.fn field(s: &str) -> String { let mut s = clip(s, 128); while s.chars().count() < 2 { s.push('\u{2800}'); } s}/// A page on juicewrld.io, else the home page.fn song_url(raw: &str) -> String { match Url::parse(raw) { Ok(u) if u.scheme() == "https" && u.host_str() == Some("juicewrld.io") && raw.len() <= 512 => u.to_string(), _ => SITE.to_string(), }}/// An https image Discord can fetch (it proxies external art), else the site's icon.fn image(raw: &str) -> String { match Url::parse(raw) { Ok(u) if u.scheme() == "https" && u.host_str().is_some() && raw.len() <= 256 => u.to_string(), _ => ICON.to_string(), }}fn song(u: &Update) -> Song { let now = unix_ms(); let position = if u.position.is_finite() { u.position.max(0.0) } else { 0.0 }; let start = now - (position * 1000.0) as i64; let end = (u.duration.is_finite() && u.duration > 0.0).then(|| start + (u.duration * 1000.0) as i64); Song { title: field(&u.title), artist: field(if u.artist.trim().is_empty() { "Juice WRLD" } else { &u.artist }), album: field(if u.album.trim().is_empty() { "juicewrld.io" } else { &u.album }), artwork: image(&u.artwork), url: song_url(&u.url), // Rounded to the second, so the same moment reported twice is the same activity. start: start / 1000 * 1000, end: end.map(|e| e / 1000 * 1000), }}fn activity(s: &Song) -> Activity<'_> { let mut times = Timestamps::new().start(s.start); if let Some(end) = s.end { times = times.end(end); } Activity::new() .activity_type(ActivityType::Listening) .status_display_type(StatusDisplayType::Details) .details(s.title.as_str()) .details_url(s.url.as_str()) .state(s.artist.as_str()) .timestamps(times) .assets( Assets::new() .large_image(s.artwork.as_str()) .large_text(s.album.as_str()) .small_image(BADGE) .small_text("juicewrld.io"), ) .buttons(vec![Button::new("Listen on juicewrld.io", s.url.as_str())])}/// Sends one activity (or a clear) and reads Discord's answer, so its replies never pile up in the pipe.fn send(client: &mut DiscordIpcClient, song: &Option<Song>) -> Result<(), String> { match song { Some(s) => client.set_activity(activity(s)), None => client.clear_activity(), } .map_err(|e| e.to_string())?; let (op, reply) = client.recv().map_err(|e| e.to_string())?; if op == 2 { return Err("Discord closed the connection".into()); } if reply.get("evt").and_then(|e| e.as_str()) == Some("ERROR") { let msg = reply.pointer("/data/message").and_then(|m| m.as_str()).unwrap_or("unknown error"); eprintln!("[presence] Discord refused the activity: {msg}"); } Ok(())}fn worker(wanted: &Arc<(Mutex<Wanted>, Condvar)>) { let (m, cv) = &**wanted; let mut client: Option<DiscordIpcClient> = None; // What Discord shows while connected (a fresh connection shows nothing). let mut shown: Option<Song> = None; let mut shown_at = Instant::now(); let mut retry_at = Instant::now(); let mut sent: VecDeque<Instant> = VecDeque::new(); let mut said_offline = false; loop { let want = { let w = lock(m); let (mut w, _) = cv.wait_timeout(w, Duration::from_secs(1)).unwrap_or_else(|e| e.into_inner()); if w.quit { if let Some(mut c) = client.take() { let _ = c.clear_activity(); let _ = c.close(); } w.done = true; cv.notify_all(); return; } w.song(Instant::now(), unix_ms()) }; let now = Instant::now(); if client.is_none() { // Connect only when there's something to show, and not more often than RETRY. if want.is_none() || now < retry_at { continue; } let mut c = DiscordIpcClient::new(APP_ID); match c.connect() { Ok(()) => { eprintln!("[presence] connected to Discord"); said_offline = false; client = Some(c); shown = None; } Err(e) => { if !said_offline { eprintln!("[presence] Discord isn't reachable ({e}); trying again every {}s", RETRY.as_secs()); said_offline = true; } retry_at = now + RETRY; continue; } } } let stale = want.is_some() && now.duration_since(shown_at) >= KEEPALIVE; if want == shown && !stale { continue; } while sent.front().is_some_and(|t| now.duration_since(*t) >= WINDOW) { sent.pop_front(); } if sent.len() >= BURST { continue; } let Some(c) = client.as_mut() else { continue }; sent.push_back(now); match send(c, &want) { Ok(()) => { if want != shown { match &want { Some(s) => eprintln!("[presence] listening: {} by {}", s.title, s.artist), None => eprintln!("[presence] cleared"), } } shown = want; shown_at = now; } Err(e) => { // Discord quit or restarted: look for it again right away, then every RETRY. eprintln!("[presence] lost Discord ({e})"); client = None; shown = None; retry_at = now; } } }}mod tests { use super::*; fn playing(title: &str, position: f64) -> Update { Update { state: "playing".into(), title: title.into(), artist: "Juice WRLD".into(), album: "Goodbye & Good Riddance".into(), artwork: "https://juicewrld.io/art/0123456789abcdef0123456789abcdef01234567.jpg".into(), position, duration: 200.0, url: "https://juicewrld.io/song/lucid-dreams".into(), } } /// A Presence whose worker never connects: what it wants is read straight from its state. fn presence() -> Presence { Presence { wanted: Arc::new((Mutex::new(Wanted::default()), Condvar::new())), now: Mutex::new(Now::default()) } } fn wanted(p: &Presence) -> Option<String> { lock(&p.wanted.0).song(Instant::now(), unix_ms()).map(|s| s.title) } fn this_windows_playback_always_wins() { let p = presence(); assert!(p.update_web(playing("Robbery", 30.0))); assert_eq!(wanted(&p).as_deref(), Some("Robbery"), "another browser's song while this window plays nothing"); p.update(playing("Lucid Dreams", 10.0)); assert_eq!(wanted(&p).as_deref(), Some("Lucid Dreams"), "this window's own wins"); p.update(Update { state: "paused".into(), ..playing("Lucid Dreams", 12.0) }); assert_eq!(wanted(&p).as_deref(), Some("Robbery"), "paused here: the other browser's again"); assert!(p.update_web(Update { state: "none".into(), ..Default::default() })); assert_eq!(wanted(&p), None); } fn the_title_bar_shows_this_windows_song_alone() { let p = presence(); p.update_web(playing("Robbery", 30.0)); assert_eq!(p.now(), Now::default(), "another browser's song never reaches the bar"); let line = p.update(playing("Lucid Dreams", 10.0)).expect("the bar's line changed"); assert_eq!(line.title, "Lucid Dreams"); } fn the_same_moment_said_again_isnt_a_change() { let p = presence(); assert!(p.update_web(playing("Robbery", 30.0))); // The next poll, its clock where it should be within a second or two: nothing new for Discord. assert!(!p.update_web(playing("Robbery", 31.5))); // A seek, another song, or new art is. assert!(p.update_web(playing("Robbery", 90.0))); assert!(p.update_web(playing("Wishing Well", 90.0))); let mut art = playing("Wishing Well", 90.0); art.artwork = "https://juicewrld.io/api/desktop/cover/1.0123456789abcdef01234567.1.x".into(); assert!(p.update_web(art)); } fn another_browsers_song_goes_stale_or_ends() { let s = song(&playing("Robbery", 30.0)); let now = Instant::now(); let fresh = Wanted { web: Some((s.clone(), now)), ..Default::default() }; assert!(fresh.song(now, unix_ms()).is_some()); assert!(fresh.song(now + WEB_FRESH + Duration::from_secs(1), unix_ms()).is_none(), "not said again for WEB_FRESH"); let end = s.end.expect("a known length"); assert!(fresh.song(now, end + WEB_ENDED_MS - 1000).is_some(), "a moment past its end: the next song's report may be on its way"); assert!(fresh.song(now, end + WEB_ENDED_MS + 1000).is_none(), "well past its end"); // This window's own song never goes stale here: the page says when it stops. let local = Wanted { local: Some(s), ..Default::default() }; assert!(local.song(now + WEB_FRESH * 10, i64::MAX / 2).is_some()); } fn a_page_going_away_clears_both() { let p = presence(); p.update(playing("Lucid Dreams", 10.0)); p.update_web(playing("Robbery", 30.0)); p.clear(); assert_eq!(wanted(&p), None); assert_eq!(p.now(), Now::default()); } fn covers_and_pages_are_the_sites_or_the_icon() { assert_eq!(image("https://juicewrld.io/api/desktop/cover/7.0123456789abcdef01234567.1732000000.abc"), "https://juicewrld.io/api/desktop/cover/7.0123456789abcdef01234567.1732000000.abc"); assert_eq!(image("http://juicewrld.io/art/x.jpg"), ICON, "https only"); assert_eq!(image(""), ICON); assert_eq!(song_url("https://juicewrld.io/song/robbery"), "https://juicewrld.io/song/robbery"); assert_eq!(song_url("https://evil.example/song/robbery"), SITE); }}