stoat-rs 0.2.5

Stoat API Wrapper
Documentation
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
use scc::HashMap;
use std::{
    collections::VecDeque,
    sync::{Arc, RwLock},
};
use stoat_models::v0::{
    Channel, ChannelVoiceState, Emoji, EmojiParent, Member, Message, Server, User, UserVoiceState,
};

use crate::types::{StoatConfig, VoiceNode};

/// Config options for the internal cache.
#[derive(Debug, Clone)]
pub struct CacheConfig {
    /// Max amount of messages to hold in the cache
    ///
    /// Defaults to 10k.
    pub max_messages: usize
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            max_messages: 10000
        }
    }
}

/// Holds all locally cached objects.
#[derive(Debug, Clone)]
pub struct GlobalCache {
    pub api_config: Arc<StoatConfig>,
    pub config: Arc<CacheConfig>,

    pub servers: Arc<HashMap<String, Server>>,
    pub users: Arc<HashMap<String, User>>,
    pub members: Arc<HashMap<String, HashMap<String, Member>>>,
    pub channels: Arc<HashMap<String, Channel>>,
    pub messages: Arc<RwLock<VecDeque<Message>>>,
    pub emojis: Arc<HashMap<String, Emoji>>,
    pub voice_states: Arc<HashMap<String, ChannelVoiceState>>,

    #[cfg(feature = "voice")]
    pub voice_connections: Arc<HashMap<String, crate::VoiceConnection>>,

    pub current_user_id: Arc<RwLock<Option<String>>>,
}

impl GlobalCache {
    pub fn new(api_config: StoatConfig, config: CacheConfig) -> Self {
        Self {
            api_config: Arc::new(api_config),
            config: Arc::new(config),
            servers: Arc::new(HashMap::new()),
            users: Arc::new(HashMap::new()),
            members: Arc::new(HashMap::new()),
            channels: Arc::new(HashMap::new()),
            messages: Arc::new(RwLock::new(VecDeque::new())),
            emojis: Arc::new(HashMap::new()),
            voice_states: Arc::new(HashMap::new()),

            #[cfg(feature = "voice")]
            voice_connections: Arc::new(HashMap::new()),

            current_user_id: Arc::new(RwLock::new(None)),
        }
    }

    /// Clears all internal state.
    pub async fn cleanup(&self) {
        self.servers.clear_async().await;
        self.users.clear_async().await;
        self.members.clear_async().await;
        self.channels.clear_async().await;
        self.messages.write().unwrap().clear();
        self.emojis.clear_async().await;
        self.voice_states.clear_async().await;

        #[cfg(feature = "voice")]
        {
            use futures::{FutureExt, future::join_all};

            let voice_connections = self.voice_connections.clone();
            let mut iter = voice_connections.begin_async().await;
            let mut conns = Vec::new();

            while let Some(entry) = iter {
                let ((_, conn), next) = entry.remove_and_async().await;
                iter = next;
                conns.push(conn);
            }

            join_all(conns.iter().map(|c| c.disconnect().boxed())).await;
        }
    }

    /// Base URL for Autumn.
    pub fn autumn_url(&self) -> &str {
        &self.api_config.features.autumn.url
    }

    /// All public Livekit voice nodes.
    pub fn livekit_nodes(&self) -> &[VoiceNode] {
        &self.api_config.features.livekit.nodes
    }

    /// Gets a server.
    pub fn get_server(&self, server_id: &str) -> Option<Server> {
        self.servers.get_sync(server_id).map(|r| r.get().clone())
    }

    /// Inserts a server.
    pub fn insert_server(&self, server: Server) {
        self.servers.upsert_sync(server.id.clone(), server);
    }

    /// Updates a server.
    pub fn update_server_with<R>(
        &self,
        server_id: &str,
        f: impl FnOnce(&mut Server) -> R,
    ) -> Option<R> {
        self.servers.get_sync(server_id).map(|mut r| f(r.get_mut()))
    }

    /// Removes a server.
    pub fn remove_server(&self, server_id: &str) -> Option<Server> {
        self.servers
            .remove_sync(server_id)
            .map(|(_, server)| server)
    }

    /// Gets a user.
    pub fn get_user(&self, user_id: &str) -> Option<User> {
        self.users.get_sync(user_id).map(|r| r.get().clone())
    }

    /// Inserts a user.
    pub fn insert_user(&self, user: User) {
        self.users.upsert_sync(user.id.clone(), user);
    }

    /// Updates a user.
    pub fn update_user_with<R>(&self, user_id: &str, f: impl FnOnce(&mut User) -> R) -> Option<R> {
        self.users.get_sync(user_id).map(|mut r| f(r.get_mut()))
    }

    /// Removes a user.
    pub fn remove_user(&self, user_id: &str) -> Option<User> {
        self.users.remove_sync(user_id).map(|(_, server)| server)
    }

    /// Gets a server member.
    pub fn get_member(&self, server_id: &str, user_id: &str) -> Option<Member> {
        self.members
            .get_sync(server_id)
            .and_then(|members| members.get_sync(user_id).map(|r| r.get().clone()))
    }

    /// Inserts a server member.
    pub fn insert_member(&self, member: Member) {
        self.members
            .entry_sync(member.id.server.clone())
            .or_default()
            .get_mut()
            .upsert_sync(member.id.user.clone(), member);
    }

    /// Updates a server member.
    pub fn update_member_with<R>(
        &self,
        server_id: &str,
        user_id: &str,
        f: impl FnOnce(&mut Member) -> R,
    ) -> Option<R> {
        self.members
            .get_sync(server_id)
            .and_then(|members| members.get_sync(user_id).map(|mut r| f(r.get_mut())))
    }

    /// Removes a server member.
    pub fn remove_member(&self, server_id: &str, user_id: &str) -> Option<Member> {
        self.members
            .get_sync(server_id)
            .and_then(|members| members.remove_sync(user_id).map(|(_, member)| member))
    }

    /// Gets a channel.
    pub fn get_channel(&self, channel_id: &str) -> Option<Channel> {
        self.channels.get_sync(channel_id).map(|r| r.get().clone())
    }

    /// Inserts a channel.
    pub fn insert_channel(&self, channel: Channel) {
        self.channels.upsert_sync(channel.id().to_string(), channel);
    }

    /// Updates a channel.
    pub fn update_channel_with<R>(
        &self,
        channel_id: &str,
        f: impl FnOnce(&mut Channel) -> R,
    ) -> Option<R> {
        self.channels
            .get_sync(channel_id)
            .map(|mut r| f(r.get_mut()))
    }

    /// Removes a channel.
    pub fn remove_channel(&self, channel_id: &str) -> Option<Channel> {
        self.channels
            .remove_sync(channel_id)
            .map(|(_, channel)| channel)
    }

    /// Gets a message.
    pub fn get_message(&self, message_id: &str) -> Option<Message> {
        self.messages
            .read()
            .unwrap()
            .iter()
            .find(|msg| &msg.id == message_id)
            .cloned()
    }

    /// Inserts a message.
    pub fn insert_message(&self, message: Message) {
        let mut messages = self.messages.write().unwrap();

        messages.push_front(message);

        if messages.len() > self.config.max_messages {
            messages.pop_back();
        }
    }

    /// Updates a message.
    pub fn update_message_with<R>(
        &self,
        message_id: &str,
        f: impl FnOnce(&mut Message) -> R,
    ) -> Option<R> {
        self.messages
            .write()
            .unwrap()
            .iter_mut()
            .find(|msg| &msg.id == message_id)
            .map(f)
    }

    /// Removes a message.
    pub fn remove_message(&self, message_id: &str) -> Option<Message> {
        let mut messages = self.messages.write().unwrap();

        if let Some((idx, _)) = messages
            .iter()
            .enumerate()
            .find(|(_, msg)| &msg.id == message_id)
        {
            messages.remove(idx)
        } else {
            None
        }
    }

    /// Bulk removes messages.
    pub fn remove_messages(&self, message_ids: &[String]) -> Vec<Message> {
        let mut channel_messages = self.messages.write().unwrap();

        let mut i = 0;
        let end = channel_messages.len();

        let mut messages = Vec::new();

        while i < channel_messages.len() - end {
            if message_ids.contains(&channel_messages[i].id) {
                messages.push(channel_messages.remove(i).unwrap());
            } else {
                i += 1;
            };
        }

        messages
    }

    /// Current logged in user.
    pub fn get_current_user(&self) -> Option<User> {
        self.users
            .get_sync(&self.get_current_user_id()?)
            .map(|r| r.get().clone())
    }

    /// Inserts a channel voice state.
    pub fn insert_voice_state(&self, voice_state: ChannelVoiceState) {
        self.voice_states
            .upsert_sync(voice_state.id.clone(), voice_state);
    }

    /// Removes a channel voice state.
    pub fn remove_voice_state(&self, channel_id: &str) -> Option<ChannelVoiceState> {
        self.voice_states
            .remove_sync(channel_id)
            .map(|(_, voice_state)| voice_state)
    }

    /// Gets a channel voice state.
    pub fn get_voice_state(&self, channel_id: &str) -> Option<ChannelVoiceState> {
        self.voice_states
            .get_sync(channel_id)
            .map(|r| r.get().clone())
    }

    /// Inserts a voice state partipant.
    pub fn insert_voice_state_partipant(&self, channel_id: &str, user_voice_state: UserVoiceState) {
        let mut channel_voice_state = self
            .voice_states
            .entry_sync(channel_id.to_string())
            .or_insert_with(|| ChannelVoiceState {
                id: channel_id.to_string(),
                participants: Vec::new(),
            });

        channel_voice_state
            .participants
            .retain(|state| state.id != user_voice_state.id);

        channel_voice_state.participants.push(user_voice_state);
    }

    /// Removes a voice state partipant
    pub fn remove_voice_state_partipant(
        &self,
        channel_id: &str,
        user_id: &str,
    ) -> Option<UserVoiceState> {
        if let Some(mut channel_voice_state) = self.voice_states.get_sync(channel_id) {
            if let Some((i, _)) = channel_voice_state
                .participants
                .iter()
                .enumerate()
                .find(|(_, state)| &state.id == user_id)
            {
                Some(channel_voice_state.participants.remove(i))
            } else {
                None
            }
        } else {
            None
        }
    }

    /// Updates a voice state partipant.
    pub fn update_voice_state_partipant_with<R>(
        &self,
        channel_id: &str,
        user_id: &str,
        f: impl FnOnce(&mut UserVoiceState) -> R,
    ) -> Option<R> {
        if let Some(mut channel_voice_state) = self.voice_states.get_sync(channel_id) {
            channel_voice_state
                .participants
                .iter_mut()
                .find(|p| p.id == user_id)
                .map(f)
        } else {
            None
        }
    }

    /// Inserts a voice connection.
    #[cfg(feature = "voice")]
    pub fn insert_voice_connection(&self, connection: crate::VoiceConnection) {
        self.voice_connections
            .upsert_sync(connection.channel_id(), connection);
    }

    /// Gets a voice connection.
    #[cfg(feature = "voice")]
    pub fn get_voice_connection(&self, channel_id: &str) -> Option<crate::VoiceConnection> {
        self.voice_connections
            .get_sync(channel_id)
            .map(|r| r.get().clone())
    }

    /// Removes a voice connection.
    #[cfg(feature = "voice")]
    pub fn remove_voice_connection(&self, channel_id: &str) -> Option<crate::VoiceConnection> {
        self.voice_connections
            .remove_sync(channel_id)
            .map(|(_, voice_connection)| voice_connection)
    }

    /// Inserts an emoji.
    pub fn insert_emoji(&self, emoji: Emoji) {
        self.emojis.upsert_sync(emoji.id.clone(), emoji);
    }

    /// Gets an emoji.
    pub fn get_emoji(&self, emoji_id: &str) -> Option<Emoji> {
        self.emojis.get_sync(emoji_id).map(|r| r.get().clone())
    }

    /// Removes an emoji.
    pub fn remove_emoji(&self, emoji_id: &str) -> Option<Emoji> {
        self.emojis.remove_sync(emoji_id).map(|(_, emoji)| emoji)
    }

    /// Removes all server emojis.
    pub fn remove_server_emojis(&self, server_id: &str) -> Vec<Emoji> {
        let parent = EmojiParent::Server {
            id: server_id.to_string(),
        };

        let mut emojis = Vec::new();

        // Workaround for no extract_if alternative
        self.emojis.retain_sync(|_, emoji| {
            if &emoji.parent == &parent {
                emojis.push(emoji.clone());

                true
            } else {
                false
            }
        });

        emojis
    }

    /// Sets the current logged in user id.
    pub fn set_current_user_id(&self, user_id: String) {
        *self.current_user_id.write().unwrap() = Some(user_id);
    }

    // Gets the current logged in user id.
    pub fn get_current_user_id(&self) -> Option<String> {
        self.current_user_id
            .read()
            .unwrap()
            .as_ref()
            .map(|v| v.clone())
    }
}

impl AsRef<GlobalCache> for GlobalCache {
    fn as_ref(&self) -> &GlobalCache {
        self
    }
}