matrix_sdk_base/response_processors/e2ee/
tracked_users.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 std::collections::BTreeSet;
16
17use matrix_sdk_crypto::OlmMachine;
18use ruma::{OwnedUserId, RoomId};
19
20use crate::{store::BaseStateStore, EncryptionState, Result, RoomMemberships};
21
22/// Update tracked users, if the room is encrypted.
23pub async fn update(
24    olm_machine: Option<&OlmMachine>,
25    room_encryption_state: EncryptionState,
26    user_ids_to_track: &BTreeSet<OwnedUserId>,
27) -> Result<()> {
28    if room_encryption_state.is_encrypted() {
29        if let Some(olm) = olm_machine {
30            if !user_ids_to_track.is_empty() {
31                olm.update_tracked_users(user_ids_to_track.iter().map(AsRef::as_ref)).await?
32            }
33        }
34    }
35
36    Ok(())
37}
38
39/// Update tracked users, if the room is encrypted, or if the room has become
40/// encrypted.
41pub async fn update_or_set_if_room_is_newly_encrypted(
42    olm_machine: Option<&OlmMachine>,
43    user_ids_to_track: &BTreeSet<OwnedUserId>,
44    new_room_encryption_state: EncryptionState,
45    previous_room_encryption_state: EncryptionState,
46    room_id: &RoomId,
47    state_store: &BaseStateStore,
48) -> Result<()> {
49    if new_room_encryption_state.is_encrypted() {
50        if let Some(olm) = olm_machine {
51            if !previous_room_encryption_state.is_encrypted() {
52                // The room turned on encryption in this sync, we need
53                // to also get all the existing users and mark them for
54                // tracking.
55                let user_ids = state_store.get_user_ids(room_id, RoomMemberships::ACTIVE).await?;
56                olm.update_tracked_users(user_ids.iter().map(AsRef::as_ref)).await?
57            }
58
59            if !user_ids_to_track.is_empty() {
60                olm.update_tracked_users(user_ids_to_track.iter().map(AsRef::as_ref)).await?;
61            }
62        }
63    }
64
65    Ok(())
66}