Everything in Rust on Servo 0.7 (trimmed: no WebXR, WebGPU, multiprocess): tabs and windows, address bar with suggestions, history, bookmarks and reading list, downloads with resume and external download managers, encrypted password vault with autofill, ad blocker (adblock-rust, 22 lists), VPN through Tor or a proxy and secure DNS via a local bridge proxy, picture in picture, Discord Rich Presence, media player and visualizer, spell check, site apps, user scripts and styles, import from other browsers, gamepads, Web Bluetooth, and every setting of the original Nacre in a plain egui interface. Not compiled yet; docs/HANDOFF.md has the first build checklist. Co-Authored-By: Claude Opus 5.5 <[email protected]>
471 lines
19 KiB
Rust
471 lines
19 KiB
Rust
//! Discord Rich Presence over the local IPC socket (the real Discord client or arRPC).
|
|
//!
|
|
//! Media tabs on supported sites get a full activity (art, linked title and creator, buttons,
|
|
//! progress bar); optionally any other tab is reported as "browsing". Each site can use its own
|
|
//! Discord application ID so its name shows, e.g. "Watching YouTube".
|
|
//!
|
|
//! A worker thread owns the socket; the browser sends it the activity it wants shown.
|
|
|
|
use std::io::{Read, Write};
|
|
use std::path::PathBuf;
|
|
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
|
|
use std::sync::{Arc, Mutex};
|
|
use std::time::Duration;
|
|
|
|
use serde_json::{Value, json};
|
|
use url::Url;
|
|
|
|
use crate::media::MediaState;
|
|
use crate::store::settings::{Rpc, RpcBrowseType, RpcBrowsing, RpcDisplay, RpcTarget};
|
|
use crate::util;
|
|
|
|
/// host -> (display name, "listen" | "watch", button label)
|
|
pub const SITES: &[(&str, &str, &str, &str)] = &[
|
|
("music.youtube.com", "YouTube Music", "listen", "Listen on YouTube Music"),
|
|
("youtube.com", "YouTube", "watch", "Watch on YouTube"),
|
|
("soundcloud.com", "SoundCloud", "listen", "Listen on SoundCloud"),
|
|
("open.spotify.com", "Spotify", "listen", "Listen on Spotify"),
|
|
("music.apple.com", "Apple Music", "listen", "Listen on Apple Music"),
|
|
("deezer.com", "Deezer", "listen", "Listen on Deezer"),
|
|
("tidal.com", "TIDAL", "listen", "Listen on TIDAL"),
|
|
("bandcamp.com", "Bandcamp", "listen", "Listen on Bandcamp"),
|
|
("mixcloud.com", "Mixcloud", "listen", "Listen on Mixcloud"),
|
|
("audiomack.com", "Audiomack", "listen", "Listen on Audiomack"),
|
|
("pandora.com", "Pandora", "listen", "Listen on Pandora"),
|
|
("twitch.tv", "Twitch", "watch", "Watch on Twitch"),
|
|
("kick.com", "Kick", "watch", "Watch on Kick"),
|
|
("netflix.com", "Netflix", "watch", "Watch on Netflix"),
|
|
("hulu.com", "Hulu", "watch", "Watch on Hulu"),
|
|
("disneyplus.com", "Disney+", "watch", "Watch on Disney+"),
|
|
("primevideo.com", "Prime Video", "watch", "Watch on Prime Video"),
|
|
("max.com", "Max", "watch", "Watch on Max"),
|
|
("crunchyroll.com", "Crunchyroll", "watch", "Watch on Crunchyroll"),
|
|
("tv.apple.com", "Apple TV+", "watch", "Watch on Apple TV+"),
|
|
("peacocktv.com", "Peacock", "watch", "Watch on Peacock"),
|
|
("paramountplus.com", "Paramount+", "watch", "Watch on Paramount+"),
|
|
("vimeo.com", "Vimeo", "watch", "Watch on Vimeo"),
|
|
("dailymotion.com", "Dailymotion", "watch", "Watch on Dailymotion"),
|
|
("nebula.tv", "Nebula", "watch", "Watch on Nebula"),
|
|
("bilibili.com", "bilibili", "watch", "Watch on bilibili"),
|
|
];
|
|
|
|
const DISCORD_DIRS: &[&str] = &["", "app/com.discordapp.Discord", "app/com.discordapp.DiscordCanary", "snap.discord"];
|
|
const ARRPC_DIRS: &[&str] = &["", ".flatpak/dev.vencord.Vesktop/xdg-run", "app/dev.vencord.Vesktop"];
|
|
|
|
/// A supported (or user-added) site for a host: (key, name, kind, button label).
|
|
pub fn site_for(host: &str, settings: &Rpc) -> Option<(String, String, String, String)> {
|
|
let host = host.trim_start_matches("www.");
|
|
let mut table: Vec<(String, String, String, String)> = SITES.iter().map(|(k, n, kind, b)| ((*k).to_owned(), (*n).to_owned(), (*kind).to_owned(), (*b).to_owned())).collect();
|
|
for custom in &settings.custom {
|
|
let key = custom.trim().trim_start_matches("www.").to_owned();
|
|
if !key.is_empty() {
|
|
table.push((key.clone(), key.clone(), "listen".into(), format!("Open on {key}")));
|
|
}
|
|
}
|
|
table.sort_by_key(|(k, ..)| std::cmp::Reverse(k.len()));
|
|
let found = table.into_iter().find(|(k, ..)| util::host_matches(host, k))?;
|
|
(!settings.disabled_sites.contains(&found.0)).then_some(found)
|
|
}
|
|
|
|
pub fn youtube_id(url: &Url) -> Option<String> {
|
|
let host = url.host_str()?;
|
|
if host == "youtu.be" {
|
|
let id: String = url.path().trim_matches('/').chars().take(11).collect();
|
|
return (!id.is_empty()).then_some(id);
|
|
}
|
|
if util::host_matches(host, "youtube.com") {
|
|
if let Some((_, v)) = url.query_pairs().find(|(k, _)| k == "v") {
|
|
return Some(v.chars().take(11).collect());
|
|
}
|
|
let parts: Vec<&str> = url.path().trim_matches('/').split('/').collect();
|
|
if parts.len() >= 2 && matches!(parts[0], "shorts" | "live" | "embed") {
|
|
return Some(parts[1].chars().take(11).collect());
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
/// Discord wants 2 to 128 characters.
|
|
fn clip(text: &str, max: usize) -> String {
|
|
let t = util::ellipsize(text.trim(), max);
|
|
if t.chars().count() < 2 { format!("{t:<2}") } else { t }
|
|
}
|
|
|
|
fn activity_type(kind: &str) -> u8 {
|
|
match kind {
|
|
"listen" => 2,
|
|
"watch" => 3,
|
|
_ => 0,
|
|
}
|
|
}
|
|
|
|
fn display_type(display: RpcDisplay) -> u8 {
|
|
match display {
|
|
RpcDisplay::Name => 0,
|
|
RpcDisplay::State => 1,
|
|
RpcDisplay::Details => 2,
|
|
}
|
|
}
|
|
|
|
fn https_short(url: &str) -> bool {
|
|
url.starts_with("https://") && url.len() <= 256
|
|
}
|
|
|
|
/// Options that Discord clients may refuse; the worker turns them off when it is told so.
|
|
#[derive(Clone, Copy, Debug)]
|
|
pub struct Quirks {
|
|
pub urls_ok: bool,
|
|
pub name_ok: bool,
|
|
}
|
|
|
|
/// Activity for a playing (or paused) media tab, plus the application ID to use.
|
|
/// `started` keeps the progress bar steady between polls: (tab id, title, start ms).
|
|
pub fn media_activity(settings: &Rpc, tab_url: &Url, tab_title: &str, favicon: &str, state: &MediaState, tab_id: u64, started: &mut Option<(u64, String, i64)>) -> Option<(Value, String)> {
|
|
let (key, name, kind, button) = site_for(&util::host_of(tab_url), settings)?;
|
|
if state.paused && !settings.show_paused {
|
|
return None;
|
|
}
|
|
let title = if state.title.trim().is_empty() { tab_title.trim().to_owned() } else { state.title.trim().to_owned() };
|
|
let creator = if state.artist.trim().is_empty() { name.clone() } else { state.artist.trim().to_owned() };
|
|
let mut link = tab_url.to_string();
|
|
let mut art = state.art.clone();
|
|
if let Some(vid) = youtube_id(tab_url) {
|
|
let music = tab_url.host_str().is_some_and(|h| h.starts_with("music."));
|
|
link = format!("https://{}.youtube.com/watch?v={vid}", if music { "music" } else { "www" });
|
|
if !(music && https_short(&art)) {
|
|
art = format!("https://i.ytimg.com/vi/{vid}/hqdefault.jpg");
|
|
}
|
|
}
|
|
if !https_short(&art) {
|
|
art = if https_short(favicon) { favicon.to_owned() } else { String::new() };
|
|
}
|
|
let by = if creator != name { format!("by {creator}") } else { name.clone() };
|
|
let mut act = json!({
|
|
"type": activity_type(&kind),
|
|
"status_display_type": display_type(settings.display),
|
|
"details": clip(&title, 128),
|
|
"state": clip(&by, 128),
|
|
"name": name,
|
|
"details_url": util::ellipsize(&link, 256),
|
|
"assets": {"large_text": clip(if state.album.is_empty() { &name } else { &state.album }, 128)},
|
|
});
|
|
if https_short(&state.creator_url) {
|
|
act["state_url"] = json!(state.creator_url);
|
|
}
|
|
if !art.is_empty() {
|
|
act["assets"]["large_image"] = json!(art);
|
|
act["assets"]["large_url"] = json!(util::ellipsize(&link, 256));
|
|
}
|
|
if state.paused {
|
|
act["state"] = json!(clip(&format!("Paused · {by}"), 128));
|
|
act["assets"]["small_text"] = json!("Paused");
|
|
} else if state.duration > 0.0 && state.duration.is_finite() {
|
|
// Discord draws a real progress bar from start and end; only move it on seeks, not on jitter.
|
|
let start = util::now_ms() as i64 - (state.position * 1000.0) as i64;
|
|
let keep = started.as_ref().filter(|(id, t, s)| *id == tab_id && *t == title && (s - start).abs() < 2500).map(|(.., s)| *s);
|
|
let start = keep.unwrap_or(start);
|
|
*started = Some((tab_id, title.clone(), start));
|
|
act["timestamps"] = json!({"start": start, "end": start + (state.duration * 1000.0) as i64});
|
|
}
|
|
if settings.button {
|
|
let mut buttons = vec![json!({"label": util::ellipsize(&button, 32), "url": util::ellipsize(&link, 512)})];
|
|
if https_short(&state.creator_url) {
|
|
buttons.push(json!({"label": if kind == "listen" { "View artist" } else { "View channel" }, "url": state.creator_url}));
|
|
}
|
|
act["buttons"] = json!(buttons);
|
|
}
|
|
let id = settings.site_ids.get(&key).map(|s| s.trim().to_owned()).filter(|s| !s.is_empty()).unwrap_or_else(|| settings.client_id.trim().to_owned());
|
|
Some((act, id))
|
|
}
|
|
|
|
/// "Browsing" activity for an ordinary tab. `since_ms` is when the user arrived on the page.
|
|
pub fn browse_activity(settings: &Rpc, url: &Url, title: &str, site_name: &str, image: &str, since_ms: i64) -> Option<Value> {
|
|
if settings.browsing == RpcBrowsing::Off || !matches!(url.scheme(), "http" | "https") {
|
|
return None;
|
|
}
|
|
let host = util::host_of(url);
|
|
let site = if site_name.trim().is_empty() { host.clone() } else { site_name.trim().to_owned() };
|
|
let by_title = settings.browsing == RpcBrowsing::Title;
|
|
// Never "Playing" (0): Discord shows one activity per type, so it would fight games for the slot.
|
|
let kind = match settings.browse_type {
|
|
RpcBrowseType::Watch => 3,
|
|
RpcBrowseType::Listen => 2,
|
|
};
|
|
let mut act = json!({
|
|
"type": kind,
|
|
"status_display_type": display_type(settings.display),
|
|
"details": clip(if by_title { title } else { &site }, 128),
|
|
"state": clip(if by_title { &site } else { &host }, 128),
|
|
"timestamps": {"start": since_ms},
|
|
"assets": {"large_text": clip(&host, 128)},
|
|
});
|
|
if https_short(image) {
|
|
act["assets"]["large_image"] = json!(image);
|
|
}
|
|
if by_title && settings.button {
|
|
act["buttons"] = json!([{"label": util::ellipsize(&format!("Open on {site}"), 32), "url": util::ellipsize(url.as_str(), 512)}]);
|
|
}
|
|
Some(act)
|
|
}
|
|
|
|
/// Socket paths to try, the chosen target's first.
|
|
pub fn socket_paths(target: RpcTarget) -> Vec<PathBuf> {
|
|
#[cfg(windows)]
|
|
{
|
|
let _ = target;
|
|
(0..10).map(|i| PathBuf::from(format!(r"\\.\pipe\discord-ipc-{i}"))).filter(|p| std::fs::metadata(p).is_ok() || std::fs::OpenOptions::new().read(true).open(p).is_ok()).collect()
|
|
}
|
|
#[cfg(not(windows))]
|
|
{
|
|
let bases: Vec<PathBuf> = ["XDG_RUNTIME_DIR", "TMPDIR", "TMP", "TEMP"].iter().filter_map(std::env::var_os).map(PathBuf::from).chain(std::iter::once(PathBuf::from("/tmp"))).collect();
|
|
let dirs: Vec<&str> = match target {
|
|
RpcTarget::Arrpc => ARRPC_DIRS.iter().chain(DISCORD_DIRS).copied().collect(),
|
|
RpcTarget::Discord => DISCORD_DIRS.iter().chain(ARRPC_DIRS).copied().collect(),
|
|
};
|
|
let mut out: Vec<PathBuf> = Vec::new();
|
|
for base in &bases {
|
|
for dir in &dirs {
|
|
for i in 0..10 {
|
|
let path = base.join(dir).join(format!("discord-ipc-{i}"));
|
|
if !out.contains(&path) && path.exists() {
|
|
out.push(path);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
type Socket = std::os::unix::net::UnixStream;
|
|
#[cfg(windows)]
|
|
type Socket = std::fs::File;
|
|
|
|
fn open(path: &PathBuf) -> std::io::Result<Socket> {
|
|
#[cfg(unix)]
|
|
{
|
|
let s = std::os::unix::net::UnixStream::connect(path)?;
|
|
s.set_read_timeout(Some(Duration::from_millis(200)))?;
|
|
Ok(s)
|
|
}
|
|
#[cfg(windows)]
|
|
{
|
|
std::fs::OpenOptions::new().read(true).write(true).open(path)
|
|
}
|
|
}
|
|
|
|
fn send_frame(s: &mut Socket, op: u32, payload: &Value) -> std::io::Result<()> {
|
|
let data = payload.to_string().into_bytes();
|
|
let mut frame = Vec::with_capacity(8 + data.len());
|
|
frame.extend_from_slice(&op.to_le_bytes());
|
|
frame.extend_from_slice(&(data.len() as u32).to_le_bytes());
|
|
frame.extend_from_slice(&data);
|
|
s.write_all(&frame)
|
|
}
|
|
|
|
/// Read one frame; `Ok(None)` when nothing arrived before the timeout.
|
|
fn read_frame(s: &mut Socket, buf: &mut Vec<u8>) -> std::io::Result<Option<(u32, Value)>> {
|
|
loop {
|
|
if buf.len() >= 8 {
|
|
let op = u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]);
|
|
let len = u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]) as usize;
|
|
if buf.len() >= 8 + len {
|
|
let body: Vec<u8> = buf.drain(..8 + len).skip(8).collect();
|
|
let value = serde_json::from_slice(&body).unwrap_or(Value::Null);
|
|
return Ok(Some((op, value)));
|
|
}
|
|
}
|
|
let mut chunk = [0u8; 4096];
|
|
match s.read(&mut chunk) {
|
|
Ok(0) => return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "closed")),
|
|
Ok(n) => buf.extend_from_slice(&chunk[..n]),
|
|
Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => return Ok(None),
|
|
Err(e) => return Err(e),
|
|
}
|
|
}
|
|
}
|
|
|
|
enum Command {
|
|
Set { client_id: String, target: RpcTarget, activity: Option<Value> },
|
|
Stop,
|
|
}
|
|
|
|
/// Handle used by the browser.
|
|
pub struct Presence {
|
|
tx: Sender<Command>,
|
|
pub status: Arc<Mutex<String>>,
|
|
last: Option<(String, Option<Value>)>,
|
|
}
|
|
|
|
impl Presence {
|
|
pub fn start(wake: Arc<dyn Fn() + Send + Sync>) -> Presence {
|
|
let (tx, rx) = mpsc::channel();
|
|
let status = Arc::new(Mutex::new("Off".to_owned()));
|
|
let s = status.clone();
|
|
let _ = std::thread::Builder::new().name("nacre-discord".into()).spawn(move || worker(rx, s, wake));
|
|
Presence { tx, status, last: None }
|
|
}
|
|
|
|
pub fn status(&self) -> String {
|
|
self.status.lock().map(|s| s.clone()).unwrap_or_default()
|
|
}
|
|
|
|
/// Show `activity` (None clears it). Repeats of the same thing are not sent again.
|
|
pub fn set(&mut self, client_id: &str, target: RpcTarget, activity: Option<Value>) {
|
|
let key = (client_id.to_owned(), activity.clone());
|
|
if self.last.as_ref() == Some(&key) {
|
|
return;
|
|
}
|
|
self.last = Some(key);
|
|
let _ = self.tx.send(Command::Set { client_id: client_id.to_owned(), target, activity });
|
|
}
|
|
|
|
/// Disconnect (Rich Presence switched off).
|
|
pub fn stop(&mut self) {
|
|
self.last = None;
|
|
let _ = self.tx.send(Command::Stop);
|
|
}
|
|
}
|
|
|
|
impl Drop for Presence {
|
|
fn drop(&mut self) {
|
|
let _ = self.tx.send(Command::Stop);
|
|
}
|
|
}
|
|
|
|
fn worker(rx: Receiver<Command>, status: Arc<Mutex<String>>, wake: Arc<dyn Fn() + Send + Sync>) {
|
|
let set_status = |text: &str| {
|
|
if let Ok(mut s) = status.lock()
|
|
&& *s != text
|
|
{
|
|
*s = text.to_owned();
|
|
wake();
|
|
}
|
|
};
|
|
let mut socket: Option<Socket> = None;
|
|
let mut connected_id = String::new();
|
|
let mut buf = Vec::new();
|
|
let mut wanted: Option<(String, RpcTarget, Option<Value>)> = None;
|
|
let mut sent: Option<Value> = None;
|
|
let mut quirks = Quirks { urls_ok: true, name_ok: true };
|
|
let mut ready = false;
|
|
let mut retry_at = std::time::Instant::now();
|
|
loop {
|
|
match rx.recv_timeout(Duration::from_millis(if socket.is_some() { 250 } else { 2000 })) {
|
|
Ok(Command::Set { client_id, target, activity }) => wanted = Some((client_id, target, activity)),
|
|
Ok(Command::Stop) => {
|
|
wanted = None;
|
|
socket = None;
|
|
ready = false;
|
|
connected_id.clear();
|
|
set_status("Off");
|
|
continue;
|
|
},
|
|
Err(RecvTimeoutError::Timeout) => {},
|
|
Err(RecvTimeoutError::Disconnected) => return,
|
|
}
|
|
let Some((client_id, target, activity)) = wanted.clone() else { continue };
|
|
if client_id.is_empty() {
|
|
set_status("Needs an application ID");
|
|
continue;
|
|
}
|
|
// (Re)connect when the app ID changed or the socket is gone.
|
|
if socket.is_none() || connected_id != client_id {
|
|
if std::time::Instant::now() < retry_at && connected_id == client_id {
|
|
continue;
|
|
}
|
|
socket = None;
|
|
ready = false;
|
|
sent = None;
|
|
buf.clear();
|
|
let paths = socket_paths(target);
|
|
for path in &paths {
|
|
if let Ok(mut s) = open(path)
|
|
&& send_frame(&mut s, 0, &json!({"v": 1, "client_id": client_id})).is_ok()
|
|
{
|
|
socket = Some(s);
|
|
break;
|
|
}
|
|
}
|
|
connected_id = client_id.clone();
|
|
if socket.is_none() {
|
|
set_status(if target == RpcTarget::Arrpc { "arRPC isn't running" } else { "Discord isn't running" });
|
|
retry_at = std::time::Instant::now() + Duration::from_secs(20);
|
|
continue;
|
|
}
|
|
set_status("Connecting");
|
|
}
|
|
let Some(s) = socket.as_mut() else { continue };
|
|
// Read replies.
|
|
loop {
|
|
match read_frame(s, &mut buf) {
|
|
Ok(Some((1, msg))) => {
|
|
match msg.get("evt").and_then(Value::as_str) {
|
|
Some("READY") => {
|
|
ready = true;
|
|
sent = None;
|
|
set_status("Connected");
|
|
},
|
|
Some("ERROR") => {
|
|
let err = msg.pointer("/data/message").and_then(Value::as_str).unwrap_or("error").to_owned();
|
|
if quirks.urls_ok && err.contains("_url") {
|
|
quirks.urls_ok = false;
|
|
sent = None;
|
|
} else if quirks.name_ok && err.to_lowercase().contains("name") {
|
|
quirks.name_ok = false;
|
|
sent = None;
|
|
} else {
|
|
set_status(&format!("Discord: {err}"));
|
|
}
|
|
},
|
|
_ => {},
|
|
}
|
|
},
|
|
Ok(Some((2, msg))) => {
|
|
let why = msg.get("message").and_then(Value::as_str).unwrap_or("check the application ID").to_owned();
|
|
set_status(&format!("Rejected: {why}"));
|
|
socket = None;
|
|
retry_at = std::time::Instant::now() + Duration::from_secs(60);
|
|
break;
|
|
},
|
|
Ok(Some((3, msg))) => {
|
|
let _ = send_frame(s, 4, &msg);
|
|
},
|
|
Ok(Some(_)) => {},
|
|
Ok(None) => break,
|
|
Err(_) => {
|
|
socket = None;
|
|
ready = false;
|
|
set_status("Disconnected");
|
|
retry_at = std::time::Instant::now() + Duration::from_secs(10);
|
|
break;
|
|
},
|
|
}
|
|
}
|
|
let (Some(s), true) = (socket.as_mut(), ready) else { continue };
|
|
let mut act = activity.clone();
|
|
if let Some(Value::Object(map)) = act.as_mut() {
|
|
if !quirks.urls_ok {
|
|
map.remove("details_url");
|
|
map.remove("state_url");
|
|
if let Some(Value::Object(assets)) = map.get_mut("assets") {
|
|
assets.remove("large_url");
|
|
}
|
|
}
|
|
if !quirks.name_ok {
|
|
map.remove("name");
|
|
}
|
|
}
|
|
if sent.as_ref() == Some(&act.clone().unwrap_or(Value::Null)) {
|
|
continue;
|
|
}
|
|
let payload = json!({"cmd": "SET_ACTIVITY", "args": {"pid": std::process::id(), "activity": act.clone().unwrap_or(Value::Null)}, "nonce": util::random_hex(16)});
|
|
if send_frame(s, 1, &payload).is_ok() {
|
|
sent = Some(act.unwrap_or(Value::Null));
|
|
} else {
|
|
socket = None;
|
|
ready = false;
|
|
}
|
|
}
|
|
}
|