Skip to main content

djs_rest/
cdn.rs

1//! [CDN](https://docs.discord.com/developers/reference#image-formatting) URLs of avatars,
2//! icons, banners, emojis, stickers and other images (D-137).
3//!
4//! A [`Cdn`] knows the base URLs; [`Rest::cdn`](crate::Rest::cdn) returns the client's, and
5//! [`Cdn::default`] works without a client. Every method returns the URL as a `String`; none
6//! can fail, since formats and sizes are enums (D-139).
7//!
8//! Without an explicit [`format`](ImageOptions::format), images are WebP, and animated ones
9//! (hashes starting with `a_`) are animated WebP (`.webp?animated=true`, D-138).
10//!
11//! discord.js counterpart: `CDN` of @discordjs/rest (`REST#cdn`).
12//!
13//! # Examples
14//!
15//! ```
16//! use djs_model::{id::UserId, util::ImageHash};
17//! use djs_rest::cdn::{Cdn, ImageFormat, ImageOptions, ImageSize};
18//!
19//! let cdn = Cdn::default();
20//! let hash: ImageHash = "a_1269e74af4df7417b13759eae50c83dc".parse()?;
21//! assert_eq!(
22//!     cdn.user_avatar(UserId::new(7), hash, ImageOptions::new().size(ImageSize::S256)),
23//!     "https://cdn.discordapp.com/avatars/7/a_1269e74af4df7417b13759eae50c83dc.webp?animated=true&size=256"
24//! );
25//! assert_eq!(
26//!     cdn.user_avatar(UserId::new(7), hash, ImageOptions::new().format(ImageFormat::Png)),
27//!     "https://cdn.discordapp.com/avatars/7/a_1269e74af4df7417b13759eae50c83dc.png"
28//! );
29//! # Ok::<(), djs_model::util::ParseImageHashError>(())
30//! ```
31
32use core::fmt::{self, Write as _};
33
34use djs_model::{
35    id::{
36        ApplicationId, ChannelId, EmojiId, GenericId, GuildId, RoleId, ScheduledEventId,
37        SoundboardSoundId, StickerId, TeamId, UserId,
38    },
39    sticker::StickerFormatType,
40    util::ImageHash,
41};
42
43/// The default CDN base URL.
44pub const DEFAULT_CDN: &str = "https://cdn.discordapp.com";
45
46/// The default media proxy base URL (GIF stickers are served from there).
47pub const DEFAULT_MEDIA_PROXY: &str = "https://media.discordapp.net";
48
49/// The application that owns the sticker pack banners (from Discord's docs).
50const STICKER_PACK_APPLICATION: u64 = 710_982_414_301_790_216;
51
52/// An [image format](https://docs.discord.com/developers/reference#image-formatting-image-formats)
53/// (the file extension of the URL, D-139). Which formats an endpoint supports is listed on its
54/// method; GIF is only animated for animated hashes.
55///
56/// discord.js counterpart: `ImageFormat` (discord-api-types).
57#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
58#[non_exhaustive]
59pub enum ImageFormat {
60    /// `.webp`, the default (D-138).
61    Webp,
62    /// `.png`.
63    Png,
64    /// `.jpg`.
65    Jpeg,
66    /// `.gif`.
67    Gif,
68}
69
70impl ImageFormat {
71    /// The file extension, without the dot.
72    ///
73    /// discord.js counterpart: the `extension` of `ImageURLOptions` (`@discordjs/rest`).
74    #[must_use]
75    pub const fn extension(self) -> &'static str {
76        match self {
77            Self::Webp => "webp",
78            Self::Png => "png",
79            Self::Jpeg => "jpg",
80            Self::Gif => "gif",
81        }
82    }
83}
84
85/// The size of an image: a power of two from 16 to 4096 pixels (D-139).
86///
87/// discord.js counterpart: `ImageSize` (discord-api-types).
88#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
89#[non_exhaustive]
90pub enum ImageSize {
91    /// 16 pixels.
92    S16,
93    /// 32 pixels.
94    S32,
95    /// 64 pixels.
96    S64,
97    /// 128 pixels.
98    S128,
99    /// 256 pixels.
100    S256,
101    /// 512 pixels.
102    S512,
103    /// 1024 pixels.
104    S1024,
105    /// 2048 pixels.
106    S2048,
107    /// 4096 pixels.
108    S4096,
109}
110
111impl ImageSize {
112    /// The size in pixels.
113    ///
114    /// discord.js counterpart: the `size` of `ImageURLOptions` (`@discordjs/rest`).
115    #[must_use]
116    pub const fn pixels(self) -> u16 {
117        match self {
118            Self::S16 => 16,
119            Self::S32 => 32,
120            Self::S64 => 64,
121            Self::S128 => 128,
122            Self::S256 => 256,
123            Self::S512 => 512,
124            Self::S1024 => 1024,
125            Self::S2048 => 2048,
126            Self::S4096 => 4096,
127        }
128    }
129
130    /// The size for `pixels`, if it is a power of two from 16 to 4096.
131    ///
132    /// discord.js counterpart: the `size` of `ImageURLOptions` (`@discordjs/rest`).
133    ///
134    /// # Examples
135    ///
136    /// ```
137    /// use djs_rest::cdn::ImageSize;
138    ///
139    /// assert_eq!(ImageSize::from_pixels(512), Some(ImageSize::S512));
140    /// assert_eq!(ImageSize::from_pixels(500), None);
141    /// ```
142    #[must_use]
143    pub const fn from_pixels(pixels: u16) -> Option<Self> {
144        Some(match pixels {
145            16 => Self::S16,
146            32 => Self::S32,
147            64 => Self::S64,
148            128 => Self::S128,
149            256 => Self::S256,
150            512 => Self::S512,
151            1024 => Self::S1024,
152            2048 => Self::S2048,
153            4096 => Self::S4096,
154            _ => return None,
155        })
156    }
157}
158
159/// The format and size of an image URL.
160///
161/// discord.js counterpart: `ImageURLOptions` (`@discordjs/rest`).
162#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
163#[non_exhaustive]
164#[must_use]
165pub struct ImageOptions {
166    /// The format; `None` is WebP, animated for animated images (D-138).
167    pub format: Option<ImageFormat>,
168    /// The size; `None` lets Discord pick the original size.
169    pub size: Option<ImageSize>,
170    /// Whether animated images are returned as a still image.
171    pub force_static: bool,
172}
173
174impl ImageOptions {
175    /// The default options: WebP (animated when the image is), original size.
176    ///
177    /// discord.js counterpart: `ImageURLOptions` (`@discordjs/rest`).
178    pub const fn new() -> Self {
179        Self {
180            format: None,
181            size: None,
182            force_static: false,
183        }
184    }
185
186    /// Sets the format.
187    ///
188    /// discord.js counterpart: the `extension` of `ImageURLOptions` (`@discordjs/rest`).
189    pub const fn format(mut self, format: ImageFormat) -> Self {
190        self.format = Some(format);
191        self
192    }
193
194    /// Sets the size.
195    ///
196    /// discord.js counterpart: the `size` of `ImageURLOptions` (`@discordjs/rest`).
197    pub const fn size(mut self, size: ImageSize) -> Self {
198        self.size = Some(size);
199        self
200    }
201
202    /// Returns a still image even for an animated one.
203    ///
204    /// discord.js counterpart: the `forceStatic` of `ImageURLOptions` (`@discordjs/rest`).
205    pub const fn force_static(mut self, force_static: bool) -> Self {
206        self.force_static = force_static;
207        self
208    }
209}
210
211/// The index of the [default avatar](https://docs.discord.com/developers/reference#image-formatting-cdn-endpoints)
212/// of a user without one: `(user_id >> 22) % 6` for users on the new username system
213/// (discriminator `0`), `discriminator % 5` for the others.
214///
215/// discord.js counterpart: the index `User#defaultAvatarURL` uses.
216///
217/// # Examples
218///
219/// ```
220/// use djs_model::id::UserId;
221/// use djs_rest::cdn::default_avatar_index;
222///
223/// assert_eq!(default_avatar_index(UserId::new(80_351_110_224_678_912), 1337), 2);
224/// assert_eq!(default_avatar_index(UserId::new(80_351_110_224_678_912), 0), 5);
225/// ```
226#[must_use]
227pub const fn default_avatar_index(user_id: UserId, discriminator: u16) -> u8 {
228    if discriminator == 0 {
229        ((user_id.get() >> 22) % 6) as u8
230    } else {
231        (discriminator % 5) as u8
232    }
233}
234
235/// Builds CDN URLs (D-137). See the [module](self) documentation.
236///
237/// discord.js counterpart: `CDN` (`@discordjs/rest`).
238#[derive(Clone, Debug, PartialEq, Eq)]
239pub struct Cdn {
240    cdn: String,
241    media_proxy: String,
242}
243
244impl Default for Cdn {
245    /// Discord's CDN and media proxy.
246    fn default() -> Self {
247        Self::new(DEFAULT_CDN, DEFAULT_MEDIA_PROXY)
248    }
249}
250
251impl Cdn {
252    /// A CDN with other base URLs (e.g. a proxy). Trailing slashes are ignored.
253    ///
254    /// discord.js counterpart: `new CDN(cdn, mediaProxy)` (`@discordjs/rest`).
255    #[must_use]
256    pub fn new(cdn: impl Into<String>, media_proxy: impl Into<String>) -> Self {
257        let trim = |mut url: String| {
258            let len = url.trim_end_matches('/').len();
259            url.truncate(len);
260            url
261        };
262        Self {
263            cdn: trim(cdn.into()),
264            media_proxy: trim(media_proxy.into()),
265        }
266    }
267
268    /// The CDN base URL.
269    ///
270    /// discord.js counterpart: the `cdn` option of `RESTOptions` (`@discordjs/rest`).
271    #[must_use]
272    pub fn base(&self) -> &str {
273        &self.cdn
274    }
275
276    /// The media proxy base URL.
277    ///
278    /// discord.js counterpart: the `mediaProxy` option of `RESTOptions` (`@discordjs/rest`).
279    #[must_use]
280    pub fn media_proxy(&self) -> &str {
281        &self.media_proxy
282    }
283
284    /// A custom emoji (PNG, JPEG, WebP, GIF). Emojis have no hash, so pass whether the emoji
285    /// is [`animated`](djs_model::emoji::Emoji::animated). Discord recommends WebP for emojis.
286    ///
287    /// discord.js counterpart: `CDN#emoji`.
288    #[must_use]
289    pub fn emoji(&self, emoji_id: EmojiId, animated: bool, options: ImageOptions) -> String {
290        self.image(format_args!("emojis/{emoji_id}"), animated, options)
291    }
292
293    /// A guild's icon (PNG, JPEG, WebP, GIF).
294    ///
295    /// discord.js counterpart: `CDN#icon`, `Guild#iconURL`.
296    #[must_use]
297    pub fn guild_icon(&self, guild_id: GuildId, hash: ImageHash, options: ImageOptions) -> String {
298        self.hashed(format_args!("icons/{guild_id}"), hash, options)
299    }
300
301    /// A guild's invite splash (PNG, JPEG, WebP).
302    ///
303    /// discord.js counterpart: `CDN#splash`, `Guild#splashURL`.
304    #[must_use]
305    pub fn guild_splash(
306        &self,
307        guild_id: GuildId,
308        hash: ImageHash,
309        options: ImageOptions,
310    ) -> String {
311        self.hashed(format_args!("splashes/{guild_id}"), hash, options)
312    }
313
314    /// A guild's discovery splash (PNG, JPEG, WebP).
315    ///
316    /// discord.js counterpart: `CDN#discoverySplash`, `Guild#discoverySplashURL`.
317    #[must_use]
318    pub fn guild_discovery_splash(
319        &self,
320        guild_id: GuildId,
321        hash: ImageHash,
322        options: ImageOptions,
323    ) -> String {
324        self.hashed(format_args!("discovery-splashes/{guild_id}"), hash, options)
325    }
326
327    /// A guild's banner (PNG, JPEG, WebP, GIF).
328    ///
329    /// discord.js counterpart: `CDN#banner`, `Guild#bannerURL`.
330    #[must_use]
331    pub fn guild_banner(
332        &self,
333        guild_id: GuildId,
334        hash: ImageHash,
335        options: ImageOptions,
336    ) -> String {
337        self.hashed(format_args!("banners/{guild_id}"), hash, options)
338    }
339
340    /// A user's profile banner (PNG, JPEG, WebP, GIF).
341    ///
342    /// discord.js counterpart: `CDN#banner`, `User#bannerURL`.
343    #[must_use]
344    pub fn user_banner(&self, user_id: UserId, hash: ImageHash, options: ImageOptions) -> String {
345        self.hashed(format_args!("banners/{user_id}"), hash, options)
346    }
347
348    /// The default avatar `index` (0-5, see [`default_avatar_index`]) of users without one
349    /// (always PNG of a fixed size).
350    ///
351    /// discord.js counterpart: `CDN#defaultAvatar`, `User#defaultAvatarURL`.
352    #[must_use]
353    pub fn default_user_avatar(&self, index: u8) -> String {
354        Self::fixed(&self.cdn, format_args!("embed/avatars/{index}"), "png")
355    }
356
357    /// A user's avatar (PNG, JPEG, WebP, GIF).
358    ///
359    /// discord.js counterpart: `CDN#avatar`, `User#avatarURL`.
360    #[must_use]
361    pub fn user_avatar(&self, user_id: UserId, hash: ImageHash, options: ImageOptions) -> String {
362        self.hashed(format_args!("avatars/{user_id}"), hash, options)
363    }
364
365    /// A member's guild-specific avatar (PNG, JPEG, WebP, GIF).
366    ///
367    /// discord.js counterpart: `CDN#guildMemberAvatar`, `GuildMember#avatarURL`.
368    #[must_use]
369    pub fn guild_member_avatar(
370        &self,
371        guild_id: GuildId,
372        user_id: UserId,
373        hash: ImageHash,
374        options: ImageOptions,
375    ) -> String {
376        self.hashed(
377            format_args!("guilds/{guild_id}/users/{user_id}/avatars"),
378            hash,
379            options,
380        )
381    }
382
383    /// A member's guild-specific banner (PNG, JPEG, WebP, GIF).
384    ///
385    /// discord.js counterpart: `CDN#guildMemberBanner`, `GuildMember#bannerURL`.
386    #[must_use]
387    pub fn guild_member_banner(
388        &self,
389        guild_id: GuildId,
390        user_id: UserId,
391        hash: ImageHash,
392        options: ImageOptions,
393    ) -> String {
394        self.hashed(
395            format_args!("guilds/{guild_id}/users/{user_id}/banners"),
396            hash,
397            options,
398        )
399    }
400
401    /// An avatar decoration, from its [`asset`](djs_model::user::AvatarDecorationData::asset)
402    /// (always PNG).
403    ///
404    /// discord.js counterpart: `CDN#avatarDecoration`, `User#avatarDecorationURL`.
405    #[must_use]
406    pub fn avatar_decoration(&self, asset: ImageHash) -> String {
407        Self::fixed(
408            &self.cdn,
409            format_args!("avatar-decoration-presets/{asset}"),
410            "png",
411        )
412    }
413
414    /// An application's icon (PNG, JPEG, WebP).
415    ///
416    /// discord.js counterpart: `CDN#appIcon`, `Application#iconURL`.
417    #[must_use]
418    pub fn application_icon(
419        &self,
420        application_id: ApplicationId,
421        hash: ImageHash,
422        options: ImageOptions,
423    ) -> String {
424        self.hashed(format_args!("app-icons/{application_id}"), hash, options)
425    }
426
427    /// An application's default rich presence invite cover (PNG, JPEG, WebP).
428    ///
429    /// discord.js counterpart: `CDN#appIcon`, `Application#coverURL`.
430    #[must_use]
431    pub fn application_cover(
432        &self,
433        application_id: ApplicationId,
434        hash: ImageHash,
435        options: ImageOptions,
436    ) -> String {
437        self.hashed(format_args!("app-icons/{application_id}"), hash, options)
438    }
439
440    /// An application's rich presence asset, e.g. an activity's `large_image` (PNG, JPEG,
441    /// WebP).
442    ///
443    /// discord.js counterpart: `CDN#appAsset`, `RichPresenceAssets#largeImageURL`.
444    #[must_use]
445    pub fn application_asset(
446        &self,
447        application_id: ApplicationId,
448        asset_id: &str,
449        options: ImageOptions,
450    ) -> String {
451        self.image(
452            format_args!("app-assets/{application_id}/{asset_id}"),
453            false,
454            options,
455        )
456    }
457
458    /// An achievement's icon (PNG, JPEG, WebP).
459    ///
460    /// discord.js counterpart: none.
461    #[must_use]
462    pub fn achievement_icon(
463        &self,
464        application_id: ApplicationId,
465        achievement_id: GenericId,
466        hash: ImageHash,
467        options: ImageOptions,
468    ) -> String {
469        self.hashed(
470            format_args!("app-assets/{application_id}/achievements/{achievement_id}/icons"),
471            hash,
472            options,
473        )
474    }
475
476    /// An asset of an application's store page (PNG, JPEG, WebP).
477    ///
478    /// discord.js counterpart: none.
479    #[must_use]
480    pub fn store_page_asset(
481        &self,
482        application_id: ApplicationId,
483        asset_id: GenericId,
484        options: ImageOptions,
485    ) -> String {
486        self.image(
487            format_args!("app-assets/{application_id}/store/{asset_id}"),
488            false,
489            options,
490        )
491    }
492
493    /// A sticker pack's banner, from its
494    /// [`banner_asset_id`](djs_model::sticker::StickerPack::banner_asset_id) (PNG, JPEG,
495    /// WebP).
496    ///
497    /// discord.js counterpart: `CDN#stickerPackBanner`, `StickerPack#bannerURL`.
498    #[must_use]
499    pub fn sticker_pack_banner(&self, banner_asset_id: GenericId, options: ImageOptions) -> String {
500        self.image(
501            format_args!("app-assets/{STICKER_PACK_APPLICATION}/store/{banner_asset_id}"),
502            false,
503            options,
504        )
505    }
506
507    /// A team's icon (PNG, JPEG, WebP).
508    ///
509    /// discord.js counterpart: `CDN#teamIcon`, `Team#iconURL`.
510    #[must_use]
511    pub fn team_icon(&self, team_id: TeamId, hash: ImageHash, options: ImageOptions) -> String {
512        self.hashed(format_args!("team-icons/{team_id}"), hash, options)
513    }
514
515    /// A sticker, in the format its `format_type` is served in (fixed size): PNG for PNG and
516    /// APNG stickers, Lottie JSON for Lottie ones, and GIF — from the media proxy — for GIF
517    /// ones.
518    ///
519    /// discord.js counterpart: `CDN#sticker`, `Sticker#url`.
520    #[must_use]
521    pub fn sticker(&self, sticker_id: StickerId, format_type: StickerFormatType) -> String {
522        let path = format_args!("stickers/{sticker_id}");
523        match format_type {
524            StickerFormatType::Gif => Self::fixed(&self.media_proxy, path, "gif"),
525            StickerFormatType::Lottie => Self::fixed(&self.cdn, path, "json"),
526            _ => Self::fixed(&self.cdn, path, "png"),
527        }
528    }
529
530    /// A role's icon (PNG, JPEG, WebP).
531    ///
532    /// discord.js counterpart: `CDN#roleIcon`, `Role#iconURL`.
533    #[must_use]
534    pub fn role_icon(&self, role_id: RoleId, hash: ImageHash, options: ImageOptions) -> String {
535        self.hashed(format_args!("role-icons/{role_id}"), hash, options)
536    }
537
538    /// A scheduled event's cover image (PNG, JPEG, WebP).
539    ///
540    /// discord.js counterpart: `CDN#guildScheduledEventCover`, `GuildScheduledEvent#coverImageURL`.
541    #[must_use]
542    pub fn guild_scheduled_event_cover(
543        &self,
544        event_id: ScheduledEventId,
545        hash: ImageHash,
546        options: ImageOptions,
547    ) -> String {
548        self.hashed(format_args!("guild-events/{event_id}"), hash, options)
549    }
550
551    /// A guild's server tag badge, from a user's
552    /// [`primary_guild`](djs_model::user::PrimaryGuild::badge) (PNG, JPEG, WebP).
553    ///
554    /// discord.js counterpart: `CDN#guildTagBadge`.
555    #[must_use]
556    pub fn guild_tag_badge(
557        &self,
558        guild_id: GuildId,
559        hash: ImageHash,
560        options: ImageOptions,
561    ) -> String {
562        self.hashed(format_args!("guild-tag-badges/{guild_id}"), hash, options)
563    }
564
565    /// A group DM's icon (PNG, JPEG, WebP). Not in Discord's table; the path discord.js uses.
566    ///
567    /// discord.js counterpart: `CDN#channelIcon`, `GroupDMChannel#iconURL`.
568    #[must_use]
569    pub fn channel_icon(
570        &self,
571        channel_id: ChannelId,
572        hash: ImageHash,
573        options: ImageOptions,
574    ) -> String {
575        self.hashed(format_args!("channel-icons/{channel_id}"), hash, options)
576    }
577
578    /// A soundboard sound's audio file (no extension; Discord serves MP3 or Ogg).
579    ///
580    /// discord.js counterpart: `CDN#soundboardSound`, `SoundboardSound#url`.
581    #[must_use]
582    pub fn soundboard_sound(&self, sound_id: SoundboardSoundId) -> String {
583        format!("{}/soundboard-sounds/{sound_id}", self.cdn)
584    }
585
586    /// An image at `path` + `/hash`, animated when the hash is.
587    fn hashed(&self, path: fmt::Arguments<'_>, hash: ImageHash, options: ImageOptions) -> String {
588        self.image(format_args!("{path}/{hash}"), hash.is_animated(), options)
589    }
590
591    /// An image at `path` with the format and size of `options` (D-138).
592    fn image(&self, path: fmt::Arguments<'_>, animated: bool, options: ImageOptions) -> String {
593        let animated = animated && !options.force_static;
594        let format = options.format.unwrap_or(ImageFormat::Webp);
595        let mut url = String::with_capacity(self.cdn.len() + 96);
596        // Writing to a `String` cannot fail.
597        let _ = write!(url, "{}/{path}.{}", self.cdn, format.extension());
598        let mut separator = '?';
599        if animated && format == ImageFormat::Webp {
600            url.push_str("?animated=true");
601            separator = '&';
602        }
603        if let Some(size) = options.size {
604            let _ = write!(url, "{separator}size={}", size.pixels());
605        }
606        url
607    }
608
609    /// An image of a fixed format and size.
610    fn fixed(base: &str, path: fmt::Arguments<'_>, extension: &str) -> String {
611        format!("{base}/{path}.{extension}")
612    }
613}
614
615#[cfg(test)]
616mod tests {
617    use super::*;
618
619    const STATIC: &str = "1269e74af4df7417b13759eae50c83dc";
620    const ANIMATED: &str = "a_1269e74af4df7417b13759eae50c83dc";
621
622    fn hash(value: &str) -> ImageHash {
623        value.parse().unwrap()
624    }
625
626    #[test]
627    fn formats_and_animation() {
628        let cdn = Cdn::default();
629        let guild = GuildId::new(1);
630        let icon = |value, options| cdn.guild_icon(guild, hash(value), options);
631        let base = "https://cdn.discordapp.com/icons/1";
632        assert_eq!(
633            icon(STATIC, ImageOptions::new()),
634            format!("{base}/{STATIC}.webp")
635        );
636        assert_eq!(
637            icon(ANIMATED, ImageOptions::new()),
638            format!("{base}/{ANIMATED}.webp?animated=true")
639        );
640        assert_eq!(
641            icon(
642                ANIMATED,
643                ImageOptions::new().force_static(true).size(ImageSize::S64)
644            ),
645            format!("{base}/{ANIMATED}.webp?size=64")
646        );
647        assert_eq!(
648            icon(ANIMATED, ImageOptions::new().format(ImageFormat::Gif)),
649            format!("{base}/{ANIMATED}.gif")
650        );
651        assert_eq!(
652            icon(STATIC, ImageOptions::new().format(ImageFormat::Jpeg)),
653            format!("{base}/{STATIC}.jpg")
654        );
655        assert_eq!(
656            cdn.emoji(
657                EmojiId::new(9),
658                true,
659                ImageOptions::new().size(ImageSize::S4096)
660            ),
661            "https://cdn.discordapp.com/emojis/9.webp?animated=true&size=4096"
662        );
663    }
664
665    #[test]
666    fn fixed_urls_and_bases() {
667        let cdn = Cdn::new("https://cdn.example.com/", "https://media.example.com");
668        assert_eq!(
669            cdn.default_user_avatar(3),
670            "https://cdn.example.com/embed/avatars/3.png"
671        );
672        assert_eq!(
673            cdn.sticker(StickerId::new(5), StickerFormatType::Gif),
674            "https://media.example.com/stickers/5.gif"
675        );
676        assert_eq!(
677            cdn.sticker(StickerId::new(5), StickerFormatType::Lottie),
678            "https://cdn.example.com/stickers/5.json"
679        );
680        assert_eq!(
681            cdn.sticker(StickerId::new(5), StickerFormatType::Apng),
682            "https://cdn.example.com/stickers/5.png"
683        );
684        assert_eq!(
685            cdn.sticker_pack_banner(GenericId::new(8), ImageOptions::new()),
686            "https://cdn.example.com/app-assets/710982414301790216/store/8.webp"
687        );
688        assert_eq!(
689            cdn.soundboard_sound(SoundboardSoundId::new(4)),
690            "https://cdn.example.com/soundboard-sounds/4"
691        );
692        assert_eq!(
693            cdn.guild_member_avatar(
694                GuildId::new(1),
695                UserId::new(2),
696                hash(STATIC),
697                ImageOptions::new().format(ImageFormat::Png)
698            ),
699            format!("https://cdn.example.com/guilds/1/users/2/avatars/{STATIC}.png")
700        );
701    }
702
703    /// Every hashed asset at the path of the docs' table of CDN endpoints (and the channel
704    /// icon, which the table leaves out).
705    #[test]
706    fn every_endpoint_has_the_docs_path() {
707        let cdn = Cdn::default();
708        let (id, other) = (1, 2);
709        let options = ImageOptions::new().format(ImageFormat::Png);
710        let hash = hash(STATIC);
711        let urls = [
712            (cdn.guild_icon(GuildId::new(id), hash, options), "icons/1"),
713            (
714                cdn.guild_splash(GuildId::new(id), hash, options),
715                "splashes/1",
716            ),
717            (
718                cdn.guild_discovery_splash(GuildId::new(id), hash, options),
719                "discovery-splashes/1",
720            ),
721            (
722                cdn.guild_banner(GuildId::new(id), hash, options),
723                "banners/1",
724            ),
725            (cdn.user_banner(UserId::new(id), hash, options), "banners/1"),
726            (cdn.user_avatar(UserId::new(id), hash, options), "avatars/1"),
727            (
728                cdn.guild_member_banner(GuildId::new(id), UserId::new(other), hash, options),
729                "guilds/1/users/2/banners",
730            ),
731            (
732                cdn.application_icon(ApplicationId::new(id), hash, options),
733                "app-icons/1",
734            ),
735            (
736                cdn.application_cover(ApplicationId::new(id), hash, options),
737                "app-icons/1",
738            ),
739            (
740                cdn.achievement_icon(ApplicationId::new(id), GenericId::new(other), hash, options),
741                "app-assets/1/achievements/2/icons",
742            ),
743            (
744                cdn.team_icon(TeamId::new(id), hash, options),
745                "team-icons/1",
746            ),
747            (
748                cdn.role_icon(RoleId::new(id), hash, options),
749                "role-icons/1",
750            ),
751            (
752                cdn.guild_scheduled_event_cover(ScheduledEventId::new(id), hash, options),
753                "guild-events/1",
754            ),
755            (
756                cdn.guild_tag_badge(GuildId::new(id), hash, options),
757                "guild-tag-badges/1",
758            ),
759            (
760                cdn.channel_icon(ChannelId::new(id), hash, options),
761                "channel-icons/1",
762            ),
763        ];
764        for (url, path) in urls {
765            assert_eq!(
766                url,
767                format!("https://cdn.discordapp.com/{path}/{STATIC}.png")
768            );
769        }
770        // Assets named by an ID or a key, never animated.
771        assert_eq!(
772            cdn.application_asset(ApplicationId::new(id), "large", options),
773            "https://cdn.discordapp.com/app-assets/1/large.png"
774        );
775        assert_eq!(
776            cdn.store_page_asset(ApplicationId::new(id), GenericId::new(other), options),
777            "https://cdn.discordapp.com/app-assets/1/store/2.png"
778        );
779        assert_eq!(
780            cdn.avatar_decoration(hash),
781            format!("https://cdn.discordapp.com/avatar-decoration-presets/{STATIC}.png")
782        );
783        assert_eq!(cdn.base(), "https://cdn.discordapp.com");
784        assert_eq!(cdn.media_proxy(), "https://media.discordapp.net");
785    }
786
787    #[test]
788    fn default_avatars_follow_the_discriminator_or_the_id() {
789        // Pomelo usernames (no discriminator): the ID's timestamp bits, modulo 6.
790        let user = UserId::new(80_351_110_224_678_912);
791        assert_eq!(default_avatar_index(user, 0), 5);
792        // Legacy discriminators, modulo 5.
793        assert_eq!(default_avatar_index(user, 1337), 2);
794        assert_eq!(default_avatar_index(user, 5), 0);
795        assert!((1..10_000).all(|discriminator| default_avatar_index(user, discriminator) < 5));
796    }
797
798    #[test]
799    fn sizes_round_trip() {
800        for pixels in [16, 32, 64, 128, 256, 512, 1024, 2048, 4096] {
801            assert_eq!(ImageSize::from_pixels(pixels).unwrap().pixels(), pixels);
802        }
803        assert_eq!(ImageSize::from_pixels(0), None);
804        assert_eq!(ImageSize::from_pixels(8192), None);
805    }
806}