Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.
Rust desktop-appdiscorddiscord-clienteguielectron-alternativelightweightlinuxmacosnative-apprustwindows
//! Third-party players inside embeds: YouTube, Twitch, Vimeo, SoundCloud,
//! TikTok, Spotify, Apple Music… Discord shows these as the provider's own
//! `<iframe>` once you press play; there is no other way to play them, so
//! RustCord does the same in a small child webview (WebView2 on Windows) that
//! sits exactly over the embed's media box. Everything around it stays native.
//!
//! The webview only ever shows a tiny wrapper page holding the iframe (same
//! sandbox as Discord's): top-level navigation is locked to that page, popups
//! open in your browser instead, and downloads are refused. One player exists
//! at a time and only after a click, so nothing is loaded for embeds you
//! merely scroll past.
use discord::model::Id;
use eframe::egui;
use std::borrow::Cow;
use std::sync::mpsc::{sync_channel, Receiver};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use wry::dpi::{PhysicalPosition, PhysicalSize};
use wry::raw_window_handle::HasWindowHandle;
use wry::{WebContext, WebView, WebViewBuilder};
/// The wrapper page's origin (wry serves `rustcord://localhost` there).
const ORIGIN: &str = "https://rustcord.localhost";
/// The iframe's host page, as Twitch wants it named (`parent=`).
pub const PARENT_HOST: &str = "rustcord.localhost";
/// How long a webview nobody plays in is kept (hidden) for the next play:
/// building one is the slow part of starting a player, but it holds memory.
pub const KEEP_WARM: Duration = Duration::from_secs(120);
/// What the chat asked to play: (message, embed index).
pub type Key = (Id, usize);
pub enum Event {
/// The player went full screen (or left it).
Fullscreen(bool),
/// A link the player wanted to open in a new window.
Open(String),
}
pub struct EmbedView {
view: WebView,
_context: Box<WebContext>,
/// The page the `rustcord` protocol serves: swapped for every player, so
/// one webview is reused instead of building a new one per play.
html: Arc<Mutex<String>>,
/// Page loads so far (each gets its own address, so none is cached).
loads: u32,
/// What is playing and in which channel; `None` while the webview only
/// waits (hidden, on a blank page) for the next play.
pub playing: Option<(Key, Id)>,
idle_since: Instant,
events: Receiver<Event>,
pub fullscreen: bool,
visible: bool,
/// Last bounds + visible region applied (to skip no-op updates).
placed: Option<([i32; 4], Option<[i32; 4]>)>,
}
fn esc(s: &str) -> String {
s.replace('&', "&").replace('"', """).replace('<', "<").replace('>', ">")
}
/// Spotify's player loads paused. The click that opened it was the "play"
/// click (in Discord it lands on the player's own button), so once the
/// player says it's ready it is told to play: its embed protocol, the one
/// Spotify's iFrame API speaks (`{type: "ready"}` in, `{command: "play"}` out).
const SPOTIFY_AUTOPLAY: &str = "const f=document.getElementById('f'),sp='https://open.spotify.com';let played=false;window.addEventListener('message',e=>{if(e.source!==f.contentWindow||e.origin!==sp||!e.data||e.data.type!=='ready')return;f.contentWindow.postMessage({command:'load_complete_ack'},sp);if(!played){played=true;f.contentWindow.postMessage({command:'play'},sp);}});";
fn page(src: &str, bg: egui::Color32) -> String {
format!(
r#"<!doctype html><html><head><meta charset="utf-8"><style>html,body{{margin:0;height:100%;background:rgb({},{},{});overflow:hidden}}iframe{{position:absolute;border:0;left:0;top:0;width:100vw;height:100vh}}</style></head><body><iframe id="f" src="{}" allow="autoplay; fullscreen; encrypted-media; clipboard-write; picture-in-picture" allowfullscreen sandbox="allow-forms allow-modals allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-presentation"></iframe><script>document.addEventListener('fullscreenchange',()=>window.ipc.postMessage(document.fullscreenElement?'fs1':'fs0'));{SPOTIFY_AUTOPLAY}</script></body></html>"#,
bg.r(),
bg.g(),
bg.b(),
esc(src)
)
}
/// The page of a webview that plays nothing: dark and empty, with the
/// connections to the usual providers opened ahead of the click.
fn blank() -> String {
r#"<!doctype html><html><head><meta charset="utf-8"><link rel="preconnect" href="https://www.youtube.com"><link rel="preconnect" href="https://i.ytimg.com"><link rel="preconnect" href="https://open.spotify.com"><style>html,body{margin:0;height:100%;background:#000}</style></head><body></body></html>"#.to_string()
}
fn physical(rect: egui::Rect, ppp: f32) -> [i32; 4] {
[(rect.left() * ppp).round() as i32, (rect.top() * ppp).round() as i32, (rect.width() * ppp).round() as i32, (rect.height() * ppp).round() as i32]
}
/// The webview's bounds for a player box, and the part of it inside `clip`
/// in the webview's own pixels (`None`: all of it shows).
fn geometry(rect: egui::Rect, clip: egui::Rect, ppp: f32) -> ([i32; 4], Option<[i32; 4]>) {
let (b, v) = (physical(rect, ppp), rect.intersect(clip));
let px = |p: f32, origin: i32, size: i32| ((p * ppp).round() as i32 - origin).clamp(0, size);
let region = [px(v.left(), b[0], b[2]), px(v.top(), b[1], b[3]), px(v.right(), b[0], b[2]), px(v.bottom(), b[1], b[3])];
(b, (region != [0, 0, b[2], b[3]]).then_some(region))
}
pub fn is_web(url: &str) -> bool {
url::Url::parse(url).is_ok_and(|u| matches!(u.scheme(), "http" | "https"))
}
/// Is `url` the wrapper page itself? Compared as a parsed origin: a prefix test
/// would also take `https://rustcord.localhost.example.com`.
fn is_wrapper(url: &str) -> bool {
url::Url::parse(url).is_ok_and(|u| match u.scheme() {
"https" => u.host_str() == Some(PARENT_HOST) && u.port().is_none() && u.username().is_empty() && u.password().is_none(),
"rustcord" => u.host_str() == Some("localhost"),
_ => false,
})
}
impl EmbedView {
/// A hidden webview showing `html`, at `b` (physical pixels).
fn create(parent: &impl HasWindowHandle, html: String, bg: egui::Color32, b: [i32; 4]) -> Result<Self, String> {
#[cfg(target_os = "linux")]
crate::linux::web_pages_available()?;
let (send, events) = sync_channel(8);
let send_popup = send.clone();
let html = Arc::new(Mutex::new(html));
let served = html.clone();
// Its own profile folder: players keep their cookies (a Spotify or
// YouTube sign-in) apart from everything else.
let dir = directories::ProjectDirs::from("dev", "RustCord", "RustCord").map(|d| d.cache_dir().join("embed-player"));
let mut context = Box::new(WebContext::new(dir));
let builder = WebViewBuilder::new_with_web_context(&mut context)
.with_custom_protocol("rustcord".into(), move |_, _| {
let body = served.lock().unwrap_or_else(|e| e.into_inner()).clone().into_bytes();
wry::http::Response::builder()
.header("Content-Type", "text/html; charset=utf-8")
.header("Cache-Control", "no-store")
.body(Cow::Owned(body))
.unwrap_or_else(|_| wry::http::Response::new(Cow::Borrowed(&b""[..])))
})
.with_url("rustcord://localhost/")
.with_autoplay(true)
.with_devtools(false)
// Shown by `place`. It may be made on a mere hover, which mustn't
// take the keyboard away from the chat.
.with_visible(false)
.with_focused(false)
.with_background_color((bg.r(), bg.g(), bg.b(), 255))
// Only the wrapper page may be the top-level document.
.with_navigation_handler(|url| is_wrapper(&url) || url == "about:blank")
.with_new_window_req_handler(move |url, _| {
if is_web(&url) {
let _ = send_popup.try_send(Event::Open(url));
}
wry::NewWindowResponse::Deny
})
.with_download_started_handler(|_, _| false)
.with_ipc_handler(move |request| {
if !is_wrapper(&request.uri().to_string()) {
return;
}
match request.body().as_str() {
"fs1" => drop(send.try_send(Event::Fullscreen(true))),
"fs0" => drop(send.try_send(Event::Fullscreen(false))),
_ => {}
}
})
.with_bounds(wry::Rect { position: PhysicalPosition::new(b[0], b[1]).into(), size: PhysicalSize::new(b[2].max(1) as u32, b[3].max(1) as u32).into() });
#[cfg(windows)]
let builder = {
use wry::WebViewBuilderExtWindows;
builder.with_https_scheme(true)
};
let view = builder.build_as_child(parent).map_err(|e| format!("Couldn't open the player: {e}"))?;
Ok(Self { view, _context: context, html, loads: 0, playing: None, idle_since: Instant::now(), events, fullscreen: false, visible: false, placed: None })
}
/// A hidden webview on the blank page, made ahead of a likely click.
pub fn warm(parent: &impl HasWindowHandle) -> Result<Self, String> {
Self::create(parent, blank(), egui::Color32::BLACK, [0, 0, 640, 360])
}
/// Open a player for `src` (an https iframe URL), to be put over `rect`.
pub fn open(parent: &impl HasWindowHandle, key: Key, channel: Id, src: &str, bg: egui::Color32, rect: egui::Rect, ppp: f32) -> Result<Self, String> {
if !src.starts_with("https://") {
return Err("This player's address isn't secure (https).".into());
}
let mut v = Self::create(parent, page(src, bg), bg, physical(rect, ppp))?;
v.playing = Some((key, channel));
Ok(v)
}
/// Play `src` in this (kept) webview instead of whatever it showed.
pub fn play(&mut self, key: Key, channel: Id, src: &str, bg: egui::Color32) -> Result<(), String> {
if !src.starts_with("https://") {
return Err("This player's address isn't secure (https).".into());
}
let _ = self.view.set_background_color((bg.r(), bg.g(), bg.b(), 255));
self.load(page(src, bg));
self.playing = Some((key, channel));
Ok(())
}
/// Stop playing: back to the blank page (so the sound stops) and hidden,
/// but kept for the next play.
pub fn stop(&mut self) {
if self.playing.take().is_some() {
self.load(blank());
self.idle_since = Instant::now();
}
self.hide();
}
/// How long nothing has been playing (`None` while something is).
pub fn idle(&self) -> Option<Duration> {
self.playing.is_none().then(|| self.idle_since.elapsed())
}
fn load(&mut self, html: String) {
*self.html.lock().unwrap_or_else(|e| e.into_inner()) = html;
self.loads += 1;
self.fullscreen = false;
let _ = self.view.load_url(&format!("{ORIGIN}/?n={}", self.loads));
}
/// What the player reported since last frame.
pub fn poll(&mut self) -> Vec<Event> {
let events: Vec<Event> = self.events.try_iter().collect();
for e in &events {
if let Event::Fullscreen(on) = e {
self.fullscreen = *on && self.playing.is_some();
self.placed = None;
}
}
events
}
pub fn hide(&mut self) {
if self.visible {
self.visible = false;
let _ = self.view.set_visible(false);
}
}
/// Does any of a player box at `rect` show inside `clip`?
pub fn in_view(rect: egui::Rect, clip: egui::Rect) -> bool {
let vis = rect.intersect(clip);
vis.width() >= 2.0 && vis.height() >= 2.0
}
/// Would `place` with these have anything to do?
pub fn misplaced(&self, rect: egui::Rect, clip: egui::Rect, ppp: f32) -> bool {
!self.visible || self.placed != Some(geometry(rect, clip, ppp))
}
/// Put the player over `rect`, showing only the part inside `clip` (the
/// chat's visible area). The webview always keeps the box's full size and
/// is cut off with a window region: resizing it (and shifting the page
/// inside to make up for it) lags behind the scrolling chat.
pub fn place(&mut self, rect: egui::Rect, clip: egui::Rect, ppp: f32) {
if !Self::in_view(rect, clip) {
return self.hide();
}
let (bounds, region) = geometry(rect, clip, ppp);
if self.placed.map(|p| p.1) != Some(region) {
self.set_region(region);
}
if self.placed.map(|p| p.0) != Some(bounds) {
let _ = self.view.set_bounds(wry::Rect {
position: PhysicalPosition::new(bounds[0], bounds[1]).into(),
size: PhysicalSize::new(bounds[2].max(1) as u32, bounds[3].max(1) as u32).into(),
});
}
self.placed = Some((bounds, region));
if !self.visible {
self.visible = true;
let _ = self.view.set_visible(true);
}
}
/// Show only `region` (left, top, right, bottom in the webview's own
/// pixels) of the webview's window; all of it with `None`.
#[cfg(windows)]
fn set_region(&self, region: Option<[i32; 4]>) {
use windows_sys::Win32::Graphics::Gdi::{CreateRectRgn, SetWindowRgn};
use wry::WebViewExtWindows;
// SAFETY: the window is `self.view`'s own; Windows takes over the
// region handle.
unsafe {
let rgn = match region {
Some([l, t, r, b]) => CreateRectRgn(l, t, r, b),
None => std::ptr::null_mut(),
};
SetWindowRgn(self.view.hwnd().0 as _, rgn, 1);
}
}
#[cfg(not(windows))]
fn set_region(&self, _region: Option<[i32; 4]>) {}
}
/// The iframe address for an embed's video, with the provider's parameters
/// the way Discord adds them (autoplay; Twitch's `parent`).
pub fn player_src(provider: Option<&str>, video_url: &str) -> Option<String> {
let mut u = url::Url::parse(video_url).ok()?;
if u.scheme() != "https" {
return None;
}
let host = u.host_str().unwrap_or("").to_ascii_lowercase();
let set = |u: &mut url::Url, add: &[(&str, &str)], strip: &[&str]| {
let kept: Vec<(String, String)> =
u.query_pairs().filter(|(k, _)| !strip.contains(&k.as_ref()) && !add.iter().any(|(a, _)| a == k)).map(|(k, v)| (k.into_owned(), v.into_owned())).collect();
let mut q = u.query_pairs_mut();
q.clear();
for (k, v) in &kept {
q.append_pair(k, v);
}
for (k, v) in add {
q.append_pair(k, v);
}
};
if provider == Some("YouTube") || host == "www.youtube.com" {
set(&mut u, &[("autoplay", "1"), ("auto_play", "1")], &[]);
} else if provider == Some("Twitch") || host.ends_with("twitch.tv") {
set(&mut u, &[("parent", PARENT_HOST), ("autoplay", "true")], &["parent"]);
} else if provider == Some("TikTok") || host == "www.tiktok.com" {
set(&mut u, &[("utm_source", "discord.gg"), ("autoplay", "1")], &[]);
} else if host == "w.soundcloud.com" {
set(&mut u, &[("auto_play", "true")], &[]);
} else if host == "player.vimeo.com" {
set(&mut u, &[("autoplay", "1")], &[]);
}
Some(u.to_string())
}
/// Spotify's embed for a link (`open.spotify.com/track/…`): (iframe URL,
/// height), with Discord's heights per kind.
pub fn spotify_embed(link: &str) -> Option<(String, f32)> {
let cleaned = link.split("/intl-").enumerate().map(|(i, p)| if i == 0 { p.to_string() } else { p.split_once('/').map(|(_, r)| format!("/{r}")).unwrap_or_default() }).collect::<String>();
let u = url::Url::parse(&cleaned).ok()?;
if u.host_str() != Some("open.spotify.com") {
return None;
}
let parts: Vec<&str> = u.path().split('/').filter(|p| !p.is_empty()).collect();
let (kind, id) = match parts.as_slice() {
["user", _, "playlist", id, ..] => ("playlist", *id),
[kind, id, ..] => (*kind, *id),
_ => return None,
};
let height = match kind {
"track" => 80.0,
"episode" | "show" => 232.0,
"album" | "artist" | "playlist" => 352.0,
_ => return None,
};
if !id.chars().all(|c| c.is_ascii_alphanumeric()) {
return None;
}
Some((format!("https://open.spotify.com/embed/{kind}/{id}?utm_source=discord&utm_medium=desktop"), height))
}
/// Apple Music's embed for a link: (iframe URL, height), as Discord sizes
/// them (a song 175, a music video 371, anything else 450).
pub fn apple_music_embed(link: &str) -> Option<(String, f32)> {
let u = url::Url::parse(link).ok()?;
if u.host_str() != Some("music.apple.com") {
return None;
}
let path = u.path().trim_start_matches('/');
let parts: Vec<&str> = path.split('/').collect();
let has_region = parts.first().is_some_and(|p| (p.len() == 2 || p.len() == 5) && p.chars().all(|c| c.is_ascii_lowercase() || c == '-'));
let mut kind = parts.get(if has_region { 1 } else { 0 }).map(|s| s.to_ascii_lowercase()).unwrap_or_default();
let song = u.query_pairs().find(|(k, _)| k == "i").map(|(_, v)| v.into_owned());
if song.is_some() {
kind = "song".into();
}
let height = match kind.as_str() {
"song" => 175.0,
"music-video" => 371.0,
_ => 450.0,
};
let mut out = url::Url::parse(&format!("https://embed.music.apple.com/{path}")).ok()?;
out.query_pairs_mut().append_pair("theme", "dark").append_pair("i", song.as_deref().unwrap_or(""));
Some((out.to_string(), height))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn youtube_gets_autoplay() {
let s = player_src(Some("YouTube"), "https://www.youtube.com/embed/dQw4w9WgXcQ").unwrap();
assert_eq!(s, "https://www.youtube.com/embed/dQw4w9WgXcQ?autoplay=1&auto_play=1");
}
#[test]
fn twitch_parent_is_replaced() {
let s = player_src(Some("Twitch"), "https://player.twitch.tv/?channel=x&parent=meta.tag").unwrap();
assert_eq!(s, "https://player.twitch.tv/?channel=x&parent=rustcord.localhost&autoplay=true");
}
#[test]
fn only_the_wrapper_page_is_the_wrapper() {
assert!(is_wrapper("https://rustcord.localhost/?n=3") && is_wrapper("rustcord://localhost/"));
assert!(is_wrapper(&format!("{ORIGIN}/")));
for other in ["https://rustcord.localhost.example.com/", "https://[email protected]/", "https://example.com/rustcord.localhost", "http://rustcord.localhost/", "rustcord://example.com/"] {
assert!(!is_wrapper(other), "{other}");
}
}
#[test]
fn http_players_are_refused() {
assert!(player_src(None, "http://example.com/player").is_none());
}
#[test]
fn spotify_kinds() {
assert_eq!(spotify_embed("https://open.spotify.com/track/4cOdK2wGLETKBW3PvgPWqT?si=abc").unwrap(), ("https://open.spotify.com/embed/track/4cOdK2wGLETKBW3PvgPWqT?utm_source=discord&utm_medium=desktop".to_string(), 80.0));
assert_eq!(spotify_embed("https://open.spotify.com/intl-de/album/abc123").unwrap().1, 352.0);
assert_eq!(spotify_embed("https://open.spotify.com/user/x/playlist/abc123").unwrap().0, "https://open.spotify.com/embed/playlist/abc123?utm_source=discord&utm_medium=desktop");
assert!(spotify_embed("https://example.com/track/abc").is_none());
}
#[test]
fn apple_music_song() {
let (url, h) = apple_music_embed("https://music.apple.com/us/album/never-gonna/1558533900?i=1558534271").unwrap();
assert_eq!(h, 175.0);
assert_eq!(url, "https://embed.music.apple.com/us/album/never-gonna/1558533900?theme=dark&i=1558534271");
assert_eq!(apple_music_embed("https://music.apple.com/us/album/never-gonna/1558533900").unwrap().1, 450.0);
}
#[test]
fn player_is_clipped_not_resized() {
let rect = egui::Rect::from_min_size(egui::pos2(100.0, 50.0), egui::vec2(400.0, 225.0));
let all = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(1000.0, 1000.0));
assert_eq!(geometry(rect, all, 1.0), ([100, 50, 400, 225], None));
// Scrolled half under the top of the chat: same bounds, the top cut off.
let clip = egui::Rect::from_min_max(egui::pos2(0.0, 150.0), egui::pos2(1000.0, 1000.0));
assert_eq!(geometry(rect, clip, 2.0), ([200, 100, 800, 450], Some([0, 200, 800, 450])));
assert!(EmbedView::in_view(rect, clip));
assert!(!EmbedView::in_view(rect, egui::Rect::from_min_max(egui::pos2(0.0, 300.0), egui::pos2(1000.0, 1000.0))));
}
#[test]
fn pages() {
let p = page("https://x.test/?a=1&b=\"2\"", egui::Color32::BLACK);
assert!(p.contains("src=\"https://x.test/?a=1&b="2"\"") && !p.contains("__place"));
assert!(p.contains("command:'play'") && !p.contains("{SPOTIFY_AUTOPLAY}"));
assert!(blank().contains("preconnect") && !blank().contains("iframe"));
}
}