essence 0.3.3

Essential models and database logic for the Adapt chat platform.
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
use crate::{
    db::{
        channel::{construct_guild_channel, query_guild_channels},
        get_pool,
        member::construct_member,
        role::construct_role,
        ChannelDbExt, DbExt, MemberDbExt, RoleDbExt,
    },
    http::guild::{CreateGuildPayload, EditGuildPayload, GetGuildQuery},
    models::{
        Guild, GuildChannel, GuildFlags, GuildMemberCount, MaybePartialUser, Member, PartialGuild,
        PermissionPair, Permissions, Role, RoleFlags,
    },
    Error, NotFoundExt,
};
use itertools::Itertools;
use std::collections::HashMap;

macro_rules! construct_partial_guild {
    ($data:ident) => {{
        PartialGuild {
            id: $data.id as _,
            name: $data.name,
            description: $data.description,
            icon: $data.icon,
            banner: $data.banner,
            owner_id: $data.owner_id as _,
            flags: GuildFlags::from_bits_truncate($data.flags as _),
            member_count: Some(GuildMemberCount {
                total: $data.member_count as _,
                online: None, // TODO
            }),
            vanity_url: $data.vanity_url,
        }
    }};
}

#[async_trait::async_trait]
pub trait GuildDbExt<'t>: DbExt<'t> {
    /// Asserts a guild with the given ID exists.
    async fn assert_guild_exists(&self, guild_id: u64) -> crate::Result<()> {
        if !sqlx::query!(
            "SELECT EXISTS(SELECT 1 FROM guilds WHERE id = $1)",
            guild_id as i64
        )
        .fetch_one(self.executor())
        .await?
        .exists
        .unwrap_or(false)
        {
            return Err(Error::NotFound {
                entity: "guild".to_string(),
                message: format!("Guild with ID {guild_id} does not exist"),
            });
        }

        Ok(())
    }

    /// Asserts the given user is a member of the given guild.
    ///
    /// # Errors
    /// * If an error occurs with fetching the member.
    async fn assert_member_in_guild(&self, guild_id: u64, user_id: u64) -> crate::Result<()> {
        self.assert_guild_exists(guild_id).await?;

        if !sqlx::query!(
            "SELECT EXISTS(SELECT 1 FROM members WHERE guild_id = $1 AND id = $2)",
            guild_id as i64,
            user_id as i64,
        )
        .fetch_one(self.executor())
        .await?
        .exists
        .unwrap_or(false)
        {
            return Err(Error::NotMember {
                guild_id,
                message: String::from(
                    "You must be a member of the guild to perform the requested action.",
                ),
            });
        }

        Ok(())
    }

    /// Asserts the given user is the owner of the given guild.
    async fn assert_member_is_owner(&self, guild_id: u64, user_id: u64) -> crate::Result<()> {
        self.assert_guild_exists(guild_id).await?;

        if !sqlx::query!(
            "SELECT EXISTS(SELECT 1 FROM guilds WHERE id = $1 AND owner_id = $2)",
            guild_id as i64,
            user_id as i64,
        )
        .fetch_one(self.executor())
        .await?
        .exists
        .unwrap_or(false)
        {
            return Err(Error::NotOwner {
                guild_id,
                message: String::from(
                    "You must be the owner of the guild to perform the requested action.",
                ),
            });
        }

        Ok(())
    }

    /// Fetches the calculated permissions value for the given member in the given guild. A channel
    /// ID may be provided to calculate the permissions for a specific channel, otherwise the
    /// permissions for the guild will be calculated.
    ///
    /// # Errors
    /// * If an error occurs with the database.
    async fn fetch_member_permissions(
        &self,
        guild_id: u64,
        user_id: u64,
        channel_id: Option<u64>,
    ) -> crate::Result<Permissions> {
        self.assert_member_in_guild(guild_id, user_id).await?;

        let mut roles = self.fetch_all_roles_in_guild(guild_id).await?;
        let overwrites = match channel_id {
            Some(channel_id) => Some(self.fetch_channel_overwrites(channel_id).await?),
            None => None,
        };

        Ok(crate::calculate_permissions(
            user_id,
            &mut roles,
            overwrites.as_ref().map(AsRef::as_ref),
        ))
    }

    /// Internally used, see [`Self::assert_member_has_permissions`] instead.
    async fn assert_member_has_permissions_with(
        &self,
        guild_id: u64,
        member_permissions: Permissions,
        required_permissions: Permissions,
    ) -> crate::Result<()> {
        if !member_permissions.contains(required_permissions) {
            return Err(Error::MissingPermissions {
                guild_id,
                permissions: required_permissions,
                message: "You do not have permission to perform the requested action.".to_string(),
            });
        }

        Ok(())
    }

    /// Asserts the given user has the given permissions in the given guild. A channel ID may be
    /// provided to assert the permissions for a specific channel, otherwise the permissions for the
    /// guild will be asserted.
    ///
    /// # Errors
    /// * If an error occurs with the database.
    /// * If the user does not have the given permissions.
    async fn assert_member_has_permissions(
        &self,
        guild_id: u64,
        user_id: u64,
        channel_id: Option<u64>,
        permissions: Permissions,
    ) -> crate::Result<()> {
        let member_permissions = self
            .fetch_member_permissions(guild_id, user_id, channel_id)
            .await?;

        self.assert_member_has_permissions_with(guild_id, member_permissions, permissions)
            .await
    }

    /// Fetches a partial guild from the database with the given ID.
    ///
    /// # Errors
    /// * If an error occurs with fetching the guild. If the guild is not found, `Ok(None)` is
    /// returned.
    async fn fetch_partial_guild(&self, guild_id: u64) -> sqlx::Result<Option<PartialGuild>> {
        let guild = sqlx::query!(
            r#"SELECT
                id,
                name,
                description,
                icon,
                banner,
                owner_id,
                flags,
                vanity_url,
                (SELECT COUNT(*) FROM members WHERE guild_id = $1) AS "member_count!"
            FROM
                guilds
            WHERE
                id = $1"#,
            guild_id as i64,
        )
        .fetch_optional(self.executor())
        .await?
        .map(|r| construct_partial_guild!(r));

        Ok(guild)
    }

    /// Fetches a guild from the database with the given ID and query.
    ///
    /// # Errors
    /// * If an error occurs with fetching the guild. If the guild is not found, `Ok(None)` is
    /// returned.
    async fn fetch_guild(
        &self,
        guild_id: u64,
        query: GetGuildQuery,
    ) -> crate::Result<Option<Guild>> {
        let partial = if let Some(partial) = self.fetch_partial_guild(guild_id).await? {
            partial
        } else {
            return Ok(None);
        };

        let channels = if query.channels {
            Some(self.fetch_all_channels_in_guild(guild_id).await?)
        } else {
            None
        };

        let roles = if query.roles {
            Some(self.fetch_all_roles_in_guild(guild_id).await?)
        } else {
            None
        };

        let members = if query.members {
            Some(self.fetch_all_members_in_guild(guild_id).await?)
        } else {
            None
        };

        Ok(Some(Guild {
            partial,
            members,
            roles,
            channels,
        }))
    }

    /// Fetches all guilds that a user is a member of, abiding by the query.
    ///
    /// # Errors
    /// * If an error occurs with fetching the guilds.
    #[allow(clippy::too_many_lines)]
    async fn fetch_all_guilds_for_user(
        &self,
        user_id: u64,
        query: GetGuildQuery,
    ) -> crate::Result<Vec<Guild>> {
        let mut guilds: HashMap<u64, Guild> = sqlx::query!(
            r#"SELECT 
                guilds.*,
                (SELECT COUNT(*) FROM members WHERE guild_id = $1) AS "member_count!"
            FROM
                guilds 
            WHERE 
                id IN (SELECT guild_id FROM members WHERE id = $1)
            "#,
            user_id as i64,
        )
        .fetch_all(self.executor())
        .await?
        .into_iter()
        .map(|r| Guild {
            partial: construct_partial_guild!(r),
            members: None,
            roles: None,
            channels: None,
        })
        .map(|guild| (guild.partial.id, guild))
        .collect();

        if query.channels {
            let mut overwrites = self.fetch_channel_overwrites_where(
                "guild_id IS NOT NULL AND guild_id IN (SELECT guild_id FROM members WHERE id = $1)",
                user_id,
            )
            .await?;

            let channels = query_guild_channels!(
                "guild_id IN (SELECT guild_id FROM members WHERE id = $1)",
                user_id as i64
            )
            .fetch_all(self.executor())
            .await?
            .into_iter()
            .map(|r| {
                construct_guild_channel!(
                    r,
                    overwrites
                        .get_mut(&(r.id as u64))
                        .unwrap_or(&mut None)
                        .take()
                        .unwrap_or_default()
                )
            })
            .collect::<crate::Result<Vec<_>>>()?
            .into_iter()
            .into_group_map_by(|c| c.guild_id);

            for (guild_id, channels) in channels {
                if let Some(guild) = guilds.get_mut(&guild_id) {
                    guild.channels = Some(channels);
                }
            }
        }

        if query.roles {
            let roles = sqlx::query!(
                r#"SELECT
                    *
                FROM
                    roles
                WHERE
                    guild_id IN (SELECT guild_id FROM members WHERE id = $1)
                ORDER BY
                    position ASC
                "#,
                user_id as i64,
            )
            .fetch_all(self.executor())
            .await?
            .into_iter()
            .map(|r| construct_role!(r))
            .into_group_map_by(|r| r.guild_id);

            for (guild_id, roles) in roles {
                if let Some(guild) = guilds.get_mut(&guild_id) {
                    guild.roles = Some(roles);
                }
            }
        }

        if query.members {
            let role_data = sqlx::query!(
                r#"SELECT
                    role_id,
                    user_id,
                    guild_id
                FROM
                    role_data
                WHERE
                    guild_id IN (SELECT guild_id FROM members WHERE id = $1)
                "#,
                user_id as i64,
            )
            .fetch_all(self.executor())
            .await?
            .into_iter()
            .into_group_map_by(|r| (r.guild_id as u64, r.user_id as u64));

            let members: HashMap<u64, Vec<Member>> = sqlx::query!(
                r#"SELECT
                    members.*,
                    users.username,
                    users.discriminator,
                    users.avatar,
                    users.banner,
                    users.bio,
                    users.flags
                FROM
                    members
                INNER JOIN
                    users
                ON
                    members.id = users.id
                WHERE
                    guild_id IN (SELECT guild_id FROM members WHERE id = $1)
                "#,
                user_id as i64,
            )
            .fetch_all(self.executor())
            .await?
            .into_iter()
            .map(|r| construct_member!(r, None))
            .into_group_map_by(|m| m.guild_id);

            for (guild_id, mut members) in members {
                if let Some(guild) = guilds.get_mut(&guild_id) {
                    for member in &mut members {
                        if let Some(roles) = role_data.get(&(guild_id, member.user_id())) {
                            member.roles = Some(roles.iter().map(|r| r.role_id as u64).collect());
                        }
                    }

                    guild.members = Some(members);
                }
            }
        }

        Ok(guilds.into_values().collect())
    }

    /// Creates a guild in the database with the given ID, owner ID and payload. Validation should
    /// be done before calling this function.
    ///
    /// * `channel_id` is the ID of the default `general` channel all guilds come with.
    /// * `role_id` is the ID of the default role (the `@everyone` role).
    ///
    /// # Note
    /// This method uses transactions, on the event of an ``Err`` the transaction must be properly
    /// rolled back, and the transaction must be committed to save the changes.
    ///
    /// # Errors
    /// * If an error occurs with creating the guild.
    async fn create_guild(
        &mut self,
        guild_id: u64,
        channel_id: u64,
        role_id: u64,
        owner_id: u64,
        payload: CreateGuildPayload,
    ) -> crate::Result<Guild> {
        let flags = payload
            .public
            .then_some(GuildFlags::PUBLIC)
            .unwrap_or_default();

        sqlx::query!(
            r#"INSERT INTO
                guilds (id, name, description, icon, banner, owner_id, flags)
            VALUES
                ($1, $2, $3, $4, $5, $6, $7)
            "#,
            guild_id as i64,
            payload.name.trim(),
            payload.description,
            payload.icon,
            payload.banner,
            owner_id as i64,
            flags.bits() as i32,
        )
        .execute(self.transaction())
        .await?;

        let joined_at = sqlx::query!(
            "INSERT INTO members (id, guild_id) VALUES ($1, $2) RETURNING joined_at",
            owner_id as i64,
            guild_id as i64,
        )
        .fetch_one(self.transaction())
        .await?
        .joined_at;

        let role_flags = RoleFlags::DEFAULT;
        let perms = sqlx::query!(
            r#"INSERT INTO roles
                (id, guild_id, name, flags, position)
            VALUES
                ($1, $2, 'Default', $3, 0)
            RETURNING
                allowed_permissions AS "allowed_permissions!",
                denied_permissions AS "denied_permissions!"
            "#,
            role_id as i64,
            guild_id as i64,
            role_flags.bits() as i32,
        )
        .fetch_one(self.transaction())
        .await?;

        // NOTE: we intentionally do not insert the default role into the role_data table as they
        // are implied to all members.

        let permissions = PermissionPair {
            allow: Permissions::from_bits_truncate(perms.allowed_permissions),
            deny: Permissions::from_bits_truncate(perms.denied_permissions),
        };

        sqlx::query!(
            r#"INSERT INTO channels
                (id, guild_id, type, name, position, slowmode, nsfw, locked)
            VALUES
                ($1, $2, 'text', 'general', 0, 0, false, false)"#,
            channel_id as i64,
            guild_id as i64,
        )
        .execute(self.transaction())
        .await?;

        let partial = PartialGuild {
            id: guild_id,
            name: payload.name,
            description: payload.description,
            icon: payload.icon,
            banner: payload.banner,
            owner_id,
            flags,
            member_count: Some(GuildMemberCount {
                total: 1,
                online: None, // TODO
            }),
            vanity_url: None,
        };

        let role = Role {
            id: role_id,
            guild_id,
            name: "Default".to_string(),
            permissions,
            flags: role_flags,
            ..Role::default()
        };

        let channel = GuildChannel {
            id: channel_id,
            guild_id,
            ..GuildChannel::default()
        };

        let member = Member {
            user: MaybePartialUser::Partial { id: owner_id },
            guild_id,
            nick: None,
            roles: Some(vec![role_id]),
            joined_at,
        };

        Ok(Guild {
            partial,
            members: Some(vec![member]),
            roles: Some(vec![role]),
            channels: Some(vec![channel]),
        })
    }

    /// Edits the guild with the given ID with the given payload. Validation should be done before
    /// calling this function. Returns a [`PartialGuild`] with updated fields on success.
    ///
    /// # Note
    /// This method uses transactions, on the event of an ``Err`` the transaction must be properly
    /// rolled back, and the transaction must be committed to save the changes.
    ///
    /// # Errors
    /// * If an error occurs with editing the guild.
    /// * If the guild does not exist.
    async fn edit_guild(
        &mut self,
        guild_id: u64,
        payload: EditGuildPayload,
    ) -> crate::Result<PartialGuild> {
        let mut guild = get_pool()
            .fetch_partial_guild(guild_id)
            .await?
            .ok_or_not_found("guild", format!("Guild with ID {guild_id} does not exist"))?;

        if let Some(name) = payload.name {
            guild.name = name;
        }

        guild.description = payload
            .description
            .into_option_or_if_absent(guild.description);
        guild.icon = payload.icon.into_option_or_if_absent(guild.icon);
        guild.banner = payload.banner.into_option_or_if_absent(guild.banner);

        match payload.public {
            Some(true) => guild.flags.insert(GuildFlags::PUBLIC),
            Some(false) => guild.flags.remove(GuildFlags::PUBLIC),
            None => (),
        }

        sqlx::query!(
            r#"UPDATE
                guilds
            SET
                name = $1, description = $2, icon = $3, banner = $4, flags = $5
            WHERE
                id = $6
            "#,
            guild.name,
            guild.description,
            guild.icon,
            guild.banner,
            guild.flags.bits() as i32,
            guild_id as i64,
        )
        .execute(self.transaction())
        .await?;

        Ok(guild)
    }

    /// Deletes a guild from the database with the given ID.
    ///
    /// # Note
    /// This method uses transactions, on the event of an ``Err`` the transaction must be properly
    /// rolled back, and the transaction must be committed to save the changes.
    ///
    /// # Errors
    /// * If an error occurs with deleting the guild.
    /// * If the guild does not exist.
    async fn delete_guild(&mut self, guild_id: u64) -> crate::Result<()> {
        sqlx::query!("DELETE FROM guilds WHERE id = $1", guild_id as i64)
            .execute(self.transaction())
            .await?;

        Ok(())
    }
}

impl<'t, T> GuildDbExt<'t> for T where T: DbExt<'t> {}