Skip to content

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

66.9 KB
Raw Blame
//! Discord's `settings-proto/1` (PreloadedUserSettings protobuf): server
//! folders and the account's status / custom status.
//!
//! The wire helpers and decoding logic are adapted from Serein
//! (crates/discord-protocol/src/guild_folders.rs and activity_sharing.rs),
//! Copyright (c) Serein contributors, MIT OR Apache-2.0.
//! Schema: discord-userdoccers/discord-protos, PreloadedUserSettings.proto.

use crate::model::Id;
use base64::engine::general_purpose::STANDARD;
use base64::Engine;

#[derive(Debug)]
pub struct DecodeError;

impl std::fmt::Display for DecodeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("couldn't decode Discord settings")
    }
}
impl std::error::Error for DecodeError {}

const MAX_STATUS_BYTES: usize = 64 * 1024;

#[derive(Clone, Debug, Default, PartialEq)]
pub struct Folder {
    /// `None` for a standalone server (not really a folder).
    pub id: Option<u64>,
    pub name: Option<String>,
    pub color: Option<u32>,
    pub guild_ids: Vec<Id>,
}

#[derive(Clone, Debug, Default, PartialEq)]
pub struct CustomStatus {
    pub text: String,
    pub emoji_id: Option<Id>,
    pub emoji_name: Option<String>,
    pub expires_at_ms: Option<u64>,
}

/// One entry of the account's favourites (field 15): a pinned DM / group DM,
/// a favourited server channel, or a category made inside Favourites.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Favorite {
    /// The channel ID, or the category's own ID.
    pub id: Id,
    pub nickname: Option<String>,
    /// A category created in the Favourites server (not a real channel).
    pub category: bool,
    pub position: u32,
    /// Favourites category this channel sits in.
    pub parent_id: Option<Id>,
    pub collapsed: bool,
}

#[derive(Clone, Debug, Default, PartialEq)]
pub struct Favorites {
    pub channels: Vec<Favorite>,
    pub muted: bool,
    /// Whether the Favourites server shows in the server list (None = default).
    pub guild_visible: Option<bool>,
}

#[derive(Clone, Debug, Default)]
pub struct UserSettings {
    /// Data version; PATCHes must send it as `required_data_version`.
    pub version: u64,
    pub folders: Vec<Folder>,
    pub favorites: Favorites,
    /// "online" | "idle" | "dnd" | "invisible"
    pub status: String,
    pub custom_status: Option<CustomStatus>,
    /// Raw field-11 body, so patches keep fields RustCord doesn't understand.
    status_wire: Vec<u8>,
    /// Nitro client theme: a custom gradient's colours ("#0016ff", …), in order.
    pub client_theme_colors: Vec<String>,
    /// Its angle (CSS degrees) and base mix (0–100), when set.
    pub client_theme_angle: Option<f32>,
    pub client_theme_base_mix: Option<f32>,
    /// One of Discord's gradient presets instead (its id), if picked.
    pub client_theme_preset: Option<u32>,
    /// Localization → language ("en-GB"), if set.
    pub locale: Option<String>,
    /// Every section as it came, for reading and changing single settings.
    pub raw: RawSettings,
}

impl UserSettings {
    /// For tests / demo data (no raw status bytes to preserve). The server list is
    /// stored raw as well, so it can be rearranged.
    pub fn new(folders: Vec<Folder>, status: &str, custom_status: Option<CustomStatus>) -> Self {
        let mut wire = Vec::new();
        message(14, &folders.iter().flat_map(encode_folder).collect::<Vec<u8>>(), &mut wire);
        let raw = RawSettings::from_wire(&wire).unwrap_or_default();
        Self { version: 0, folders, favorites: Favorites::default(), status: status.to_string(), custom_status, status_wire: Vec::new(), raw, ..Default::default() }
    }
}

// ---- wire helpers -----------------------------------------------------------

struct Field<'a> {
    number: u64,
    wire_type: u8,
    value: &'a [u8],
    raw: &'a [u8],
}

impl<'a> Field<'a> {
    fn message(&self) -> Result<&'a [u8], DecodeError> {
        if self.wire_type == 2 { Ok(self.value) } else { Err(DecodeError) }
    }
    fn integer(&self) -> Result<u64, DecodeError> {
        if self.wire_type != 0 {
            return Err(DecodeError);
        }
        let mut value = self.value;
        varint(&mut value)
    }
    fn fixed64(&self) -> Result<u64, DecodeError> {
        if self.wire_type == 1 && self.value.len() == 8 {
            Ok(u64::from_le_bytes(self.value.try_into().map_err(|_| DecodeError)?))
        } else {
            Err(DecodeError)
        }
    }
}

fn varint(input: &mut &[u8]) -> Result<u64, DecodeError> {
    let mut value = 0;
    for shift in (0..70).step_by(7) {
        let (&byte, rest) = input.split_first().ok_or(DecodeError)?;
        *input = rest;
        if shift == 63 && byte > 1 {
            return Err(DecodeError);
        }
        value |= u64::from(byte & 0x7f) << shift;
        if byte < 128 {
            return Ok(value);
        }
    }
    Err(DecodeError)
}

fn fields(mut bytes: &[u8]) -> Result<Vec<Field<'_>>, DecodeError> {
    let mut result = Vec::new();
    while !bytes.is_empty() {
        if result.len() >= 8192 {
            return Err(DecodeError);
        }
        let start = bytes;
        let tag = varint(&mut bytes)?;
        let number = tag >> 3;
        if number == 0 || number > 0x1fff_ffff {
            return Err(DecodeError);
        }
        let wire_type = (tag & 7) as u8;
        let value = match wire_type {
            0 => {
                let before = bytes;
                varint(&mut bytes)?;
                &before[..before.len() - bytes.len()]
            }
            1 | 2 | 5 => {
                let length = match wire_type {
                    1 => 8,
                    5 => 4,
                    _ => usize::try_from(varint(&mut bytes)?).map_err(|_| DecodeError)?,
                };
                let value = bytes.get(..length).ok_or(DecodeError)?;
                bytes = &bytes[length..];
                value
            }
            _ => return Err(DecodeError),
        };
        result.push(Field { number, wire_type, value, raw: &start[..start.len() - bytes.len()] });
    }
    Ok(result)
}

fn write_varint(mut value: u64, output: &mut Vec<u8>) {
    while value >= 128 {
        output.push(value as u8 | 0x80);
        value >>= 7;
    }
    output.push(value as u8);
}

fn message(number: u64, value: &[u8], output: &mut Vec<u8>) {
    write_varint(number << 3 | 2, output);
    write_varint(value.len() as u64, output);
    output.extend_from_slice(value);
}

fn fixed64_field(number: u64, value: u64, output: &mut Vec<u8>) {
    write_varint(number << 3 | 1, output);
    output.extend_from_slice(&value.to_le_bytes());
}

fn string_field(number: u64, text: &str, output: &mut Vec<u8>) {
    let mut wrapper = Vec::new();
    message(1, text.as_bytes(), &mut wrapper);
    message(number, &wrapper, output);
}

fn wrapper_integer(bytes: &[u8]) -> Result<u64, DecodeError> {
    let mut number = 0;
    for f in fields(bytes)? {
        if f.number == 1 {
            number = f.integer()?;
        }
    }
    Ok(number)
}

fn string_value(bytes: &[u8]) -> Result<String, DecodeError> {
    let mut text = String::new();
    for f in fields(bytes)? {
        if f.number == 1 {
            text = String::from_utf8_lossy(f.message()?).into_owned();
        }
    }
    Ok(text)
}

// ---- decode -----------------------------------------------------------------

/// A server-list entry (field 1 of the list) for `f`, as [`decode_folder`] reads it.
fn encode_folder(f: &Folder) -> Vec<u8> {
    let wrapped = |n: u64| {
        let mut w = vec![1 << 3];
        write_varint(n, &mut w);
        w
    };
    let mut body = Vec::new();
    message(1, &f.guild_ids.iter().flat_map(|g| g.0.to_le_bytes()).collect::<Vec<u8>>(), &mut body);
    if let Some(id) = f.id {
        message(2, &wrapped(id), &mut body);
    }
    if let Some(name) = &f.name {
        string_field(3, name, &mut body);
    }
    if let Some(color) = f.color {
        message(4, &wrapped(u64::from(color)), &mut body);
    }
    let mut out = Vec::new();
    message(1, &body, &mut out);
    out
}

fn decode_folder(bytes: &[u8]) -> Result<Folder, DecodeError> {
    let mut folder = Folder::default();
    for f in fields(bytes)? {
        match f.number {
            1 => {
                let packed = if f.wire_type == 1 { f.value } else { f.message()? };
                if packed.len() % 8 != 0 {
                    return Err(DecodeError);
                }
                for id in packed.chunks_exact(8) {
                    folder.guild_ids.push(Id(u64::from_le_bytes(id.try_into().map_err(|_| DecodeError)?)));
                }
            }
            2 => folder.id = Some(wrapper_integer(f.message()?)?).filter(|id| *id != 0),
            3 => {
                let name: String = string_value(f.message()?)?
                    .chars()
                    .map(|c| if c.is_control() { ' ' } else { c })
                    .take(100)
                    .collect();
                folder.name = Some(name).filter(|n| !n.trim().is_empty());
            }
            4 => folder.color = u32::try_from(wrapper_integer(f.message()?)?).ok().filter(|c| *c <= 0xff_ffff),
            _ => {}
        }
    }
    Ok(folder)
}

fn decode_custom_status(bytes: &[u8]) -> Result<CustomStatus, DecodeError> {
    let mut cs = CustomStatus::default();
    for f in fields(bytes)? {
        match f.number {
            1 => cs.text = String::from_utf8_lossy(f.message()?).into_owned(),
            2 => cs.emoji_id = Some(Id(f.fixed64()?)).filter(|id| id.0 != 0),
            3 => cs.emoji_name = Some(String::from_utf8_lossy(f.message()?).into_owned()).filter(|s| !s.is_empty()),
            4 => cs.expires_at_ms = Some(f.fixed64()?).filter(|v| *v != 0),
            _ => {}
        }
    }
    Ok(cs)
}

fn decode_favorite(id: Id, bytes: &[u8]) -> Result<Favorite, DecodeError> {
    let mut fav = Favorite { id, ..Default::default() };
    for f in fields(bytes)? {
        match f.number {
            1 => fav.nickname = Some(String::from_utf8_lossy(f.message()?).into_owned()).filter(|s| !s.trim().is_empty()),
            2 => fav.category = f.integer()? == 2,
            3 => fav.position = f.integer()? as u32,
            4 => fav.parent_id = Some(Id(f.fixed64()?)).filter(|p| p.0 != 0),
            6 => fav.collapsed = f.integer()? != 0,
            _ => {}
        }
    }
    Ok(fav)
}

fn decode_favorites(bytes: &[u8]) -> Result<Favorites, DecodeError> {
    let mut out = Favorites::default();
    for f in fields(bytes)? {
        match f.number {
            // map<fixed64, FavoriteChannel>: entries of {1: key, 2: value}.
            1 => {
                let (mut key, mut value) = (None, None);
                for e in fields(f.message()?)? {
                    match e.number {
                        1 => key = Some(Id(e.fixed64()?)),
                        2 => value = Some(e.message()?),
                        _ => {}
                    }
                }
                if let (Some(id), Some(v)) = (key.filter(|k| k.0 != 0), value) {
                    out.channels.push(decode_favorite(id, v)?);
                }
            }
            2 => out.muted = f.integer()? != 0,
            3 => out.guild_visible = Some(wrapper_integer(f.message()?)? != 0),
            _ => {}
        }
    }
    out.channels.sort_by_key(|c| (c.position, c.id));
    Ok(out)
}

/// Decode the `settings` base64 string from `GET /users/@me/settings-proto/1`.
pub fn decode(settings_b64: &str) -> Result<UserSettings, DecodeError> {
    let wire = STANDARD.decode(settings_b64).map_err(|_| DecodeError)?;
    decode_wire(&wire)
}

/// [`decode`] from the protobuf bytes themselves.
pub fn decode_wire(wire: &[u8]) -> Result<UserSettings, DecodeError> {
    let mut out = UserSettings { status: "online".into(), raw: RawSettings::from_wire(wire)?, ..Default::default() };
    for f in fields(wire)? {
        match f.number {
            1 => {
                for v in fields(f.message()?)? {
                    if v.number == 3 {
                        out.version = v.integer()?;
                    }
                }
            }
            11 => {
                let body = f.message()?;
                if body.len() > MAX_STATUS_BYTES {
                    return Err(DecodeError);
                }
                out.status_wire = body.to_vec();
                for s in fields(body)? {
                    match s.number {
                        1 => {
                            let st = string_value(s.message()?)?;
                            if !st.is_empty() {
                                out.status = st;
                            }
                        }
                        2 => {
                            let cs = decode_custom_status(s.message()?)?;
                            let expired = cs.expires_at_ms.is_some_and(|e| e < now_ms());
                            if (!cs.text.is_empty() || cs.emoji_name.is_some()) && !expired {
                                out.custom_status = Some(cs);
                            }
                        }
                        _ => {}
                    }
                }
            }
            14 => {
                let mut seen = std::collections::HashSet::new();
                for entry in fields(f.message()?)? {
                    if entry.number == 1 {
                        let mut folder = decode_folder(entry.message()?)?;
                        folder.guild_ids.retain(|id| id.0 != 0 && seen.insert(*id));
                        // An ID-less "folder" with several servers is really loose servers.
                        if folder.id.is_none() && folder.guild_ids.len() > 1 {
                            for id in folder.guild_ids {
                                out.folders.push(Folder { guild_ids: vec![id], ..Default::default() });
                            }
                        } else if !folder.guild_ids.is_empty() {
                            out.folders.push(folder);
                        }
                    }
                }
            }
            15 => out.favorites = decode_favorites(f.message()?)?,
            // Localization: 1 = locale (StringValue).
            12 => {
                for l in fields(f.message()?)? {
                    if l.number == 1 {
                        let v = string_value(l.message()?)?;
                        if !v.is_empty() {
                            out.locale = Some(v);
                        }
                    }
                }
            }
            // Appearance → client theme: a gradient preset (2, UInt32Value) or
            // custom colours / angle / base mix (4).
            13 => {
                for a in fields(f.message()?)? {
                    if a.number != 3 {
                        continue;
                    }
                    for c in fields(a.message()?)? {
                        match c.number {
                            2 => out.client_theme_preset = Some(wrapper_integer(c.message()?)? as u32),
                            4 => {
                                for k in fields(c.message()?)? {
                                    match (k.number, k.wire_type) {
                                        (1, 2) => {
                                            let hex = String::from_utf8_lossy(k.message()?).into_owned();
                                            if hex.starts_with('#') && hex.len() == 7 {
                                                out.client_theme_colors.push(hex);
                                            }
                                        }
                                        // int32: negative angles come as 64-bit two's complement.
                                        (3, 0) => out.client_theme_angle = Some(k.integer()? as i64 as i32 as f32),
                                        (4, 0) => out.client_theme_base_mix = Some(k.integer()? as f32),
                                        _ => {}
                                    }
                                }
                            }
                            _ => {}
                        }
                    }
                }
            }
            _ => {}
        }
    }
    Ok(out)
}

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

/// Patch that replaces status and custom status, keeping other field-11
/// subfields (game sharing etc). Send with `required_data_version`.
pub fn encode_status_patch(current: &UserSettings, status: &str, custom: Option<&CustomStatus>) -> Result<String, DecodeError> {
    let mut body = Vec::new();
    for f in fields(&current.status_wire)? {
        // 1 = status, 2 = custom status, 4 = status expiry: rewritten below.
        if !matches!(f.number, 1 | 2 | 4) {
            body.extend_from_slice(f.raw);
        }
    }
    string_field(1, status, &mut body);
    if let Some(cs) = custom.filter(|c| !c.text.is_empty() || c.emoji_name.is_some()) {
        let mut inner = Vec::new();
        if !cs.text.is_empty() {
            message(1, cs.text.as_bytes(), &mut inner);
        }
        if let Some(id) = cs.emoji_id {
            fixed64_field(2, id.0, &mut inner);
        }
        if let Some(name) = &cs.emoji_name {
            message(3, name.as_bytes(), &mut inner);
        }
        if let Some(e) = cs.expires_at_ms {
            fixed64_field(4, e, &mut inner);
        }
        message(2, &inner, &mut body);
    }
    if body.len() > MAX_STATUS_BYTES {
        return Err(DecodeError);
    }
    let mut patch = Vec::new();
    message(11, &body, &mut patch);
    Ok(STANDARD.encode(patch))
}

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

    fn settings_with(status: &str, custom: &str, folders: &[(Option<u64>, &str, &[u64])]) -> String {
        let mut wire = Vec::new();
        let mut version = Vec::new();
        version.push(3 << 3);
        write_varint(7, &mut version);
        message(1, &version, &mut wire);
        let mut st = Vec::new();
        string_field(1, status, &mut st);
        let mut cs = Vec::new();
        message(1, custom.as_bytes(), &mut cs);
        message(2, &cs, &mut st);
        message(99, b"keep me", &mut st);
        message(11, &st, &mut wire);
        let mut sub = Vec::new();
        for (id, name, guilds) in folders {
            let mut e = Vec::new();
            let ids: Vec<u8> = guilds.iter().flat_map(|g| g.to_le_bytes()).collect();
            message(1, &ids, &mut e);
            if let Some(id) = id {
                let mut w = vec![8];
                write_varint(*id, &mut w);
                message(2, &w, &mut e);
            }
            if !name.is_empty() {
                string_field(3, name, &mut e);
            }
            message(1, &e, &mut sub);
        }
        message(14, &sub, &mut wire);
        STANDARD.encode(wire)
    }

    #[test]
    fn decodes_status_custom_and_folders() {
        let s = decode(&settings_with("dnd", ".gg/rust", &[(Some(5), "Games", &[1, 2]), (None, "", &[3])])).unwrap();
        assert_eq!(s.version, 7);
        assert_eq!(s.status, "dnd");
        assert_eq!(s.custom_status.unwrap().text, ".gg/rust");
        assert_eq!(s.folders.len(), 2);
        assert_eq!(s.folders[0].name.as_deref(), Some("Games"));
        assert_eq!(s.folders[0].guild_ids, vec![Id(1), Id(2)]);
        assert_eq!(s.folders[1].id, None);
    }

    #[test]
    fn decodes_favorites() {
        let fav = |key: u64, nick: &str, kind: u64, pos: u64, parent: u64| {
            let mut v = Vec::new();
            if !nick.is_empty() {
                message(1, nick.as_bytes(), &mut v);
            }
            v.push(2 << 3);
            write_varint(kind, &mut v);
            v.push(3 << 3);
            write_varint(pos, &mut v);
            if parent != 0 {
                fixed64_field(4, parent, &mut v);
            }
            let mut entry = Vec::new();
            fixed64_field(1, key, &mut entry);
            message(2, &v, &mut entry);
            entry
        };
        let mut favs = Vec::new();
        message(1, &fav(500, "", 1, 2, 0), &mut favs);
        message(1, &fav(600, "Channels", 2, 1, 0), &mut favs);
        message(1, &fav(700, "chat", 1, 0, 600), &mut favs);
        let mut wire = Vec::new();
        message(15, &favs, &mut wire);
        let s = decode(&STANDARD.encode(wire)).unwrap();
        let c = &s.favorites.channels;
        assert_eq!(c.len(), 3);
        assert_eq!(c[0].id, Id(700));
        assert_eq!(c[0].parent_id, Some(Id(600)));
        assert_eq!(c[0].nickname.as_deref(), Some("chat"));
        assert!(c[1].category);
        assert_eq!(c[2].id, Id(500));
    }

    #[test]
    fn status_patch_keeps_unknown_fields() {
        let s = decode(&settings_with("online", "old", &[])).unwrap();
        let cs = CustomStatus { text: "new".into(), ..Default::default() };
        let patch = STANDARD.decode(encode_status_patch(&s, "idle", Some(&cs)).unwrap()).unwrap();
        let top = fields(&patch).unwrap();
        let body = top[0].message().unwrap();
        let sub = fields(body).unwrap();
        assert!(sub.iter().any(|f| f.number == 99));
        let re = decode(&STANDARD.encode(&patch)).unwrap();
        assert_eq!(re.status, "idle");
        assert_eq!(re.custom_status.unwrap().text, "new");
    }
}

// ---- any single setting ---------------------------------------------------------
//
// Field numbers: discord-userdoccers/discord-protos, PreloadedUserSettings.proto.
// A setting is addressed by its path of field numbers, e.g. `[6, 4]` is
// `text_and_images.render_spoilers`. Discord replaces a whole top-level section
// when a patch carries it, so a patch is that section with one field changed
// and every other byte of it copied.

/// A value to store, by how the schema types it.
#[derive(Clone, Debug, PartialEq)]
pub enum Leaf {
    /// A plain `bool` (left out when false).
    Bool(bool),
    /// `google.protobuf.BoolValue`: set or unset is told apart from false.
    BoolValue(bool),
    UInt32Value(u32),
    /// A plain enum or integer (left out when 0).
    Enum(u64),
    StringValue(String),
    /// A plain `float` (left out when 0).
    Float(f32),
}

/// The account's settings, section by section, undecoded.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RawSettings {
    sections: std::collections::BTreeMap<u64, Vec<u8>>,
}

fn leaf_of<'a>(bytes: &'a [u8], path: &[u64]) -> Option<(u8, &'a [u8])> {
    let (first, rest) = path.split_first()?;
    // The last occurrence wins, as in protobuf.
    let f = fields(bytes).ok()?.into_iter().rev().find(|f| f.number == *first)?;
    if rest.is_empty() {
        Some((f.wire_type, f.value))
    } else {
        leaf_of(f.message().ok()?, rest)
    }
}

fn replaced(bytes: &[u8], path: &[u64], leaf: &Leaf) -> Result<Vec<u8>, DecodeError> {
    let (first, rest) = path.split_first().ok_or(DecodeError)?;
    let mut out = Vec::with_capacity(bytes.len() + 8);
    let mut old: &[u8] = &[];
    for f in fields(bytes)? {
        if f.number == *first {
            if !rest.is_empty() {
                old = f.message()?;
            }
        } else {
            out.extend_from_slice(f.raw);
        }
    }
    if !rest.is_empty() {
        message(*first, &replaced(old, rest, leaf)?, &mut out);
        return Ok(out);
    }
    let varint_field = |v: u64, out: &mut Vec<u8>| {
        write_varint(*first << 3, out);
        write_varint(v, out);
    };
    let wrapped = |v: u64, out: &mut Vec<u8>| {
        let mut w = Vec::new();
        if v != 0 {
            w.push(1 << 3);
            write_varint(v, &mut w);
        }
        message(*first, &w, out);
    };
    match leaf {
        Leaf::Bool(false) | Leaf::Enum(0) => {}
        Leaf::Bool(true) => varint_field(1, &mut out),
        Leaf::Enum(v) => varint_field(*v, &mut out),
        Leaf::BoolValue(v) => wrapped(u64::from(*v), &mut out),
        Leaf::UInt32Value(v) => wrapped(u64::from(*v), &mut out),
        Leaf::StringValue(s) => {
            let mut w = Vec::new();
            if !s.is_empty() {
                message(1, s.as_bytes(), &mut w);
            }
            message(*first, &w, &mut out);
        }
        Leaf::Float(v) => {
            if *v != 0.0 {
                write_varint(*first << 3 | 5, &mut out);
                out.extend_from_slice(&v.to_le_bytes());
            }
        }
    }
    Ok(out)
}

impl RawSettings {
    pub fn from_wire(wire: &[u8]) -> Result<Self, DecodeError> {
        let mut sections = std::collections::BTreeMap::new();
        for f in fields(wire)? {
            if f.wire_type == 2 {
                sections.insert(f.number, f.value.to_vec());
            }
        }
        Ok(Self { sections })
    }

    pub fn from_base64(settings_b64: &str) -> Result<Self, DecodeError> {
        Self::from_wire(&STANDARD.decode(settings_b64).map_err(|_| DecodeError)?)
    }

    pub fn is_empty(&self) -> bool {
        self.sections.is_empty()
    }

    /// Take the sections `newer` carries (a partial update from the gateway).
    pub fn merge(&mut self, newer: &RawSettings) {
        for (n, body) in &newer.sections {
            self.sections.insert(*n, body.clone());
        }
    }

    /// All of it as protobuf bytes again.
    pub fn to_wire(&self) -> Vec<u8> {
        let mut out = Vec::new();
        for (n, body) in &self.sections {
            message(*n, body, &mut out);
        }
        out
    }

    fn leaf(&self, path: &[u64]) -> Option<(u8, &[u8])> {
        let (section, rest) = path.split_first()?;
        leaf_of(self.sections.get(section)?, rest)
    }

    /// An integer, enum or bool setting (plain or wrapped); `None` when unset.
    pub fn uint(&self, path: &[u64]) -> Option<u64> {
        match self.leaf(path)? {
            (0, mut v) => varint(&mut v).ok(),
            (2, v) => wrapper_integer(v).ok(),
            _ => None,
        }
    }

    pub fn bool(&self, path: &[u64]) -> Option<bool> {
        self.uint(path).map(|v| v != 0)
    }

    pub fn string(&self, path: &[u64]) -> Option<String> {
        match self.leaf(path)? {
            (2, v) => string_value(v).ok(),
            _ => None,
        }
    }

    pub fn float(&self, path: &[u64]) -> Option<f32> {
        match self.leaf(path)? {
            (5, v) => Some(f32::from_le_bytes(v.try_into().ok()?)),
            _ => None,
        }
    }

    /// Change one setting here and return the patch for
    /// `PATCH /users/@me/settings-proto/1` (`{"settings": …}`).
    pub fn set(&mut self, path: &[u64], leaf: Leaf) -> Result<String, DecodeError> {
        let (section, rest) = path.split_first().ok_or(DecodeError)?;
        if rest.is_empty() {
            return Err(DecodeError);
        }
        let body = replaced(self.sections.get(section).map_or(&[][..], Vec::as_slice), rest, &leaf)?;
        let mut patch = Vec::new();
        message(*section, &body, &mut patch);
        self.sections.insert(*section, body);
        Ok(STANDARD.encode(patch))
    }

    /// Move a server in the server list: the context menu's "Move to…" (first, last, into a
    /// folder) and dragging it on the rail (next to a server, inside that server's folder if
    /// it is in one, or next to a folder). `guild` is taken out of wherever it is; a server
    /// not in the stored list yet (newly joined, shown on top) is simply placed. Every other
    /// byte of the server list (field 14) is kept. Returns the patch for
    /// `PATCH /users/@me/settings-proto/1`, or `None` when nothing changes.
    pub fn move_guild(&mut self, guild: Id, to: GuildMove) -> Result<Option<String>, DecodeError> {
        if matches!(to, GuildMove::Before(target) | GuildMove::After(target) if target == guild) {
            return Ok(None);
        }
        let (list, rest) = server_list(self.sections.get(&14).map_or(&[][..], Vec::as_slice))?;
        let mut entries: Vec<ListEntry> = Vec::new();
        for (folder, raw) in list {
            if !folder.guild_ids.contains(&guild) {
                entries.push((folder, raw));
                continue;
            }
            let ids: Vec<Id> = folder.guild_ids.iter().copied().filter(|g| *g != guild).collect();
            if ids.is_empty() {
                // A loose server, or a folder holding only this server, goes with it.
                continue;
            }
            let raw = with_guilds(&raw, &ids)?;
            entries.push((Folder { guild_ids: ids, ..folder }, raw));
        }
        let loose = || {
            let mut body = Vec::new();
            message(1, &guild.0.to_le_bytes(), &mut body);
            let mut raw = Vec::new();
            message(1, &body, &mut raw);
            (Folder { id: None, name: None, color: None, guild_ids: vec![guild] }, raw)
        };
        let folder_at = |entries: &[ListEntry], id: u64| entries.iter().position(|(f, _)| f.id == Some(id));
        match to {
            GuildMove::First => entries.insert(0, loose()),
            GuildMove::Last => entries.push(loose()),
            GuildMove::Folder(id) => {
                let Some(at) = folder_at(&entries, id) else { return Ok(None) };
                let mut ids = entries[at].0.guild_ids.clone();
                ids.push(guild);
                entries[at].1 = with_guilds(&entries[at].1, &ids)?;
                entries[at].0.guild_ids = ids;
            }
            GuildMove::BeforeFolder(id) | GuildMove::AfterFolder(id) => {
                let Some(at) = folder_at(&entries, id) else { return Ok(None) };
                let at = if matches!(to, GuildMove::AfterFolder(_)) { at + 1 } else { at };
                entries.insert(at, loose());
            }
            GuildMove::Before(target) | GuildMove::After(target) => {
                let after = usize::from(matches!(to, GuildMove::After(_)));
                match entries.iter().position(|(f, _)| f.guild_ids.contains(&target)) {
                    Some(at) if entries[at].0.id.is_some() => {
                        let mut ids = entries[at].0.guild_ids.clone();
                        let index = ids.iter().position(|g| *g == target).unwrap_or(0) + after;
                        ids.insert(index, guild);
                        entries[at].1 = with_guilds(&entries[at].1, &ids)?;
                        entries[at].0.guild_ids = ids;
                    }
                    Some(at) => entries.insert(at + after, loose()),
                    // The target is a newly joined server, shown above the stored list.
                    None => entries.insert(0, loose()),
                }
            }
        }
        Ok(self.store_server_list(entries, &rest))
    }

    /// Move a folder in the server list (dragged on the rail): next to a loose server or
    /// next to another folder (`Before` / `After` a server in a folder means next to that
    /// folder), first or last. Folders don't nest, so `GuildMove::Folder` changes nothing.
    /// Every other byte of the server list is kept. Returns the patch for
    /// `PATCH /users/@me/settings-proto/1`, or `None` when nothing changes.
    pub fn move_folder(&mut self, folder: u64, to: GuildMove) -> Result<Option<String>, DecodeError> {
        let (mut entries, rest) = server_list(self.sections.get(&14).map_or(&[][..], Vec::as_slice))?;
        let Some(from) = entries.iter().position(|(f, _)| f.id == Some(folder)) else { return Ok(None) };
        let moved = entries.remove(from);
        let after = usize::from(matches!(to, GuildMove::After(_) | GuildMove::AfterFolder(_)));
        let at = match to {
            GuildMove::First => Some(0),
            GuildMove::Last => Some(entries.len()),
            GuildMove::Folder(_) => None,
            GuildMove::BeforeFolder(id) | GuildMove::AfterFolder(id) => entries.iter().position(|(f, _)| f.id == Some(id)).map(|at| at + after),
            GuildMove::Before(g) | GuildMove::After(g) => match entries.iter().position(|(f, _)| f.guild_ids.contains(&g)) {
                Some(at) => Some(at + after),
                // A newly joined server, shown above the stored list.
                None if moved.0.guild_ids.contains(&g) => None,
                None => Some(0),
            },
        };
        let Some(at) = at else { return Ok(None) };
        entries.insert(at, moved);
        Ok(self.store_server_list(entries, &rest))
    }

    /// Put the server list back together from its entries (and the bytes that aren't
    /// entries); the patch when it changed.
    fn store_server_list(&mut self, entries: Vec<ListEntry>, rest: &[u8]) -> Option<String> {
        let mut body: Vec<u8> = entries.into_iter().flat_map(|(_, raw)| raw).collect();
        body.extend_from_slice(rest);
        if self.sections.get(&14).map_or(&[][..], Vec::as_slice) == body.as_slice() {
            return None;
        }
        let mut patch = Vec::new();
        message(14, &body, &mut patch);
        self.sections.insert(14, body);
        Some(STANDARD.encode(patch))
    }

    /// The server list (folders and loose servers) as stored now.
    pub fn folders(&self) -> Vec<Folder> {
        let mut wire = Vec::new();
        if let Some(body) = self.sections.get(&14) {
            message(14, body, &mut wire);
        }
        decode_wire(&wire).map(|s| s.folders).unwrap_or_default()
    }
}

/// Where [`RawSettings::move_guild`] puts a server.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GuildMove {
    First,
    Last,
    /// Into the folder with this id (at its end).
    Folder(u64),
    /// As a loose server just above / below the folder with this id.
    BeforeFolder(u64),
    AfterFolder(u64),
    /// Just above / below this server, inside its folder if it is in one.
    Before(Id),
    After(Id),
}

/// A server-list entry: a folder (or loose server), decoded, and its raw bytes.
type ListEntry = (Folder, Vec<u8>);

/// The server list's entries and the list's other bytes.
fn server_list(body: &[u8]) -> Result<(Vec<ListEntry>, Vec<u8>), DecodeError> {
    let mut entries = Vec::new();
    let mut rest = Vec::new();
    for f in fields(body)? {
        if f.number == 1 {
            entries.push((decode_folder(f.message()?)?, f.raw.to_vec()));
        } else {
            rest.extend_from_slice(f.raw);
        }
    }
    Ok((entries, rest))
}

/// One server-list entry (`raw`: field 1 of the list, a folder) with its servers replaced
/// by `ids`, keeping the folder's other fields (id, name, colour).
fn with_guilds(raw: &[u8], ids: &[Id]) -> Result<Vec<u8>, DecodeError> {
    let entry = fields(raw)?.into_iter().next().ok_or(DecodeError)?;
    let mut body = Vec::new();
    let packed: Vec<u8> = ids.iter().flat_map(|g| g.0.to_le_bytes()).collect();
    message(1, &packed, &mut body);
    for sub in fields(entry.message()?)? {
        if sub.number != 1 {
            body.extend_from_slice(sub.raw);
        }
    }
    let mut out = Vec::new();
    message(1, &body, &mut out);
    Ok(out)
}

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

    fn folder(ids: &[u64], id: Option<u64>, name: Option<&str>) -> Vec<u8> {
        let mut body = Vec::new();
        let packed: Vec<u8> = ids.iter().flat_map(|g| g.to_le_bytes()).collect();
        message(1, &packed, &mut body);
        if let Some(id) = id {
            let mut w = Vec::new();
            w.push(1 << 3);
            write_varint(id, &mut w);
            message(2, &w, &mut body);
        }
        if let Some(n) = name {
            string_field(3, n, &mut body);
        }
        let mut out = Vec::new();
        message(1, &body, &mut out);
        out
    }

    fn settings(entries: &[Vec<u8>]) -> RawSettings {
        let body: Vec<u8> = entries.concat();
        let mut wire = Vec::new();
        message(14, &body, &mut wire);
        // Another section that must not change.
        string_field(11, "x", &mut wire);
        RawSettings::from_wire(&wire).unwrap()
    }

    fn ids(s: &RawSettings) -> Vec<(Option<u64>, Vec<u64>)> {
        s.folders().into_iter().map(|f| (f.id, f.guild_ids.into_iter().map(|g| g.0).collect())).collect()
    }

    #[test]
    fn moves_loose_server_first_and_last() {
        let mut s = settings(&[folder(&[1], None, None), folder(&[2], None, None), folder(&[3, 4], Some(9), Some("F"))]);
        let section11 = s.sections.get(&11).cloned();
        assert!(s.move_guild(Id(2), GuildMove::First).unwrap().is_some());
        assert_eq!(ids(&s), vec![(None, vec![2]), (None, vec![1]), (Some(9), vec![3, 4])]);
        s.move_guild(Id(2), GuildMove::Last).unwrap();
        assert_eq!(ids(&s), vec![(None, vec![1]), (Some(9), vec![3, 4]), (None, vec![2])]);
        assert_eq!(s.sections.get(&11).cloned(), section11);
    }

    #[test]
    fn takes_server_out_of_folder_keeping_its_name() {
        let mut s = settings(&[folder(&[1], None, None), folder(&[3, 4], Some(9), Some("Games"))]);
        s.move_guild(Id(3), GuildMove::First).unwrap();
        assert_eq!(ids(&s), vec![(None, vec![3]), (None, vec![1]), (Some(9), vec![4])]);
        assert_eq!(s.folders()[2].name.as_deref(), Some("Games"));
    }

    #[test]
    fn moves_into_folder_and_places_new_servers() {
        let mut s = settings(&[folder(&[1], None, None), folder(&[3], Some(9), Some("Games"))]);
        s.move_guild(Id(1), GuildMove::Folder(9)).unwrap();
        assert_eq!(ids(&s), vec![(Some(9), vec![3, 1])]);
        assert!(s.move_guild(Id(1), GuildMove::Folder(9)).unwrap().is_none(), "already its last server");
        // A newly joined server is not stored yet: moving it adds it.
        s.move_guild(Id(77), GuildMove::Last).unwrap();
        assert_eq!(ids(&s), vec![(Some(9), vec![3, 1]), (None, vec![77])]);
    }

    #[test]
    fn drags_next_to_servers_and_folders() {
        let mut s = settings(&[folder(&[1], None, None), folder(&[2], None, None), folder(&[3, 4], Some(9), Some("F"))]);
        let section11 = s.sections.get(&11).cloned();
        s.move_guild(Id(1), GuildMove::After(Id(2))).unwrap();
        assert_eq!(ids(&s), vec![(None, vec![2]), (None, vec![1]), (Some(9), vec![3, 4])]);
        // Next to a server in a folder: into that folder, at that place.
        s.move_guild(Id(2), GuildMove::Before(Id(4))).unwrap();
        assert_eq!(ids(&s), vec![(None, vec![1]), (Some(9), vec![3, 2, 4])]);
        assert_eq!(s.folders()[1].name.as_deref(), Some("F"));
        // Out of the folder, below it.
        s.move_guild(Id(3), GuildMove::AfterFolder(9)).unwrap();
        assert_eq!(ids(&s), vec![(None, vec![1]), (Some(9), vec![2, 4]), (None, vec![3])]);
        s.move_guild(Id(3), GuildMove::BeforeFolder(9)).unwrap();
        assert_eq!(ids(&s), vec![(None, vec![1]), (None, vec![3]), (Some(9), vec![2, 4])]);
        // No change: no patch.
        assert!(s.move_guild(Id(3), GuildMove::After(Id(1))).unwrap().is_none());
        assert!(s.move_guild(Id(3), GuildMove::Before(Id(3))).unwrap().is_none());
        // The last server out of a folder takes the folder with it.
        s.move_guild(Id(2), GuildMove::First).unwrap();
        s.move_guild(Id(4), GuildMove::First).unwrap();
        assert_eq!(ids(&s), vec![(None, vec![4]), (None, vec![2]), (None, vec![1]), (None, vec![3])]);
        assert_eq!(s.sections.get(&11).cloned(), section11);
    }

    #[test]
    fn demo_server_list_round_trips() {
        let f = Folder { id: Some(1), name: Some("Rust Stuff".into()), color: Some(0xE8590C), guild_ids: vec![Id(5), Id(6)] };
        let loose = Folder { guild_ids: vec![Id(7)], ..Default::default() };
        let s = UserSettings::new(vec![loose.clone(), f.clone()], "online", None);
        assert_eq!(s.raw.folders(), vec![loose, f]);
    }

    #[test]
    fn drags_folders() {
        let mut s = settings(&[folder(&[1], None, None), folder(&[3, 4], Some(9), Some("F")), folder(&[5], Some(8), Some("G")), folder(&[2], None, None)]);
        let section11 = s.sections.get(&11).cloned();
        s.move_folder(9, GuildMove::After(Id(2))).unwrap();
        assert_eq!(ids(&s), vec![(None, vec![1]), (Some(8), vec![5]), (None, vec![2]), (Some(9), vec![3, 4])]);
        assert_eq!(s.folders()[3].name.as_deref(), Some("F"));
        s.move_folder(9, GuildMove::BeforeFolder(8)).unwrap();
        assert_eq!(ids(&s), vec![(None, vec![1]), (Some(9), vec![3, 4]), (Some(8), vec![5]), (None, vec![2])]);
        // Next to a server in another folder: next to that folder.
        s.move_folder(8, GuildMove::Before(Id(4))).unwrap();
        assert_eq!(ids(&s), vec![(None, vec![1]), (Some(8), vec![5]), (Some(9), vec![3, 4]), (None, vec![2])]);
        s.move_folder(9, GuildMove::First).unwrap();
        assert_eq!(ids(&s)[0], (Some(9), vec![3, 4]));
        // No change, a folder into a folder, onto itself, or an unknown folder: no patch.
        assert!(s.move_folder(9, GuildMove::Before(Id(1))).unwrap().is_none());
        assert!(s.move_folder(9, GuildMove::Folder(8)).unwrap().is_none());
        assert!(s.move_folder(9, GuildMove::After(Id(3))).unwrap().is_none());
        assert!(s.move_folder(7, GuildMove::Last).unwrap().is_none());
        assert_eq!(s.sections.get(&11).cloned(), section11);
    }
}

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

    #[test]
    fn set_keeps_the_rest_of_the_section() {
        let mut text = Vec::new();
        string_field(4, "ON_CLICK", &mut text);
        message(99, b"keep me", &mut text);
        let mut wire = Vec::new();
        message(6, &text, &mut wire);
        let mut raw = RawSettings::from_wire(&wire).unwrap();
        assert_eq!(raw.string(&[6, 4]).as_deref(), Some("ON_CLICK"));
        assert_eq!(raw.bool(&[6, 28]), None);

        let patch = raw.set(&[6, 4], Leaf::StringValue("ALWAYS".into())).unwrap();
        let sent = RawSettings::from_base64(&patch).unwrap();
        assert_eq!(sent.string(&[6, 4]).as_deref(), Some("ALWAYS"));
        assert!(leaf_of(&sent.sections[&6], &[99]).is_some());

        // A wrapped false is stored (it differs from unset); nested paths work.
        raw.set(&[6, 28], Leaf::BoolValue(false)).unwrap();
        assert_eq!(raw.bool(&[6, 28]), Some(false));
        raw.set(&[6, 29, 2], Leaf::Enum(3)).unwrap();
        raw.set(&[6, 29, 1], Leaf::Enum(2)).unwrap();
        assert_eq!(raw.uint(&[6, 29, 2]), Some(3));
        assert_eq!(raw.uint(&[6, 29, 1]), Some(2));
        assert_eq!(raw.string(&[6, 4]).as_deref(), Some("ALWAYS"));
        raw.set(&[5, 9, 1], Leaf::Float(42.0)).unwrap();
        assert_eq!(raw.float(&[5, 9, 1]), Some(42.0));
        raw.set(&[8, 4], Leaf::Bool(true)).unwrap();
        assert_eq!(raw.bool(&[8, 4]), Some(true));
        raw.set(&[8, 4], Leaf::Bool(false)).unwrap();
        assert_eq!(raw.bool(&[8, 4]), None);
        assert_eq!(RawSettings::from_wire(&raw.to_wire()).unwrap(), raw);
    }
}

// ---- settings-proto/2 (FrecencyUserSettings) ----------------------------------
//
// Schema: discord-userdoccers/discord-protos, FrecencyUserSettings.proto.
// Only what the expression picker needs is decoded: favourite GIFs (field 2)
// and sticker use (field 4). Patches rewrite field 2 alone and copy every
// other byte of it (other favourites, unknown subfields) unchanged.

/// A GIF in the account's favourites (`FavoriteGIFs.gifs` map entry).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct FavoriteGif {
    /// The map key: what gets sent (a Tenor page or attachment link).
    pub url: String,
    /// The media to show: an MP4 when `format` is 2 (video), else an image.
    pub src: String,
    /// 1 image, 2 video.
    pub format: u32,
    pub width: u32,
    pub height: u32,
    /// Higher = favourited later.
    pub order: u32,
}

/// How often one thing was used: Discord's `FrecencyItem` (its total
/// uses and the times of the last ten).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Uses {
    pub total: u64,
    /// Milliseconds since 1970, oldest first.
    pub recent: Vec<u64>,
}

/// How many use times Discord keeps per thing (its `maxSamples`).
pub const MAX_RECENT_USES: usize = 10;
/// How many emoji Discord's Frequently Used holds (`numFrequentlyItems`).
pub const FREQUENT_EMOJI: usize = 42;

impl Uses {
    /// One more use at `at` (Discord's `track`).
    pub fn track(&mut self, at: u64) {
        self.total += 1;
        self.recent.push(at);
        self.recent.sort_unstable();
        let extra = self.recent.len().saturating_sub(MAX_RECENT_USES);
        self.recent.drain(..extra);
    }

    /// Discord's frecency (module 283047, read 2026-12-02): the last uses
    /// weighted by age in whole days (100 up to 3, 70 up to 15, 50 up to
    /// 30, 30 up to 45, 10 up to 80, then 1), and
    /// `ceil(total × weights ÷ uses counted)`.
    pub fn frecency(&self, now: u64) -> f64 {
        match self.weights(now) {
            Some((score, counted)) => (self.total as f64 * score / counted as f64).ceil(),
            None => 0.0,
        }
    }

    /// Discord's ranking for reactions (its emoji store, module 121681):
    /// `trunc(1000 × (0.2 × total ÷ most total + 0.8 × weights ÷ 1000))`,
    /// where `most` is the most any reaction was used.
    pub fn reaction_frecency(&self, now: u64, most: u64) -> f64 {
        match self.weights(now) {
            Some((score, _)) if most > 0 => (1000.0 * (self.total as f64 / most as f64 * 0.2 + score / 1000.0 * 0.8)).trunc(),
            _ => 0.0,
        }
    }

    /// The weights of the last uses added up, and how many were counted.
    fn weights(&self, now: u64) -> Option<(f64, usize)> {
        if self.recent.is_empty() {
            return None;
        }
        let weight = |ts: u64| {
            // Milliseconds (seconds, just in case).
            let ts = if ts < 100_000_000_000 { ts * 1000 } else { ts };
            match now.saturating_sub(ts) / 86_400_000 {
                0..=3 => 100.0,
                4..=15 => 70.0,
                16..=30 => 50.0,
                31..=45 => 30.0,
                46..=80 => 10.0,
                _ => 1.0,
            }
        };
        let counted = &self.recent[self.recent.len().saturating_sub(MAX_RECENT_USES)..];
        Some((counted.iter().map(|&t| weight(t)).sum(), counted.len()))
    }
}

#[derive(Clone, Debug, Default)]
pub struct Frecency {
    /// Data version; PATCHes send it as `required_data_version`.
    pub version: u64,
    /// Favourite GIFs, most recently added first.
    pub favorite_gifs: Vec<FavoriteGif>,
    /// Sticker IDs, most used first (Discord's own frecency ranking).
    pub stickers: Vec<Id>,
    /// Emoji use, by Discord's key: a server emoji's ID, a Unicode emoji's
    /// name ("thumbsup").
    pub emoji: std::collections::BTreeMap<String, Uses>,
    /// Reactions given, by the same keys (Discord counts them apart).
    pub reaction_emoji: std::collections::BTreeMap<String, Uses>,
    /// Favourite emoji, in their order (the same keys).
    pub favorite_emoji: Vec<String>,
    /// Raw field-2 body (`FavoriteGIFs`), so patches keep what RustCord doesn't read.
    gifs_wire: Vec<u8>,
}

impl Frecency {
    pub fn is_favorite_gif(&self, url: &str) -> bool {
        self.favorite_gifs.iter().any(|g| g.url == url)
    }

    /// Frequently Used: the most used emoji keys, best first, as many as
    /// Discord shows.
    pub fn frequent_emoji(&self, now: u64) -> Vec<String> {
        let mut ranked: Vec<(f64, &String)> = self.emoji.iter().map(|(k, u)| (u.frecency(now), k)).filter(|(f, _)| *f > 0.0).collect();
        ranked.sort_by(|a, b| b.0.total_cmp(&a.0).then_with(|| a.1.cmp(b.1)));
        ranked.into_iter().take(FREQUENT_EMOJI).map(|(_, k)| k.clone()).collect()
    }

    /// The reactions you use most, best first (the reaction picker's
    /// Frequently Used and the quick reactions on a message).
    pub fn frequent_reactions(&self, now: u64) -> Vec<String> {
        let most = self.reaction_emoji.values().map(|u| u.total).max().unwrap_or(0);
        let mut ranked: Vec<(f64, &String)> = self.reaction_emoji.iter().map(|(k, u)| (u.reaction_frecency(now, most), k)).filter(|(f, _)| *f > 0.0).collect();
        ranked.sort_by(|a, b| b.0.total_cmp(&a.0).then_with(|| a.1.cmp(b.1)));
        ranked.into_iter().take(FREQUENT_EMOJI).map(|(_, k)| k.clone()).collect()
    }

    /// Apply a favourite change locally (what the patch will make true).
    pub fn set_favorite_gif(&mut self, gif: &FavoriteGif, add: bool) {
        // Keep the wire copy in step, so a second change before Discord
        // answers builds on the first.
        if let Ok(body) = favorite_gifs_body(self, gif, add) {
            self.gifs_wire = body;
        }
        self.favorite_gifs.retain(|g| g.url != gif.url);
        if add {
            let order = self.favorite_gifs.iter().map(|g| g.order).max().unwrap_or(0) + 1;
            self.favorite_gifs.insert(0, FavoriteGif { order, ..gif.clone() });
        }
    }
}

const MAX_FRECENCY_BYTES: usize = 4 * 1024 * 1024;

fn decode_favorite_gif(url: String, bytes: &[u8]) -> Result<FavoriteGif, DecodeError> {
    let mut g = FavoriteGif { url, ..Default::default() };
    for f in fields(bytes)? {
        match f.number {
            1 => g.format = f.integer()? as u32,
            2 => g.src = String::from_utf8_lossy(f.message()?).into_owned(),
            3 => g.width = f.integer()? as u32,
            4 => g.height = f.integer()? as u32,
            5 => g.order = f.integer()? as u32,
            _ => {}
        }
    }
    Ok(g)
}

/// A map entry `{1: key, 2: value}`: (key field, value bytes).
fn map_entry(bytes: &[u8]) -> Result<(Option<Field<'_>>, Option<&[u8]>), DecodeError> {
    let (mut key, mut value) = (None, None);
    for e in fields(bytes)? {
        match e.number {
            1 => key = Some(e),
            2 => value = Some(e.message()?),
            _ => {}
        }
    }
    Ok((key, value))
}

/// A `FrecencyItem`'s uses (Discord's own `frecency` / `score` fields are
/// left out: it works them out again from these, as RustCord does).
fn decode_uses(bytes: &[u8]) -> Result<Uses, DecodeError> {
    let mut uses = Uses::default();
    for f in fields(bytes)? {
        match (f.number, f.wire_type) {
            (1, _) => uses.total = f.integer()?,
            // recent_uses: packed (usually) or one varint per use.
            (2, 2) => {
                let mut packed = f.value;
                while !packed.is_empty() && uses.recent.len() < 64 {
                    uses.recent.push(varint(&mut packed)?);
                }
            }
            (2, 0) => uses.recent.push(f.integer()?),
            _ => {}
        }
    }
    uses.recent.retain(|&t| t > 0);
    uses.recent.sort_unstable();
    Ok(uses)
}

/// A `FrecencyItem` as Discord writes it: total, the recent uses (packed),
/// and its frecency in both the `frecency` and `score` fields.
fn encode_uses(uses: &Uses, now: u64, out: &mut Vec<u8>) {
    let int = |n: u64, v: u64, out: &mut Vec<u8>| {
        if v != 0 {
            write_varint(n << 3, out);
            write_varint(v, out);
        }
    };
    int(1, uses.total, out);
    if !uses.recent.is_empty() {
        let mut packed = Vec::new();
        for &t in &uses.recent {
            write_varint(t, &mut packed);
        }
        message(2, &packed, out);
    }
    let frecency = uses.frecency(now) as i64 as u64;
    int(3, frecency, out);
    int(4, frecency, out);
}

/// Discord's frecency score: uses, weighted by how recent the last ones are.
fn frecency_score(bytes: &[u8], now: u64) -> Result<f64, DecodeError> {
    let (mut total, mut stored, mut recent) = (0u64, 0i64, Vec::new());
    for f in fields(bytes)? {
        match (f.number, f.wire_type) {
            (1, _) => total = f.integer()?,
            // recent_uses: packed (usually) or one varint per use.
            (2, 2) => {
                let mut packed = f.value;
                while !packed.is_empty() && recent.len() < 64 {
                    recent.push(varint(&mut packed)?);
                }
            }
            (2, 0) => recent.push(f.integer()?),
            (3, 0) | (4, 0) => stored = stored.max(f.integer()? as u32 as i32 as i64),
            _ => {}
        }
    }
    if recent.is_empty() {
        return Ok(if stored > 0 { stored as f64 } else { total as f64 });
    }
    let weight = |ts: u64| {
        // Milliseconds (seconds, just in case).
        let ts = if ts < 100_000_000_000 { ts * 1000 } else { ts };
        let days = now.saturating_sub(ts) / 86_400_000;
        match days {
            0..=3 => 100.0,
            4..=15 => 70.0,
            16..=30 => 50.0,
            31..=45 => 30.0,
            46..=80 => 10.0,
            _ => 1.0,
        }
    };
    let avg = recent.iter().map(|&t| weight(t)).sum::<f64>() / recent.len() as f64;
    Ok(total.max(recent.len() as u64) as f64 * avg)
}

/// `StickerFrecency.stickers`: map<fixed64, FrecencyItem>.
fn sticker_frecency(bytes: &[u8], now: u64, out: &mut Vec<(f64, Id)>) -> Result<(), DecodeError> {
    for s in fields(bytes)? {
        if s.number != 1 {
            continue;
        }
        if let (Some(key), Some(value)) = map_entry(s.message()?)? {
            let id = Id(if key.wire_type == 0 { key.integer()? } else { key.fixed64()? });
            if id.0 != 0 {
                out.push((frecency_score(value, now)?, id));
            }
        }
    }
    Ok(())
}

/// Decode the `settings` base64 string from `GET /users/@me/settings-proto/2`.
pub fn decode_frecency(settings_b64: &str) -> Result<Frecency, DecodeError> {
    let wire = STANDARD.decode(settings_b64).map_err(|_| DecodeError)?;
    if wire.len() > MAX_FRECENCY_BYTES {
        return Err(DecodeError);
    }
    let now = now_ms();
    let mut out = Frecency::default();
    let mut stickers: Vec<(f64, Id)> = Vec::new();
    for f in fields(&wire)? {
        match f.number {
            1 => {
                for v in fields(f.message()?)? {
                    if v.number == 3 {
                        out.version = v.integer()?;
                    }
                }
            }
            2 => {
                let body = f.message()?;
                out.gifs_wire = body.to_vec();
                for g in fields(body)? {
                    if g.number != 1 {
                        continue;
                    }
                    if let (Some(key), Some(value)) = map_entry(g.message()?)? {
                        let url = String::from_utf8_lossy(key.message()?).into_owned();
                        if !url.is_empty() {
                            out.favorite_gifs.push(decode_favorite_gif(url, value)?);
                        }
                    }
                }
            }
            // Sticker and emoji use are only a nicety: a surprise in them
            // mustn't hide the favourite GIFs.
            4 => {
                let _ = sticker_frecency(f.message()?, now, &mut stickers);
            }
            // FavoriteEmojis: `emojis`, repeated string.
            5 => {
                if let Ok(list) = f.message().and_then(fields) {
                    out.favorite_emoji = list.iter().filter(|e| e.number == 1).filter_map(|e| e.message().ok()).map(|b| String::from_utf8_lossy(b).into_owned()).collect();
                }
            }
            // EmojiFrecency: `emojis`, map<string, FrecencyItem>; 13 is
            // the same for reactions.
            6 => {
                let _ = emoji_frecency(f.message()?, &mut out.emoji);
            }
            13 => {
                let _ = emoji_frecency(f.message()?, &mut out.reaction_emoji);
            }
            _ => {}
        }
    }
    out.favorite_gifs.sort_by(|a, b| b.order.cmp(&a.order));
    stickers.sort_by(|a, b| b.0.total_cmp(&a.0).then(b.1 .0.cmp(&a.1 .0)));
    out.stickers = stickers.into_iter().map(|(_, id)| id).collect();
    Ok(out)
}

/// `EmojiFrecency.emojis`: map<string, FrecencyItem>.
fn emoji_frecency(bytes: &[u8], out: &mut std::collections::BTreeMap<String, Uses>) -> Result<(), DecodeError> {
    for e in fields(bytes)? {
        if e.number != 1 {
            continue;
        }
        if let (Some(key), Some(value)) = map_entry(e.message()?)? {
            let key = String::from_utf8_lossy(key.message()?).into_owned();
            if !key.is_empty() {
                out.insert(key, decode_uses(value)?);
            }
        }
    }
    Ok(())
}

/// Patch for `PATCH /users/@me/settings-proto/2` carrying emoji use: the
/// emoji sent (field 6) and the reactions given (field 13), each whole
/// (Discord replaces a section a patch carries), every entry as the maps
/// hold it. `None` leaves that section out. Send with
/// `required_data_version`.
pub fn encode_emoji_frecency_patch(emoji: Option<&std::collections::BTreeMap<String, Uses>>, reactions: Option<&std::collections::BTreeMap<String, Uses>>) -> String {
    let now = now_ms();
    let section = |number: u64, map: &std::collections::BTreeMap<String, Uses>, patch: &mut Vec<u8>| {
        let mut body = Vec::new();
        for (key, uses) in map {
            let mut value = Vec::new();
            encode_uses(uses, now, &mut value);
            let mut entry = Vec::new();
            message(1, key.as_bytes(), &mut entry);
            message(2, &value, &mut entry);
            message(1, &entry, &mut body);
        }
        message(number, &body, patch);
    };
    let mut patch = Vec::new();
    if let Some(map) = emoji {
        section(6, map, &mut patch);
    }
    if let Some(map) = reactions {
        section(13, map, &mut patch);
    }
    STANDARD.encode(patch)
}

/// `FavoriteGIFs` with `gif` added (or replaced) / removed; every other entry
/// and unknown field is copied byte for byte.
fn favorite_gifs_body(current: &Frecency, gif: &FavoriteGif, add: bool) -> Result<Vec<u8>, DecodeError> {
    let mut body = Vec::new();
    let mut max_order = 0u32;
    for f in fields(&current.gifs_wire)? {
        if f.number == 1 {
            let (key, value) = map_entry(f.message()?)?;
            let key = match key {
                Some(k) => String::from_utf8_lossy(k.message()?).into_owned(),
                None => String::new(),
            };
            if key == gif.url {
                continue;
            }
            if let Some(v) = value {
                max_order = max_order.max(decode_favorite_gif(key, v)?.order);
            }
        }
        body.extend_from_slice(f.raw);
    }
    if add {
        let int = |n: u64, v: u32, out: &mut Vec<u8>| {
            if v != 0 {
                write_varint(n << 3, out);
                write_varint(v as u64, out);
            }
        };
        let mut value = Vec::new();
        int(1, gif.format, &mut value);
        if !gif.src.is_empty() {
            message(2, gif.src.as_bytes(), &mut value);
        }
        int(3, gif.width, &mut value);
        int(4, gif.height, &mut value);
        int(5, max_order + 1, &mut value);
        let mut entry = Vec::new();
        message(1, gif.url.as_bytes(), &mut entry);
        message(2, &value, &mut entry);
        message(1, &entry, &mut body);
    }
    Ok(body)
}

/// Patch for `PATCH /users/@me/settings-proto/2` that favourites (or
/// unfavourites) one GIF. Only field 2 is sent; send with
/// `required_data_version`.
pub fn encode_favorite_gif_patch(current: &Frecency, gif: &FavoriteGif, add: bool) -> Result<String, DecodeError> {
    let body = favorite_gifs_body(current, gif, add)?;
    let mut patch = Vec::new();
    message(2, &body, &mut patch);
    Ok(STANDARD.encode(patch))
}

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

    fn gif_entry(url: &str, src: &str, order: u32) -> Vec<u8> {
        let mut v = Vec::new();
        v.push(1 << 3);
        write_varint(2, &mut v);
        message(2, src.as_bytes(), &mut v);
        v.push(3 << 3);
        write_varint(498, &mut v);
        v.push(4 << 3);
        write_varint(280, &mut v);
        v.push(5 << 3);
        write_varint(order as u64, &mut v);
        let mut e = Vec::new();
        message(1, url.as_bytes(), &mut e);
        message(2, &v, &mut e);
        e
    }

    fn sample() -> (Vec<u8>, Vec<u8>) {
        let mut gifs = Vec::new();
        message(1, &gif_entry("https://tenor.com/a", "https://media.tenor.com/a.mp4", 1), &mut gifs);
        message(1, &gif_entry("https://tenor.com/b", "https://media.tenor.com/b.mp4", 2), &mut gifs);
        // hide_tooltip + a field RustCord doesn't know: both must survive patches.
        gifs.extend_from_slice(&[2 << 3, 1]);
        message(9, b"future", &mut gifs);
        let mut stickers = Vec::new();
        let now = now_ms();
        for (id, uses, age_days) in [(10u64, 3u64, 1u64), (20, 9, 2), (30, 50, 400)] {
            let mut item = Vec::new();
            item.push(1 << 3);
            write_varint(uses, &mut item);
            let mut packed = Vec::new();
            write_varint(now - age_days * 86_400_000, &mut packed);
            message(2, &packed, &mut item);
            let mut e = Vec::new();
            fixed64_field(1, id, &mut e);
            message(2, &item, &mut e);
            message(1, &e, &mut stickers);
        }
        let mut wire = Vec::new();
        let mut version = Vec::new();
        version.push(3 << 3);
        write_varint(41, &mut version);
        message(1, &version, &mut wire);
        message(2, &gifs, &mut wire);
        message(4, &stickers, &mut wire);
        message(6, b"emoji frecency RustCord never touches", &mut wire);
        (wire, gifs)
    }

    #[test]
    fn decodes_favorites_and_sticker_ranking() {
        let (wire, _) = sample();
        let f = decode_frecency(&STANDARD.encode(&wire)).unwrap();
        assert_eq!(f.version, 41);
        assert_eq!(f.favorite_gifs.len(), 2);
        assert_eq!(f.favorite_gifs[0].url, "https://tenor.com/b");
        assert_eq!(f.favorite_gifs[0].format, 2);
        assert_eq!(f.favorite_gifs[0].width, 498);
        // 9 recent uses beats 3; 50 uses over a year ago count for nothing.
        assert_eq!(f.stickers, vec![Id(20), Id(10), Id(30)]);
    }

    #[test]
    fn favorite_patch_keeps_everything_else() {
        let (wire, gifs) = sample();
        let f = decode_frecency(&STANDARD.encode(&wire)).unwrap();
        let new = FavoriteGif { url: "https://tenor.com/c".into(), src: "https://media.tenor.com/c.gif".into(), format: 1, width: 220, height: 200, order: 0 };
        let patch = STANDARD.decode(encode_favorite_gif_patch(&f, &new, true).unwrap()).unwrap();
        let top = fields(&patch).unwrap();
        assert_eq!(top.len(), 1);
        assert_eq!(top[0].number, 2);
        let body = top[0].message().unwrap();
        // The old body comes first, byte for byte, then the new entry.
        assert!(body.starts_with(&gifs));
        let re = decode_frecency(&STANDARD.encode(&patch)).unwrap();
        assert_eq!(re.favorite_gifs.len(), 3);
        assert_eq!(re.favorite_gifs[0].url, "https://tenor.com/c");
        assert_eq!(re.favorite_gifs[0].order, 3);
        assert_eq!(re.favorite_gifs[0].src, "https://media.tenor.com/c.gif");

        // Removing drops exactly that entry.
        let a = f.favorite_gifs.iter().find(|g| g.url == "https://tenor.com/a").unwrap();
        let patch = STANDARD.decode(encode_favorite_gif_patch(&f, a, false).unwrap()).unwrap();
        let body = fields(&patch).unwrap()[0].message().unwrap().to_vec();
        let mut expected = Vec::new();
        message(1, &gif_entry("https://tenor.com/b", "https://media.tenor.com/b.mp4", 2), &mut expected);
        expected.extend_from_slice(&[2 << 3, 1]);
        message(9, b"future", &mut expected);
        assert_eq!(body, expected);
    }

    #[test]
    fn local_change_builds_on_itself() {
        let (wire, _) = sample();
        let mut f = decode_frecency(&STANDARD.encode(&wire)).unwrap();
        let a = f.favorite_gifs.iter().find(|g| g.url == "https://tenor.com/a").cloned().unwrap();
        f.set_favorite_gif(&a, false);
        assert!(!f.is_favorite_gif("https://tenor.com/a"));
        let x = FavoriteGif { url: "x".into(), src: "y".into(), ..Default::default() };
        let patch = STANDARD.decode(encode_favorite_gif_patch(&f, &x, true).unwrap()).unwrap();
        let re = decode_frecency(&STANDARD.encode(&patch)).unwrap();
        let urls: Vec<_> = re.favorite_gifs.iter().map(|g| g.url.as_str()).collect();
        assert_eq!(urls, vec!["x", "https://tenor.com/b"]);
    }

    /// A FrecencyItem the way Discord sends it.
    fn item(total: u64, recent: &[u64]) -> Vec<u8> {
        let mut v = Vec::new();
        v.push(1 << 3);
        write_varint(total, &mut v);
        let mut packed = Vec::new();
        for &t in recent {
            write_varint(t, &mut packed);
        }
        message(2, &packed, &mut v);
        // (Discord's own frecency and score, which are worked out again.)
        v.push(3 << 3);
        write_varint(999, &mut v);
        v
    }

    fn emoji_wire(entries: &[(&str, Vec<u8>)], favourites: &[&str]) -> Vec<u8> {
        let mut map = Vec::new();
        for (key, value) in entries {
            let mut e = Vec::new();
            message(1, key.as_bytes(), &mut e);
            message(2, value, &mut e);
            message(1, &e, &mut map);
        }
        let mut favs = Vec::new();
        for f in favourites {
            message(1, f.as_bytes(), &mut favs);
        }
        let mut wire = Vec::new();
        message(5, &favs, &mut wire);
        message(6, &map, &mut wire);
        wire
    }

    #[test]
    fn emoji_use_ranks_like_discord() {
        let now = now_ms();
        let day = 86_400_000u64;
        let wire = emoji_wire(
            &[
                // Used 6 times, recently: 6 × 100 = 600.
                ("100", item(6, &[now - day; 6])),
                // A server emoji, used twice 10 days ago: 2 × 70 = 140.
                ("123456789012345678", item(2, &[now - 10 * day, now - 10 * day])),
                // Once, 100 days ago: 1 × 1 = 1 (still listed, last).
                ("speech_left", item(1, &[now - 100 * day])),
                // Twice, a week and 31 days ago: ceil(2 × (70 + 30) / 2) = 100.
                ("poop", item(2, &[now - 7 * day, now - 31 * day])),
            ],
            &["fire", "123456789012345678"],
        );
        let f = decode_frecency(&STANDARD.encode(&wire)).unwrap();
        assert_eq!(f.favorite_emoji, vec!["fire", "123456789012345678"]);
        assert_eq!(f.emoji["poop"].frecency(now), 100.0);
        assert_eq!(f.frequent_emoji(now), vec!["100", "123456789012345678", "poop", "speech_left"]);
    }

    #[test]
    fn tracking_keeps_the_last_ten_uses() {
        let mut u = Uses::default();
        for t in 1..=12 {
            u.track(1_700_000_000_000 + t);
        }
        assert_eq!(u.total, 12);
        assert_eq!(u.recent.len(), MAX_RECENT_USES);
        assert_eq!(u.recent[0], 1_700_000_000_003);
    }

    #[test]
    fn emoji_patch_round_trips() {
        let now = now_ms();
        let mut emoji = std::collections::BTreeMap::new();
        emoji.insert("thumbsup".to_string(), Uses { total: 3, recent: vec![now - 1000, now - 500] });
        emoji.insert("1234".to_string(), Uses { total: 1, recent: vec![now] });
        let patch = STANDARD.decode(encode_emoji_frecency_patch(Some(&emoji), None)).unwrap();
        // Only field 6 is sent.
        assert!(fields(&patch).unwrap().iter().all(|f| f.number == 6));
        let back = decode_frecency(&STANDARD.encode(&patch)).unwrap();
        assert_eq!(back.emoji, emoji);
        // Reactions go in field 13, alone or with the rest.
        let patch = STANDARD.decode(encode_emoji_frecency_patch(None, Some(&emoji))).unwrap();
        assert!(fields(&patch).unwrap().iter().all(|f| f.number == 13));
        let back = decode_frecency(&STANDARD.encode(&patch)).unwrap();
        assert_eq!((back.emoji.len(), back.reaction_emoji), (0, emoji));
    }

    #[test]
    fn reactions_rank_like_discord() {
        let now = now_ms();
        // Most used (10, all recent): 1000 × (0.2 + 0.8 × 1000 / 1000) = 1000.
        let top = Uses { total: 10, recent: vec![now; 10] };
        assert_eq!(top.reaction_frecency(now, 10), 1000.0);
        // Once, today: 1000 × (0.2 × 1/10 + 0.8 × 100/1000) = 100.
        let once = Uses { total: 1, recent: vec![now] };
        assert_eq!(once.reaction_frecency(now, 10), 100.0);
    }
}