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_common::timer;
18use matrix_sdk_crypto::OlmMachine;
19use ruma::{OwnedUserId, RoomId};
20
21use crate::{EncryptionState, Result, RoomMemberships, store::BaseStateStore};
22
23/// Update tracked users, if the room is encrypted.
24pub async fn update(
25    olm_machine: Option<&OlmMachine>,
26    room_encryption_state: EncryptionState,
27    user_ids_to_track: &BTreeSet<OwnedUserId>,
28) -> Result<()> {
29    if room_encryption_state.is_encrypted()
30        && let Some(olm) = olm_machine
31        && !user_ids_to_track.is_empty()
32    {
33        olm.update_tracked_users(user_ids_to_track.iter().map(AsRef::as_ref)).await?
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    let _timer = timer!(tracing::Level::TRACE, "update_or_set_if_room_is_newly_encrypted");
50
51    if new_room_encryption_state.is_encrypted()
52        && let Some(olm) = olm_machine
53    {
54        if !previous_room_encryption_state.is_encrypted() {
55            // The room turned on encryption in this sync, we need
56            // to also get all the existing users and mark them for
57            // tracking.
58            let user_ids = state_store.get_user_ids(room_id, RoomMemberships::ACTIVE).await?;
59            olm.update_tracked_users(user_ids.iter().map(AsRef::as_ref)).await?
60        }
61
62        if !user_ids_to_track.is_empty() {
63            olm.update_tracked_users(user_ids_to_track.iter().map(AsRef::as_ref)).await?;
64        }
65    }
66
67    Ok(())
68}