Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(cache,model)!: parse image hashes #1405

Merged
merged 18 commits into from
Jan 1, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions cache/in-memory/src/event/guild.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,11 +181,11 @@ impl UpdateCache for GuildUpdate {
if let Some(mut guild) = cache.guilds.get_mut(&self.0.id) {
guild.afk_channel_id = self.afk_channel_id;
guild.afk_timeout = self.afk_timeout;
guild.banner = self.banner.clone();
guild.banner = self.banner;
guild.default_message_notifications = self.default_message_notifications;
guild.description = self.description.clone();
guild.features = self.features.clone();
guild.icon = self.icon.clone();
guild.icon = self.icon;
guild.max_members = self.max_members;
guild.max_presences = Some(self.max_presences.unwrap_or(25000));
guild.mfa_level = self.mfa_level;
Expand All @@ -199,7 +199,7 @@ impl UpdateCache for GuildUpdate {
guild
.premium_subscription_count
.replace(self.premium_subscription_count.unwrap_or_default());
guild.splash = self.splash.clone();
guild.splash = self.splash;
guild.system_channel_id = self.system_channel_id;
guild.verification_level = self.verification_level;
guild.vanity_url_code = self.vanity_url_code.clone();
Expand Down
19 changes: 13 additions & 6 deletions cache/in-memory/src/event/interaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,18 @@ mod tests {
guild::{PartialMember, Permissions, Role},
id::Id,
user::User,
util::{image_hash::ImageHashParseError, ImageHash},
};

#[test]
fn test_interaction_create() {
fn test_interaction_create() -> Result<(), ImageHashParseError> {
let timestamp = Timestamp::from_secs(1_632_072_645).expect("non zero");
// let avatar1 = ImageHash::parse(b"1ef6bca4fddaa303a9cd32dd70fb395d")?;
let avatar2 = ImageHash::parse(b"3a43231a99f4dfcf0fd94d1d8defd301")?;
let avatar3 = ImageHash::parse(b"5e23c298295ad37936cfe24ad314774f")?;

let cache = InMemoryCache::new();

cache.update(&InteractionCreate(Interaction::ApplicationCommand(
Box::new(ApplicationCommand {
application_id: Id::new(1).expect("non zero"),
Expand Down Expand Up @@ -121,7 +126,7 @@ mod tests {
attachments: Vec::new(),
author: User {
accent_color: None,
avatar: Some("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_owned()),
avatar: Some(avatar3),
banner: None,
bot: false,
discriminator: 1,
Expand Down Expand Up @@ -199,7 +204,7 @@ mod tests {
Id::new(7).expect("non zero"),
User {
accent_color: None,
avatar: Some("different avatar".into()),
avatar: Some(avatar2),
banner: None,
bot: false,
discriminator: 5678,
Expand Down Expand Up @@ -233,7 +238,7 @@ mod tests {
roles: Vec::new(),
user: Some(User {
accent_color: None,
avatar: Some("avatar string".into()),
avatar: Some(avatar3),
banner: None,
bot: false,
discriminator: 1234,
Expand Down Expand Up @@ -264,20 +269,22 @@ mod tests {
.member(Id::new(3).expect("non zero"), Id::new(6).expect("non zero"))
.unwrap();
let user = cache.user(member.user_id).unwrap();
assert_eq!(user.avatar.as_ref().unwrap(), "avatar string");
assert_eq!(user.avatar.as_ref().unwrap(), &avatar3);
}

{
let member = cache
.member(Id::new(3).expect("non zero"), Id::new(7).expect("non zero"))
.unwrap();
let user = cache.user(member.user_id).unwrap();
assert_eq!(user.avatar.as_ref().unwrap(), "different avatar");
assert_eq!(user.avatar.as_ref().unwrap(), &avatar2);
}

{
let guild_roles = cache.guild_roles(Id::new(3).expect("non zero")).unwrap();
assert_eq!(guild_roles.len(), 1);
}

Ok(())
}
}
4 changes: 2 additions & 2 deletions cache/in-memory/src/event/member.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ impl InMemoryCache {

let (avatar, deaf, mute) = match self.members.get(&id) {
Some(m) if &*m == member => return,
Some(m) => (m.avatar().map(ToString::to_string), m.deaf(), m.mute()),
Some(m) => (m.avatar(), m.deaf(), m.mute()),
None => (None, None, None),
};

Expand Down Expand Up @@ -197,7 +197,7 @@ impl UpdateCache for MemberUpdate {
None => return,
};

member.avatar = self.avatar.clone();
member.avatar = self.avatar;
member.deaf = self.deaf.or_else(|| member.deaf());
member.mute = self.mute.or_else(|| member.mute());
member.nick = self.nick.clone();
Expand Down
9 changes: 7 additions & 2 deletions cache/in-memory/src/event/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,23 +137,26 @@ mod tests {
guild::PartialMember,
id::Id,
user::User,
util::{image_hash::ImageHashParseError, ImageHash},
};

#[test]
fn test_message_create() {
fn test_message_create() -> Result<(), ImageHashParseError> {
let joined_at = Timestamp::from_secs(1_632_072_645).expect("non zero");
let cache = InMemoryCache::builder()
.resource_types(ResourceType::MESSAGE | ResourceType::MEMBER | ResourceType::USER)
.message_cache_size(1)
.build();

let avatar = ImageHash::parse(b"e91c75bc7656063cc745f4e79d0b7664")?;
let mut msg = Message {
activity: None,
application: None,
application_id: None,
attachments: Vec::new(),
author: User {
accent_color: None,
avatar: Some("".to_owned()),
avatar: Some(avatar),
banner: None,
bot: false,
discriminator: 1,
Expand Down Expand Up @@ -239,5 +242,7 @@ mod tests {
assert_eq!(Some(5), iter.next().map(Id::get));
assert_eq!(Some(4), iter.next().map(Id::get));
assert!(iter.next().is_none());

Ok(())
}
}
9 changes: 7 additions & 2 deletions cache/in-memory/src/event/voice_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ mod tests {
use twilight_model::{
datetime::Timestamp,
id::{marker::ChannelMarker, Id},
util::{image_hash::ImageHashParseError, ImageHash},
};

#[test]
Expand Down Expand Up @@ -320,12 +321,14 @@ mod tests {
}

#[test]
fn test_voice_states_members() {
fn test_voice_states_members() -> Result<(), ImageHashParseError> {
let joined_at = Timestamp::from_secs(1_632_072_645).expect("non zero");
use twilight_model::{guild::member::Member, user::User};

let cache = InMemoryCache::new();

let avatar = ImageHash::parse(b"169280485ba78d541a9090e7ea35a14e")?;

let mutation = VoiceStateUpdate(VoiceState {
channel_id: Some(Id::new(4).expect("non zero")),
deaf: false,
Expand All @@ -343,7 +346,7 @@ mod tests {
roles: Vec::new(),
user: User {
accent_color: None,
avatar: Some("".to_owned()),
avatar: Some(avatar),
banner: None,
bot: false,
discriminator: 1,
Expand Down Expand Up @@ -389,5 +392,7 @@ mod tests {
.user_id,
Id::new(3).expect("non zero"),
);

Ok(())
}
}
25 changes: 13 additions & 12 deletions cache/in-memory/src/model/guild.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use twilight_model::{
marker::{ApplicationMarker, ChannelMarker, GuildMarker, UserMarker},
Id,
},
util::image_hash::ImageHash,
};

/// Represents a cached [`Guild`].
Expand All @@ -21,13 +22,13 @@ pub struct CachedGuild {
pub(crate) afk_channel_id: Option<Id<ChannelMarker>>,
pub(crate) afk_timeout: u64,
pub(crate) application_id: Option<Id<ApplicationMarker>>,
pub(crate) banner: Option<String>,
pub(crate) banner: Option<ImageHash>,
pub(crate) default_message_notifications: DefaultMessageNotificationLevel,
pub(crate) description: Option<String>,
pub(crate) discovery_splash: Option<String>,
pub(crate) discovery_splash: Option<ImageHash>,
pub(crate) explicit_content_filter: ExplicitContentFilter,
pub(crate) features: Vec<String>,
pub(crate) icon: Option<String>,
pub(crate) icon: Option<ImageHash>,
pub(crate) id: Id<GuildMarker>,
pub(crate) joined_at: Option<Timestamp>,
pub(crate) large: bool,
Expand All @@ -44,7 +45,7 @@ pub struct CachedGuild {
pub(crate) premium_subscription_count: Option<u64>,
pub(crate) premium_tier: PremiumTier,
pub(crate) rules_channel_id: Option<Id<ChannelMarker>>,
pub(crate) splash: Option<String>,
pub(crate) splash: Option<ImageHash>,
pub(crate) system_channel_id: Option<Id<ChannelMarker>>,
pub(crate) system_channel_flags: SystemChannelFlags,
pub(crate) unavailable: bool,
Expand Down Expand Up @@ -75,8 +76,8 @@ impl CachedGuild {
/// See [Discord Docs/Image Formatting].
///
/// [Discord Docs/Image Formatting]: https://discord.com/developers/docs/reference#image-formatting
pub fn banner(&self) -> Option<&str> {
self.banner.as_deref()
pub const fn banner(&self) -> Option<&ImageHash> {
self.banner.as_ref()
}

/// Default message notification level.
Expand All @@ -94,8 +95,8 @@ impl CachedGuild {
/// See [Discord Docs/Image Formatting].
///
/// [Discord Docs/Image Formatting]: https://discord.com/developers/docs/reference#image-formatting
pub fn discovery_splash(&self) -> Option<&str> {
self.discovery_splash.as_deref()
pub const fn discovery_splash(&self) -> Option<&ImageHash> {
self.discovery_splash.as_ref()
}

/// Explicit content filter level.
Expand All @@ -117,8 +118,8 @@ impl CachedGuild {
/// See [Discord Docs/Image Formatting].
///
/// [Discord Docs/Image Formatting]: https://discord.com/developers/docs/reference#image-formatting
pub fn icon(&self) -> Option<&str> {
self.icon.as_deref()
pub const fn icon(&self) -> Option<&ImageHash> {
self.icon.as_ref()
}

/// ID of the guild.
Expand Down Expand Up @@ -208,8 +209,8 @@ impl CachedGuild {
/// See [Discord Docs/Image Formatting].
///
/// [Discord Docs/Image Formatting]: https://discord.com/developers/docs/reference#image-formatting
pub fn splash(&self) -> Option<&str> {
self.splash.as_deref()
pub const fn splash(&self) -> Option<&ImageHash> {
self.splash.as_ref()
}

/// ID of the channel where notices are posted.
Expand Down
7 changes: 4 additions & 3 deletions cache/in-memory/src/model/member.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@ use twilight_model::{
marker::{GuildMarker, RoleMarker, UserMarker},
Id,
},
util::image_hash::ImageHash,
};

/// Represents a cached [`Member`].
///
/// [`Member`]: twilight_model::guild::Member
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct CachedMember {
pub(crate) avatar: Option<String>,
pub(crate) avatar: Option<ImageHash>,
pub(crate) communication_disabled_until: Option<Timestamp>,
pub(crate) deaf: Option<bool>,
pub(crate) guild_id: Id<GuildMarker>,
Expand All @@ -29,8 +30,8 @@ pub struct CachedMember {

impl CachedMember {
/// Member's guild avatar.
pub fn avatar(&self) -> Option<&str> {
self.avatar.as_deref()
pub fn avatar(&self) -> Option<ImageHash> {
self.avatar
}

/// When the user can resume communication in a guild again.
Expand Down
9 changes: 7 additions & 2 deletions cache/in-memory/src/model/sticker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ mod tests {
},
id::Id,
user::{PremiumType, User, UserFlags},
util::{image_hash::ImageHashParseError, ImageHash},
};

assert_fields!(
Expand All @@ -142,7 +143,9 @@ mod tests {
assert_impl_all!(CachedSticker: Clone, Debug, Eq, PartialEq);

#[test]
fn test_eq_sticker() {
fn test_eq_sticker() -> Result<(), ImageHashParseError> {
let avatar = ImageHash::parse(b"5bf451026c107906b4dccea015320222")?;

let sticker = Sticker {
available: true,
description: Some("sticker".into()),
Expand All @@ -156,7 +159,7 @@ mod tests {
tags: "foo,bar,baz".into(),
user: Some(User {
accent_color: None,
avatar: Some("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_owned()),
avatar: Some(avatar),
banner: None,
bot: false,
discriminator: 1,
Expand Down Expand Up @@ -190,5 +193,7 @@ mod tests {
};

assert_eq!(cached, sticker);

Ok(())
}
}
16 changes: 12 additions & 4 deletions cache/in-memory/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@ use twilight_model::{
Id,
},
user::{CurrentUser, User},
util::image_hash::ImageHash,
voice::VoiceState,
};

pub fn cache_with_message_and_reactions() -> InMemoryCache {
let joined_at = Timestamp::from_secs(1_632_072_645).expect("non zero");
let cache = InMemoryCache::new();
let avatar = ImageHash::parse(b"6961d9f1fdb5880bf4a3ec6348d3bbcf").unwrap();

let msg = Message {
activity: None,
Expand All @@ -26,7 +28,7 @@ pub fn cache_with_message_and_reactions() -> InMemoryCache {
attachments: Vec::new(),
author: User {
accent_color: None,
avatar: Some("".to_owned()),
avatar: Some(avatar),
banner: None,
bot: false,
discriminator: 1,
Expand Down Expand Up @@ -99,7 +101,7 @@ pub fn cache_with_message_and_reactions() -> InMemoryCache {
roles: Vec::new(),
user: User {
accent_color: None,
avatar: Some("".to_owned()),
avatar: Some(avatar),
banner: None,
bot: false,
discriminator: 1,
Expand All @@ -121,6 +123,9 @@ pub fn cache_with_message_and_reactions() -> InMemoryCache {

cache.update(&reaction);

let user_5_input = b"ef678abdee09d8dfb14e83381983d5e4";
let user_5_avatar = ImageHash::parse(user_5_input).unwrap();

reaction.member.replace(Member {
avatar: None,
communication_disabled_until: None,
Expand All @@ -134,7 +139,7 @@ pub fn cache_with_message_and_reactions() -> InMemoryCache {
roles: Vec::new(),
user: User {
accent_color: None,
avatar: Some("".to_owned()),
avatar: Some(user_5_avatar),
banner: None,
bot: false,
discriminator: 2,
Expand Down Expand Up @@ -273,10 +278,13 @@ pub fn voice_state(
}

pub fn user(id: Id<UserMarker>) -> User {
let banner_hash = b"16ed037ab6dae5e1739f15c745d12454";
let banner = ImageHash::parse(banner_hash).expect("valid hash");

User {
accent_color: None,
avatar: None,
banner: Some("06c16474723fe537c283b8efa61a30c8".to_owned()),
banner: Some(banner),
bot: false,
discriminator: 1,
email: None,
Expand Down
Loading