1use 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
43pub const DEFAULT_CDN: &str = "https://cdn.discordapp.com";
45
46pub const DEFAULT_MEDIA_PROXY: &str = "https://media.discordapp.net";
48
49const STICKER_PACK_APPLICATION: u64 = 710_982_414_301_790_216;
51
52#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
58#[non_exhaustive]
59pub enum ImageFormat {
60 Webp,
62 Png,
64 Jpeg,
66 Gif,
68}
69
70impl ImageFormat {
71 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
89#[non_exhaustive]
90pub enum ImageSize {
91 S16,
93 S32,
95 S64,
97 S128,
99 S256,
101 S512,
103 S1024,
105 S2048,
107 S4096,
109}
110
111impl ImageSize {
112 #[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 #[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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
163#[non_exhaustive]
164#[must_use]
165pub struct ImageOptions {
166 pub format: Option<ImageFormat>,
168 pub size: Option<ImageSize>,
170 pub force_static: bool,
172}
173
174impl ImageOptions {
175 pub const fn new() -> Self {
179 Self {
180 format: None,
181 size: None,
182 force_static: false,
183 }
184 }
185
186 pub const fn format(mut self, format: ImageFormat) -> Self {
190 self.format = Some(format);
191 self
192 }
193
194 pub const fn size(mut self, size: ImageSize) -> Self {
198 self.size = Some(size);
199 self
200 }
201
202 pub const fn force_static(mut self, force_static: bool) -> Self {
206 self.force_static = force_static;
207 self
208 }
209}
210
211#[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#[derive(Clone, Debug, PartialEq, Eq)]
239pub struct Cdn {
240 cdn: String,
241 media_proxy: String,
242}
243
244impl Default for Cdn {
245 fn default() -> Self {
247 Self::new(DEFAULT_CDN, DEFAULT_MEDIA_PROXY)
248 }
249}
250
251impl Cdn {
252 #[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 #[must_use]
272 pub fn base(&self) -> &str {
273 &self.cdn
274 }
275
276 #[must_use]
280 pub fn media_proxy(&self) -> &str {
281 &self.media_proxy
282 }
283
284 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[must_use]
582 pub fn soundboard_sound(&self, sound_id: SoundboardSoundId) -> String {
583 format!("{}/soundboard-sounds/{sound_id}", self.cdn)
584 }
585
586 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 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 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 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 #[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 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 let user = UserId::new(80_351_110_224_678_912);
791 assert_eq!(default_avatar_index(user, 0), 5);
792 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}