Skip to content

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

57.5 KB
Raw Blame
//! Typed Discord entities.
//!
//! Every struct is lenient (`#[serde(default)]`) because user-account payloads
//! vary between API revisions and partial objects are common.

use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;
use std::fmt;

/// First second of 2015, the epoch Discord snowflakes count from.
pub const DISCORD_EPOCH: u64 = 1_420_070_400_000;

/// A Discord snowflake. Serialized as a string, accepts strings or numbers.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Id(pub u64);

impl Id {
    pub fn timestamp_ms(self) -> u64 {
        (self.0 >> 22) + DISCORD_EPOCH
    }

    pub fn from_timestamp_ms(ms: u64) -> Self {
        Id(ms.saturating_sub(DISCORD_EPOCH) << 22)
    }

    pub fn from_value(v: &Value) -> Option<Self> {
        match v {
            Value::String(s) => s.parse().ok().map(Id),
            Value::Number(n) => n.as_u64().map(Id),
            _ => None,
        }
    }
}

impl fmt::Display for Id {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl Serialize for Id {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(&self.0.to_string())
    }
}

impl<'de> Deserialize<'de> for Id {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        struct V;
        impl<'de> de::Visitor<'de> for V {
            type Value = Id;
            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("a snowflake id")
            }
            fn visit_str<E: de::Error>(self, v: &str) -> Result<Id, E> {
                v.parse().map(Id).map_err(E::custom)
            }
            fn visit_u64<E: de::Error>(self, v: u64) -> Result<Id, E> {
                Ok(Id(v))
            }
            fn visit_i64<E: de::Error>(self, v: i64) -> Result<Id, E> {
                Ok(Id(v as u64))
            }
        }
        d.deserialize_any(V)
    }
}

pub mod channel_kind {
    pub const GUILD_TEXT: u8 = 0;
    pub const DM: u8 = 1;
    pub const GUILD_VOICE: u8 = 2;
    pub const GROUP_DM: u8 = 3;
    pub const GUILD_CATEGORY: u8 = 4;
    pub const GUILD_ANNOUNCEMENT: u8 = 5;
    pub const ANNOUNCEMENT_THREAD: u8 = 10;
    pub const PUBLIC_THREAD: u8 = 11;
    pub const PRIVATE_THREAD: u8 = 12;
    pub const GUILD_STAGE_VOICE: u8 = 13;
    pub const GUILD_DIRECTORY: u8 = 14;
    pub const GUILD_FORUM: u8 = 15;
    pub const GUILD_MEDIA: u8 = 16;
    pub const MEDIA_THREAD: u8 = 19;
    /// Discord's "server hub" (Guild Space): a page of widgets, not a channel
    /// you read. Every server has one; Discord's channel list leaves it out.
    pub const GUILD_SPACE: u8 = 20;
    pub const GUILD_APP: u8 = 21;

    pub fn is_thread(k: u8) -> bool {
        matches!(k, ANNOUNCEMENT_THREAD | PUBLIC_THREAD | PRIVATE_THREAD | MEDIA_THREAD)
    }
    /// Thread-only channels: forum and media channels, whose content is posts.
    pub fn is_forum(k: u8) -> bool {
        matches!(k, GUILD_FORUM | GUILD_MEDIA)
    }
    /// Kinds Discord's channel list shows (Guild Space, lobbies and kinds
    /// newer than RustCord are left out, as Discord leaves out what it
    /// doesn't know).
    pub fn is_listed(k: u8) -> bool {
        matches!(
            k,
            GUILD_TEXT | GUILD_VOICE | GUILD_CATEGORY | GUILD_ANNOUNCEMENT | GUILD_STAGE_VOICE | GUILD_DIRECTORY | GUILD_FORUM | GUILD_MEDIA | GUILD_APP
        )
    }
    pub fn is_voice(k: u8) -> bool {
        matches!(k, GUILD_VOICE | GUILD_STAGE_VOICE)
    }
    /// Channels whose message history RustCord can show.
    pub fn is_text(k: u8) -> bool {
        matches!(k, GUILD_TEXT | DM | GROUP_DM | GUILD_ANNOUNCEMENT) || is_thread(k)
    }
}

pub mod permissions {
    pub const CREATE_INSTANT_INVITE: u64 = 1 << 0;
    pub const ADMINISTRATOR: u64 = 1 << 3;
    pub const MANAGE_CHANNELS: u64 = 1 << 4;
    pub const MANAGE_GUILD: u64 = 1 << 5;
    pub const VIEW_CHANNEL: u64 = 1 << 10;
    pub const SEND_MESSAGES: u64 = 1 << 11;
    pub const ATTACH_FILES: u64 = 1 << 15;
    pub const USE_EXTERNAL_EMOJIS: u64 = 1 << 18;
    pub const MUTE_MEMBERS: u64 = 1 << 22;
    pub const DEAFEN_MEMBERS: u64 = 1 << 23;
    pub const MOVE_MEMBERS: u64 = 1 << 24;
    pub const CHANGE_NICKNAME: u64 = 1 << 26;
    pub const MANAGE_ROLES: u64 = 1 << 28;
}

#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct ActivityEmoji {
    pub name: Option<String>,
    pub id: Option<Id>,
    pub animated: bool,
}

/// A rich presence / custom status entry.
#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct Activity {
    /// 0 playing, 1 streaming, 2 listening, 3 watching, 4 custom, 5 competing
    #[serde(rename = "type")]
    pub kind: u8,
    pub name: String,
    pub state: Option<String>,
    pub details: Option<String>,
    pub emoji: Option<ActivityEmoji>,
    pub application_id: Option<Id>,
    pub timestamps: Option<ActivityTimestamps>,
    pub assets: Option<ActivityAssets>,
    /// Spotify: the track ID (for Listen Along).
    pub sync_id: Option<String>,
    /// Spotify: `spotify:<user id>` party (Listen Along joins it).
    pub party: Option<ActivityParty>,
    /// Activity flags (256: an embedded activity, played inside a call).
    pub flags: u32,
}

#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct ActivityParty {
    pub id: Option<String>,
}

#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct ActivityTimestamps {
    /// Unix milliseconds (some clients send them as strings).
    #[serde(deserialize_with = "lenient_u64")]
    pub start: Option<u64>,
    #[serde(deserialize_with = "lenient_u64")]
    pub end: Option<u64>,
}

/// `null` (as well as a missing field) reads as the type's default.
fn null_default<'de, D: Deserializer<'de>, T: Default + Deserialize<'de>>(d: D) -> Result<T, D::Error> {
    Ok(Option::<T>::deserialize(d)?.unwrap_or_default())
}

fn lenient_u64<'de, D: Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {
    Ok(match Value::deserialize(d)? {
        Value::Number(n) => n.as_u64().or_else(|| n.as_f64().map(|f| f as u64)),
        Value::String(s) => s.parse().ok(),
        _ => None,
    })
}

#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct ActivityAssets {
    pub large_image: Option<String>,
    pub large_text: Option<String>,
    pub small_image: Option<String>,
    pub small_text: Option<String>,
}

impl Activity {
    /// URL for a rich-presence asset key: an app asset ID, an `mp:` media
    /// proxy path, or one of the platforms Discord knows by prefix (Spotify
    /// album art, a Twitch stream's preview, a YouTube thumbnail). Never a
    /// bare web address: Discord sends outside pictures through its own proxy
    /// (`mp:external/…`), and loading one straight from wherever someone
    /// pointed their status would give that server your IP address.
    pub fn asset_url(&self, key: &str) -> Option<String> {
        if let Some(rest) = key.strip_prefix("mp:") {
            return Some(format!("https://media.discordapp.net/{rest}"));
        }
        if let Some(rest) = key.strip_prefix("spotify:") {
            return Some(format!("https://i.scdn.co/image/{rest}"));
        }
        if let Some(rest) = key.strip_prefix("twitch:") {
            return Some(format!("https://static-cdn.jtvnw.net/previews-ttv/live_user_{rest}-640x360.jpg"));
        }
        if let Some(rest) = key.strip_prefix("youtube:") {
            return Some(format!("https://i.ytimg.com/vi/{rest}/hqdefault_live.jpg"));
        }
        if key.is_empty() || !key.chars().all(|c| c.is_ascii_digit()) {
            return None;
        }
        Some(format!("https://cdn.discordapp.com/app-assets/{}/{key}.png?size=160", self.application_id?))
    }

    pub fn large_image_url(&self) -> Option<String> {
        self.asset_url(self.assets.as_ref()?.large_image.as_deref()?)
    }

    /// The small picture Discord puts on the large one's corner.
    pub fn small_image_url(&self) -> Option<String> {
        self.asset_url(self.assets.as_ref()?.small_image.as_deref()?)
    }
}

#[derive(Clone, Debug, Default, PartialEq)]
pub struct Presence {
    /// "online" | "idle" | "dnd" | "offline"
    pub status: String,
    pub activities: Vec<Activity>,
    /// Which apps they're on: (desktop, mobile, web), each a status or None.
    pub client_status: ClientStatus,
}

#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct ClientStatus {
    pub desktop: Option<String>,
    pub mobile: Option<String>,
    pub web: Option<String>,
}

impl Presence {
    /// Online only on their phone: Discord draws a phone instead of a dot.
    pub fn on_mobile(&self) -> bool {
        self.status == "online"
            && self.client_status.mobile.as_deref() == Some("online")
            && self.client_status.desktop.is_none()
            && self.client_status.web.is_none()
    }

    pub fn custom_status(&self) -> Option<&Activity> {
        self.activities.iter().find(|a| a.kind == 4)
    }

    /// First game (or other non-custom activity) and how many more there are,
    /// for Discord's "🎮 Project Zomboid +1".
    pub fn game(&self) -> Option<(String, usize)> {
        let games: Vec<&Activity> = self.activities.iter().filter(|a| a.kind != 4).collect();
        let first = games.first()?;
        Some((first.name.clone(), games.len() - 1))
    }

    /// "Playing ROBLOX" style line, for the first non-custom activity.
    pub fn activity_line(&self) -> Option<String> {
        let a = self.activities.iter().find(|a| a.kind != 4)?;
        Some(match a.kind {
            1 => format!("Streaming {}", a.name),
            2 => format!("Listening to {}", a.name),
            3 => format!("Watching {}", a.name),
            5 => format!("Competing in {}", a.name),
            _ => format!("Playing {}", a.name),
        })
    }
}

/// `GET /guilds/{id}/profile`: the card shown when you click a server tag.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct GuildProfile {
    pub id: Id,
    pub name: String,
    pub icon_hash: Option<String>,
    pub member_count: u64,
    pub online_count: u64,
    pub description: String,
    pub brand_color_primary: Option<String>,
    pub tag: Option<String>,
    pub badge_hash: Option<String>,
    pub custom_banner_hash: Option<String>,
    pub traits: Vec<GuildTrait>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct GuildTrait {
    pub emoji_id: Option<Id>,
    pub emoji_name: Option<String>,
    pub emoji_animated: bool,
    pub label: String,
}

impl GuildProfile {
    pub fn icon_url(&self) -> Option<String> {
        let h = self.icon_hash.as_deref()?;
        let ext = if h.starts_with("a_") { "gif" } else { "png" };
        Some(format!("https://cdn.discordapp.com/icons/{}/{h}.{ext}?size=128", self.id))
    }

    pub fn badge_url(&self) -> Option<String> {
        Some(format!("https://cdn.discordapp.com/guild-tag-badges/{}/{}.png?size=32", self.id, self.badge_hash.as_deref()?))
    }

    pub fn banner_url(&self) -> Option<String> {
        Some(format!("https://cdn.discordapp.com/discovery-splashes/{}/{}.png?size=600", self.id, self.custom_banner_hash.as_deref()?))
    }

    /// Brand colour as 0xRRGGBB.
    pub fn brand_color(&self) -> Option<u32> {
        u32::from_str_radix(self.brand_color_primary.as_deref()?.trim_start_matches('#'), 16).ok()
    }
}

/// One result from Discord's GIF picker (Tenor behind Discord's API).
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct Gif {
    /// Tenor page link: what gets sent, Discord embeds it.
    pub url: String,
    /// The animated GIF.
    pub src: String,
    pub gif_src: Option<String>,
    /// Still frame (cheap to show in a grid).
    pub preview: Option<String>,
    pub width: f32,
    pub height: f32,
}

impl Gif {
    /// What a picker tile plays: the MP4 clip asked for (`src`), else the GIF.
    pub fn animated(&self) -> &str {
        if self.src.is_empty() {
            self.gif_src.as_deref().unwrap_or_default()
        } else {
            &self.src
        }
    }

    /// Image for the grid tile (still frame if Discord gave one).
    pub fn still(&self) -> &str {
        self.preview.as_deref().filter(|s| !s.is_empty()).unwrap_or_else(|| self.animated())
    }
}

/// 1 friend, 2 blocked, 3 incoming request, 4 outgoing request.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct Relationship {
    pub id: Id,
    #[serde(rename = "type")]
    pub kind: u8,
    /// You ignore this person (Discord's "Ignore", separate from blocking).
    #[serde(default)]
    pub user_ignored: bool,
    pub nickname: Option<String>,
    pub user: Option<User>,
    /// When you became friends (ISO-8601).
    pub since: Option<String>,
}

/// A user's server tag (the small badge + text after their name).
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct PrimaryGuild {
    pub identity_guild_id: Option<Id>,
    pub identity_enabled: Option<bool>,
    pub tag: Option<String>,
    pub badge: Option<String>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct AvatarDecoration {
    pub asset: String,
    pub sku_id: Option<Id>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct User {
    pub id: Id,
    pub username: String,
    pub global_name: Option<String>,
    pub discriminator: Option<String>,
    pub avatar: Option<String>,
    pub bot: bool,
    pub primary_guild: Option<PrimaryGuild>,
    /// Older name for `primary_guild`.
    pub clan: Option<PrimaryGuild>,
    pub avatar_decoration_data: Option<AvatarDecoration>,
    /// Nitro tier (only sent for your own account): 0 none, 1 Classic,
    /// 2 Nitro, 3 Basic.
    pub premium_type: Option<u8>,
    pub banner: Option<String>,
    pub accent_color: Option<u32>,
    pub bio: Option<String>,
    /// Discord's own system account ("OFFICIAL").
    pub system: bool,
    pub public_flags: u64,
    /// Shop cosmetics (nameplate).
    pub collectibles: Option<Collectibles>,
    /// Nitro display name style (font, effect, colours).
    pub display_name_styles: Option<DisplayNameStyle>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct Collectibles {
    pub nameplate: Option<Nameplate>,
}

/// The picture behind a name in the member list, DM list and user panel.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct Nameplate {
    pub asset: String,
    pub palette: Option<String>,
    pub label: Option<String>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct DisplayNameStyle {
    pub font_id: u32,
    pub effect_id: u32,
    pub colors: Vec<u32>,
}

impl User {
    /// Verified app (bot) badge.
    pub fn verified_bot(&self) -> bool {
        self.bot && self.public_flags & (1 << 16) != 0
    }

    /// Still image of the user's nameplate, if they have one.
    pub fn nameplate_url(&self) -> Option<String> {
        let np = self.collectibles.as_ref()?.nameplate.as_ref().filter(|n| !n.asset.is_empty())?;
        let asset = if np.asset.ends_with('/') { np.asset.clone() } else { format!("{}/", np.asset) };
        Some(format!("https://cdn.discordapp.com/assets/collectibles/{asset}static.png"))
    }

    /// The nameplate's palette colour (Discord's dark-theme background, 0xRRGGBB):
    /// the tint behind the picture and the plated buttons' hover.
    pub fn nameplate_color(&self) -> Option<u32> {
        let np = self.collectibles.as_ref()?.nameplate.as_ref().filter(|n| !n.asset.is_empty())?;
        Some(match np.palette.as_deref()? {
            "crimson" => 0x900007,
            "berry" => 0x893A99,
            "sky" => 0x0080B7,
            "teal" => 0x086460,
            "forest" => 0x2D5401,
            "bubble_gum" => 0xDC3E97,
            "violet" => 0x730BC8,
            "cobalt" => 0x0131C2,
            "clover" => 0x047B20,
            "lemon" => 0xF6CD12,
            "white" => 0xFFFFFF,
            "black" => 0x000000,
            _ => return None,
        })
    }

    /// Colours of a Nitro display name style (gradient when there are two).
    pub fn name_colors(&self) -> Option<&[u32]> {
        self.display_name_styles.as_ref().map(|s| s.colors.as_slice()).filter(|c| !c.is_empty())
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct ProfileBadge {
    pub id: String,
    pub description: String,
    pub icon: String,
    pub link: Option<String>,
}

impl ProfileBadge {
    pub fn icon_url(&self) -> String {
        format!("https://cdn.discordapp.com/badge-icons/{}.png", self.icon)
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct ProfileMeta {
    pub bio: Option<String>,
    pub pronouns: Option<String>,
    pub banner: Option<String>,
    pub accent_color: Option<u32>,
    pub theme_colors: Option<Vec<u32>>,
    pub profile_effect: Option<ProfileEffectRef>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct ProfileEffectRef {
    pub id: Id,
    /// The shop product the effect is (what its pictures are looked up by).
    pub sku_id: Option<Id>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct ProfileMember {
    pub nick: Option<String>,
    pub roles: Vec<Id>,
    pub joined_at: Option<String>,
    /// The display name style they set for this server (replaces their own there).
    pub display_name_styles: Option<DisplayNameStyle>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct MutualGuild {
    pub id: Id,
    pub nick: Option<String>,
}

/// A linked account shown on a profile (Steam, Spotify, GitHub…).
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct ConnectedAccount {
    #[serde(rename = "type")]
    pub kind: String,
    pub id: String,
    pub name: String,
    pub verified: bool,
    /// Extra facts some platforms share (Steam games, X followers…).
    pub metadata: Option<Value>,
}

impl ConnectedAccount {
    /// Where the account lives, when Discord links it: its platform list's
    /// `getPlatformUserUrl` (web module 573648, read 2026-11-27). Xbox,
    /// PlayStation, Battle.net, Epic, Riot, PayPal and the like have none.
    pub fn link(&self) -> Option<String> {
        let (n, id) = (crate::http::url_encode(&self.name), crate::http::url_encode(&self.id));
        Some(match self.kind.as_str() {
            "twitch" => format!("https://www.twitch.tv/{n}"),
            "youtube" => format!("https://www.youtube.com/channel/{id}"),
            // (A DID such as did:plc:…, its colons kept.)
            "bluesky" => format!("https://bsky.app/profile/{}", id.replace("%3A", ":")),
            "steam" => format!("https://steamcommunity.com/profiles/{id}"),
            "reddit" => format!("https://www.reddit.com/u/{n}"),
            "twitter" => format!("https://x.com/{n}"),
            "spotify" => format!("https://open.spotify.com/user/{id}"),
            "github" => format!("https://github.com/{n}"),
            "roblox" => format!("https://roblox.com/users/{id}/profile"),
            "ebay" => format!("https://www.ebay.com/usr/{n}"),
            "tiktok" => format!("https://www.tiktok.com/@{n}"),
            "instagram" => format!("https://www.instagram.com/{n}"),
            "letterboxd" => format!("https://letterboxd.com/{n}/"),
            "domain" => format!("https://{}/", self.id),
            _ => return None,
        })
    }
}

/// `GET /users/{id}/profile`
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct UserProfile {
    pub user: User,
    pub user_profile: Option<ProfileMeta>,
    pub guild_member_profile: Option<ProfileMeta>,
    pub guild_member: Option<ProfileMember>,
    pub badges: Vec<ProfileBadge>,
    pub guild_badges: Vec<ProfileBadge>,
    pub premium_since: Option<String>,
    pub mutual_guilds: Vec<MutualGuild>,
    pub mutual_friends: Vec<User>,
    pub mutual_friends_count: Option<u32>,
    pub connected_accounts: Vec<ConnectedAccount>,
    /// Profile widgets (favourite / current / played games: "Game Collection").
    pub widgets: Vec<ProfileWidget>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct ProfileWidget {
    pub data: ProfileWidgetData,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct ProfileWidgetData {
    #[serde(rename = "type")]
    pub kind: String,
    pub games: Vec<ProfileGame>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct ProfileGame {
    pub game_id: Id,
    /// The user's note on a favourite game ("2016-2025 :)").
    pub comment: Option<String>,
    /// Chips under a favourite game ("Obsessed", "Open to play").
    pub tags: Vec<String>,
}

/// A game (application) as Discord's public application info gives it.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct AppInfo {
    pub id: Id,
    pub name: String,
    pub icon: Option<String>,
    /// Store-page cover art.
    pub cover_image: Option<String>,
    /// Box art from Discord's game database (the Board's covers), a full URL.
    pub game_cover: Option<String>,
}

impl AppInfo {
    pub fn icon_url(&self) -> Option<String> {
        Some(format!("https://cdn.discordapp.com/app-icons/{}/{}.png?size=64", self.id, self.icon.as_deref()?))
    }

    /// Cover art if the app has one, else its icon (larger).
    /// One entry of `GET /games`: its name, icon and box art.
    pub fn from_game(game: &serde_json::Value) -> Option<Self> {
        let media = &game["media"];
        let cover = media["cover_url"].as_str().or_else(|| media["cover"]["value"].as_str().filter(|_| media["cover"]["type"] == "url"));
        Some(Self {
            id: Id::from_value(&game["id"])?,
            name: game["name"].as_str().unwrap_or_default().to_string(),
            icon: media["icon"]["value"].as_str().filter(|_| media["icon"]["type"] == "hash").map(str::to_string),
            cover_image: None,
            game_cover: cover.map(str::to_string),
        })
    }

    /// Box art (as Discord's Board asks for it) if the game has any, else the
    /// app's store cover, else its icon (larger).
    pub fn cover_url(&self) -> Option<String> {
        if let Some(art) = &self.game_cover {
            return Some(format!("{art}?keep_aspect_ratio=true&format=webp"));
        }
        match self.cover_image.as_deref() {
            Some(c) => Some(format!("https://cdn.discordapp.com/app-icons/{}/{c}.png?size=256", self.id)),
            None => Some(format!("https://cdn.discordapp.com/app-icons/{}/{}.png?size=256", self.id, self.icon.as_deref()?)),
        }
    }
}

impl UserProfile {
    fn pick<'a>(&'a self, f: impl Fn(&'a ProfileMeta) -> Option<&'a String>) -> Option<&'a str> {
        let nonempty = |s: Option<&'a String>| s.map(String::as_str).filter(|s| !s.trim().is_empty());
        nonempty(self.guild_member_profile.as_ref().and_then(&f))
            .or_else(|| nonempty(self.user_profile.as_ref().and_then(&f)))
    }

    pub fn bio(&self) -> Option<&str> {
        self.pick(|m| m.bio.as_ref())
            .or_else(|| self.user.bio.as_deref().filter(|s| !s.trim().is_empty()))
    }

    pub fn pronouns(&self) -> Option<&str> {
        self.pick(|m| m.pronouns.as_ref())
    }

    pub fn banner_url(&self) -> Option<String> {
        let hash = self
            .user_profile
            .as_ref()
            .and_then(|p| p.banner.clone())
            .or_else(|| self.user.banner.clone())?;
        let ext = if hash.starts_with("a_") { "gif" } else { "png" };
        Some(format!("https://cdn.discordapp.com/banners/{}/{}.{ext}?size=600", self.user.id, hash))
    }

    pub fn accent_color(&self) -> Option<u32> {
        self.user_profile.as_ref().and_then(|p| p.accent_color).or(self.user.accent_color)
    }

    /// Nitro profile theme (primary, accent).
    pub fn theme_colors(&self) -> Option<(u32, u32)> {
        let c = self
            .guild_member_profile
            .as_ref()
            .and_then(|p| p.theme_colors.clone())
            .or_else(|| self.user_profile.as_ref().and_then(|p| p.theme_colors.clone()))?;
        Some((*c.first()?, *c.get(1).or(c.first())?))
    }

    /// "Game Collection": favourite games first, then current, then played.
    pub fn game_ids(&self) -> Vec<Id> {
        let mut out = Vec::new();
        for kind in ["favorite_games", "current_games", "played_games"] {
            for w in self.widgets.iter().filter(|w| w.data.kind == kind) {
                for g in &w.data.games {
                    if g.game_id.0 != 0 && !out.contains(&g.game_id) {
                        out.push(g.game_id);
                    }
                }
            }
        }
        out
    }

    /// Nitro profile effect (the animated overlay on the card).
    pub fn profile_effect(&self) -> Option<Id> {
        self.guild_member_profile
            .as_ref()
            .and_then(|p| p.profile_effect.as_ref())
            .or_else(|| self.user_profile.as_ref().and_then(|p| p.profile_effect.as_ref()))
            .map(|e| e.sku_id.unwrap_or(e.id))
            .filter(|id| id.0 != 0)
    }
}

impl User {
    /// (tag text, badge image URL) if the user shows a server tag.
    /// The server the user's tag belongs to.
    pub fn server_tag_guild(&self) -> Option<Id> {
        let pg = self.primary_guild.as_ref().or(self.clan.as_ref())?;
        pg.identity_guild_id.filter(|_| pg.identity_enabled != Some(false) && pg.tag.as_deref().is_some_and(|t| !t.is_empty()))
    }

    pub fn server_tag(&self) -> Option<(String, Option<String>)> {
        let pg = self.primary_guild.as_ref().or(self.clan.as_ref())?;
        if pg.identity_enabled == Some(false) {
            return None;
        }
        let tag = pg.tag.clone().filter(|t| !t.is_empty())?;
        let badge = match (pg.identity_guild_id, &pg.badge) {
            (Some(g), Some(b)) => Some(format!("https://cdn.discordapp.com/guild-tag-badges/{g}/{b}.png?size=32")),
            _ => None,
        };
        Some((tag, badge))
    }

    pub fn decoration_url(&self) -> Option<String> {
        self.avatar_decoration_data.as_ref().filter(|d| !d.asset.is_empty()).map(|d| {
            format!("https://cdn.discordapp.com/avatar-decoration-presets/{}.png?size=96&passthrough=false", d.asset)
        })
    }

    pub fn display_name(&self) -> &str {
        self.global_name
            .as_deref()
            .filter(|s| !s.is_empty())
            .unwrap_or(&self.username)
    }

    pub fn avatar_url(&self, size: u32) -> Option<String> {
        self.avatar.as_ref().map(|hash| {
            format!(
                "https://cdn.discordapp.com/avatars/{}/{}.png?size={}",
                self.id, hash, size
            )
        })
    }

    /// The user's avatar, or Discord's default avatar for them.
    pub fn avatar_or_default(&self, size: u32) -> String {
        self.avatar_url(size).unwrap_or_else(|| {
            let legacy = self
                .discriminator
                .as_deref()
                .and_then(|d| d.parse::<u64>().ok())
                .filter(|d| *d != 0);
            let index = match legacy {
                Some(d) => d % 5,
                None => (self.id.0 >> 22) % 6,
            };
            format!("https://cdn.discordapp.com/embed/avatars/{index}.png")
        })
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct Role {
    pub id: Id,
    pub name: String,
    pub color: u32,
    pub position: i32,
    pub permissions: String,
    pub icon: Option<String>,
    pub unicode_emoji: Option<String>,
    /// "Display role members separately": its own group in the member list.
    pub hoist: bool,
    /// Bot / booster roles: Discord assigns these, nobody can by hand.
    pub managed: bool,
    /// Anyone may @mention it (otherwise only with Mention Everyone).
    pub mentionable: bool,
    /// What kind of managed role it is (`tags`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<RoleTags>,
}

/// A role's `tags`: only whether it's the server's booster role, which Discord
/// marks with a `premium_subscriber` key that is present and null.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct RoleTags {
    pub premium_subscriber: bool,
}

impl Serialize for RoleTags {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        let mut m = serde_json::Map::new();
        if self.premium_subscriber {
            m.insert("premium_subscriber".into(), Value::Null);
        }
        m.serialize(s)
    }
}

impl<'de> Deserialize<'de> for RoleTags {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let v = Value::deserialize(d)?;
        Ok(RoleTags { premium_subscriber: v.get("premium_subscriber").is_some() })
    }
}

impl Role {
    /// The role Discord gives to people boosting the server.
    pub fn is_booster_role(&self) -> bool {
        self.tags.is_some_and(|t| t.premium_subscriber)
    }

    pub fn permission_bits(&self) -> u64 {
        self.permissions.parse().unwrap_or(0)
    }

    pub fn icon_url(&self) -> Option<String> {
        self.icon
            .as_ref()
            .map(|h| format!("https://cdn.discordapp.com/role-icons/{}/{}.png?size=40", self.id, h))
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct GuildEmoji {
    pub id: Option<Id>,
    pub name: Option<String>,
    pub animated: bool,
    pub available: Option<bool>,
    /// Added by an integration (Twitch, YouTube): usable in other servers
    /// without Nitro.
    pub managed: bool,
}

impl GuildEmoji {
    pub fn url(&self) -> Option<String> {
        self.id.map(|id| emoji_url(id, self.animated, 48))
    }
}

/// CDN URL of a custom emoji (`.gif` when animated).
pub fn emoji_url(id: Id, animated: bool, size: u32) -> String {
    format!("https://cdn.discordapp.com/emojis/{id}.{}?size={size}", if animated { "gif" } else { "png" })
}

impl User {
    /// Animated avatar (`a_` hash) as a GIF, else the normal one.
    pub fn avatar_animated(&self, size: u32) -> String {
        match self.avatar.as_deref() {
            Some(h) if h.starts_with("a_") => format!("https://cdn.discordapp.com/avatars/{}/{h}.gif?size={size}", self.id),
            _ => self.avatar_or_default(size),
        }
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct PermissionOverwrite {
    pub id: Id,
    /// 0 / "role" for roles, 1 / "member" for members.
    #[serde(rename = "type")]
    pub kind: Value,
    pub allow: String,
    pub deny: String,
}

impl PermissionOverwrite {
    pub fn is_member(&self) -> bool {
        self.kind.as_u64() == Some(1) || self.kind.as_str() == Some("member")
    }
    pub fn allow_bits(&self) -> u64 {
        self.allow.parse().unwrap_or(0)
    }
    pub fn deny_bits(&self) -> u64 {
        self.deny.parse().unwrap_or(0)
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct Guild {
    pub id: Id,
    pub name: String,
    pub icon: Option<String>,
    pub owner_id: Option<Id>,
    pub roles: Vec<Role>,
    pub emojis: Vec<GuildEmoji>,
    pub stickers: Vec<Sticker>,
    pub channels: Vec<Channel>,
    pub unavailable: bool,
    /// Banner hash (shown at the top of the channel list).
    pub banner: Option<String>,
    /// Boost level 0-3.
    pub premium_tier: Option<u8>,
    pub premium_subscription_count: Option<u32>,
    /// Show the "Boost Goal" bar in the channel list.
    pub premium_progress_bar_enabled: Option<bool>,
    pub features: Option<Vec<String>>,
    /// Features the server bought with Boosts (`premium_features.features`:
    /// GUILD_TAGS, ENHANCED_ROLE_COLORS, …); None when Discord didn't say.
    pub boost_features: Option<Vec<String>>,
    /// The server's tag (`profile` on the guild object): None without one.
    pub profile: Option<GuildTag>,
}

/// A server's own tag: the letters and the badge image hash.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct GuildTag {
    pub tag: Option<String>,
    pub badge: Option<String>,
}

impl Guild {
    /// Take the banner / boost fields from a guild object, READY's
    /// `properties` or GUILD_UPDATE (only the keys that are present).
    pub fn apply_extras(&mut self, v: &Value) {
        if v.get("banner").is_some() {
            self.banner = v["banner"].as_str().map(String::from);
        }
        if let Some(n) = v["premium_tier"].as_u64() {
            self.premium_tier = Some(n as u8);
        }
        if let Some(n) = v["premium_subscription_count"].as_u64() {
            self.premium_subscription_count = Some(n as u32);
        }
        if let Some(b) = v["premium_progress_bar_enabled"].as_bool() {
            self.premium_progress_bar_enabled = Some(b);
        }
        if let Some(f) = v["features"].as_array() {
            self.features = Some(f.iter().filter_map(|s| s.as_str().map(String::from)).collect());
        }
        if let Some(f) = v["premium_features"]["features"].as_array() {
            self.boost_features = Some(f.iter().filter_map(|s| s.as_str().map(String::from)).collect());
        }
        if v.get("profile").is_some() {
            self.profile = Option::<GuildTag>::deserialize(&v["profile"]).ok().flatten();
        }
    }

    /// (letters, badge image URL) of the tag members can wear: Discord
    /// offers it only with the GUILD_TAGS feature and letters set.
    pub fn tag(&self) -> Option<(&str, Option<String>)> {
        if !self.features.as_ref().is_some_and(|f| f.iter().any(|f| f == "GUILD_TAGS")) {
            return None;
        }
        let p = self.profile.as_ref()?;
        let tag = p.tag.as_deref().filter(|t| !t.is_empty())?;
        let badge = p.badge.as_ref().map(|b| format!("https://cdn.discordapp.com/guild-tag-badges/{}/{b}.png?size=32", self.id));
        Some((tag, badge))
    }
}

/// A server's sticker (or one from Discord's packs).
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct Sticker {
    pub id: Id,
    pub name: String,
    pub description: Option<String>,
    pub tags: String,
    /// 1 PNG, 2 APNG, 3 Lottie, 4 GIF.
    pub format_type: u8,
    pub available: Option<bool>,
    pub guild_id: Option<Id>,
}

impl Sticker {
    /// The still picture (Discord web's rules). An APNG's first frame comes
    /// from the media proxy with `passthrough=false`; a GIF's file shows as
    /// its first frame. Lottie stickers have no raster form: None (they are
    /// drawn from [`Sticker::animated_url`]'s JSON).
    pub fn image_url(id: Id, format_type: u8, size: u32) -> Option<String> {
        match format_type {
            1 => Some(format!("https://media.discordapp.net/stickers/{id}.png?size={size}")),
            2 => Some(format!("https://media.discordapp.net/stickers/{id}.png?size={size}&passthrough=false")),
            4 => Some(format!("https://media.discordapp.net/stickers/{id}.gif?size={size}")),
            _ => None,
        }
    }

    /// The file that animates: the APNG itself, the GIF, or the Lottie JSON
    /// (`discord.com/stickers/{id}.json`, which redirects to the CDN: asked
    /// there directly). None for a plain PNG.
    pub fn animated_url(id: Id, format_type: u8, size: u32) -> Option<String> {
        match format_type {
            2 => Some(format!("https://media.discordapp.net/stickers/{id}.png?size={size}")),
            3 => Some(format!("https://cdn.discordapp.com/stickers/{id}.json")),
            4 => Some(format!("https://media.discordapp.net/stickers/{id}.gif?size={size}")),
            _ => None,
        }
    }
}

impl Guild {
    pub fn icon_url(&self, size: u32) -> Option<String> {
        self.icon.as_ref().map(|hash| {
            format!(
                "https://cdn.discordapp.com/icons/{}/{}.png?size={}",
                self.id, hash, size
            )
        })
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct Channel {
    pub id: Id,
    #[serde(rename = "type")]
    pub kind: u8,
    pub guild_id: Option<Id>,
    pub name: Option<String>,
    pub topic: Option<String>,
    /// Voice channels: the bitrate (bit/s) members' voices are encoded at.
    pub bitrate: Option<u32>,
    pub position: i32,
    pub parent_id: Option<Id>,
    pub recipients: Vec<User>,
    /// Group DMs: the group's picture (`channel-icons/{id}/{icon}`).
    pub icon: Option<String>,
    pub permission_overwrites: Vec<PermissionOverwrite>,
    pub last_message_id: Option<Id>,
    /// Threads: how many messages they hold.
    pub message_count: Option<u32>,
    pub nsfw: bool,
    /// Slowmode, in seconds.
    pub rate_limit_per_user: u32,
    /// DMs from people you share no friendship with, awaiting approval.
    pub is_message_request: bool,
    pub is_message_request_timestamp: Option<String>,
    /// A message request Discord filed as spam.
    pub is_spam: bool,
    /// Channel flags: threads 2 = pinned post; any 131072 = a channel you may
    /// not see, sent with its name blanked.
    #[serde(deserialize_with = "null_default")]
    pub flags: u32,
    /// Threads: who started it. Group DMs: the group's owner.
    pub owner_id: Option<Id>,
    /// Threads: archived / locked.
    pub thread_metadata: Option<ThreadMetadata>,
    /// Forum posts: the tags put on it.
    #[serde(deserialize_with = "null_default")]
    pub applied_tags: Vec<Id>,
    /// Forum channels: the tags posts can carry.
    #[serde(deserialize_with = "null_default")]
    pub available_tags: Vec<ForumTag>,
    /// Forum channels: 0 latest activity, 1 creation date.
    pub default_sort_order: Option<u8>,
    /// Forum channels: the reaction offered on every post.
    pub default_reaction_emoji: Option<DefaultReaction>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct DefaultReaction {
    pub emoji_id: Option<Id>,
    pub emoji_name: Option<String>,
}

impl Channel {
    pub const FLAG_PINNED: u32 = 1 << 1;
    pub const FLAG_REQUIRE_TAG: u32 = 1 << 4;
    pub const FLAG_OBFUSCATED: u32 = 1 << 17;

    /// A thread that has been archived (it leaves the channel list).
    pub fn archived(&self) -> bool {
        self.thread_metadata.as_ref().is_some_and(|m| m.archived)
    }
    pub fn locked(&self) -> bool {
        self.thread_metadata.as_ref().is_some_and(|m| m.locked)
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct ThreadMetadata {
    pub archived: bool,
    pub locked: bool,
    pub create_timestamp: Option<String>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct ForumTag {
    pub id: Id,
    pub name: String,
    /// Only moderators may put it on a post.
    #[serde(deserialize_with = "null_default")]
    pub moderated: bool,
    pub emoji_id: Option<Id>,
    pub emoji_name: Option<String>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct PartialMember {
    pub nick: Option<String>,
    pub roles: Vec<Id>,
    pub display_name_styles: Option<DisplayNameStyle>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct Attachment {
    pub id: Id,
    pub filename: String,
    pub url: String,
    pub proxy_url: String,
    pub content_type: Option<String>,
    pub width: Option<u32>,
    pub height: Option<u32>,
    pub size: u64,
    /// Discord's tiny blurred preview of the picture (a base64 ThumbHash), shown while
    /// the real one loads.
    pub placeholder: Option<String>,
    /// The picture's description (alt text), when its sender wrote one.
    #[serde(default)]
    pub description: Option<String>,
}

impl Attachment {
    pub fn is_image(&self) -> bool {
        match &self.content_type {
            Some(ct) => ct.starts_with("image/"),
            None => {
                let f = self.filename.to_ascii_lowercase();
                [".png", ".jpg", ".jpeg", ".gif", ".webp"]
                    .iter()
                    .any(|ext| f.ends_with(ext))
            }
        }
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct EmbedMedia {
    pub url: String,
    pub proxy_url: Option<String>,
    pub width: Option<u32>,
    pub height: Option<u32>,
    /// Discord's tiny blurred preview (a base64 ThumbHash).
    pub placeholder: Option<String>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct EmbedNamed {
    pub name: String,
    pub url: Option<String>,
    pub icon_url: Option<String>,
    pub proxy_icon_url: Option<String>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct EmbedFooter {
    pub text: String,
    pub icon_url: Option<String>,
    pub proxy_icon_url: Option<String>,
}

/// Message components: action rows, buttons and selects, plus the
/// "Components V2" layout pieces (containers, sections, text, media…).
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct Component {
    /// 1 action row, 2 button, 3/5/6/7/8 selects, 9 section, 10 text,
    /// 11 thumbnail, 12 media gallery, 13 file, 14 separator, 17 container.
    #[serde(rename = "type")]
    pub kind: u8,
    pub custom_id: Option<String>,
    /// Buttons: 1 primary, 2 secondary, 3 success, 4 danger, 5 link, 6 premium.
    pub style: Option<u8>,
    pub label: Option<String>,
    pub emoji: Option<ReactionEmoji>,
    pub url: Option<String>,
    pub disabled: bool,
    pub placeholder: Option<String>,
    pub options: Vec<SelectOption>,
    pub components: Vec<Component>,
    /// Text display.
    pub content: Option<String>,
    /// Section's thumbnail or button on the right.
    pub accessory: Option<Box<Component>>,
    /// Thumbnail / file media.
    pub media: Option<UnfurledMedia>,
    pub file: Option<UnfurledMedia>,
    pub items: Vec<MediaItem>,
    pub description: Option<String>,
    /// Separator: draw a line? 1 small / 2 large gap.
    pub divider: Option<bool>,
    pub spacing: Option<u8>,
    /// Container.
    pub accent_color: Option<u32>,
    pub spoiler: bool,
    /// Form (modal) pieces: a text input's (type 4) starting text and
    /// limits, a select's pick limits, and a label's (type 18) one child.
    pub value: Option<String>,
    pub required: Option<bool>,
    pub min_length: Option<u32>,
    pub max_length: Option<u32>,
    pub min_values: Option<u32>,
    pub max_values: Option<u32>,
    pub component: Option<Box<Component>>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct SelectOption {
    pub label: String,
    pub value: String,
    pub description: Option<String>,
    pub emoji: Option<ReactionEmoji>,
    pub default: bool,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct UnfurledMedia {
    pub url: String,
    pub proxy_url: Option<String>,
    pub width: Option<u32>,
    pub height: Option<u32>,
    pub content_type: Option<String>,
}

impl UnfurledMedia {
    pub fn best_url(&self) -> String {
        self.proxy_url.clone().filter(|u| !u.is_empty()).unwrap_or_else(|| self.url.clone())
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct MediaItem {
    pub media: UnfurledMedia,
    pub description: Option<String>,
    pub spoiler: bool,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct EmbedField {
    pub name: String,
    pub value: String,
    pub inline: bool,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct Embed {
    #[serde(rename = "type")]
    pub kind: Option<String>,
    pub title: Option<String>,
    pub description: Option<String>,
    pub url: Option<String>,
    pub color: Option<u32>,
    pub author: Option<EmbedNamed>,
    pub provider: Option<EmbedNamed>,
    pub image: Option<EmbedMedia>,
    pub thumbnail: Option<EmbedMedia>,
    pub video: Option<EmbedMedia>,
    pub fields: Vec<EmbedField>,
    pub footer: Option<EmbedFooter>,
    /// ISO-8601, shown after the footer text.
    pub timestamp: Option<String>,
}

impl Embed {
    /// An actual GIF file among the embed's media, if there is one.
    pub fn gif_url(&self) -> Option<String> {
        [self.image.as_ref(), self.thumbnail.as_ref()].into_iter().flatten().find_map(|m| {
            let path = m.url.split(['?', '#']).next().unwrap_or(&m.url);
            path.ends_with(".gif").then(|| m.proxy_url.clone().unwrap_or_else(|| m.url.clone()))
        })
    }

    /// The clip of a GIF embed (`gifv` is an MP4 that Discord loops),
    /// through Discord's media proxy like the official client.
    pub fn video_url(&self) -> Option<String> {
        let v = self.video.as_ref()?;
        Some(v.proxy_url.clone().filter(|u| !u.is_empty()).unwrap_or_else(|| v.url.clone()))
    }
}

#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct ReactionEmoji {
    /// Set for custom emoji.
    pub id: Option<Id>,
    /// The Unicode emoji, or the custom emoji's name.
    pub name: Option<String>,
    pub animated: bool,
}

impl ReactionEmoji {
    pub fn unicode(s: &str) -> Self {
        Self { id: None, name: Some(s.to_string()), animated: false }
    }

    /// Same emoji? Custom emoji compare by id, Unicode ones by name.
    pub fn same(&self, other: &ReactionEmoji) -> bool {
        match (self.id, other.id) {
            (Some(a), Some(b)) => a == b,
            (None, None) => self.name == other.name,
            _ => false,
        }
    }

    /// Path segment for the reactions endpoint: `name:id` or the
    /// percent-encoded Unicode emoji.
    pub fn api_path(&self) -> String {
        let raw = match self.id {
            Some(id) => format!("{}:{}", self.name.as_deref().unwrap_or("_"), id),
            None => self.name.clone().unwrap_or_default(),
        };
        raw.bytes()
            .map(|b| match b {
                b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b':' => (b as char).to_string(),
                _ => format!("%{b:02X}"),
            })
            .collect()
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct Reaction {
    pub count: u32,
    pub me: bool,
    pub emoji: ReactionEmoji,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct StickerItem {
    pub id: Id,
    pub name: String,
    pub format_type: u8,
}

/// How a message deleted while MessageLogger is active should be drawn.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum DeletedStyle {
    #[default]
    Text,
    Overlay,
}

#[derive(Clone, Debug)]
pub struct PastEdit {
    pub content: String,
    pub timestamp: Option<String>,
}

/// Client-side state attached to a message. Never sent to Discord; Rencord
/// plugins write to it and the UI renders it.
#[derive(Clone, Debug, Default)]
pub struct LocalMeta {
    pub deleted: bool,
    pub deleted_style: DeletedStyle,
    pub edit_history: Vec<PastEdit>,
    pub edits_inline: bool,
    /// Optimistically inserted, waiting for the gateway echo.
    pub pending: bool,
    pub failed: bool,
    /// Number of files being uploaded with this (pending) message.
    pub uploading: usize,
}

/// The call a type-3 system message is about.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct MessageCall {
    pub participants: Vec<Id>,
    /// `None` while the call is still running.
    pub ended_timestamp: Option<String>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct Message {
    pub id: Id,
    pub channel_id: Id,
    pub guild_id: Option<Id>,
    pub author: User,
    pub member: Option<PartialMember>,
    pub content: String,
    /// A DM call's system message (type 3): who took part, and when it ended.
    pub call: Option<MessageCall>,
    pub timestamp: String,
    pub edited_timestamp: Option<String>,
    pub attachments: Vec<Attachment>,
    pub embeds: Vec<Embed>,
    pub mentions: Vec<User>,
    pub mention_roles: Vec<Id>,
    pub mention_everyone: bool,
    pub referenced_message: Option<Box<Message>>,
    #[serde(rename = "type")]
    pub kind: u8,
    pub nonce: Option<Value>,
    pub sticker_items: Vec<StickerItem>,
    pub reactions: Vec<Reaction>,
    pub pinned: bool,
    pub message_reference: Option<IncomingReference>,
    /// Forwarded message contents.
    pub message_snapshots: Vec<MessageSnapshot>,
    /// Buttons, selects and Components V2 layout.
    pub components: Vec<Component>,
    /// The bot that sent it (for button interactions).
    pub application_id: Option<Id>,
    pub webhook_id: Option<Id>,
    pub flags: u64,
    /// "used /command" header on slash-command replies.
    pub interaction_metadata: Option<InteractionMetadata>,
    pub poll: Option<Poll>,
    #[serde(skip)]
    pub meta: LocalMeta,
}

/// A poll on a message: question, answers, and the vote counts so far.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct Poll {
    pub question: PollMedia,
    pub answers: Vec<PollAnswer>,
    /// When voting closes (ISO 8601).
    pub expiry: Option<String>,
    pub allow_multiselect: bool,
    pub layout_type: u8,
    pub results: Option<PollResults>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct PollMedia {
    pub text: Option<String>,
    pub emoji: Option<ReactionEmoji>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct PollAnswer {
    pub answer_id: u32,
    pub poll_media: PollMedia,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct PollResults {
    pub is_finalized: bool,
    pub answer_counts: Vec<PollAnswerCount>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct PollAnswerCount {
    pub id: u32,
    pub count: u32,
    pub me_voted: bool,
}

impl Poll {
    /// (votes, whether you voted) for one answer.
    pub fn votes(&self, answer: u32) -> (u32, bool) {
        self.results
            .as_ref()
            .and_then(|r| r.answer_counts.iter().find(|c| c.id == answer))
            .map_or((0, false), |c| (c.count, c.me_voted))
    }

    pub fn total_votes(&self) -> u32 {
        self.results.as_ref().map_or(0, |r| r.answer_counts.iter().map(|c| c.count).sum())
    }

    pub fn voted(&self) -> bool {
        self.results.as_ref().is_some_and(|r| r.answer_counts.iter().any(|c| c.me_voted))
    }

    pub fn finalized(&self) -> bool {
        self.results.as_ref().is_some_and(|r| r.is_finalized)
    }

    /// A vote came in (or was taken back) over the gateway.
    pub fn apply_vote(&mut self, answer: u32, add: bool, mine: bool) {
        let results = self.results.get_or_insert_with(Default::default);
        let i = match results.answer_counts.iter().position(|c| c.id == answer) {
            Some(i) => i,
            None => {
                results.answer_counts.push(PollAnswerCount { id: answer, count: 0, me_voted: false });
                results.answer_counts.len() - 1
            }
        };
        let c = &mut results.answer_counts[i];
        // Your own vote is applied optimistically; the echo mustn't count twice.
        if mine && c.me_voted == add {
            return;
        }
        c.count = if add { c.count + 1 } else { c.count.saturating_sub(1) };
        if mine {
            c.me_voted = add;
        }
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct InteractionMetadata {
    /// 2 = slash command, 3 = component.
    #[serde(rename = "type")]
    pub kind: u8,
    pub name: Option<String>,
    pub user: Option<User>,
}

impl Message {
    /// Components V2 messages (flag 1 << 15) are laid out entirely by
    /// their components (no content / embeds).
    pub fn is_components_v2(&self) -> bool {
        self.flags & (1 << 15) != 0
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct IncomingReference {
    /// 0 = reply, 1 = forward.
    #[serde(rename = "type")]
    pub kind: u8,
    pub message_id: Option<Id>,
    pub channel_id: Option<Id>,
    pub guild_id: Option<Id>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct MessageSnapshot {
    pub message: Box<Message>,
}

impl Message {
    pub fn is_forward(&self) -> bool {
        self.message_reference.as_ref().is_some_and(|r| r.kind == 1) && !self.message_snapshots.is_empty()
    }

    pub fn link(&self) -> String {
        let guild = self.guild_id.map(|g| g.to_string()).unwrap_or_else(|| "@me".into());
        format!("https://discord.com/channels/{guild}/{}/{}", self.channel_id, self.id)
    }
}

impl Message {
    pub fn display_name(&self) -> &str {
        self.member
            .as_ref()
            .and_then(|m| m.nick.as_deref())
            .filter(|n| !n.is_empty())
            .unwrap_or_else(|| self.author.display_name())
    }

    pub fn nonce_string(&self) -> Option<String> {
        match self.nonce.as_ref()? {
            Value::String(s) => Some(s.clone()),
            Value::Number(n) => Some(n.to_string()),
            _ => None,
        }
    }

    /// Apply a (possibly partial) MESSAGE_UPDATE payload.
    pub fn apply_partial(&mut self, v: &Value) {
        if let Some(c) = v.get("content").and_then(Value::as_str) {
            self.content = c.to_string();
        }
        if let Some(t) = v.get("edited_timestamp") {
            self.edited_timestamp = t.as_str().map(String::from);
        }
        if let Some(a) = v.get("attachments") {
            if let Ok(x) = Vec::<Attachment>::deserialize(a) {
                self.attachments = x;
            }
        }
        if let Some(e) = v.get("embeds") {
            if let Ok(x) = Vec::<Embed>::deserialize(e) {
                self.embeds = x;
            }
        }
        if let Some(p) = v.get("pinned").and_then(Value::as_bool) {
            self.pinned = p;
        }
        if let Some(c) = v.get("components") {
            if let Ok(x) = Vec::<Component>::deserialize(c) {
                self.components = x;
            }
        }
        if let Some(f) = v.get("flags").and_then(Value::as_u64) {
            self.flags = f;
        }
        if let Some(m) = v.get("mentions") {
            if let Ok(x) = Vec::<User>::deserialize(m) {
                self.mentions = x;
            }
        }
    }
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct MessageReference {
    /// 0 = reply, 1 = forward.
    #[serde(rename = "type", skip_serializing_if = "is_zero_u8")]
    pub kind: u8,
    pub message_id: Id,
    pub channel_id: Id,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub guild_id: Option<Id>,
}

fn is_zero_u8(v: &u8) -> bool {
    *v == 0
}

/// A local file to upload with a message.
#[derive(Clone, Debug)]
pub struct Upload {
    pub filename: String,
    pub data: UploadData,
}

/// Where an upload's bytes are: in memory (a pasted picture, a preview
/// already loaded) or still on disk (read while it is sent).
#[derive(Clone, Debug)]
pub enum UploadData {
    Memory(std::sync::Arc<[u8]>),
    Disk(std::path::PathBuf),
}

impl Upload {
    /// The whole file, read now (the demo serves uploads back from memory).
    pub fn read_all(&self) -> std::io::Result<std::sync::Arc<[u8]>> {
        match &self.data {
            UploadData::Memory(b) => Ok(b.clone()),
            UploadData::Disk(p) => std::fs::read(p).map(Into::into),
        }
    }
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct AllowedMentions {
    pub parse: Vec<String>,
    pub replied_user: bool,
}

/// A message about to be sent. Rencord `before_send` hooks may rewrite it.
#[derive(Clone, Debug, Default, Serialize)]
pub struct OutgoingMessage {
    #[serde(skip)]
    pub channel_id: Id,
    pub content: String,
    pub nonce: String,
    pub tts: bool,
    #[serde(skip_serializing_if = "is_zero")]
    pub flags: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message_reference: Option<MessageReference>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allowed_mentions: Option<AllowedMentions>,
    #[serde(skip)]
    pub uploads: Vec<Upload>,
    /// The answer to a captcha Discord demanded for this message, solved by the person.
    #[serde(skip)]
    pub captcha: Option<CaptchaAnswer>,
}

/// A solved captcha, sent back with the request that Discord challenged.
#[derive(Clone, Debug, Default)]
pub struct CaptchaAnswer {
    /// The captcha widget's response.
    pub key: String,
    /// `captcha_rqtoken` and `captcha_session_id` of Discord's challenge.
    pub rqtoken: Option<String>,
    pub session_id: Option<String>,
}

fn is_zero(v: &u64) -> bool {
    *v == 0
}

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

    #[test]
    fn own_vote_echo_counts_once() {
        let mut p = Poll::default();
        p.apply_vote(1, true, true); // optimistic
        p.apply_vote(1, true, true); // gateway echo
        p.apply_vote(1, true, false); // someone else
        assert_eq!(p.votes(1), (2, true));
        p.apply_vote(1, false, true);
        p.apply_vote(1, false, true);
        assert_eq!(p.votes(1), (1, false));
        assert_eq!(p.total_votes(), 1);
    }
}

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

    #[test]
    fn activity_pictures_only_come_through_known_places() {
        let a = Activity { application_id: Some(Id(7)), ..Default::default() };
        assert_eq!(a.asset_url("mp:external/abc/x.png").as_deref(), Some("https://media.discordapp.net/external/abc/x.png"));
        assert_eq!(a.asset_url("123").as_deref(), Some("https://cdn.discordapp.com/app-assets/7/123.png?size=160"));
        assert_eq!(a.asset_url("https://ip-logger.example/pixel.png"), None);
        assert_eq!(a.asset_url("http://ip-logger.example/pixel.png"), None);
    }
}