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
// Copyright 2024 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use matrix_sdk::{Client, RoomListEntry};

use super::Filter;

/// An enum to represent whether a room is about “people” (strictly 2 users) or
/// “group” (1 or more than 2 users).
///
/// Ideally, we would only want to rely on the
/// [`matrix_sdk::BaseRoom::is_direct`] method, but the rules are a little bit
/// different for this high-level UI API.
///
/// This is implemented this way so that it's impossible to filter by “group”
/// and by “people” at the same time: these criteria are mutually
/// exclusive by design per filter.
#[derive(Copy, Clone, PartialEq)]
pub enum RoomCategory {
    Group,
    People,
}

type DirectTargetsLength = usize;

struct CategoryRoomMatcher<F>
where
    F: Fn(&RoomListEntry) -> Option<DirectTargetsLength>,
{
    /// _Direct targets_ mean the number of users in a direct room, except us.
    /// So if it returns 1, it means there are 2 users in the direct room.
    number_of_direct_targets: F,
}

impl<F> CategoryRoomMatcher<F>
where
    F: Fn(&RoomListEntry) -> Option<DirectTargetsLength>,
{
    fn matches(&self, room_list_entry: &RoomListEntry, expected_kind: RoomCategory) -> bool {
        if !matches!(room_list_entry, RoomListEntry::Filled(_) | RoomListEntry::Invalidated(_)) {
            return false;
        }

        let kind = match (self.number_of_direct_targets)(room_list_entry) {
            // If 1, we are sure it's a direct room between two users. It's the strict
            // definition of the `People` category, all good.
            Some(1) => RoomCategory::People,

            // If smaller than 1, we are not sure it's a direct room, it's then a `Group`.
            // If greater than 1, we are sure it's a direct room but not between
            // two users, so it's a `Group` based on our expectation.
            Some(_) => RoomCategory::Group,

            // Don't know.
            None => return false,
        };

        kind == expected_kind
    }
}

/// Create a new filter that will accept all filled or invalidated entries, and
/// if the associated rooms fit in the `expected_category`. The category is
/// defined by [`RoomCategory`], see this type to learn more.
pub fn new_filter(client: &Client, expected_category: RoomCategory) -> impl Filter {
    let client = client.clone();

    let matcher = CategoryRoomMatcher {
        number_of_direct_targets: move |room| {
            let room_id = room.as_room_id()?;
            let room = client.get_room(room_id)?;

            Some(room.direct_targets_length())
        },
    };

    move |room_list_entry| -> bool { matcher.matches(room_list_entry, expected_category) }
}

#[cfg(test)]
mod tests {
    use std::ops::Not;

    use matrix_sdk::RoomListEntry;
    use ruma::room_id;

    use super::{CategoryRoomMatcher, RoomCategory};

    #[test]
    fn test_kind_is_group() {
        let matcher = CategoryRoomMatcher { number_of_direct_targets: |_| Some(42) };

        // Expect `People`.
        {
            let expected_kind = RoomCategory::People;

            assert!(matcher.matches(&RoomListEntry::Empty, expected_kind).not());
            assert!(
                matcher
                    .matches(
                        &RoomListEntry::Filled(room_id!("!r0:bar.org").to_owned(),),
                        expected_kind,
                    )
                    .not()
            );
            assert!(matcher
                .matches(
                    &RoomListEntry::Invalidated(room_id!("!r0:bar.org").to_owned()),
                    expected_kind
                )
                .not());
        }

        // Expect `Group`.
        {
            let expected_kind = RoomCategory::Group;

            assert!(matcher.matches(&RoomListEntry::Empty, expected_kind).not());
            assert!(matcher.matches(
                &RoomListEntry::Filled(room_id!("!r0:bar.org").to_owned(),),
                expected_kind,
            ));
            assert!(matcher.matches(
                &RoomListEntry::Invalidated(room_id!("!r0:bar.org").to_owned()),
                expected_kind,
            ));
        }
    }

    #[test]
    fn test_kind_is_people() {
        let matcher = CategoryRoomMatcher { number_of_direct_targets: |_| Some(1) };

        // Expect `People`.
        {
            let expected_kind = RoomCategory::People;

            assert!(matcher.matches(&RoomListEntry::Empty, expected_kind).not());
            assert!(matcher.matches(
                &RoomListEntry::Filled(room_id!("!r0:bar.org").to_owned()),
                expected_kind,
            ));
            assert!(matcher.matches(
                &RoomListEntry::Invalidated(room_id!("!r0:bar.org").to_owned()),
                expected_kind
            ));
        }

        // Expect `Group`.
        {
            let expected_kind = RoomCategory::Group;

            assert!(matcher.matches(&RoomListEntry::Empty, expected_kind).not());
            assert!(
                matcher
                    .matches(
                        &RoomListEntry::Filled(room_id!("!r0:bar.org").to_owned(),),
                        expected_kind,
                    )
                    .not()
            );
            assert!(matcher
                .matches(
                    &RoomListEntry::Invalidated(room_id!("!r0:bar.org").to_owned()),
                    expected_kind,
                )
                .not());
        }
    }

    #[test]
    fn test_room_kind_cannot_be_found() {
        let matcher = CategoryRoomMatcher { number_of_direct_targets: |_| None };

        assert!(matcher.matches(&RoomListEntry::Empty, RoomCategory::Group).not());
        assert!(matcher
            .matches(
                &RoomListEntry::Filled(room_id!("!r0:bar.org").to_owned()),
                RoomCategory::Group
            )
            .not());
        assert!(matcher
            .matches(
                &RoomListEntry::Invalidated(room_id!("!r0:bar.org").to_owned()),
                RoomCategory::Group
            )
            .not());
    }
}