1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
use crate::{config::ResourceType, InMemoryCache, UpdateCache};
use twilight_model::{gateway::payload::incoming::VoiceStateUpdate, voice::VoiceState};

impl InMemoryCache {
    pub(crate) fn cache_voice_states(&self, voice_states: impl IntoIterator<Item = VoiceState>) {
        for voice_state in voice_states {
            self.cache_voice_state(voice_state);
        }
    }

    fn cache_voice_state(&self, voice_state: VoiceState) {
        // This should always exist, but just in case use a match
        let guild_id = match voice_state.guild_id {
            Some(id) => id,
            None => return,
        };

        let user_id = voice_state.user_id;

        // Check if the user is switching channels in the same guild (ie. they already have a voice state entry)
        if let Some(voice_state) = self.voice_states.get(&(guild_id, user_id)) {
            if let Some(channel_id) = voice_state.channel_id {
                let remove_channel_mapping = self
                    .voice_state_channels
                    .get_mut(&channel_id)
                    .map(|mut channel_voice_states| {
                        channel_voice_states.remove(&(guild_id, user_id));

                        channel_voice_states.is_empty()
                    })
                    .unwrap_or_default();

                if remove_channel_mapping {
                    self.voice_state_channels.remove(&channel_id);
                }
            }
        }

        // Check if the voice channel_id does not exist, signifying that the user has left
        if voice_state.channel_id.is_none() {
            {
                let remove_guild = self
                    .voice_state_guilds
                    .get_mut(&guild_id)
                    .map(|mut guild_users| {
                        guild_users.remove(&user_id);

                        guild_users.is_empty()
                    })
                    .unwrap_or_default();

                if remove_guild {
                    self.voice_state_guilds.remove(&guild_id);
                }
            }

            self.voice_states.remove(&(guild_id, user_id));

            return;
        }

        let maybe_channel_id = voice_state.channel_id;
        self.voice_states.insert((guild_id, user_id), voice_state);

        self.voice_state_guilds
            .entry(guild_id)
            .or_default()
            .insert(user_id);

        if let Some(channel_id) = maybe_channel_id {
            self.voice_state_channels
                .entry(channel_id)
                .or_default()
                .insert((guild_id, user_id));
        }
    }
}

impl UpdateCache for VoiceStateUpdate {
    fn update(&self, cache: &InMemoryCache) {
        if !cache.wants(ResourceType::VOICE_STATE) {
            return;
        }

        cache.cache_voice_state(self.0.clone());

        if let (Some(guild_id), Some(member)) = (self.0.guild_id, &self.0.member) {
            cache.cache_member(guild_id, member.clone());
        }
    }
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use super::*;
    use crate::test;
    use twilight_model::{
        datetime::Timestamp,
        id::{ChannelId, GuildId, UserId},
    };

    #[test]
    fn test_voice_state_inserts_and_removes() {
        let cache = InMemoryCache::new();

        // Note: Channel ids are `<guildid><idx>` where idx is the index of the channel id
        // This is done to prevent channel id collisions between guilds
        // The other 2 ids are not special since they can't overlap

        // User 1 joins guild 1's channel 11 (1 channel, 1 guild)
        {
            // Ids for this insert
            let (guild_id, channel_id, user_id) = (
                GuildId::new(1).expect("non zero"),
                ChannelId::new(11).expect("non zero"),
                UserId::new(1).expect("non zero"),
            );
            cache.cache_voice_state(test::voice_state(guild_id, Some(channel_id), user_id));

            // The new user should show up in the global voice states
            assert!(cache.voice_states.contains_key(&(guild_id, user_id)));
            // There should only be the one new voice state in there
            assert_eq!(1, cache.voice_states.len());

            // The new channel should show up in the voice states by channel lookup
            assert!(cache.voice_state_channels.contains_key(&channel_id));
            assert_eq!(1, cache.voice_state_channels.len());

            // The new guild should also show up in the voice states by guild lookup
            assert!(cache.voice_state_guilds.contains_key(&guild_id));
            assert_eq!(1, cache.voice_state_guilds.len());
        }

        // User 2 joins guild 2's channel 21 (2 channels, 2 guilds)
        {
            // Ids for this insert
            let (guild_id, channel_id, user_id) = (
                GuildId::new(2).expect("non zero"),
                ChannelId::new(21).expect("non zero"),
                UserId::new(2).expect("non zero"),
            );
            cache.cache_voice_state(test::voice_state(guild_id, Some(channel_id), user_id));

            // The new voice state should show up in the global voice states
            assert!(cache.voice_states.contains_key(&(guild_id, user_id)));
            // There should be two voice states now that we have inserted another
            assert_eq!(2, cache.voice_states.len());

            // The new channel should also show up in the voice states by channel lookup
            assert!(cache.voice_state_channels.contains_key(&channel_id));
            assert_eq!(2, cache.voice_state_channels.len());

            // The new guild should also show up in the voice states by guild lookup
            assert!(cache.voice_state_guilds.contains_key(&guild_id));
            assert_eq!(2, cache.voice_state_guilds.len());
        }

        // User 3 joins guild 1's channel 12  (3 channels, 2 guilds)
        {
            // Ids for this insert
            let (guild_id, channel_id, user_id) = (
                GuildId::new(1).expect("non zero"),
                ChannelId::new(12).expect("non zero"),
                UserId::new(3).expect("non zero"),
            );
            cache.cache_voice_state(test::voice_state(guild_id, Some(channel_id), user_id));

            // The new voice state should show up in the global voice states
            assert!(cache.voice_states.contains_key(&(guild_id, user_id)));
            assert_eq!(3, cache.voice_states.len());

            // The new channel should also show up in the voice states by channel lookup
            assert!(cache.voice_state_channels.contains_key(&channel_id));
            assert_eq!(3, cache.voice_state_channels.len());

            // The guild should still show up in the voice states by guild lookup
            assert!(cache.voice_state_guilds.contains_key(&guild_id));
            // Since we have used a guild that has been inserted into the cache already, there
            // should not be a new guild in the map
            assert_eq!(2, cache.voice_state_guilds.len());
        }

        // User 3 moves to guild 1's channel 11 (2 channels, 2 guilds)
        {
            // Ids for this insert
            let (guild_id, channel_id, user_id) = (
                GuildId::new(1).expect("non zero"),
                ChannelId::new(11).expect("non zero"),
                UserId::new(3).expect("non zero"),
            );
            cache.cache_voice_state(test::voice_state(guild_id, Some(channel_id), user_id));

            // The new voice state should show up in the global voice states
            assert!(cache.voice_states.contains_key(&(guild_id, user_id)));
            // The amount of global voice states should not change since it was a move, not a join
            assert_eq!(3, cache.voice_states.len());

            // The new channel should show up in the voice states by channel lookup
            assert!(cache.voice_state_channels.contains_key(&channel_id));
            // The old channel should be removed from the lookup table
            assert_eq!(2, cache.voice_state_channels.len());

            // The guild should still show up in the voice states by guild lookup
            assert!(cache.voice_state_guilds.contains_key(&guild_id));
            assert_eq!(2, cache.voice_state_guilds.len());
        }

        // User 3 dcs (2 channels, 2 guilds)
        {
            let (guild_id, channel_id, user_id) = (
                GuildId::new(1).expect("non zero"),
                ChannelId::new(11).expect("non zero"),
                UserId::new(3).expect("non zero"),
            );
            cache.cache_voice_state(test::voice_state(guild_id, None, user_id));

            // Now that the user left, they should not show up in the voice states
            assert!(!cache.voice_states.contains_key(&(guild_id, user_id)));
            assert_eq!(2, cache.voice_states.len());

            // Since they were not alone in their channel, the channel and guild mappings should not disappear
            assert!(cache.voice_state_channels.contains_key(&channel_id));
            // assert_eq!(2, cache.voice_state_channels.len());
            assert!(cache.voice_state_guilds.contains_key(&guild_id));
            assert_eq!(2, cache.voice_state_guilds.len());
        }

        // User 2 dcs (1 channel, 1 guild)
        {
            let (guild_id, channel_id, user_id) = (
                GuildId::new(2).expect("non zero"),
                ChannelId::new(21).expect("non zero"),
                UserId::new(2).expect("non zero"),
            );
            cache.cache_voice_state(test::voice_state(guild_id, None, user_id));

            // Now that the user left, they should not show up in the voice states
            assert!(!cache.voice_states.contains_key(&(guild_id, user_id)));
            assert_eq!(1, cache.voice_states.len());

            // Since they were the last in their channel, the mapping should disappear
            assert!(!cache.voice_state_channels.contains_key(&channel_id));
            assert_eq!(1, cache.voice_state_channels.len());

            // Since they were the last in their guild, the mapping should disappear
            assert!(!cache.voice_state_guilds.contains_key(&guild_id));
            assert_eq!(1, cache.voice_state_guilds.len());
        }

        // User 1 dcs (0 channels, 0 guilds)
        {
            let (guild_id, _channel_id, user_id) = (
                GuildId::new(1).expect("non zero"),
                ChannelId::new(11).expect("non zero"),
                UserId::new(1).expect("non zero"),
            );
            cache.cache_voice_state(test::voice_state(guild_id, None, user_id));

            // Since the last person has disconnected, the global voice states, guilds, and channels should all be gone
            assert!(cache.voice_states.is_empty());
            assert!(cache.voice_state_channels.is_empty());
            assert!(cache.voice_state_guilds.is_empty());
        }
    }

    #[test]
    fn test_voice_states() {
        let cache = InMemoryCache::new();
        cache.cache_voice_state(test::voice_state(
            GuildId::new(1).expect("non zero"),
            Some(ChannelId::new(2).expect("non zero")),
            UserId::new(3).expect("non zero"),
        ));
        cache.cache_voice_state(test::voice_state(
            GuildId::new(1).expect("non zero"),
            Some(ChannelId::new(2).expect("non zero")),
            UserId::new(4).expect("non zero"),
        ));

        // Returns both voice states for the channel that exists.
        assert_eq!(
            2,
            cache
                .voice_channel_states(ChannelId::new(2).expect("non zero"))
                .unwrap()
                .count()
        );

        // Returns None if the channel does not exist.
        assert!(cache
            .voice_channel_states(ChannelId::new(1).expect("non zero"))
            .is_none());
    }

    #[test]
    fn test_voice_states_with_no_cached_guilds() {
        let cache = InMemoryCache::builder()
            .resource_types(ResourceType::VOICE_STATE)
            .build();

        cache.update(&VoiceStateUpdate(VoiceState {
            channel_id: None,
            deaf: false,
            guild_id: Some(GuildId::new(1).expect("non zero")),
            member: None,
            mute: false,
            self_deaf: false,
            self_mute: false,
            self_stream: false,
            session_id: "38fj3jfkh3pfho3prh2".to_string(),
            suppress: false,
            token: None,
            user_id: UserId::new(1).expect("non zero"),
            request_to_speak_timestamp: Some(
                Timestamp::from_str("2021-04-21T22:16:50+00:00").expect("proper datetime"),
            ),
        }));
    }

    #[test]
    fn test_voice_states_members() {
        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 mutation = VoiceStateUpdate(VoiceState {
            channel_id: Some(ChannelId::new(4).expect("non zero")),
            deaf: false,
            guild_id: Some(GuildId::new(2).expect("non zero")),
            member: Some(Member {
                avatar: None,
                communication_disabled_until: None,
                deaf: false,
                guild_id: GuildId::new(2).expect("non zero"),
                joined_at,
                mute: false,
                nick: None,
                pending: false,
                premium_since: None,
                roles: Vec::new(),
                user: User {
                    accent_color: None,
                    avatar: Some("".to_owned()),
                    banner: None,
                    bot: false,
                    discriminator: 1,
                    email: None,
                    flags: None,
                    id: UserId::new(3).expect("non zero"),
                    locale: None,
                    mfa_enabled: None,
                    name: "test".to_owned(),
                    premium_type: None,
                    public_flags: None,
                    system: None,
                    verified: None,
                },
            }),
            mute: false,
            self_deaf: false,
            self_mute: false,
            self_stream: false,
            session_id: "".to_owned(),
            suppress: false,
            token: None,
            user_id: UserId::new(3).expect("non zero"),
            request_to_speak_timestamp: Some(
                Timestamp::from_str("2021-04-21T22:16:50+00:00").expect("proper datetime"),
            ),
        });

        cache.update(&mutation);

        assert_eq!(cache.members.len(), 1);
        {
            let entry = cache
                .user_guilds
                .get(&UserId::new(3).expect("non zero"))
                .unwrap();
            assert_eq!(entry.value().len(), 1);
        }
        assert_eq!(
            cache
                .member(
                    GuildId::new(2).expect("non zero"),
                    UserId::new(3).expect("non zero")
                )
                .unwrap()
                .user_id,
            UserId::new(3).expect("non zero"),
        );
    }
}