Skip to content

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

10.8 KB
Raw Blame
//! Frequently Used emoji, kept the way Discord keeps them: in your frecency
//! settings (settings-proto 2), so the picker shows the same emoji in
//! RustCord and in Discord's apps. Emoji you send count in one list, emoji
//! you react with in another (Discord's `emojiFrecency` and
//! `emojiReactionFrecency`); server emoji count as well as Unicode ones.
//!
//! RustCord counts your uses on top of what Discord sent (as Discord's
//! client does with its pending uses), and, with Settings → Experimental →
//! "Sync Frequently Used emoji", sends them back half a minute after the
//! last one.

use crate::app::RustCord;
use discord::model::Id;
use discord::settings_proto::encode_emoji_frecency_patch;
use reqwest::Method;
use serde_json::json;
use std::time::{Duration, Instant};

/// How long after your last emoji RustCord waits before telling Discord:
/// one request for a burst of uses.
const SYNC_AFTER: Duration = Duration::from_secs(30);

/// An emoji use Discord hasn't been told about yet.
#[derive(Clone, Debug)]
pub struct PendingUse {
    /// Discord's key: a server emoji's ID, a Unicode emoji's name.
    pub key: String,
    /// A reaction (counted apart from emoji you send).
    pub reaction: bool,
    /// When, in milliseconds since 1970.
    pub at: u64,
}

/// The skin tone modifiers, light (1) to dark (5).
const TONES: [char; 5] = ['\u{1F3FB}', '\u{1F3FC}', '\u{1F3FD}', '\u{1F3FE}', '\u{1F3FF}'];

/// Discord's key for a Unicode emoji: its name ("thumbsup"), with
/// "_toneN" when it has a skin tone ("pray_tone1").
pub fn unicode_key(emoji: &str) -> Option<String> {
    let tone = emoji.chars().find_map(|c| TONES.iter().position(|t| *t == c)).map(|i| i + 1);
    let base: String = emoji.chars().filter(|c| !TONES.contains(c)).collect();
    let name = name_of(&base).or_else(|| crate::emoji::shortcode_of(&base))?;
    Some(match tone {
        Some(n) => format!("{name}_tone{n}"),
        None => name.to_string(),
    })
}

/// The Unicode emoji a key stands for.
pub fn unicode_from_key(key: &str) -> Option<String> {
    let lookup = |name: &str| crate::emoji::by_any_name(name).map(str::to_string).or_else(|| crate::emoji::from_shortcode(name));
    if let Some(e) = lookup(key) {
        return Some(e);
    }
    let (name, tone) = key.rsplit_once("_tone")?;
    let tone: u8 = tone.parse().ok().filter(|n| (1..=5).contains(n))?;
    let base = lookup(name)?;
    Some(crate::emoji::toned(&base, tone).map_or(base, str::to_string))
}

/// The picker's name for a Unicode emoji (without variation selectors).
fn name_of(emoji: &str) -> Option<&'static str> {
    use std::collections::HashMap;
    use std::sync::OnceLock;
    static MAP: OnceLock<HashMap<String, &'static str>> = OnceLock::new();
    let bare = |s: &str| s.chars().filter(|c| *c != '\u{FE0F}').collect::<String>();
    let map = MAP.get_or_init(|| crate::emoji_data::CATEGORIES.iter().flat_map(|(_, items)| items.iter()).map(|(e, n)| (bare(e), *n)).collect());
    map.get(&bare(emoji)).copied()
}

/// Discord's keys for the emoji in a message: `<:name:id>` and
/// `<a:name:id>` by ID, Unicode emoji by name, each once.
pub fn keys_in_text(text: &str) -> Vec<String> {
    let mut keys: Vec<String> = Vec::new();
    let mut push = |k: String| {
        if !keys.contains(&k) {
            keys.push(k);
        }
    };
    let chars: Vec<char> = text.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        if chars[i] == '<' {
            // <:name:id> or <a:name:id>
            if let Some(end) = chars[i..].iter().position(|c| *c == '>').map(|e| i + e) {
                let token: String = chars[i + 1..end].iter().collect();
                let parts: Vec<&str> = token.split(':').collect();
                if parts.len() == 3 && (parts[0].is_empty() || parts[0] == "a") && parts[2].parse::<u64>().is_ok() {
                    push(parts[2].to_string());
                    i = end + 1;
                    continue;
                }
            }
        }
        if let Some(n) = crate::emoji::emoji_len(&chars, i) {
            let seq: String = chars[i..i + n].iter().collect();
            if let Some(k) = unicode_key(&seq) {
                push(k);
            }
            i += n;
            continue;
        }
        i += 1;
    }
    keys
}

fn now_ms() -> u64 {
    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis() as u64)
}

impl RustCord {
    /// You used these emoji (sent them, or reacted with them): count them
    /// now, and tell Discord after a while.
    pub fn track_emoji(&mut self, keys: Vec<String>, reaction: bool) {
        if keys.is_empty() {
            return;
        }
        let at = now_ms();
        for key in keys {
            if let Some(f) = self.compose.frecency.as_mut() {
                let map = if reaction { &mut f.reaction_emoji } else { &mut f.emoji };
                map.entry(key.clone()).or_default().track(at);
            }
            self.compose.emoji_pending.push(PendingUse { key, reaction, at });
        }
        self.compose.emoji_sync_at = Some(Instant::now() + SYNC_AFTER);
        self.want_frecency();
    }

    /// You reacted with `emoji` (counted apart from emoji you send).
    pub fn track_reaction(&mut self, emoji: &discord::model::ReactionEmoji) {
        let key = match (emoji.id, emoji.name.as_deref()) {
            (Some(id), _) => Some(id.0.to_string()),
            (None, Some(e)) => unicode_key(e),
            _ => None,
        };
        self.track_emoji(key.into_iter().collect(), true);
    }

    /// Discord's frecency settings arrived: your uses it doesn't know about
    /// yet go on top (Discord's client replays its pending uses the same way).
    pub(super) fn replay_pending_emoji(&mut self) {
        let Some(f) = self.compose.frecency.as_mut() else { return };
        for p in &self.compose.emoji_pending {
            let map = if p.reaction { &mut f.reaction_emoji } else { &mut f.emoji };
            map.entry(p.key.clone()).or_default().track(p.at);
        }
    }

    /// Each frame: send the counted uses when it's time, and take Discord's
    /// answer.
    pub(super) fn emoji_sync_tick(&mut self) {
        if let Some(r) = self.api_take("expr:emoji-sync") {
            let sent = std::mem::take(&mut self.compose.emoji_sent);
            match r {
                Ok(v) if v["out_of_date"].as_bool() == Some(true) => {
                    // Changed elsewhere meanwhile: fetch it, RustCord's go on top, try again.
                    log::info!("emoji frecency: changed elsewhere, merging");
                    self.compose.frecency_at = None;
                    self.want_frecency();
                    self.compose.emoji_sync_at = Some(Instant::now() + SYNC_AFTER);
                }
                Ok(v) => {
                    let n = sent.min(self.compose.emoji_pending.len());
                    self.compose.emoji_pending.drain(..n);
                    if let Some(f) = v["settings"].as_str().and_then(|s| discord::settings_proto::decode_frecency(s).ok()) {
                        self.compose.frecency = Some(f);
                        self.replay_pending_emoji();
                    }
                    log::info!("emoji frecency: sent {n} uses");
                }
                Err(e) => {
                    log::warn!("emoji frecency: {e}");
                    self.compose.emoji_sync_at = Some(Instant::now() + SYNC_AFTER * 4);
                }
            }
        }
        let due = self.compose.emoji_sync_at.is_some_and(|t| Instant::now() >= t);
        if !due || !self.prefs.experiments.emoji_sync || self.demo || self.compose.emoji_pending.is_empty() {
            return;
        }
        if self.api_busy("expr:emoji-sync") || self.api_busy("expr:fav") || self.api_busy("expr:frecency") {
            return;
        }
        let Some(f) = self.compose.frecency.as_ref() else { return };
        self.compose.emoji_sync_at = None;
        // Only the lists that changed.
        let (sent, reacted) = (self.compose.emoji_pending.iter().any(|p| !p.reaction), self.compose.emoji_pending.iter().any(|p| p.reaction));
        let patch = encode_emoji_frecency_patch(sent.then_some(&f.emoji), reacted.then_some(&f.reaction_emoji));
        let version = f.version;
        self.compose.emoji_sent = self.compose.emoji_pending.len();
        self.api("expr:emoji-sync", Method::PATCH, "/users/@me/settings-proto/2", Some(json!({ "settings": patch, "required_data_version": version })));
    }

    /// The server's most used emoji (Discord's "Top Emoji in <server>"),
    /// asked for once per session, as Discord does once a day.
    pub(super) fn top_emoji(&self, guild: Id) -> Vec<Id> {
        match self.api_results.get(&format!("top-emojis:{guild}")) {
            Some(Ok(v)) => {
                let mut items: Vec<(u64, Id)> = v["items"]
                    .as_array()
                    .into_iter()
                    .flatten()
                    .filter_map(|e| Some((e["emoji_rank"].as_u64().unwrap_or(u64::MAX), Id(e["emoji_id"].as_str()?.parse().ok()?))))
                    .collect();
                items.sort_by_key(|(rank, _)| *rank);
                items.into_iter().map(|(_, id)| id).collect()
            }
            _ => Vec::new(),
        }
    }

    pub(super) fn want_top_emoji(&mut self, guild: Id) {
        if !self.demo {
            self.api_get_once(&format!("top-emojis:{guild}"), format!("/guilds/{guild}/top-emojis"));
        }
    }

    /// The Unicode emoji you use most, for the quick reactions on a
    /// message: Discord's reaction ranking once it has arrived, else the
    /// local list.
    pub fn quick_reactions(&self, n: usize) -> Vec<String> {
        if let Some(f) = &self.compose.frecency {
            let list: Vec<String> = f.frequent_reactions(now_ms()).iter().filter_map(|k| unicode_from_key(k)).take(n).collect();
            if list.len() >= n {
                return list;
            }
        }
        self.frequent.iter().take(n).cloned().collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn unicode_keys_are_discords_names() {
        assert_eq!(unicode_key("👍").as_deref(), Some("thumbsup"));
        assert_eq!(unicode_key("💯").as_deref(), Some("100"));
        assert_eq!(unicode_key("🙏🏻").as_deref(), Some("pray_tone1"));
        // (Compared without variation selectors, which look the same.)
        let back = |k: &str| unicode_from_key(k).map(|e| e.replace('\u{FE0F}', ""));
        assert_eq!(back("pray_tone1").as_deref(), Some("🙏🏻"));
        assert_eq!(back("thumbsup").as_deref(), Some("👍"));
        assert_eq!(unicode_from_key("no_such_emoji_name"), None);
    }

    #[test]
    fn finds_every_emoji_in_a_message() {
        let keys = keys_in_text("hi 👍 <:pepe:123456789012345678> and <a:dance:987654321098765432> 👍 💯 <@1234>");
        assert_eq!(keys, vec!["thumbsup", "123456789012345678", "987654321098765432", "100"]);
    }
}