fractal/session/model/room_list/
mod.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
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 std::{
    cell::Cell,
    collections::{HashMap, HashSet},
};

use gtk::{
    gio, glib,
    glib::{clone, closure_local},
    prelude::*,
    subclass::prelude::*,
};
use indexmap::IndexMap;
use matrix_sdk::sync::RoomUpdates;
use ruma::{OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, RoomId, RoomOrAliasId, UserId};
use tracing::{error, warn};

mod room_list_metainfo;

use self::room_list_metainfo::RoomListMetainfo;
pub use self::room_list_metainfo::RoomMetainfo;
use crate::{
    gettext_f,
    prelude::*,
    session::model::{Room, Session},
    spawn_tokio,
};

mod imp {
    use std::{cell::RefCell, sync::LazyLock};

    use glib::subclass::Signal;

    use super::*;

    #[derive(Debug, Default, glib::Properties)]
    #[properties(wrapper_type = super::RoomList)]
    pub struct RoomList {
        /// The list of rooms.
        pub list: RefCell<IndexMap<OwnedRoomId, Room>>,
        /// The list of rooms we are currently joining.
        pub pending_rooms: RefCell<HashSet<OwnedRoomOrAliasId>>,
        /// The list of rooms that were upgraded and for which we haven't joined
        /// the successor yet.
        pub tombstoned_rooms: RefCell<HashSet<OwnedRoomId>>,
        /// The current session.
        #[property(get, construct_only)]
        pub session: glib::WeakRef<Session>,
        /// The rooms metainfo that allow to restore this `RoomList` from its
        /// previous state.
        ///
        /// This is in a Mutex because updating the data in the store is async
        /// and we don't want to overwrite newer data with older data.
        pub metainfo: RoomListMetainfo,
    }

    #[glib::object_subclass]
    impl ObjectSubclass for RoomList {
        const NAME: &'static str = "RoomList";
        type Type = super::RoomList;
        type Interfaces = (gio::ListModel,);
    }

    #[glib::derived_properties]
    impl ObjectImpl for RoomList {
        fn signals() -> &'static [Signal] {
            static SIGNALS: LazyLock<Vec<Signal>> =
                LazyLock::new(|| vec![Signal::builder("pending-rooms-changed").build()]);
            SIGNALS.as_ref()
        }

        fn constructed(&self) {
            self.parent_constructed();
            self.metainfo.set_room_list(&self.obj());
        }
    }

    impl ListModelImpl for RoomList {
        fn item_type(&self) -> glib::Type {
            Room::static_type()
        }

        fn n_items(&self) -> u32 {
            self.list.borrow().len() as u32
        }

        fn item(&self, position: u32) -> Option<glib::Object> {
            self.list
                .borrow()
                .get_index(position as usize)
                .map(|(_, v)| v.upcast_ref::<glib::Object>())
                .cloned()
        }
    }
}

glib::wrapper! {
    /// List of all joined rooms of the user.
    ///
    /// This is the parent ListModel of the sidebar from which all other models
    /// are derived.
    ///
    /// The `RoomList` also takes care of all so called *pending rooms*, i.e.
    /// rooms the user requested to join, but received no response from the
    /// server yet.
    pub struct RoomList(ObjectSubclass<imp::RoomList>)
        @implements gio::ListModel;
}

impl RoomList {
    pub fn new(session: &Session) -> Self {
        glib::Object::builder().property("session", session).build()
    }

    /// Get a snapshot of the rooms list.
    pub fn snapshot(&self) -> Vec<Room> {
        self.imp().list.borrow().values().cloned().collect()
    }

    /// Whether the room with the given identifier is pending.
    pub fn is_pending_room(&self, identifier: &RoomOrAliasId) -> bool {
        self.imp().pending_rooms.borrow().contains(identifier)
    }

    fn pending_rooms_remove(&self, identifier: &RoomOrAliasId) {
        self.imp().pending_rooms.borrow_mut().remove(identifier);
        self.emit_by_name::<()>("pending-rooms-changed", &[]);
    }

    fn pending_rooms_insert(&self, identifier: OwnedRoomOrAliasId) {
        self.imp().pending_rooms.borrow_mut().insert(identifier);
        self.emit_by_name::<()>("pending-rooms-changed", &[]);
    }

    fn pending_rooms_replace_or_remove(&self, identifier: &RoomOrAliasId, room_id: &RoomId) {
        {
            let mut pending_rooms = self.imp().pending_rooms.borrow_mut();
            pending_rooms.remove(identifier);
            if !self.contains(room_id) {
                pending_rooms.insert(room_id.to_owned().into());
            }
        }
        self.emit_by_name::<()>("pending-rooms-changed", &[]);
    }

    /// Get the room with the given room ID, if any.
    pub fn get(&self, room_id: &RoomId) -> Option<Room> {
        self.imp().list.borrow().get(room_id).cloned()
    }

    /// Get the room with the given identifier, if any.
    pub fn get_by_identifier(&self, identifier: &RoomOrAliasId) -> Option<Room> {
        match <&RoomId>::try_from(identifier) {
            Ok(room_id) => self.get(room_id),
            Err(room_alias) => {
                let mut matches = self
                    .imp()
                    .list
                    .borrow()
                    .iter()
                    .filter(|(_, room)| {
                        let matrix_room = room.matrix_room();
                        matrix_room.canonical_alias().as_deref() == Some(room_alias)
                            || matrix_room.alt_aliases().iter().any(|a| a == room_alias)
                    })
                    .map(|(room_id, room)| (room_id.clone(), room.clone()))
                    .collect::<HashMap<_, _>>();

                if matches.len() <= 1 {
                    return matches.into_values().next();
                }

                // The alias is shared between upgraded rooms. We want the latest room, so
                // filter out those that are predecessors.
                let predecessors = matches
                    .iter()
                    .filter_map(|(_, room)| room.predecessor_id().cloned())
                    .collect::<Vec<_>>();
                for room_id in predecessors {
                    matches.remove(&room_id);
                }

                if matches.len() <= 1 {
                    return matches.into_values().next();
                }

                // Ideally this should not happen, return the one with the latest activity.
                matches
                    .into_values()
                    .fold(None::<Room>, |latest_room, room| {
                        latest_room
                            .filter(|r| r.latest_activity() >= room.latest_activity())
                            .or(Some(room))
                    })
            }
        }
    }

    /// Wait till the room with the given ID becomes available.
    pub async fn get_wait(&self, room_id: &RoomId) -> Option<Room> {
        if let Some(room) = self.get(room_id) {
            Some(room)
        } else {
            let (sender, receiver) = futures_channel::oneshot::channel();

            let room_id = room_id.to_owned();
            let sender = Cell::new(Some(sender));
            // FIXME: add a timeout
            let handler_id = self.connect_items_changed(move |obj, _, _, _| {
                if let Some(room) = obj.get(&room_id) {
                    if let Some(sender) = sender.take() {
                        sender.send(Some(room)).unwrap();
                    }
                }
            });

            let room = receiver.await.unwrap();
            self.disconnect(handler_id);
            room
        }
    }

    /// Whether this list contains the room with the given ID.
    pub fn contains(&self, room_id: &RoomId) -> bool {
        self.imp().list.borrow().contains_key(room_id)
    }

    /// Remove the room with the given ID.
    pub fn remove(&self, room_id: &RoomId) {
        let imp = self.imp();

        let removed = {
            let mut list = imp.list.borrow_mut();

            list.shift_remove_full(room_id)
        };

        imp.tombstoned_rooms.borrow_mut().remove(room_id);

        if let Some((position, ..)) = removed {
            self.items_changed(position as u32, 1, 0);
        }
    }

    fn items_added(&self, added: usize) {
        let position = {
            let imp = self.imp();
            let list = imp.list.borrow();

            let position = list.len().saturating_sub(added);

            let mut tombstoned_rooms_to_remove = Vec::new();
            for (_room_id, room) in list.iter().skip(position) {
                room.connect_room_forgotten(clone!(
                    #[weak(rename_to = obj)]
                    self,
                    move |room| {
                        obj.remove(room.room_id());
                    }
                ));

                // Check if the new room is the successor to a tombstoned room.
                if let Some(predecessor_id) = room.predecessor_id() {
                    if imp.tombstoned_rooms.borrow().contains(predecessor_id) {
                        if let Some(room) = self.get(predecessor_id) {
                            room.update_successor();
                            tombstoned_rooms_to_remove.push(predecessor_id.clone());
                        }
                    }
                }
            }

            if !tombstoned_rooms_to_remove.is_empty() {
                let mut tombstoned_rooms = imp.tombstoned_rooms.borrow_mut();
                for room_id in tombstoned_rooms_to_remove {
                    tombstoned_rooms.remove(&room_id);
                }
            }

            position
        };

        self.items_changed(position as u32, 0, added as u32);
    }

    /// Loads the state from the `Store`.
    ///
    /// Note that the `Store` currently doesn't store all events, therefore, we
    /// aren't really loading much via this function.
    pub async fn load(&self) {
        let imp = self.imp();

        let rooms = imp.metainfo.load_rooms().await;
        let added = rooms.len();
        imp.list.borrow_mut().extend(rooms);

        self.items_added(added);
    }

    pub fn handle_room_updates(&self, rooms: RoomUpdates) {
        let Some(session) = self.session() else {
            return;
        };
        let imp = self.imp();
        let client = session.client();

        let mut new_rooms = HashMap::new();

        for (room_id, left_room) in rooms.leave {
            let room = if let Some(room) = self.get(&room_id) {
                room
            } else if let Some(matrix_room) = client.get_room(&room_id) {
                new_rooms
                    .entry(room_id.clone())
                    .or_insert_with(|| Room::new(&session, matrix_room, None))
                    .clone()
            } else {
                warn!("Could not find left room {room_id}");
                continue;
            };

            self.pending_rooms_remove((*room_id).into());
            room.handle_ambiguity_changes(left_room.ambiguity_changes.values());
        }

        for (room_id, joined_room) in rooms.join {
            let room = if let Some(room) = self.get(&room_id) {
                room
            } else if let Some(matrix_room) = client.get_room(&room_id) {
                new_rooms
                    .entry(room_id.clone())
                    .or_insert_with(|| Room::new(&session, matrix_room, None))
                    .clone()
            } else {
                warn!("Could not find joined room {room_id}");
                continue;
            };

            self.pending_rooms_remove((*room_id).into());
            imp.metainfo.watch_room(&room);
            room.handle_ambiguity_changes(joined_room.ambiguity_changes.values());
        }

        for (room_id, _invited_room) in rooms.invite {
            let room = if let Some(room) = self.get(&room_id) {
                room
            } else if let Some(matrix_room) = client.get_room(&room_id) {
                new_rooms
                    .entry(room_id.clone())
                    .or_insert_with(|| Room::new(&session, matrix_room, None))
                    .clone()
            } else {
                warn!("Could not find invited room {room_id}");
                continue;
            };

            self.pending_rooms_remove((*room_id).into());
            imp.metainfo.watch_room(&room);
        }

        if !new_rooms.is_empty() {
            let added = new_rooms.len();
            imp.list.borrow_mut().extend(new_rooms);
            self.items_added(added);
        }
    }

    /// Join the room with the given identifier.
    pub async fn join_by_id_or_alias(
        &self,
        identifier: OwnedRoomOrAliasId,
        via: Vec<OwnedServerName>,
    ) -> Result<OwnedRoomId, String> {
        let Some(session) = self.session() else {
            return Err("Could not upgrade Session".to_owned());
        };
        let client = session.client();
        let identifier_clone = identifier.clone();

        self.pending_rooms_insert(identifier.clone());

        let handle = spawn_tokio!(async move {
            client
                .join_room_by_id_or_alias(&identifier_clone, &via)
                .await
        });

        match handle.await.unwrap() {
            Ok(matrix_room) => {
                self.pending_rooms_replace_or_remove(&identifier, matrix_room.room_id());
                Ok(matrix_room.room_id().to_owned())
            }
            Err(error) => {
                self.pending_rooms_remove(&identifier);
                error!("Joining room {identifier} failed: {error}");

                let error = gettext_f(
                    // Translators: Do NOT translate the content between '{' and '}', this is a
                    // variable name.
                    "Could not join room {room_name}",
                    &[("room_name", identifier.as_str())],
                );

                Err(error)
            }
        }
    }

    pub fn connect_pending_rooms_changed<F: Fn(&Self) + 'static>(
        &self,
        f: F,
    ) -> glib::SignalHandlerId {
        self.connect_closure(
            "pending-rooms-changed",
            true,
            closure_local!(move |obj: Self| {
                f(&obj);
            }),
        )
    }

    /// Get the room with the given identifier, if it is joined.
    pub fn joined_room(&self, identifier: &RoomOrAliasId) -> Option<Room> {
        self.get_by_identifier(identifier).filter(Room::is_joined)
    }

    /// Add a room that was tombstoned but for which we haven't joined the
    /// successor yet.
    pub fn add_tombstoned_room(&self, room_id: OwnedRoomId) {
        self.imp().tombstoned_rooms.borrow_mut().insert(room_id);
    }

    /// Get the joined room that is a direct chat with the user with the given
    /// ID.
    ///
    /// If several rooms are found, returns the room with the latest activity.
    pub fn direct_chat(&self, user_id: &UserId) -> Option<Room> {
        self.imp()
            .list
            .borrow()
            .values()
            .filter(|r| {
                // A joined room where the direct member is the given user.
                r.is_joined() && r.direct_member().as_ref().map(|m| &**m.user_id()) == Some(user_id)
            })
            // Take the room with the latest activity.
            .max_by(|x, y| x.latest_activity().cmp(&y.latest_activity()))
            .cloned()
    }
}