Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

11.3 KB
Raw Blame
//! # Rencord
//!
//! RustCord's built-in client-mod system: a native take on Vencord.
//!
//! Vencord plugins patch Discord's web bundle and React tree, which a native
//! client doesn't have. Rencord instead exposes typed hooks at the points
//! Vencord plugins usually patch (sending, editing, incoming messages,
//! deletions, typing and message context menus), so Vencord plugins can be
//! ported natively. Settings are declarative and rendered by the client.

pub mod plugins;
pub mod settings;
pub mod theme;

pub use settings::{PluginSettings, SettingDef, SettingKind, SettingValue};

use discord::model::{Id, Message, OutgoingMessage};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::path::PathBuf;

#[derive(Clone, Debug)]
pub struct PluginMeta {
    pub id: &'static str,
    pub name: &'static str,
    pub description: &'static str,
    pub authors: &'static [&'static str],
    /// The Vencord plugin this recreates, if any.
    pub vencord_equivalent: Option<&'static str>,
    pub default_enabled: bool,
}

/// Context handed to every hook.
pub struct Cx<'a> {
    /// The logged-in user's id.
    pub me: Option<Id>,
    pub settings: &'a PluginSettings,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DeleteAction {
    /// Drop the message from the client (default Discord behaviour).
    Remove,
    /// Keep the message; the plugin has marked it in `msg.meta`.
    Keep,
}

#[derive(Clone, Debug)]
pub struct MessageAction {
    pub id: &'static str,
    pub label: String,
    pub danger: bool,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ActionOutcome {
    Nothing,
    RemoveMessage,
}

/// A Rencord plugin. Every hook has a no-op default, so a plugin only
/// implements what it needs.
pub trait Plugin: Send {
    fn meta(&self) -> PluginMeta;

    fn settings(&self) -> Vec<SettingDef> {
        Vec::new()
    }

    fn start(&mut self, _cx: &Cx) {}
    fn stop(&mut self, _cx: &Cx) {}

    /// Called before a message is sent. Mutate it, or return `false` to cancel.
    fn before_send(&mut self, _cx: &Cx, _msg: &mut OutgoingMessage) -> bool {
        true
    }

    /// Called before an edit is submitted. Return `false` to cancel.
    fn before_edit(&mut self, _cx: &Cx, _channel: Id, _content: &mut String) -> bool {
        true
    }

    /// A message arrived over the gateway.
    fn message_create(&mut self, _cx: &Cx, _msg: &mut Message) {}

    /// A message was edited. `new` starts as a copy of `old` with the update applied.
    fn message_update(&mut self, _cx: &Cx, _old: &Message, _new: &mut Message) {}

    /// A message was deleted.
    fn message_delete(&mut self, _cx: &Cx, _msg: &mut Message) -> DeleteAction {
        DeleteAction::Remove
    }

    /// RustCord is about to send a typing indicator. Return `false` to suppress it.
    fn typing(&mut self, _cx: &Cx, _channel: Id) -> bool {
        true
    }

    /// A reply to `author`'s message in `channel` is being started. Return
    /// `false` to start it with the reply bar's "@" (ping the author) off;
    /// the bar's toggle still has the last word.
    fn reply_mention(&mut self, _cx: &Cx, _channel: Id, _author: Id) -> bool {
        true
    }

    /// Extra entries for a message's context menu.
    fn message_actions(&self, _cx: &Cx, _msg: &Message) -> Vec<MessageAction> {
        Vec::new()
    }

    fn run_message_action(&mut self, _cx: &Cx, _action: &str, _msg: &mut Message) -> ActionOutcome {
        ActionOutcome::Nothing
    }
}

pub struct Entry {
    pub plugin: Box<dyn Plugin>,
    pub meta: PluginMeta,
    pub enabled: bool,
    pub settings: PluginSettings,
    /// Set if the plugin panicked; it is disabled until restart.
    pub crashed: Option<String>,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct PluginConfig {
    pub enabled: bool,
    #[serde(default)]
    pub settings: BTreeMap<String, SettingValue>,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct ThemeConfig {
    /// URL or local file path of the active theme.
    #[serde(default)]
    pub source: Option<String>,
    /// QuickCSS, translated after the theme so it wins.
    #[serde(default)]
    pub quick_css: String,
    /// Base appearance: "dark" (default), "ash" or "onyx".
    #[serde(default)]
    pub base: String,
}

#[derive(Default, Serialize, Deserialize)]
struct ConfigFile {
    #[serde(default)]
    plugins: BTreeMap<String, PluginConfig>,
    #[serde(default)]
    theme: ThemeConfig,
}

pub struct Rencord {
    entries: Vec<Entry>,
    path: Option<PathBuf>,
    me: Option<Id>,
    pub theme: ThemeConfig,
}

impl Entry {
    /// Run one of the plugin's hooks. A plugin that panics is disabled
    /// instead of taking the client down, and the hook gives `fallback`.
    fn guarded<R>(&mut self, me: Option<Id>, fallback: R, f: impl FnOnce(&mut dyn Plugin, &Cx) -> R) -> R {
        let cx = Cx { me, settings: &self.settings };
        let plugin = self.plugin.as_mut();
        match catch_unwind(AssertUnwindSafe(|| f(plugin, &cx))) {
            Ok(r) => r,
            Err(_) => {
                log::error!("Rencord plugin {} panicked and was disabled", self.meta.id);
                self.enabled = false;
                self.crashed = Some("This plugin crashed and was disabled.".into());
                fallback
            }
        }
    }
}

impl Rencord {
    /// Load built-in plugins and saved settings from `path` (if any).
    pub fn load(path: Option<PathBuf>) -> Self {
        let file: ConfigFile = path
            .as_ref()
            .and_then(|p| std::fs::read_to_string(p).ok())
            .and_then(|s| serde_json::from_str(&s).ok())
            .unwrap_or_default();

        let entries = plugins::builtin()
            .into_iter()
            .map(|plugin| {
                let meta = plugin.meta();
                let saved = file.plugins.get(meta.id);
                Entry {
                    enabled: saved.map(|s| s.enabled).unwrap_or(meta.default_enabled),
                    settings: PluginSettings::new(
                        plugin.settings(),
                        saved.map(|s| s.settings.clone()).unwrap_or_default(),
                    ),
                    plugin,
                    meta,
                    crashed: None,
                }
            })
            .collect();

        let mut r = Self { entries, path, me: None, theme: file.theme };
        let me = r.me;
        for e in r.entries.iter_mut().filter(|e| e.enabled) {
            e.guarded(me, (), |p, cx| p.start(cx));
        }
        r
    }

    pub fn save(&self) {
        let Some(path) = &self.path else { return };
        let file = ConfigFile {
            plugins: self
                .entries
                .iter()
                .map(|e| {
                    (
                        e.meta.id.to_string(),
                        PluginConfig { enabled: e.enabled, settings: e.settings.values().clone() },
                    )
                })
                .collect(),
            theme: self.theme.clone(),
        };
        match serde_json::to_string_pretty(&file) {
            Ok(json) => {
                if let Some(dir) = path.parent() {
                    let _ = std::fs::create_dir_all(dir);
                }
                if let Err(e) = std::fs::write(path, json) {
                    log::error!("couldn't save Rencord config: {e}");
                }
            }
            Err(e) => log::error!("couldn't serialize Rencord config: {e}"),
        }
    }

    pub fn set_me(&mut self, me: Option<Id>) {
        self.me = me;
    }

    pub fn entries(&self) -> &[Entry] {
        &self.entries
    }

    /// The plugin with this id, if it's enabled (for features the client
    /// implements itself, like MessageSelect).
    pub fn enabled(&self, id: &str) -> Option<&Entry> {
        self.entries.iter().find(|e| e.enabled && e.meta.id == id)
    }

    pub fn set_enabled(&mut self, index: usize, enabled: bool) {
        let me = self.me;
        let Some(e) = self.entries.get_mut(index) else { return };
        if e.enabled == enabled {
            return;
        }
        e.enabled = enabled;
        if enabled {
            e.crashed = None;
        }
        if enabled {
            e.guarded(me, (), |p, cx| p.start(cx));
        } else {
            e.guarded(me, (), |p, cx| p.stop(cx));
        }
        self.save();
    }

    pub fn set_setting(&mut self, index: usize, key: &str, value: SettingValue) {
        if let Some(e) = self.entries.get_mut(index) {
            e.settings.set(key, value);
            self.save();
        }
    }

    /// Run `f` for every enabled plugin, isolating panics: a crashing plugin
    /// is disabled instead of taking the client down.
    fn each(&mut self, mut f: impl FnMut(&mut dyn Plugin, &Cx) -> bool) -> bool {
        let me = self.me;
        for e in self.entries.iter_mut().filter(|e| e.enabled) {
            if !e.guarded(me, true, &mut f) {
                return false;
            }
        }
        true
    }

    pub fn before_send(&mut self, msg: &mut OutgoingMessage) -> bool {
        self.each(|p, cx| p.before_send(cx, msg))
    }

    pub fn before_edit(&mut self, channel: Id, content: &mut String) -> bool {
        self.each(|p, cx| p.before_edit(cx, channel, content))
    }

    pub fn message_create(&mut self, msg: &mut Message) {
        self.each(|p, cx| {
            p.message_create(cx, msg);
            true
        });
    }

    pub fn message_update(&mut self, old: &Message, new: &mut Message) {
        self.each(|p, cx| {
            p.message_update(cx, old, new);
            true
        });
    }

    /// `Keep` if any plugin wants to keep the message.
    pub fn message_delete(&mut self, msg: &mut Message) -> DeleteAction {
        let mut action = DeleteAction::Remove;
        self.each(|p, cx| {
            if p.message_delete(cx, msg) == DeleteAction::Keep {
                action = DeleteAction::Keep;
            }
            true
        });
        action
    }

    pub fn typing(&mut self, channel: Id) -> bool {
        self.each(|p, cx| p.typing(cx, channel))
    }

    /// Whether a new reply to `author` starts with its ping on.
    pub fn reply_mention(&mut self, channel: Id, author: Id) -> bool {
        self.each(|p, cx| p.reply_mention(cx, channel, author))
    }

    /// (plugin index, action) pairs for a message's context menu.
    pub fn message_actions(&self, msg: &Message) -> Vec<(usize, MessageAction)> {
        let me = self.me;
        self.entries
            .iter()
            .enumerate()
            .filter(|(_, e)| e.enabled)
            .flat_map(|(i, e)| {
                let cx = Cx { me, settings: &e.settings };
                // (A menu is drawn from `&self`: a plugin that panics here
                // just offers nothing, and is disabled by its next hook.)
                catch_unwind(AssertUnwindSafe(|| e.plugin.message_actions(&cx, msg)))
                    .unwrap_or_default()
                    .into_iter()
                    .map(move |a| (i, a))
            })
            .collect()
    }

    pub fn run_message_action(&mut self, index: usize, action: &str, msg: &mut Message) -> ActionOutcome {
        let me = self.me;
        match self.entries.get_mut(index) {
            Some(e) if e.enabled => e.guarded(me, ActionOutcome::Nothing, |p, cx| p.run_message_action(cx, action, msg)),
            _ => ActionOutcome::Nothing,
        }
    }
}