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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
use std::{
    collections::{HashMap, HashSet},
    mem,
};

use serde::{Deserialize, Serialize};

use crate::{
    channel::{Channel, Message},
    check_name_validity, check_permission,
    error::{DataError, Error},
    get_system_millis, new_id,
    permission::{
        ChannelPermission, ChannelPermissions, HubPermission, HubPermissions, PermissionSetting,
    },
    user::User,
    Result, ID,
};

/// Relative path of the folder in which Hub information files (`hub.json`) files are stored.
pub const HUB_INFO_FOLDER: &str = "data/hubs/info/";
/// Relative path of the folder in which Hub data files are stored (channel directories and messages).
pub const HUB_DATA_FOLDER: &str = "data/hubs/data/";

/// Represents a member of a hub that maps to a user.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct HubMember {
    /// ID of the user that the hub member represents.
    pub user: ID,
    /// Time in milliseconds since Unix Epoch that the user became a member of the hub.
    pub joined: u128,
    /// ID of the hub that this hub member is in.
    pub hub: ID,
    /// Name used by the hub member.
    pub nickname: String,
    /// Groups that the hub member is part of.
    pub groups: Vec<ID>,
    /// Hub permission settings that the hub member has.
    pub hub_permissions: HubPermissions,
    /// Mapping of channel permission settings the hub member has to the channel they apply to.
    pub channel_permissions: HashMap<ID, ChannelPermissions>,
}

impl HubMember {
    /// Creates a new hub member based on a user and the ID of the hub they are part of.
    pub fn new(user: &User, hub: ID) -> Self {
        Self {
            nickname: user.username.clone(),
            user: user.id.clone(),
            hub,
            groups: Vec::new(),
            joined: get_system_millis(),
            hub_permissions: HashMap::new(),
            channel_permissions: HashMap::new(),
        }
    }

    /// Changes the nickname of the hub member or returns an error if [`check_name_validity`] fails.
    pub fn set_nickname(&mut self, nickname: String) -> Result<()> {
        check_name_validity(&nickname)?;
        self.nickname = nickname;
        Ok(())
    }

    /// Adds the hub member to a permission group.
    pub fn join_group(&mut self, group: &mut PermissionGroup) {
        if !self.groups.contains(&group.id) {
            self.groups.push(group.id.clone());
        }
        if !group.members.contains(&self.user) {
            group.members.push(self.user.clone());
        }
    }

    /// Removes the hub member from a permission group.
    pub fn leave_group(&mut self, group: &mut PermissionGroup) {
        if let Some(index) = self.groups.iter().position(|id| id == &group.id) {
            self.groups.remove(index);
        }
        if let Some(index) = group.members.iter().position(|id| id == &self.user) {
            group.members.remove(index);
        }
    }

    /// Sets a hub permission for the hub member.
    pub fn set_permission(&mut self, permission: HubPermission, value: PermissionSetting) {
        self.hub_permissions.insert(permission, value);
    }

    /// Sets a channel permission for the hub member in the specified channel.
    pub fn set_channel_permission(
        &mut self,
        channel: &ID,
        permission: ChannelPermission,
        value: PermissionSetting,
    ) {
        let channel_permissions = self
            .channel_permissions
            .entry(*channel)
            .or_insert(HashMap::new());
        channel_permissions.insert(permission, value);
    }

    /// Checks if the hub member has the `HubPermission::All` permission or if they inherit it from a permission group they are in.
    pub fn has_all_permissions(&self) -> bool {
        if let Some(value) = self.hub_permissions.get(&HubPermission::All) {
            if value == &Some(true) {
                return true;
            }
        }
        false
    }

    /// Checks if the hub member has the given hub permission or if they inherit it from a permission group they are in.
    pub fn has_permission(&self, permission: HubPermission, hub: &Hub) -> bool {
        if hub.owner == self.user {
            // If the user is the owner of the hub they are all powerful.
            return true;
        }
        if self.has_all_permissions() {
            // If the user has the `All` hub permission we do not need to check individual permissions, even for channels.
            return true;
        }
        if let Some(value) = self.hub_permissions.get(&permission) {
            match value {
                &Some(true) => {
                    return true;
                }
                &Some(false) => {
                    return false;
                }
                None => {}
            };
        } else {
            for group in self.groups.iter() {
                if let Some(group) = hub.groups.get(&group) {
                    if group.has_permission(&permission) {
                        return true;
                    }
                }
            }
        }
        false
    }

    /// Checks if the hub member has the given channel permission in the given channel or if they inherit it from a permission group they are in.
    pub fn has_channel_permission(
        &self,
        channel: &ID,
        permission: &ChannelPermission,
        hub: &Hub,
    ) -> bool {
        if hub.owner == self.user {
            // If the user is the owner of the hub they are all powerful.
            return true;
        }
        if self.has_all_permissions() {
            // If the user has the `All` hub permission we do not need to check individual permissions, even for channels.
            return true;
        }
        if let Some(channel) = self.channel_permissions.get(channel) {
            if let Some(value) = channel.get(&ChannelPermission::All) {
                if value == &Some(true) {
                    return true;
                }
            }
            if let Some(value) = channel.get(permission) {
                match value {
                    &Some(true) => {
                        return true;
                    }
                    &Some(false) => {
                        return false;
                    }
                    None => {
                        if self.has_permission(permission.hub_equivalent(), hub) {
                            return true;
                        }
                    }
                };
            }
        } else {
            for group in self.groups.iter() {
                if let Some(group) = hub.groups.get(&group) {
                    if group.has_channel_permission(channel, permission) {
                        return true;
                    }
                }
            }
        }
        false
    }
}

/// Represents a set of permissions that can be easily given to any hub member.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct PermissionGroup {
    /// ID of the group.
    pub id: ID,
    /// Name of the group.
    pub name: String,
    /// Array of the IDs of hub members who are members of the group.
    pub members: Vec<ID>,
    /// Hub permission settings that the group has.
    pub hub_permissions: HubPermissions,
    /// Mapping of channel permission settings the group has to the channel they apply to.
    pub channel_permissions: HashMap<ID, ChannelPermissions>,
    /// Time in milliseconds since Unix Epoch that the group was created.
    pub created: u128,
}

impl PermissionGroup {
    /// Creates a new permission group given a name and an ID.
    pub fn new(name: String, id: ID) -> Self {
        Self {
            created: get_system_millis(),
            id,
            name,
            members: Vec::new(),
            hub_permissions: HashMap::new(),
            channel_permissions: HashMap::new(),
        }
    }

    /// Adds a hub member to the group, maps to `HubMember::join_group`.
    pub fn add_member(&mut self, user: &mut HubMember) {
        user.join_group(self)
    }

    /// Removes a hub member from the group, maps to `HubMember::leave_group`.
    pub fn remove_member(&mut self, user: &mut HubMember) {
        user.leave_group(self)
    }

    /// Changes the setting of a hub permission for the group.
    pub fn set_permission(&mut self, permission: HubPermission, value: PermissionSetting) {
        self.hub_permissions.insert(permission, value);
    }

    /// Changes the setting of a channel permission for a specific channel for the group.
    pub fn set_channel_permission(
        &mut self,
        channel_id: ID,
        permission: ChannelPermission,
        value: PermissionSetting,
    ) {
        let channel_permissions = self
            .channel_permissions
            .entry(channel_id)
            .or_insert(HashMap::new());
        channel_permissions.insert(permission, value);
    }

    /// Checks if the group has the `All` permission.
    pub fn has_all_permissions(&self) -> bool {
        if let Some(value) = self.hub_permissions.get(&HubPermission::All) {
            if value == &Some(true) {
                return true;
            }
        }
        false
    }

    /// Checks if the group has a permission.
    pub fn has_permission(&self, permission: &HubPermission) -> bool {
        if self.has_all_permissions() {
            return true;
        }
        if let Some(value) = self.hub_permissions.get(permission) {
            if value == &Some(true) {
                return true;
            }
        }
        return false;
    }

    /// Checks if the group has a permission in a specific channel.
    pub fn has_channel_permission(&self, channel_id: &ID, permission: &ChannelPermission) -> bool {
        if self.has_all_permissions() {
            return true;
        }
        if let Some(channel) = self.channel_permissions.get(channel_id) {
            if let Some(value) = channel.get(&ChannelPermission::All) {
                if value == &Some(true) {
                    return true;
                }
            }
            if let Some(value) = channel.get(&permission) {
                if value == &Some(true) {
                    return true;
                } else if value == &None {
                    if self.has_permission(&permission.hub_equivalent()) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}

/// Represents a group of users, permission groups and channels.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Hub {
    /// Map of channels to their IDs.
    pub channels: HashMap<ID, Channel>,
    /// Map of hub members to their corresponding user's IDs.
    pub members: HashMap<ID, HubMember>,
    /// List of IDs of all users that are banned from the hub.
    pub bans: HashSet<ID>,
    /// List of IDs of all the users who cannot send **any** messages in the hub.
    pub mutes: HashSet<ID>,
    /// Description of the hub.
    pub description: String,
    /// ID of the user who owns the hub, also the creator.
    pub owner: ID,
    /// Map of permission groups to their IDs.
    pub groups: HashMap<ID, PermissionGroup>,
    /// ID of the default permission group to be given to new hub members, for now this is always the "everyone" group.
    pub default_group: ID,
    /// Name of the hub.
    pub name: String,
    /// ID of the hub.
    pub id: ID,
    /// Time the hub was created in milliseconds since Unix Epoch.
    pub created: u128,
}

impl Hub {
    /// Creates a new hub given the ID of the user who should be the owner, the name and the ID the hub should have.
    pub fn new(name: String, id: ID, creator: &User) -> Self {
        let creator_id = creator.id.clone();
        let mut everyone = PermissionGroup::new(String::from("everyone"), new_id());
        let mut owner = HubMember::new(creator, id.clone());
        let mut members = HashMap::new();
        let mut groups = HashMap::new();
        owner.join_group(&mut everyone);
        owner.set_permission(HubPermission::All, Some(true));
        members.insert(creator_id.clone(), owner);
        groups.insert(everyone.id.clone(), everyone.clone());
        Self {
            name,
            id,
            groups,
            description: String::new(),
            default_group: everyone.id.clone(),
            owner: creator_id,
            bans: HashSet::new(),
            mutes: HashSet::new(),
            channels: HashMap::new(),
            members,
            created: get_system_millis(),
        }
    }

    /// Creates a new channel while checking that the given user has permission to do so.
    ///
    /// # Errors
    ///
    /// This function will return an error in the following situations, but is not
    /// limited to just these cases:
    ///
    /// * Failed to pass [`check_name_validity`].
    /// * The user it not in the hub.
    /// * The user does not have permission create new channels.
    /// * Any of the reasons outlined in [`Channel::create_dir`].
    pub async fn new_channel(&mut self, member_id: &ID, name: String) -> Result<ID> {
        check_name_validity(&name)?;
        let member = self.get_member(member_id)?;
        check_permission!(member, HubPermission::CreateChannel, self);
        let mut id = new_id();
        while self.channels.contains_key(&id) {
            id = new_id();
        }
        let channel = Channel::new(name, id.clone(), self.id.clone());
        channel.create_dir().await?;
        {
            self.get_member_mut(member_id)?.set_channel_permission(
                &channel.id,
                ChannelPermission::ViewChannel,
                Some(true),
            );
        }
        self.channels.insert(id.clone(), channel);
        Ok(id)
    }

    /// Gets a reference to the channel.
    /// Returns an error if the channel could not be found or the user did not have permission to view the channel.
    pub fn get_channel(&self, member_id: &ID, channel_id: &ID) -> Result<&Channel> {
        let member = self.get_member(member_id)?;
        check_permission!(member, channel_id, ChannelPermission::ViewChannel, self);
        if let Some(channel) = self.channels.get(channel_id) {
            Ok(channel)
        } else {
            Err(Error::ChannelNotFound)
        }
    }

    /// Gets a mutable reference to the channel.
    /// Returns an error if the channel could not be found or the user did not have permission to view the channel.
    pub fn get_channel_mut(&mut self, member_id: &ID, channel_id: &ID) -> Result<&mut Channel> {
        let member = self.get_member(member_id)?;
        check_permission!(member, channel_id, ChannelPermission::ViewChannel, self);
        if let Some(channel) = self.channels.get_mut(channel_id) {
            Ok(channel)
        } else {
            Err(Error::ChannelNotFound)
        }
    }

    /// Gets a reference to the hub member, returns an error if the member could not be found.
    pub fn get_member(&self, member_id: &ID) -> Result<HubMember> {
        if let Some(member) = self.members.get(member_id) {
            Ok(member.clone())
        } else {
            Err(Error::MemberNotFound)
        }
    }

    /// Gets a mutable reference to the hub member, returns an error if the member could not be found.
    pub fn get_member_mut(&mut self, member_id: &ID) -> Result<&mut HubMember> {
        if let Some(member) = self.members.get_mut(member_id) {
            Ok(member)
        } else {
            Err(Error::MemberNotFound)
        }
    }

    /// Changes the description of a channel while checking that the given user has permission to do so.
    ///
    /// # Errors
    ///
    /// This function will return an error in the following situations, but is not
    /// limited to just these cases:
    ///
    /// * Description is bigger than [`crate::MAX_DESCRIPTION_SIZE`].
    /// * The user it not in the hub.
    /// * The user does not have permission to view the channel.
    /// * The user does not have permission to configure the channel.
    /// * The channel does not exist.
    pub async fn change_channel_description(
        &mut self,
        user_id: &ID,
        channel_id: &ID,
        new_description: String,
    ) -> Result<String> {
        if new_description.as_bytes().len() > crate::MAX_DESCRIPTION_SIZE {
            Err(Error::TooBig)
        } else {
            if let Some(user) = self.members.get(user_id) {
                check_permission!(user, channel_id, ChannelPermission::ViewChannel, self);
                check_permission!(user, channel_id, ChannelPermission::Configure, self);
                if let Some(channel) = self.channels.get_mut(channel_id) {
                    Ok(mem::replace(&mut channel.description, new_description))
                } else {
                    Err(Error::ChannelNotFound)
                }
            } else {
                Err(Error::NotInHub)
            }
        }
    }

    /// Renames a channel while checking that the given user has permission to do so.
    ///
    /// # Errors
    ///
    /// This function will return an error in the following situations, but is not
    /// limited to just these cases:
    ///
    /// * Failed to pass [`check_name_validity`].
    /// * The user it not in the hub.
    /// * The user does not have permission to view the channel.
    /// * The user does not have permission to configure the channel.
    /// * The channel does not exist.
    pub async fn rename_channel(
        &mut self,
        user_id: &ID,
        channel_id: &ID,
        new_name: String,
    ) -> Result<String> {
        check_name_validity(&new_name)?;
        if let Some(user) = self.members.get(user_id) {
            check_permission!(user, channel_id, ChannelPermission::ViewChannel, self);
            check_permission!(user, channel_id, ChannelPermission::Configure, self);
            if let Some(channel) = self.channels.get_mut(channel_id) {
                Ok(mem::replace(&mut channel.name, new_name))
            } else {
                Err(Error::ChannelNotFound)
            }
        } else {
            Err(Error::NotInHub)
        }
    }

    /// Deletes a channel while checking that the given user has permission to do so.
    ///
    /// # Errors
    ///
    /// This function will return an error in the following situations, but is not
    /// limited to just these cases:
    ///
    /// * The user is not in the hub.
    /// * The channel does not exist.
    /// * THe user does not have permission to view the channel.
    /// * The user does not have permission to delete the channel.
    pub async fn delete_channel(&mut self, user_id: &ID, channel_id: &ID) -> Result<()> {
        if let Some(user) = self.members.get(user_id) {
            check_permission!(user, HubPermission::DeleteChannel, self);
            check_permission!(user, channel_id, ChannelPermission::ViewChannel, self);
            if let Some(_) = self.channels.remove(channel_id) {
                Ok(())
            } else {
                Err(Error::ChannelNotFound)
            }
        } else {
            Err(Error::NotInHub)
        }
    }

    /// Sends a message as a user while checking that the user has permission to view the given channel and to write to it.
    ///
    /// # Errors
    ///
    /// This function will return an error in the following situations, but is not
    /// limited to just these cases:
    ///
    /// * The user is not in the hub.
    /// * THe user is muted and cannot send messages.
    /// * The channel does not exist.
    /// * The user does not have permission to view the channel.
    /// * The user does not have permission to send messages in the channel.
    /// * The message could not be added to the channel for any of the reasons outlined in [`Channel::add_message`].
    pub async fn send_message(
        &mut self,
        user_id: &ID,
        channel_id: &ID,
        message: String,
    ) -> Result<Message> {
        if let Some(member) = self.members.get(&user_id) {
            if !self.mutes.contains(&user_id) {
                check_permission!(member, channel_id, ChannelPermission::ViewChannel, self);
                check_permission!(member, channel_id, ChannelPermission::SendMessage, self);
                if let Some(channel) = self.channels.get(&channel_id) {
                    let message = Message {
                        id: new_id(),
                        sender: member.user.clone(),
                        created: get_system_millis(),
                        content: message,
                    };
                    channel.add_message(message.clone()).await?;
                    Ok(message)
                } else {
                    Err(Error::ChannelNotFound)
                }
            } else {
                Err(Error::Muted)
            }
        } else {
            Err(Error::NotInHub)
        }
    }

    /// Gets the file path to be used for storing the hub's data.
    pub fn get_info_path(&self) -> String {
        format!("{}{:x}", HUB_INFO_FOLDER, self.id.as_u128())
    }

    /// Gets the path of the directory in which channel folders should be stored.
    pub fn get_data_path(&self) -> String {
        format!("{}{:x}/", HUB_DATA_FOLDER, self.id.as_u128())
    }

    /// Saves the hub's data to disk.
    ///
    /// # Errors
    ///
    /// This function will return an error in the following situations, but is not
    /// limited to just these cases:
    ///
    /// * The hub data could not be serialized.
    /// * The hub info folder does not exist and could not be created.
    /// * The data could not be written to the disk.
    pub async fn save(&self) -> Result<()> {
        tokio::fs::create_dir_all(HUB_INFO_FOLDER).await?;
        tokio::fs::write(
            self.get_info_path(),
            &bincode::serialize(self).map_err(|_| DataError::Serialize)?,
        )
        .await?;
        Ok(())
    }

    /// Loads a hub's data given its ID.
    ///
    /// # Errors
    ///
    /// This function will return an error in the following situations, but is not
    /// limited to just these cases:
    ///
    /// * There is no hub with that ID.
    /// * The hub's data file was corrupt and could not be deserialized.
    pub async fn load(id: &ID) -> Result<Self> {
        let filename = format!("{}{:x}", HUB_INFO_FOLDER, id.as_u128());
        let path = std::path::Path::new(&filename);
        if !path.exists() {
            return Err(Error::HubNotFound);
        }
        bincode::deserialize(&tokio::fs::read(path).await?).map_err(|_| DataError::Deserialize)?
    }

    /// Adds a user to a hub, creating and returning the resulting hub member.
    ///
    /// # Errors
    ///
    /// This function will return an error in the following situations, but is not
    /// limited to just this case:
    ///
    /// * The default permission group could not be found.
    pub fn user_join(&mut self, user: &User) -> Result<HubMember> {
        let mut member = HubMember::new(user, self.id.clone());
        if let Some(group) = self.groups.get_mut(&self.default_group) {
            group.add_member(&mut member);
            self.members.insert(member.user.clone(), member.clone());
            Ok(member)
        } else {
            Err(Error::GroupNotFound)
        }
    }

    /// Removes the given user from the hub.
    ///
    /// # Errors
    ///
    /// This function will return an error in the following situations, but is not
    /// limited to just these cases:
    ///
    /// * The user is not in the hub.
    /// * One of the permission groups the user was in could not be found in the hub.
    pub fn user_leave(&mut self, user: &User) -> Result<()> {
        if let Some(member) = self.members.get_mut(&user.id) {
            if let Some(group) = self.groups.get_mut(&self.default_group) {
                member.leave_group(group);
                self.members.remove(&user.id);
                Ok(())
            } else {
                Err(Error::GroupNotFound)
            }
        } else {
            Err(Error::NotInHub)
        }
    }

    /// Kicks the given user from the hub, forcing them to leave.
    ///
    /// # Errors
    ///
    /// This function will return an error in the following situations, but is not
    /// limited to just these cases:
    ///
    /// * The user could not be removed from the hub for any of the reasons outlined in [`Hub::user_leave`].
    /// * The user's data failed to load for any of the reasons outlined in [`User::load`].
    /// * The user's data failed to save for any of the reasons outlined in [`User::save`].
    pub async fn kick_user(&mut self, user_id: &ID) -> Result<()> {
        if self.members.contains_key(user_id) {
            let mut user = User::load(user_id).await?;
            self.user_leave(&user)?;
            if let Some(index) = user.in_hubs.iter().position(|id| id == &self.id) {
                user.in_hubs.remove(index);
            }
            user.save().await?;
            self.members.remove(&user_id);
        }
        Ok(())
    }

    /// Kicks the given user and adds them to the banned list.
    ///
    /// # Errors
    ///
    /// Possible errors outlined by [`Hub::kick_user`].
    pub async fn ban_user(&mut self, user_id: ID) -> Result<()> {
        self.kick_user(&user_id).await?;
        self.bans.insert(user_id);
        Ok(())
    }

    /// Removes the given user from the banned lis.
    pub fn unban_user(&mut self, user_id: &ID) {
        self.bans.remove(user_id);
    }

    /// Adds the given user to the mute list, preventing them from sending messages.
    pub fn mute_user(&mut self, user_id: ID) {
        self.mutes.insert(user_id);
    }

    /// Removes the given user from the mutes list, allowing them to send messages.
    pub fn unmute_user(&mut self, user_id: &ID) {
        self.mutes.remove(user_id);
    }

    /// Gets a list of the channels that the given user has permission to view.
    ///
    /// # Errors
    ///
    /// This function will only return an error if the given user is not in the hub.
    pub fn get_channels_for_user(&self, user_id: &ID) -> Result<HashMap<ID, Channel>> {
        let hub_im = self.clone();
        if let Some(user) = self.members.get(user_id) {
            let mut result = HashMap::new();
            for channel in self.channels.clone() {
                if user.has_channel_permission(&channel.0, &ChannelPermission::ViewChannel, &hub_im)
                {
                    result.insert(channel.0.clone(), channel.1.clone());
                }
            }
            Ok(result)
        } else {
            Err(Error::MemberNotFound)
        }
    }

    /// Returns a hub object with only the items that the given user is allowed to view.
    /// Only hides channels that the user does not have permission to view.
    ///
    /// # Errors
    ///
    /// Possible errors are outlined by [`Hub::get_channels_for_user`].
    pub fn strip(&self, user_id: &ID) -> Result<Self> {
        let mut hub = self.clone();
        hub.channels = self.get_channels_for_user(user_id)?;
        Ok(hub)
    }
}