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
use futures_util::StreamExt;
use gtk::{
    gio,
    glib::{self, clone},
    prelude::*,
    subclass::prelude::*,
};
use indexmap::IndexSet;
use ruma::{events::ignored_user_list::IgnoredUserListEventContent, OwnedUserId};
use tracing::{debug, error, warn};

use super::Session;
use crate::{spawn, spawn_tokio};

mod imp {
    use std::cell::RefCell;

    use super::*;

    #[derive(Debug, Default, glib::Properties)]
    #[properties(wrapper_type = super::IgnoredUsers)]
    pub struct IgnoredUsers {
        /// The current session.
        #[property(get, set = Self::set_session, explicit_notify, nullable)]
        pub session: glib::WeakRef<Session>,
        /// The content of the ignored user list event.
        pub list: RefCell<IndexSet<OwnedUserId>>,
        abort_handle: RefCell<Option<tokio::task::AbortHandle>>,
    }

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

    #[glib::derived_properties]
    impl ObjectImpl for IgnoredUsers {
        fn dispose(&self) {
            if let Some(abort_handle) = self.abort_handle.take() {
                abort_handle.abort();
            }
        }
    }

    impl ListModelImpl for IgnoredUsers {
        fn item_type(&self) -> glib::Type {
            gtk::StringObject::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(|user_id| gtk::StringObject::new(user_id.as_str()).upcast())
        }
    }

    impl IgnoredUsers {
        /// Set the current session.
        fn set_session(&self, session: Option<Session>) {
            if self.session.upgrade() == session {
                return;
            }

            self.session.set(session.as_ref());

            self.init();
            self.obj().notify_session();
        }

        /// Listen to changes of the ignored users list.
        fn init(&self) {
            if let Some(abort_handle) = self.abort_handle.take() {
                abort_handle.abort();
            }

            let Some(session) = self.session.upgrade() else {
                return;
            };
            let obj = self.obj();

            let obj_weak = glib::SendWeakRef::from(obj.downgrade());
            let subscriber = session.client().subscribe_to_ignore_user_list_changes();
            let fut = subscriber.for_each(move |_| {
                let obj_weak = obj_weak.clone();
                async move {
                    let ctx = glib::MainContext::default();
                    ctx.spawn(async move {
                        spawn!(async move {
                            if let Some(obj) = obj_weak.upgrade() {
                                obj.imp().load_list().await;
                            }
                        });
                    });
                }
            });

            let abort_handle = spawn_tokio!(fut).abort_handle();
            self.abort_handle.replace(Some(abort_handle));

            spawn!(clone!(
                #[weak(rename_to = imp)]
                self,
                async move {
                    imp.load_list().await;
                }
            ));
        }

        /// Load the list from the store and update it.
        async fn load_list(&self) {
            let Some(session) = self.session.upgrade() else {
                return;
            };

            let client = session.client();
            let handle = spawn_tokio!(async move {
                client
                    .account()
                    .account_data::<IgnoredUserListEventContent>()
                    .await
            });

            let raw = match handle.await.unwrap() {
                Ok(Some(raw)) => raw,
                Ok(None) => {
                    debug!("Got no ignored users list");
                    self.update_list(IndexSet::new());
                    return;
                }
                Err(error) => {
                    error!("Could not get ignored users list: {error}");
                    return;
                }
            };

            match raw.deserialize() {
                Ok(content) => self.update_list(content.ignored_users.into_keys().collect()),
                Err(error) => {
                    error!("Could not deserialize ignored users list: {error}");
                }
            }
        }

        /// Update the list with the given new list.
        fn update_list(&self, new_list: IndexSet<OwnedUserId>) {
            if *self.list.borrow() == new_list {
                return;
            }

            let old_len = self.n_items();
            let new_len = new_list.len() as u32;

            let mut pos = 0;
            {
                let old_list = self.list.borrow();

                for old_item in old_list.iter() {
                    let Some(new_item) = new_list.get_index(pos as usize) else {
                        break;
                    };

                    if old_item != new_item {
                        break;
                    }

                    pos += 1;
                }
            }

            if old_len == new_len && pos == new_len {
                // Nothing changed.
                return;
            }

            self.list.replace(new_list);

            self.obj().items_changed(
                pos,
                old_len.saturating_sub(pos),
                new_len.saturating_sub(pos),
            );
        }
    }
}

glib::wrapper! {
    /// The list of ignored users of a `Session`.
    pub struct IgnoredUsers(ObjectSubclass<imp::IgnoredUsers>)
        @implements gio::ListModel;
}

impl IgnoredUsers {
    pub fn new() -> Self {
        glib::Object::new()
    }

    /// Whether this list contains the given user ID.
    pub fn contains(&self, user_id: &OwnedUserId) -> bool {
        self.imp().list.borrow().contains(user_id)
    }

    /// Add the user with the given ID to the list.
    pub async fn add(&self, user_id: &OwnedUserId) -> Result<(), ()> {
        let Some(session) = self.session() else {
            return Err(());
        };

        if self.contains(user_id) {
            warn!("Trying to add `{user_id}` to the ignored users but they are already in the list, ignoring");
            return Ok(());
        }

        let client = session.client();
        let user_id_clone = user_id.clone();
        let handle =
            spawn_tokio!(async move { client.account().ignore_user(&user_id_clone).await });

        match handle.await.unwrap() {
            Ok(_) => {
                let (pos, added) = self.imp().list.borrow_mut().insert_full(user_id.clone());

                if added {
                    self.items_changed(pos as u32, 0, 1);
                }
                Ok(())
            }
            Err(error) => {
                error!("Could not add `{user_id}` to the ignored users: {error}");
                Err(())
            }
        }
    }

    /// Remove the user with the given ID from the list.
    pub async fn remove(&self, user_id: &OwnedUserId) -> Result<(), ()> {
        let Some(session) = self.session() else {
            return Err(());
        };

        if !self.contains(user_id) {
            warn!("Trying to remove `{user_id}` from the ignored users but they are not in the list, ignoring");
            return Ok(());
        }

        let client = session.client();
        let user_id_clone = user_id.clone();
        let handle =
            spawn_tokio!(async move { client.account().unignore_user(&user_id_clone).await });

        match handle.await.unwrap() {
            Ok(_) => {
                let removed = self.imp().list.borrow_mut().shift_remove_full(user_id);

                if let Some((pos, _)) = removed {
                    self.items_changed(pos as u32, 1, 0);
                }
                Ok(())
            }
            Err(error) => {
                error!("Could not remove `{user_id}` from the ignored users: {error}");
                Err(())
            }
        }
    }
}

impl Default for IgnoredUsers {
    fn default() -> Self {
        Self::new()
    }
}