tulpje_cache/models/
presence.rs

1use serde::{Deserialize, Serialize};
2use twilight_model::{
3    gateway::presence::{Activity, ClientStatus, Presence, Status},
4    id::{
5        Id,
6        marker::{GuildMarker, UserMarker},
7    },
8};
9
10use crate::{Cache, Error};
11
12#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
13pub struct CachedPresence {
14    pub activities: Vec<Activity>,
15    pub client_status: ClientStatus,
16    pub guild_id: Id<GuildMarker>,
17    pub status: Status,
18    pub user_id: Id<UserMarker>,
19}
20
21impl From<Presence> for CachedPresence {
22    fn from(presence: Presence) -> Self {
23        let Presence {
24            activities,
25            client_status,
26            guild_id,
27            status,
28            user,
29        } = presence;
30
31        Self {
32            activities,
33            client_status,
34            guild_id,
35            status,
36            user_id: user.id(),
37        }
38    }
39}
40
41impl PartialEq<Presence> for CachedPresence {
42    fn eq(&self, other: &Presence) -> bool {
43        self.activities == other.activities
44            && self.client_status == other.client_status
45            && self.guild_id == other.guild_id
46            && self.status == other.status
47            && self.user_id == other.user.id()
48    }
49}
50
51impl Cache {
52    pub(crate) async fn cache_presences(
53        &self,
54        guild_id: Id<GuildMarker>,
55        presences: impl IntoIterator<Item = Presence>,
56    ) -> Result<(), Error> {
57        for presence in presences {
58            self.cache_presence(guild_id, presence).await?;
59        }
60
61        Ok(())
62    }
63
64    pub(crate) async fn cache_presence(
65        &self,
66        guild_id: Id<GuildMarker>,
67        presence: Presence,
68    ) -> Result<(), Error> {
69        self.guild_presences
70            .insert(&guild_id, &presence.user.id())
71            .await?;
72
73        self.presences
74            .insert(
75                &(guild_id, presence.user.id()),
76                &CachedPresence::from(presence),
77            )
78            .await?;
79
80        Ok(())
81    }
82}