twilight_cache_inmemory/event/
presence.rs1use crate::{config::ResourceType, CacheableModels, InMemoryCache, UpdateCache};
2use twilight_model::{
3 gateway::{payload::incoming::PresenceUpdate, presence::Presence},
4 id::{marker::GuildMarker, Id},
5};
6
7impl<CacheModels: CacheableModels> InMemoryCache<CacheModels> {
8 pub(crate) fn cache_presences(
9 &self,
10 guild_id: Id<GuildMarker>,
11 presences: impl IntoIterator<Item = Presence>,
12 ) {
13 for presence in presences {
14 self.cache_presence(guild_id, presence);
15 }
16 }
17
18 fn cache_presence(&self, guild_id: Id<GuildMarker>, presence: Presence) {
19 self.guild_presences
20 .entry(guild_id)
21 .or_default()
22 .insert(presence.user.id());
23
24 self.presences.insert(
25 (guild_id, presence.user.id()),
26 CacheModels::Presence::from(presence),
27 );
28 }
29}
30
31impl<CacheModels: CacheableModels> UpdateCache<CacheModels> for PresenceUpdate {
32 fn update(&self, cache: &InMemoryCache<CacheModels>) {
33 if !cache.wants(ResourceType::PRESENCE) {
34 return;
35 }
36
37 cache.cache_presence(self.guild_id, self.0.clone());
38 }
39}
40
41#[cfg(test)]
42mod tests {
43 use crate::{test, DefaultInMemoryCache};
44 use twilight_model::{
45 gateway::{
46 event::Event,
47 payload::incoming::PresenceUpdate,
48 presence::{ClientStatus, Presence, Status, UserOrId},
49 },
50 id::Id,
51 };
52
53 #[test]
54 fn presence_update() {
55 let cache = DefaultInMemoryCache::new();
56
57 let guild_id = Id::new(1);
58 let user_id = Id::new(1);
59
60 let payload = PresenceUpdate(Presence {
61 activities: Vec::new(),
62 client_status: ClientStatus {
63 desktop: Some(Status::Online),
64 mobile: None,
65 web: None,
66 },
67 guild_id,
68 status: Status::Online,
69 user: UserOrId::User(test::user(user_id)),
70 });
71 cache.update(&Event::PresenceUpdate(Box::new(payload)));
72
73 assert_eq!(1, cache.presences.len());
74 assert_eq!(1, cache.guild_presences.len());
75 assert!(cache
76 .guild_presences
77 .get(&guild_id)
78 .unwrap()
79 .contains(&user_id));
80 }
81}