xmpp/
room_manager.rs

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
// Copyright (c) 2024 xmpp-rs contributors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

use crate::{
    jid::BareJid,
    muc::{private_message::RoomPrivateMessageSettings, room::RoomMessageSettings},
    parsers::{disco::DiscoInfoResult, occupant_id::OccupantId},
    RoomNick,
};

use alloc::collections::BTreeMap;

#[derive(Clone, Debug, Default)]
pub struct RoomManager {
    pub rooms: BTreeMap<BareJid, Room>,
}

impl RoomManager {
    pub fn get(&self, room: &BareJid) -> Option<Room> {
        self.rooms.get(room).cloned()
    }

    /// Gets the user's nickname in a specific room. Panic if not joined/joining
    pub fn get_nick(&self, room: &BareJid) -> Option<RoomNick> {
        if let Some(room) = self.get(room) {
            match room.status {
                RoomStatus::Joined | RoomStatus::Joining => Some(room.nick.clone()),
                // TODO: should calling get_nick on room leaving return nick?
                _ => None,
            }
        } else {
            None
        }
    }

    /// Unchecked variant of [`RoomManager::get_nick`]
    pub fn get_nick_unchecked(&self, room: &BareJid) -> RoomNick {
        self.get(room).unwrap().nick.clone()
    }

    /// Sets a room to joining
    pub fn set_room_joining(&mut self, room: &BareJid, requested_nick: &RoomNick) {
        if let Some(entry) = self.rooms.get_mut(room) {
            match entry.status {
                RoomStatus::Joining | RoomStatus::Joined => {
                    warn!("Trying to set room joining which is already joining/joined: {room}");
                }
                _ => entry.status = RoomStatus::Joining,
            }
        } else {
            self.rooms.insert(
                room.to_owned(),
                Room {
                    status: RoomStatus::Joining,
                    jid: room.to_owned(),
                    nick: requested_nick.to_owned(),
                    info: None,
                    members: BTreeMap::new(),
                },
            );
        }
    }

    /// Sets a room to joined, panics if it's not joining/joined
    pub fn set_room_joined(&mut self, room: &BareJid, nick: &RoomNick) {
        if let Some(entry) = self.rooms.get_mut(room) {
            match entry.status {
                RoomStatus::Joining => {
                    entry.status = RoomStatus::Joined;
                    entry.nick = nick.to_owned();
                    return;
                }
                RoomStatus::Joined => {
                    warn!("Trying to set room joined which is already joined: {room}");
                    return;
                }
                _ => {
                    error!("Trying to set room joined which is leaving/left: {room}");
                }
            }
        } else {
            error!("Trying to set room joined which is unknown: {room}");
        }

        unreachable!("Your client tried to set a room joined which was not joining. This is probably a logic bug!");
    }

    /// Sets a room to leaving, panics if it's already left, or unknown
    pub fn set_room_leaving(&mut self, room: &BareJid) {
        if let Some(entry) = self.rooms.get_mut(room) {
            match entry.status {
                RoomStatus::Joining | RoomStatus::Joined => {
                    entry.status = RoomStatus::Leaving;
                    return;
                }
                RoomStatus::Leaving => {
                    warn!("Trying to set room leaving which is already leaving: {room}");
                    return;
                }
                _ => {
                    error!("Trying to set room joined which is leaving/left: {room}");
                }
            }
        } else {
            error!("Trying to set room joined which is unknown: {room}");
        }

        unreachable!("Your client tried to set a room leaving which was not joining/joined/leaving. This is probably a logic bug!");
    }

    pub fn set_room_left(&mut self, room: &BareJid) {
        if let Some(entry) = self.rooms.get_mut(room) {
            match entry.status {
                RoomStatus::Leaving => {
                    entry.status = RoomStatus::None;
                    return;
                }
                RoomStatus::None => {
                    warn!("Trying to set room left which is already left: {room}");
                    return;
                }
                _ => {
                    error!("Trying to set room left which is joined/joining: {room}");
                }
            }
        } else {
            error!("Trying to set room left which is unknown: {room}");
        }

        unreachable!("Your client tried to set a room left which was not leaving/left. This is probably a logic bug!");
    }

    /// Checks whether the room is already joined
    pub fn is_joined(&self, room: &BareJid) -> bool {
        self.get(room)
            .map(|r| r.status == RoomStatus::Joined)
            .unwrap_or(false)
    }

    /// Checks whether the room is already joining
    pub fn is_joining(&self, room: &BareJid) -> bool {
        self.get(room)
            .map(|r| r.status == RoomStatus::Joining)
            .unwrap_or(false)
    }

    /// Checks whether the room is already leaving
    pub fn is_leaving(&self, room: &BareJid) -> bool {
        self.get(room)
            .map(|r| r.status == RoomStatus::Leaving)
            .unwrap_or(false)
    }

    /// Lists currently joined rooms
    pub fn rooms_joined<'a>(&'a self) -> Vec<&'a Room> {
        self.rooms
            .iter()
            .filter_map(|(_barejid, room)| {
                if room.status == RoomStatus::Joined {
                    Some(room)
                } else {
                    None
                }
            })
            .collect()
    }
}

/// A chatroom based on the MUC protocol.
///
/// Members are stored with a RoomNick->OccupantId mapping, because the latter
/// is guaranteed to be stable
#[derive(Clone, Debug)]
pub struct Room {
    pub status: RoomStatus,
    pub jid: BareJid,
    /// Nickname associated with the user in a certain Room.
    ///
    /// - when RoomStatus::Joining, it's the nick requested by the client
    /// - when RoomStatus::Joined, it's the nick approved by the server
    ///
    /// Indeed, the server may have reserved nicks, or other reasons to rewrite
    /// the user's nickname.
    pub nick: RoomNick,
    // TODO
    pub info: Option<DiscoInfoResult>,
    pub members: BTreeMap<OccupantId, RoomMember>,
}

impl Room {
    pub fn message<'a>(&self, message: &'a str) -> RoomMessageSettings<'a> {
        RoomMessageSettings::new(self.jid.clone(), message)
    }

    pub fn member<'a>(&'a self, id: &OccupantId) -> Option<&'a RoomMember> {
        self.members.get(id)
    }
}

/// A chatroom member.
#[derive(Clone, Debug)]
pub struct RoomMember {
    pub room: BareJid,
    pub nick: RoomNick,
    pub occupant_id: OccupantId,
}

impl RoomMember {
    pub fn nick(&self) -> &RoomNick {
        &self.nick
    }

    pub fn nick_str(&self) -> &str {
        self.nick.as_str()
    }

    pub fn message<'a>(&self, message: &'a str) -> RoomPrivateMessageSettings<'a> {
        RoomPrivateMessageSettings::new(self.room.clone(), self.nick.clone(), message)
    }
}

/// Connection status to a room.
#[derive(Clone, Debug, PartialEq)]
pub enum RoomStatus {
    Joining,
    Joined,
    Leaving,
    None,
}