Skip to main content

matrix_sdk_base/room/
tags.rs

1// Copyright 2025 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use bitflags::bitflags;
16use ruma::events::{AnyRoomAccountDataEvent, RoomAccountDataEventType, tag::Tags};
17use serde::{Deserialize, Serialize};
18
19use super::Room;
20use crate::{StateStore, store::Result as StoreResult};
21
22impl Room {
23    /// Get the `Tags` for this room.
24    pub async fn tags(&self) -> StoreResult<Option<Tags>> {
25        if let Some(AnyRoomAccountDataEvent::Tag(event)) = self
26            .store
27            .get_room_account_data_event(self.room_id(), RoomAccountDataEventType::Tag)
28            .await?
29            .and_then(|raw| raw.deserialize().ok())
30        {
31            Ok(Some(event.content.tags))
32        } else {
33            Ok(None)
34        }
35    }
36
37    /// Check whether the room is marked as favourite.
38    ///
39    /// A room is considered favourite if it has received the `m.favourite` tag.
40    pub fn is_favourite(&self) -> bool {
41        self.info.read().base_info.notable_tags.contains(RoomNotableTags::FAVOURITE)
42    }
43
44    /// Check whether the room is marked as low priority.
45    ///
46    /// A room is considered low priority if it has received the `m.lowpriority`
47    /// tag.
48    pub fn is_low_priority(&self) -> bool {
49        self.info.read().base_info.notable_tags.contains(RoomNotableTags::LOW_PRIORITY)
50    }
51}
52
53bitflags! {
54    /// Notable tags, i.e. subset of tags that we are more interested by.
55    ///
56    /// We are not interested by all the tags. Some tags are more important than
57    /// others, and this struct describes them.
58    #[repr(transparent)]
59    #[derive(Debug, Default, Clone, Copy, Deserialize, Serialize)]
60    pub(crate) struct RoomNotableTags: u8 {
61        /// The `m.favourite` tag.
62        const FAVOURITE = 0b0000_0001;
63
64        /// THe `m.lowpriority` tag.
65        const LOW_PRIORITY = 0b0000_0010;
66    }
67}
68
69#[cfg(test)]
70mod tests {
71    use std::ops::Not;
72
73    use matrix_sdk_common::cross_process_lock::CrossProcessLockConfig;
74    use matrix_sdk_test::async_test;
75    use ruma::{
76        events::tag::{TagInfo, TagName, Tags},
77        owned_device_id, owned_user_id, room_id,
78        serde::Raw,
79    };
80    use serde_json::json;
81    use stream_assert::{assert_pending, assert_ready};
82
83    use super::{super::BaseRoomInfo, RoomNotableTags};
84    use crate::{
85        BaseClient, DmRoomDefinition, RoomState, SessionMeta,
86        client::ThreadingSupport,
87        response_processors as processors,
88        store::{RoomLoadSettings, StoreConfig},
89    };
90
91    #[async_test]
92    async fn test_is_favourite() {
93        // Given a room,
94        let client = BaseClient::new(
95            StoreConfig::new(CrossProcessLockConfig::SingleProcess),
96            ThreadingSupport::Disabled,
97            DmRoomDefinition::default(),
98        );
99
100        client
101            .activate(
102                SessionMeta {
103                    user_id: owned_user_id!("@alice:example.org"),
104                    device_id: owned_device_id!("AYEAYEAYE"),
105                },
106                RoomLoadSettings::default(),
107                #[cfg(feature = "e2e-encryption")]
108                None,
109            )
110            .await
111            .unwrap();
112
113        let room_id = room_id!("!test:localhost");
114        let room = client.get_or_create_room(room_id, RoomState::Joined);
115
116        // Sanity checks to ensure the room isn't marked as favourite.
117        assert!(room.is_favourite().not());
118
119        // Subscribe to the `RoomInfo`.
120        let mut room_info_subscriber = room.subscribe_info();
121
122        assert_pending!(room_info_subscriber);
123
124        // Create the tag.
125        let tag_raw = Raw::new(&json!({
126            "content": {
127                "tags": {
128                    "m.favourite": {
129                        "order": 0.0
130                    },
131                },
132            },
133            "type": "m.tag",
134        }))
135        .unwrap()
136        .cast_unchecked();
137
138        // When the new tag is handled and applied.
139        let mut context = processors::Context::default();
140
141        processors::account_data::for_room(&mut context, room_id, &[tag_raw], &client.state_store);
142
143        processors::changes::save_and_apply(
144            context.clone(),
145            &client.state_store,
146            &client.state_store_lock().lock().await,
147            &client.ignore_user_list_changes,
148            None,
149        )
150        .await
151        .unwrap();
152
153        // The `RoomInfo` is getting notified.
154        assert_ready!(room_info_subscriber);
155        assert_pending!(room_info_subscriber);
156
157        // The room is now marked as favourite.
158        assert!(room.is_favourite());
159
160        // Now, let's remove the tag.
161        let tag_raw = Raw::new(&json!({
162            "content": {
163                "tags": {},
164            },
165            "type": "m.tag"
166        }))
167        .unwrap()
168        .cast_unchecked();
169
170        processors::account_data::for_room(&mut context, room_id, &[tag_raw], &client.state_store);
171
172        processors::changes::save_and_apply(
173            context,
174            &client.state_store,
175            &client.state_store_lock().lock().await,
176            &client.ignore_user_list_changes,
177            None,
178        )
179        .await
180        .unwrap();
181
182        // The `RoomInfo` is getting notified.
183        assert_ready!(room_info_subscriber);
184        assert_pending!(room_info_subscriber);
185
186        // The room is now marked as _not_ favourite.
187        assert!(room.is_favourite().not());
188    }
189
190    #[async_test]
191    async fn test_is_low_priority() {
192        // Given a room,
193        let client = BaseClient::new(
194            StoreConfig::new(CrossProcessLockConfig::SingleProcess),
195            ThreadingSupport::Disabled,
196            DmRoomDefinition::default(),
197        );
198
199        client
200            .activate(
201                SessionMeta {
202                    user_id: owned_user_id!("@alice:example.org"),
203                    device_id: owned_device_id!("AYEAYEAYE"),
204                },
205                RoomLoadSettings::default(),
206                #[cfg(feature = "e2e-encryption")]
207                None,
208            )
209            .await
210            .unwrap();
211
212        let room_id = room_id!("!test:localhost");
213        let room = client.get_or_create_room(room_id, RoomState::Joined);
214
215        // Sanity checks to ensure the room isn't marked as low priority.
216        assert!(!room.is_low_priority());
217
218        // Subscribe to the `RoomInfo`.
219        let mut room_info_subscriber = room.subscribe_info();
220
221        assert_pending!(room_info_subscriber);
222
223        // Create the tag.
224        let tag_raw = Raw::new(&json!({
225            "content": {
226                "tags": {
227                    "m.lowpriority": {
228                        "order": 0.0
229                    },
230                }
231            },
232            "type": "m.tag"
233        }))
234        .unwrap()
235        .cast_unchecked();
236
237        // When the new tag is handled and applied.
238        let mut context = processors::Context::default();
239
240        processors::account_data::for_room(&mut context, room_id, &[tag_raw], &client.state_store);
241
242        processors::changes::save_and_apply(
243            context.clone(),
244            &client.state_store,
245            &client.state_store_lock().lock().await,
246            &client.ignore_user_list_changes,
247            None,
248        )
249        .await
250        .unwrap();
251
252        // The `RoomInfo` is getting notified.
253        assert_ready!(room_info_subscriber);
254        assert_pending!(room_info_subscriber);
255
256        // The room is now marked as low priority.
257        assert!(room.is_low_priority());
258
259        // Now, let's remove the tag.
260        let tag_raw = Raw::new(&json!({
261            "content": {
262                "tags": {},
263            },
264            "type": "m.tag"
265        }))
266        .unwrap()
267        .cast_unchecked();
268
269        processors::account_data::for_room(&mut context, room_id, &[tag_raw], &client.state_store);
270
271        processors::changes::save_and_apply(
272            context,
273            &client.state_store,
274            &client.state_store_lock().lock().await,
275            &client.ignore_user_list_changes,
276            None,
277        )
278        .await
279        .unwrap();
280
281        // The `RoomInfo` is getting notified.
282        assert_ready!(room_info_subscriber);
283        assert_pending!(room_info_subscriber);
284
285        // The room is now marked as _not_ low priority.
286        assert!(room.is_low_priority().not());
287    }
288
289    #[test]
290    fn test_handle_notable_tags_favourite() {
291        let mut base_room_info = BaseRoomInfo::default();
292
293        let mut tags = Tags::new();
294        tags.insert(TagName::Favorite, TagInfo::default());
295
296        assert!(base_room_info.notable_tags.contains(RoomNotableTags::FAVOURITE).not());
297        base_room_info.handle_notable_tags(&tags);
298        assert!(base_room_info.notable_tags.contains(RoomNotableTags::FAVOURITE));
299        tags.clear();
300        base_room_info.handle_notable_tags(&tags);
301        assert!(base_room_info.notable_tags.contains(RoomNotableTags::FAVOURITE).not());
302    }
303
304    #[test]
305    fn test_handle_notable_tags_low_priority() {
306        let mut base_room_info = BaseRoomInfo::default();
307
308        let mut tags = Tags::new();
309        tags.insert(TagName::LowPriority, TagInfo::default());
310
311        assert!(base_room_info.notable_tags.contains(RoomNotableTags::LOW_PRIORITY).not());
312        base_room_info.handle_notable_tags(&tags);
313        assert!(base_room_info.notable_tags.contains(RoomNotableTags::LOW_PRIORITY));
314        tags.clear();
315        base_room_info.handle_notable_tags(&tags);
316        assert!(base_room_info.notable_tags.contains(RoomNotableTags::LOW_PRIORITY).not());
317    }
318}