diff --git a/Cargo.lock b/Cargo.lock index f2109f4bb19..921417ebefc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4725,7 +4725,7 @@ dependencies = [ [[package]] name = "ruma" version = "0.14.1" -source = "git+https://github.com/ruma/ruma?rev=289bee87974bd3c2ad14a6c15801c80b683b67dc#289bee87974bd3c2ad14a6c15801c80b683b67dc" +source = "git+https://github.com/ruma/ruma?rev=4ec4532a0e5b328283c729aefafa8a1cbef2204a#4ec4532a0e5b328283c729aefafa8a1cbef2204a" dependencies = [ "assign", "js_int", @@ -4743,7 +4743,7 @@ dependencies = [ [[package]] name = "ruma-client-api" version = "0.22.1" -source = "git+https://github.com/ruma/ruma?rev=289bee87974bd3c2ad14a6c15801c80b683b67dc#289bee87974bd3c2ad14a6c15801c80b683b67dc" +source = "git+https://github.com/ruma/ruma?rev=4ec4532a0e5b328283c729aefafa8a1cbef2204a#4ec4532a0e5b328283c729aefafa8a1cbef2204a" dependencies = [ "as_variant", "assign", @@ -4766,7 +4766,7 @@ dependencies = [ [[package]] name = "ruma-common" version = "0.17.1" -source = "git+https://github.com/ruma/ruma?rev=289bee87974bd3c2ad14a6c15801c80b683b67dc#289bee87974bd3c2ad14a6c15801c80b683b67dc" +source = "git+https://github.com/ruma/ruma?rev=4ec4532a0e5b328283c729aefafa8a1cbef2204a#4ec4532a0e5b328283c729aefafa8a1cbef2204a" dependencies = [ "as_variant", "base64", @@ -4799,7 +4799,7 @@ dependencies = [ [[package]] name = "ruma-events" version = "0.32.1" -source = "git+https://github.com/ruma/ruma?rev=289bee87974bd3c2ad14a6c15801c80b683b67dc#289bee87974bd3c2ad14a6c15801c80b683b67dc" +source = "git+https://github.com/ruma/ruma?rev=4ec4532a0e5b328283c729aefafa8a1cbef2204a#4ec4532a0e5b328283c729aefafa8a1cbef2204a" dependencies = [ "as_variant", "indexmap", @@ -4826,7 +4826,7 @@ dependencies = [ [[package]] name = "ruma-federation-api" version = "0.13.1" -source = "git+https://github.com/ruma/ruma?rev=289bee87974bd3c2ad14a6c15801c80b683b67dc#289bee87974bd3c2ad14a6c15801c80b683b67dc" +source = "git+https://github.com/ruma/ruma?rev=4ec4532a0e5b328283c729aefafa8a1cbef2204a#4ec4532a0e5b328283c729aefafa8a1cbef2204a" dependencies = [ "headers", "http", @@ -4847,7 +4847,7 @@ dependencies = [ [[package]] name = "ruma-html" version = "0.6.0" -source = "git+https://github.com/ruma/ruma?rev=289bee87974bd3c2ad14a6c15801c80b683b67dc#289bee87974bd3c2ad14a6c15801c80b683b67dc" +source = "git+https://github.com/ruma/ruma?rev=4ec4532a0e5b328283c729aefafa8a1cbef2204a#4ec4532a0e5b328283c729aefafa8a1cbef2204a" dependencies = [ "as_variant", "html5ever", @@ -4858,7 +4858,7 @@ dependencies = [ [[package]] name = "ruma-identifiers-validation" version = "0.12.0" -source = "git+https://github.com/ruma/ruma?rev=289bee87974bd3c2ad14a6c15801c80b683b67dc#289bee87974bd3c2ad14a6c15801c80b683b67dc" +source = "git+https://github.com/ruma/ruma?rev=4ec4532a0e5b328283c729aefafa8a1cbef2204a#4ec4532a0e5b328283c729aefafa8a1cbef2204a" dependencies = [ "js_int", "thiserror 2.0.17", @@ -4867,7 +4867,7 @@ dependencies = [ [[package]] name = "ruma-macros" version = "0.17.1" -source = "git+https://github.com/ruma/ruma?rev=289bee87974bd3c2ad14a6c15801c80b683b67dc#289bee87974bd3c2ad14a6c15801c80b683b67dc" +source = "git+https://github.com/ruma/ruma?rev=4ec4532a0e5b328283c729aefafa8a1cbef2204a#4ec4532a0e5b328283c729aefafa8a1cbef2204a" dependencies = [ "as_variant", "cfg-if", @@ -4883,7 +4883,7 @@ dependencies = [ [[package]] name = "ruma-signatures" version = "0.19.0" -source = "git+https://github.com/ruma/ruma?rev=289bee87974bd3c2ad14a6c15801c80b683b67dc#289bee87974bd3c2ad14a6c15801c80b683b67dc" +source = "git+https://github.com/ruma/ruma?rev=4ec4532a0e5b328283c729aefafa8a1cbef2204a#4ec4532a0e5b328283c729aefafa8a1cbef2204a" dependencies = [ "base64", "ed25519-dalek", @@ -6944,9 +6944,9 @@ dependencies = [ [[package]] name = "wildmatch" -version = "2.3.4" +version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3928939971918220fed093266b809d1ee4ec6c1a2d72692ff6876898f3b16c19" +checksum = "29333c3ea1ba8b17211763463ff24ee84e41c78224c16b001cd907e663a38c68" [[package]] name = "winapi" diff --git a/Cargo.toml b/Cargo.toml index b41624aa2ff..14944e1bd8f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -70,7 +70,7 @@ rand = { version = "0.8.5", default-features = false, features = ["std", "std_rn regex = { version = "1.12.2", default-features = false } reqwest = { version = "0.12.24", default-features = false } rmp-serde = { version = "1.3.0", default-features = false } -ruma = { git = "https://github.com/ruma/ruma", rev = "289bee87974bd3c2ad14a6c15801c80b683b67dc", features = [ +ruma = { git = "https://github.com/ruma/ruma", rev = "4ec4532a0e5b328283c729aefafa8a1cbef2204a", features = [ "client-api-c", "compat-unset-avatar", "compat-upload-signatures", diff --git a/benchmarks/benches/crypto_bench.rs b/benchmarks/benches/crypto_bench.rs index 759c526361c..465f2745e80 100644 --- a/benchmarks/benches/crypto_bench.rs +++ b/benchmarks/benches/crypto_bench.rs @@ -1,11 +1,11 @@ -use std::{ops::Deref, sync::Arc}; +use std::sync::Arc; use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main}; use matrix_sdk_crypto::{EncryptionSettings, OlmMachine}; use matrix_sdk_sqlite::SqliteCryptoStore; use matrix_sdk_test::ruma_response_from_json; use ruma::{ - DeviceId, OwnedUserId, TransactionId, UserId, + DeviceId, TransactionId, UserId, api::client::{ keys::{claim_keys, get_keys}, to_device::send_event_to_device::v3::Response as ToDeviceResponse, @@ -182,7 +182,7 @@ pub fn room_key_sharing(c: &mut Criterion) { let room_id = room_id!("!test:localhost"); let to_device_response = ToDeviceResponse::new(); - let users: Vec = keys_query_response.device_keys.keys().cloned().collect(); + let users: Vec = keys_query_response.device_keys.keys().cloned().collect(); let count = response.one_time_keys.values().fold(0, |acc, d| acc + d.len()); @@ -199,11 +199,7 @@ pub fn room_key_sharing(c: &mut Criterion) { group.bench_function(BenchmarkId::new("Room key sharing [memory]", &name), |b| { b.to_async(&runtime).iter(|| async { let requests = machine - .share_room_key( - room_id, - users.iter().map(Deref::deref), - EncryptionSettings::default(), - ) + .share_room_key(room_id, users.iter(), EncryptionSettings::default()) .await .unwrap(); @@ -231,11 +227,7 @@ pub fn room_key_sharing(c: &mut Criterion) { group.bench_function(BenchmarkId::new("Room key sharing [SQLite]", &name), |b| { b.to_async(&runtime).iter(|| async { let requests = machine - .share_room_key( - room_id, - users.iter().map(Deref::deref), - EncryptionSettings::default(), - ) + .share_room_key(room_id, users.iter(), EncryptionSettings::default()) .await .unwrap(); @@ -263,7 +255,7 @@ pub fn devices_missing_sessions_collecting(c: &mut Criterion) { let machine = runtime.block_on(OlmMachine::new(alice_id(), alice_device_id())); let response = huge_keys_query_response(); let txn_id = TransactionId::new(); - let users: Vec = response.device_keys.keys().cloned().collect(); + let users: Vec = response.device_keys.keys().cloned().collect(); let count = response.device_keys.values().fold(0, |acc, d| acc + d.len()); @@ -278,7 +270,7 @@ pub fn devices_missing_sessions_collecting(c: &mut Criterion) { group.bench_function(BenchmarkId::new("Devices collecting [memory]", &name), |b| { b.to_async(&runtime).iter_with_large_drop(|| async { - machine.get_missing_sessions(users.iter().map(Deref::deref)).await.unwrap() + machine.get_missing_sessions(users.iter()).await.unwrap() }) }); @@ -294,9 +286,8 @@ pub fn devices_missing_sessions_collecting(c: &mut Criterion) { runtime.block_on(machine.mark_request_as_sent(&txn_id, &response)).unwrap(); group.bench_function(BenchmarkId::new("Devices collecting [SQLite]", &name), |b| { - b.to_async(&runtime).iter(|| async { - machine.get_missing_sessions(users.iter().map(Deref::deref)).await.unwrap() - }) + b.to_async(&runtime) + .iter(|| async { machine.get_missing_sessions(users.iter()).await.unwrap() }) }); { diff --git a/benchmarks/benches/event_cache.rs b/benchmarks/benches/event_cache.rs index abddbc8df6a..c6b53fe1f9f 100644 --- a/benchmarks/benches/event_cache.rs +++ b/benchmarks/benches/event_cache.rs @@ -324,7 +324,7 @@ fn find_event_relations(c: &mut Criterion) { .await .unwrap() .unwrap(); - assert_eq!(target.event_id().as_deref().unwrap(), target_event_id); + assert_eq!(target.event_id().unwrap(), target_event_id); assert_eq!(relations.len(), num_related_events as usize); }, criterion::BatchSize::PerIteration, diff --git a/benchmarks/benches/room_bench.rs b/benchmarks/benches/room_bench.rs index a06d61c325c..a4dcd4d47f0 100644 --- a/benchmarks/benches/room_bench.rs +++ b/benchmarks/benches/room_bench.rs @@ -13,7 +13,7 @@ use matrix_sdk_sqlite::SqliteStateStore; use matrix_sdk_test::{JoinedRoomBuilder, event_factory::EventFactory}; use matrix_sdk_ui::timeline::{TimelineBuilder, TimelineFocus}; use ruma::{ - EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedUserId, + EventId, MilliSecondsSinceUnixEpoch, UserId, api::client::membership::get_member_events, events::room::member::{MembershipState, RoomMemberEvent}, mxc_uri, owned_device_id, owned_room_id, owned_user_id, @@ -31,7 +31,7 @@ pub fn receive_all_members_benchmark(c: &mut Criterion) { let f = EventFactory::new().room(&room_id); let mut member_events: Vec> = Vec::with_capacity(MEMBERS_IN_ROOM); for i in 0..MEMBERS_IN_ROOM { - let user_id = OwnedUserId::try_from(format!("@user_{i}:matrix.org")).unwrap(); + let user_id = UserId::try_from(format!("@user_{i}:matrix.org")).unwrap(); let event = f .member(&user_id) .membership(MembershipState::Join) @@ -113,7 +113,7 @@ pub fn load_pinned_events_benchmark(c: &mut Criterion) { let mut joined_room_builder = JoinedRoomBuilder::new(&room_id).add_state_event(f.room_encryption()); - let pinned_event_ids: Vec = (0..PINNED_EVENTS_COUNT) + let pinned_event_ids: Vec = (0..PINNED_EVENTS_COUNT) .map(|i| EventId::parse(format!("${i}")).expect("Invalid event id")) .collect(); joined_room_builder = diff --git a/bindings/matrix-sdk-crypto-ffi/src/dehydrated_devices.rs b/bindings/matrix-sdk-crypto-ffi/src/dehydrated_devices.rs index 7597d0ffb21..f3d9b83ca99 100644 --- a/bindings/matrix-sdk-crypto-ffi/src/dehydrated_devices.rs +++ b/bindings/matrix-sdk-crypto-ffi/src/dehydrated_devices.rs @@ -9,7 +9,7 @@ use matrix_sdk_crypto::{ store::types::DehydratedDeviceKey as InnerDehydratedDeviceKey, DecryptionSettings, }; -use ruma::{api::client::dehydrated_device, events::AnyToDeviceEvent, serde::Raw, OwnedDeviceId}; +use ruma::{api::client::dehydrated_device, events::AnyToDeviceEvent, serde::Raw, DeviceId}; use serde_json::json; use crate::{CryptoStoreError, DehydratedDeviceKey}; @@ -86,7 +86,7 @@ impl DehydratedDevices { device_data: String, ) -> Result, DehydrationError> { let device_data: Raw<_> = serde_json::from_str(&device_data)?; - let device_id: OwnedDeviceId = device_id.into(); + let device_id: DeviceId = device_id.into(); let key = InnerDehydratedDeviceKey::from_slice(&pickle_key.inner)?; diff --git a/bindings/matrix-sdk-crypto-ffi/src/error.rs b/bindings/matrix-sdk-crypto-ffi/src/error.rs index 9bf81f5d21d..9611d6d272a 100644 --- a/bindings/matrix-sdk-crypto-ffi/src/error.rs +++ b/bindings/matrix-sdk-crypto-ffi/src/error.rs @@ -6,7 +6,7 @@ use matrix_sdk_crypto::{ SignatureError as InnerSignatureError, }; use matrix_sdk_sqlite::OpenStoreError; -use ruma::{IdParseError, OwnedUserId}; +use ruma::{IdParseError, UserId}; #[derive(Debug, thiserror::Error, uniffi::Error)] #[uniffi(flat_error)] @@ -38,7 +38,7 @@ pub enum SignatureError { #[error(transparent)] CryptoStore(#[from] InnerStoreError), #[error("Unknown device {0} {1}")] - UnknownDevice(OwnedUserId, String), + UnknownDevice(UserId, String), #[error("Unknown user identity {0}")] UnknownUserIdentity(String), } diff --git a/bindings/matrix-sdk-crypto-ffi/src/lib.rs b/bindings/matrix-sdk-crypto-ffi/src/lib.rs index a8223e53e29..6c4a8acd755 100644 --- a/bindings/matrix-sdk-crypto-ffi/src/lib.rs +++ b/bindings/matrix-sdk-crypto-ffi/src/lib.rs @@ -54,9 +54,9 @@ pub use responses::{ Request, RequestType, SignatureUploadRequest, UploadSigningKeysRequest, }; use ruma::{ - events::room::history_visibility::HistoryVisibility as RustHistoryVisibility, - DeviceKeyAlgorithm, DeviceKeyId, MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedUserId, - RoomId, SecondsSinceUnixEpoch, UserId, + events::room::history_visibility::HistoryVisibility as RustHistoryVisibility, DeviceId, + DeviceKeyAlgorithm, DeviceKeyId, MilliSecondsSinceUnixEpoch, RoomId, SecondsSinceUnixEpoch, + UserId, }; use serde::{Deserialize, Serialize}; use tokio::runtime::Runtime; @@ -248,7 +248,7 @@ async fn migrate_data( listener(processed_steps, total_steps); let user_id = parse_user_id(&data.account.user_id)?; - let device_id: OwnedDeviceId = data.account.device_id.into(); + let device_id: DeviceId = data.account.device_id.into(); let account = Account::from_libolm_pickle(&data.account.pickle, &data.pickle_key)?; let pickle = account.pickle(); @@ -285,7 +285,7 @@ async fn migrate_data( .map(|k| BackupDecryptionKey::from_base58(k.as_str())) .transpose()?; - let cross_signing = PrivateCrossSigningIdentity::empty((*user_id).into()); + let cross_signing = PrivateCrossSigningIdentity::empty(&user_id); cross_signing .import_secrets_unchecked( data.cross_signing.master_key.as_deref(), @@ -307,7 +307,7 @@ async fn migrate_data( .filter_map(|s| parse_user_id(&s).ok().map(|u| (u, true))) .collect(); - let tracked_users: Vec<_> = tracked_users.iter().map(|(u, d)| (&**u, *d)).collect(); + let tracked_users: Vec<_> = tracked_users.iter().map(|(u, d)| (u, *d)).collect(); store.save_tracked_users(tracked_users.as_slice()).await?; processed_steps += 1; @@ -395,7 +395,7 @@ async fn migrate_session_data( let processed_steps = 0; let user_id = UserId::parse(data.user_id)?; - let device_id: OwnedDeviceId = data.device_id.into(); + let device_id: DeviceId = data.device_id.into(); let identity_keys = IdentityKeys { ed25519: Ed25519PublicKey::from_base64(&data.ed25519_key)?, @@ -425,8 +425,8 @@ fn collect_sessions( total_steps: usize, listener: &dyn Fn(usize, usize), pickle_key: &[u8], - user_id: OwnedUserId, - device_id: OwnedDeviceId, + user_id: UserId, + device_id: DeviceId, identity_keys: Arc, session_pickles: Vec, group_session_pickles: Vec, @@ -949,7 +949,7 @@ impl From for RustRoomSettings { } } -fn parse_user_id(user_id: &str) -> Result { +fn parse_user_id(user_id: &str) -> Result { ruma::UserId::parse(user_id).map_err(|e| CryptoStoreError::InvalidUserId(user_id.to_owned(), e)) } diff --git a/bindings/matrix-sdk-crypto-ffi/src/machine.rs b/bindings/matrix-sdk-crypto-ffi/src/machine.rs index 3cd1248ea42..30ef5218162 100644 --- a/bindings/matrix-sdk-crypto-ffi/src/machine.rs +++ b/bindings/matrix-sdk-crypto-ffi/src/machine.rs @@ -2,7 +2,6 @@ use std::{ collections::{BTreeMap, HashMap}, io::Cursor, mem::ManuallyDrop, - ops::Deref, sync::Arc, time::Duration, }; @@ -43,8 +42,7 @@ use ruma::{ }, serde::Raw, to_device::DeviceIdOrAllDevices, - DeviceKeyAlgorithm, EventId, OneTimeKeyAlgorithm, OwnedTransactionId, OwnedUserId, RoomId, - UserId, + DeviceKeyAlgorithm, EventId, OneTimeKeyAlgorithm, RoomId, TransactionId, UserId, }; use serde::{Deserialize, Serialize}; use serde_json::{value::RawValue, Value}; @@ -206,7 +204,7 @@ impl OlmMachine { mut passphrase: Option, ) -> Result, CryptoStoreError> { let user_id = parse_user_id(&user_id)?; - let device_id = device_id.as_str().into(); + let device_id = device_id.into(); let runtime = Runtime::new().expect("Couldn't create a tokio runtime"); let store = runtime @@ -216,7 +214,7 @@ impl OlmMachine { let inner = runtime.block_on(InnerMachine::with_store( &user_id, - device_id, + &device_id, Arc::new(store), None, ))?; @@ -354,7 +352,7 @@ impl OlmMachine { Ok(self .runtime - .block_on(self.inner.get_device(&user_id, device_id.as_str().into(), timeout))? + .block_on(self.inner.get_device(&user_id, &device_id.into(), timeout))? .map(|d| d.into())) } @@ -379,7 +377,7 @@ impl OlmMachine { let user_id = UserId::parse(user_id)?; let device = self.runtime.block_on(self.inner.get_device( &user_id, - device_id.as_str().into(), + &device_id.clone().into(), None, ))?; @@ -400,11 +398,8 @@ impl OlmMachine { ) -> Result<(), CryptoStoreError> { let user_id = parse_user_id(&user_id)?; - let device = self.runtime.block_on(self.inner.get_device( - &user_id, - device_id.as_str().into(), - None, - ))?; + let device = + self.runtime.block_on(self.inner.get_device(&user_id, &device_id.into(), None))?; if let Some(device) = device { self.runtime.block_on(device.set_local_trust(trust_state))?; @@ -474,7 +469,7 @@ impl OlmMachine { request_type: RequestType, response_body: String, ) -> Result<(), CryptoStoreError> { - let id: OwnedTransactionId = request_id.into(); + let id: TransactionId = request_id.into(); let response = response_from_string(&response_body); @@ -586,10 +581,9 @@ impl OlmMachine { /// /// `users` - The users that should be queued up for a key query. pub fn update_tracked_users(&self, users: Vec) -> Result<(), CryptoStoreError> { - let users: Vec = - users.into_iter().filter_map(|u| UserId::parse(u).ok()).collect(); + let users: Vec = users.into_iter().filter_map(|u| UserId::parse(u).ok()).collect(); - self.runtime.block_on(self.inner.update_tracked_users(users.iter().map(Deref::deref)))?; + self.runtime.block_on(self.inner.update_tracked_users(users.iter()))?; Ok(()) } @@ -621,13 +615,9 @@ impl OlmMachine { &self, users: Vec, ) -> Result, CryptoStoreError> { - let users: Vec = - users.into_iter().filter_map(|u| UserId::parse(u).ok()).collect(); + let users: Vec = users.into_iter().filter_map(|u| UserId::parse(u).ok()).collect(); - Ok(self - .runtime - .block_on(self.inner.get_missing_sessions(users.iter().map(Deref::deref)))? - .map(|r| r.into())) + Ok(self.runtime.block_on(self.inner.get_missing_sessions(users.iter()))?.map(|r| r.into())) } /// Get the stored room settings, such as the encryption algorithm or @@ -750,15 +740,11 @@ impl OlmMachine { users: Vec, settings: EncryptionSettings, ) -> Result, CryptoStoreError> { - let users: Vec = - users.into_iter().filter_map(|u| UserId::parse(u).ok()).collect(); + let users: Vec = users.into_iter().filter_map(|u| UserId::parse(u).ok()).collect(); let room_id = RoomId::parse(room_id)?; - let requests = self.runtime.block_on(self.inner.share_room_key( - &room_id, - users.iter().map(Deref::deref), - settings, - ))?; + let requests = + self.runtime.block_on(self.inner.share_room_key(&room_id, users.iter(), settings))?; Ok(requests.into_iter().map(|r| r.as_ref().into()).collect()) } @@ -839,10 +825,10 @@ impl OlmMachine { share_strategy: CollectStrategy, ) -> Result, CryptoStoreError> { let user_id = parse_user_id(&user_id)?; - let device_id = device_id.as_str().into(); + let device_id = device_id.into(); let content = serde_json::from_str(&content)?; - let device = self.runtime.block_on(self.inner.get_device(&user_id, device_id, None))?; + let device = self.runtime.block_on(self.inner.get_device(&user_id, &device_id, None))?; if let Some(device) = device { let encrypted_content = self.runtime.block_on(device.encrypt_event_raw( @@ -852,8 +838,8 @@ impl OlmMachine { ))?; let request = ToDeviceRequest::new( - user_id.as_ref(), - DeviceIdOrAllDevices::DeviceId(device_id.to_owned()), + &user_id, + DeviceIdOrAllDevices::DeviceId(device_id), "m.room.encrypted", encrypted_content.cast(), ); @@ -1269,13 +1255,13 @@ impl OlmMachine { methods: Vec, ) -> Result, CryptoStoreError> { let user_id = parse_user_id(&user_id)?; - let device_id = device_id.as_str().into(); + let device_id = device_id.into(); let methods = methods.into_iter().map(VerificationMethod::from).collect(); Ok( if let Some(device) = - self.runtime.block_on(self.inner.get_device(&user_id, device_id, None))? + self.runtime.block_on(self.inner.get_device(&user_id, &device_id, None))? { let (verification, request) = device.request_verification_with_methods(methods); @@ -1361,11 +1347,11 @@ impl OlmMachine { device_id: String, ) -> Result, CryptoStoreError> { let user_id = parse_user_id(&user_id)?; - let device_id = device_id.as_str().into(); + let device_id = device_id.into(); Ok( if let Some(device) = - self.runtime.block_on(self.inner.get_device(&user_id, device_id, None))? + self.runtime.block_on(self.inner.get_device(&user_id, &device_id, None))? { let (sas, request) = self.runtime.block_on(device.start_verification())?; diff --git a/bindings/matrix-sdk-crypto-ffi/src/responses.rs b/bindings/matrix-sdk-crypto-ffi/src/responses.rs index 48e296137b4..735d4f3459e 100644 --- a/bindings/matrix-sdk-crypto-ffi/src/responses.rs +++ b/bindings/matrix-sdk-crypto-ffi/src/responses.rs @@ -28,7 +28,7 @@ use ruma::{ }, assign, events::MessageLikeEventContent, - OwnedTransactionId, UserId, + TransactionId, UserId, }; use serde_json::json; @@ -181,8 +181,8 @@ impl From for Request { } } -impl From<(OwnedTransactionId, KeysClaimRequest)> for Request { - fn from(request_tuple: (OwnedTransactionId, KeysClaimRequest)) -> Self { +impl From<(TransactionId, KeysClaimRequest)> for Request { + fn from(request_tuple: (TransactionId, KeysClaimRequest)) -> Self { let (request_id, request) = request_tuple; Request::KeysClaim { @@ -201,8 +201,8 @@ impl From<(OwnedTransactionId, KeysClaimRequest)> for Request { } } -impl From<(OwnedTransactionId, KeysBackupRequest)> for Request { - fn from(request_tuple: (OwnedTransactionId, KeysBackupRequest)) -> Self { +impl From<(TransactionId, KeysBackupRequest)> for Request { + fn from(request_tuple: (TransactionId, KeysBackupRequest)) -> Self { let (request_id, request) = request_tuple; Request::KeysBackup { diff --git a/bindings/matrix-sdk-ffi/src/client.rs b/bindings/matrix-sdk-ffi/src/client.rs index 7bc24344d16..27cad43978e 100644 --- a/bindings/matrix-sdk-ffi/src/client.rs +++ b/bindings/matrix-sdk-ffi/src/client.rs @@ -105,7 +105,7 @@ use ruma::{ }, push::{HttpPusherData as RumaHttpPusherData, PushFormat as RumaPushFormat}, room::RoomType, - OwnedDeviceId, OwnedServerName, RoomAliasId, RoomOrAliasId, ServerName, + DeviceId, RoomAliasId, RoomOrAliasId, ServerName, }; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; @@ -614,7 +614,7 @@ impl Client { let registration_data = oidc_configuration.registration_data()?; let redirect_uri = oidc_configuration.redirect_uri()?; - let device_id = device_id.map(OwnedDeviceId::from); + let device_id = device_id.map(DeviceId::from); let additional_scopes = additional_scopes.map(|scopes| scopes.into_iter().map(Scope::new).collect::>()); @@ -1600,8 +1600,8 @@ impl Client { } pub async fn get_profile(&self, user_id: String) -> Result { - let user_id = <&UserId>::try_from(user_id.as_str())?; - UserProfile::fetch(&self.inner.account(), user_id).await + let user_id = UserId::try_from(user_id)?; + UserProfile::fetch(&self.inner.account(), &user_id).await } pub async fn notification_client( @@ -1686,8 +1686,8 @@ impl Client { /// Otherwise use `join_room_by_id_or_alias` so you can pass a list of /// server names for the homeserver to find the room. pub async fn join_room_by_id(&self, room_id: String) -> Result, ClientError> { - let room_id = RoomId::parse(room_id)?; - let room = self.inner.join_room_by_id(room_id.as_ref()).await?; + let room_id = RoomId::try_from(room_id)?; + let room = self.inner.join_room_by_id(&room_id).await?; Ok(Arc::new(Room::new(room, self.utd_hook_manager.get().cloned()))) } @@ -1702,13 +1702,12 @@ impl Client { room_id_or_alias: String, server_names: Vec, ) -> Result, ClientError> { - let room_id = RoomOrAliasId::parse(&room_id_or_alias)?; + let room_id = RoomOrAliasId::try_from(room_id_or_alias)?; let server_names = server_names .iter() - .map(|name| OwnedServerName::try_from(name.as_str())) + .map(|name| ServerName::try_from(name.as_str())) .collect::, _>>()?; - let room = - self.inner.join_room_by_id_or_alias(room_id.as_ref(), server_names.as_ref()).await?; + let room = self.inner.join_room_by_id_or_alias(&room_id, server_names.as_ref()).await?; Ok(Arc::new(Room::new(room, self.utd_hook_manager.get().cloned()))) } @@ -1776,7 +1775,7 @@ impl Client { room_id: String, via_servers: Vec, ) -> Result, ClientError> { - let room_id = RoomId::parse(&room_id).context("room_id is not a valid room id")?; + let room_id = RoomId::try_from(room_id).context("room_id is not a valid room id")?; let via_servers = via_servers .into_iter() @@ -1784,11 +1783,7 @@ impl Client { .collect::, _>>() .context("at least one `via` server name is invalid")?; - // The `into()` call below doesn't work if I do `(&room_id).into()`, so I let - // rustc win that one fight. - let room_id: &RoomId = &room_id; - - let room_preview = self.inner.get_room_preview(room_id.into(), via_servers).await?; + let room_preview = self.inner.get_room_preview(&room_id.into(), via_servers).await?; Ok(Arc::new(RoomPreview::new(self.inner.clone(), room_preview))) } @@ -1799,13 +1794,9 @@ impl Client { room_alias: String, ) -> Result, ClientError> { let room_alias = - RoomAliasId::parse(&room_alias).context("room_alias is not a valid room alias")?; - - // The `into()` call below doesn't work if I do `(&room_id).into()`, so I let - // rustc win that one fight. - let room_alias: &RoomAliasId = &room_alias; + RoomAliasId::try_from(room_alias).context("room_alias is not a valid room alias")?; - let room_preview = self.inner.get_room_preview(room_alias.into(), Vec::new()).await?; + let room_preview = self.inner.get_room_preview(&room_alias.into(), Vec::new()).await?; Ok(Arc::new(RoomPreview::new(self.inner.clone(), room_preview))) } diff --git a/bindings/matrix-sdk-ffi/src/client_builder.rs b/bindings/matrix-sdk-ffi/src/client_builder.rs index 77d974956cb..1f1cc2023c7 100644 --- a/bindings/matrix-sdk-ffi/src/client_builder.rs +++ b/bindings/matrix-sdk-ffi/src/client_builder.rs @@ -406,7 +406,7 @@ impl ClientBuilder { None => { if let Some(username) = builder.username { let user = UserId::parse(username)?; - inner_builder.server_name(user.server_name()) + inner_builder.server_name(&user.server_name()) } else { return Err(ClientBuildError::Generic { message: "Failed to build: One of homeserver_url, server_name, server_name_or_homeserver_url or username must be called.".to_owned(), diff --git a/bindings/matrix-sdk-ffi/src/encryption.rs b/bindings/matrix-sdk-ffi/src/encryption.rs index f694d3553d9..a37a803c63d 100644 --- a/bindings/matrix-sdk-ffi/src/encryption.rs +++ b/bindings/matrix-sdk-ffi/src/encryption.rs @@ -20,6 +20,7 @@ use matrix_sdk::{ encryption::{backups, recovery}, }; use matrix_sdk_common::{SendOutsideWasm, SyncOutsideWasm}; +use ruma::UserId; use thiserror::Error; use tracing::{error, info}; use zeroize::Zeroize; @@ -466,7 +467,8 @@ impl Encryption { user_id: String, fallback_to_server: bool, ) -> Result>, ClientError> { - match self.inner.get_user_identity(user_id.as_str().try_into()?).await { + let user_id = UserId::try_from(user_id)?; + match self.inner.get_user_identity(&user_id).await { Ok(Some(identity)) => { return Ok(Some(Arc::new(UserIdentity { inner: identity }))); } @@ -481,7 +483,7 @@ impl Encryption { info!("Requesting identity from the server."); if fallback_to_server { - let identity = self.inner.request_user_identity(user_id.as_str().try_into()?).await?; + let identity = self.inner.request_user_identity(&user_id).await?; Ok(identity.map(|identity| Arc::new(UserIdentity { inner: identity }))) } else { Ok(None) diff --git a/bindings/matrix-sdk-ffi/src/error.rs b/bindings/matrix-sdk-ffi/src/error.rs index 74d055777e3..b8508734cd4 100644 --- a/bindings/matrix-sdk-ffi/src/error.rs +++ b/bindings/matrix-sdk-ffi/src/error.rs @@ -239,7 +239,7 @@ impl From for ClientError { } } -/// Bindings version of the sdk type replacing OwnedUserId/DeviceIds with simple +/// Bindings version of the sdk type replacing UserId/DeviceIds with simple /// String. /// /// Represent a failed to send unrecoverable error of an event sent via the @@ -317,7 +317,7 @@ impl From for QueueWedgeError { .collect(), }, SdkQueueWedgeError::IdentityViolations { users } => Self::IdentityViolations { - users: users.iter().map(ruma::OwnedUserId::to_string).collect(), + users: users.iter().map(ruma::UserId::to_string).collect(), }, SdkQueueWedgeError::CrossVerificationRequired => Self::CrossVerificationRequired, SdkQueueWedgeError::MissingMediaContent => Self::MissingMediaContent, diff --git a/bindings/matrix-sdk-ffi/src/notification.rs b/bindings/matrix-sdk-ffi/src/notification.rs index b44c097c3db..2c7449671cd 100644 --- a/bindings/matrix-sdk-ffi/src/notification.rs +++ b/bindings/matrix-sdk-ffi/src/notification.rs @@ -19,7 +19,7 @@ use matrix_sdk_ui::notification_client::{ NotificationItem as SdkNotificationItem, NotificationStatus as SdkNotificationStatus, RawNotificationEvent as SdkRawNotificationEvent, }; -use ruma::{EventId, OwnedEventId, OwnedRoomId, RoomId}; +use ruma::{EventId, RoomId}; use crate::{ client::{Client, JoinRule}, @@ -242,13 +242,13 @@ pub struct NotificationItemsRequest { } impl NotificationItemsRequest { - /// The parsed [`OwnedRoomId`] to use with the SDK crates. - pub fn room_id(&self) -> Result { + /// The parsed [`RoomId`] to use with the SDK crates. + pub fn room_id(&self) -> Result { RoomId::parse(&self.room_id).map_err(ClientError::from) } - /// The parsed [`OwnedEventId`] list to use with the SDK crates. - pub fn event_ids(&self) -> Result, ClientError> { + /// The parsed [`EventId`] list to use with the SDK crates. + pub fn event_ids(&self) -> Result, ClientError> { self.event_ids .iter() .map(|id| EventId::parse(id).map_err(ClientError::from)) diff --git a/bindings/matrix-sdk-ffi/src/room/mod.rs b/bindings/matrix-sdk-ffi/src/room/mod.rs index 5a22cafc520..01be45289b3 100644 --- a/bindings/matrix-sdk-ffi/src/room/mod.rs +++ b/bindings/matrix-sdk-ffi/src/room/mod.rs @@ -48,8 +48,7 @@ use ruma::{ }, AnyMessageLikeEventContent, AnySyncTimelineEvent, }, - EventId, Int, OwnedDeviceId, OwnedRoomOrAliasId, OwnedServerName, OwnedUserId, RoomAliasId, - ServerName, UserId, + DeviceId, EventId, Int, RoomAliasId, RoomOrAliasId, ServerName, UserId, }; use tracing::{error, warn}; @@ -595,9 +594,8 @@ impl Room { } pub async fn invite_user_by_id(&self, user_id: String) -> Result<(), ClientError> { - let user = - <&UserId>::try_from(user_id.as_str()).context("Could not create user from string")?; - self.inner.invite_user_by_id(user).await?; + let user = UserId::try_from(user_id).context("Could not create user from string")?; + self.inner.invite_user_by_id(&user).await?; Ok(()) } @@ -729,13 +727,17 @@ impl Room { updates: Vec, ) -> Result<(), ClientError> { let updates = updates - .iter() + .into_iter() .map(|update| { - let user_id: &UserId = update.user_id.as_str().try_into()?; + let user_id: UserId = update.user_id.try_into()?; let power_level = Int::new(update.power_level).context("Invalid power level")?; Ok((user_id, power_level)) }) .collect::>>()?; + let updates = updates + .iter() + .map(|(user_id, power_level)| (user_id, *power_level)) + .collect::>(); self.inner.update_power_levels(updates).await.map_err(ClientError::from_err)?; Ok(()) @@ -815,7 +817,7 @@ impl Room { thread_root: Option, ) -> Result<(), ClientError> { let thread_root = thread_root.map(EventId::parse).transpose()?; - Ok(self.inner.save_composer_draft(draft.try_into()?, thread_root.as_deref()).await?) + Ok(self.inner.save_composer_draft(draft.try_into()?, thread_root.as_ref()).await?) } /// Retrieve the `ComposerDraft` stored in the state store for this room. @@ -824,7 +826,7 @@ impl Room { thread_root: Option, ) -> Result, ClientError> { let thread_root = thread_root.map(EventId::parse).transpose()?; - Ok(self.inner.load_composer_draft(thread_root.as_deref()).await?.map(Into::into)) + Ok(self.inner.load_composer_draft(thread_root.as_ref()).await?.map(Into::into)) } /// Remove the `ComposerDraft` stored in the state store for this room. @@ -833,7 +835,7 @@ impl Room { thread_root: Option, ) -> Result<(), ClientError> { let thread_root = thread_root.map(EventId::parse).transpose()?; - Ok(self.inner.clear_composer_draft(thread_root.as_deref()).await?) + Ok(self.inner.clear_composer_draft(thread_root.as_ref()).await?) } /// Edit an event given its event id. @@ -871,8 +873,7 @@ impl Room { user_ids: Vec, send_handle: Arc, ) -> Result<(), ClientError> { - let user_ids: Vec = - user_ids.iter().map(UserId::parse).collect::>()?; + let user_ids: Vec = user_ids.iter().map(UserId::parse).collect::>()?; let encryption = self.inner.client().encryption(); @@ -908,7 +909,7 @@ impl Room { let user_id = UserId::parse(user_id)?; for device_id in device_ids { - let device_id: OwnedDeviceId = device_id.as_str().into(); + let device_id: DeviceId = device_id.as_str().into(); if let Some(device) = encryption.get_device(&user_id, &device_id).await? { device.set_local_trust(LocalTrust::Ignored).await?; @@ -1176,7 +1177,7 @@ impl Room { /// invited, knocked or banned rooms. async fn preview_room(&self, via: Vec) -> Result, ClientError> { // Validate parameters first. - let server_names: Vec = via + let server_names: Vec = via .into_iter() .map(|server| ServerName::parse(server).map_err(ClientError::from)) .collect::>()?; @@ -1185,10 +1186,10 @@ impl Room { let client = self.inner.client(); let (room_or_alias_id, mut server_names) = if let Some(alias) = self.inner.canonical_alias() { - let room_or_alias_id: OwnedRoomOrAliasId = alias.into(); + let room_or_alias_id: RoomOrAliasId = alias.into(); (room_or_alias_id, Vec::new()) } else { - let room_or_alias_id: OwnedRoomOrAliasId = self.inner.room_id().to_owned().into(); + let room_or_alias_id: RoomOrAliasId = self.inner.room_id().to_owned().into(); (room_or_alias_id, server_names) }; @@ -1197,7 +1198,7 @@ impl Room { if server_names.is_empty() { if let Ok(invite_details) = self.inner.invite_details().await { if let Some(inviter) = invite_details.inviter { - server_names.push(inviter.user_id().server_name().to_owned()); + server_names.push(inviter.user_id().server_name()); } } } diff --git a/bindings/matrix-sdk-ffi/src/room/power_levels.rs b/bindings/matrix-sdk-ffi/src/room/power_levels.rs index b14e21e69c3..8e8e21a6113 100644 --- a/bindings/matrix-sdk-ffi/src/room/power_levels.rs +++ b/bindings/matrix-sdk-ffi/src/room/power_levels.rs @@ -17,7 +17,7 @@ use std::collections::HashMap; use anyhow::Result; use ruma::{ events::{room::power_levels::RoomPowerLevels as RumaPowerLevels, TimelineEventType}, - OwnedUserId, UserId, + UserId, }; use crate::{ @@ -28,11 +28,11 @@ use crate::{ #[derive(uniffi::Object)] pub struct RoomPowerLevels { inner: RumaPowerLevels, - own_user_id: OwnedUserId, + own_user_id: UserId, } impl RoomPowerLevels { - pub fn new(value: RumaPowerLevels, own_user_id: OwnedUserId) -> Self { + pub fn new(value: RumaPowerLevels, own_user_id: UserId) -> Self { Self { inner: value, own_user_id } } } diff --git a/bindings/matrix-sdk-ffi/src/room_list.rs b/bindings/matrix-sdk-ffi/src/room_list.rs index 95349758114..ceecc5f1f60 100644 --- a/bindings/matrix-sdk-ffi/src/room_list.rs +++ b/bindings/matrix-sdk-ffi/src/room_list.rs @@ -104,9 +104,9 @@ impl RoomListService { } fn room(&self, room_id: String) -> Result, RoomListError> { - let room_id = <&RoomId>::try_from(room_id.as_str()).map_err(RoomListError::from)?; + let room_id = RoomId::try_from(room_id).map_err(RoomListError::from)?; - Ok(Arc::new(Room::new(self.inner.room(room_id)?, self.utd_hook.clone()))) + Ok(Arc::new(Room::new(self.inner.room(&room_id)?, self.utd_hook.clone()))) } async fn all_rooms(self: Arc) -> Result, RoomListError> { @@ -144,9 +144,7 @@ impl RoomListService { }) .collect::, _>>()?; - self.inner - .subscribe_to_rooms(&room_ids.iter().map(AsRef::as_ref).collect::>()) - .await; + self.inner.subscribe_to_rooms(&room_ids.iter().collect::>()).await; Ok(()) } diff --git a/bindings/matrix-sdk-ffi/src/ruma.rs b/bindings/matrix-sdk-ffi/src/ruma.rs index bd167f90669..adde0976d3a 100644 --- a/bindings/matrix-sdk-ffi/src/ruma.rs +++ b/bindings/matrix-sdk-ffi/src/ruma.rs @@ -82,7 +82,7 @@ use ruma::{ }, serde::JsonObject, KeyDerivationAlgorithm as RumaKeyDerivationAlgorithm, MatrixToUri, MatrixUri as RumaMatrixUri, - OwnedRoomId, OwnedUserId, UInt, UserId, + RoomId, UInt, UserId, }; use tracing::info; @@ -330,7 +330,7 @@ pub struct Mentions { impl From for ruma::events::Mentions { fn from(value: Mentions) -> Self { - let mut user_ids = BTreeSet::::new(); + let mut user_ids = BTreeSet::::new(); for user_id in value.user_ids { if let Ok(user_id) = UserId::parse(user_id) { user_ids.insert(user_id); @@ -1403,10 +1403,10 @@ pub struct SimplePushRule { pub rule_id: String, } -impl TryFrom> for SimplePushRule { +impl TryFrom> for SimplePushRule { type Error = String; - fn try_from(value: RumaSimplePushRule) -> Result { + fn try_from(value: RumaSimplePushRule) -> Result { Ok(Self { actions: value .actions @@ -1420,10 +1420,10 @@ impl TryFrom> for SimplePushRule { } } -impl TryFrom> for SimplePushRule { +impl TryFrom> for SimplePushRule { type Error = String; - fn try_from(value: RumaSimplePushRule) -> Result { + fn try_from(value: RumaSimplePushRule) -> Result { Ok(Self { actions: value .actions diff --git a/bindings/matrix-sdk-ffi/src/timeline/mod.rs b/bindings/matrix-sdk-ffi/src/timeline/mod.rs index 868bd5a5dde..d8681ab1f19 100644 --- a/bindings/matrix-sdk-ffi/src/timeline/mod.rs +++ b/bindings/matrix-sdk-ffi/src/timeline/mod.rs @@ -377,7 +377,7 @@ impl Timeline { /// Returns the latest [`EventId`] in the timeline. pub async fn latest_event_id(&self) -> Option { - self.inner.latest_event_id().await.as_deref().map(ToString::to_string) + self.inner.latest_event_id().await.as_ref().map(ToString::to_string) } /// Queues an event in the room's send queue so it's processed for @@ -631,9 +631,9 @@ impl Timeline { } pub async fn fetch_details_for_event(&self, event_id: String) -> Result<(), ClientError> { - let event_id = <&EventId>::try_from(event_id.as_str())?; + let event_id = EventId::try_from(event_id)?; self.inner - .fetch_details_for_event(event_id) + .fetch_details_for_event(&event_id) .await .map_err(|e| ClientError::from_str(e, Some("Fetching event details".to_owned())))?; Ok(()) diff --git a/crates/matrix-sdk-base/src/client.rs b/crates/matrix-sdk-base/src/client.rs index 5bf4a391b60..048634a37ec 100644 --- a/crates/matrix-sdk-base/src/client.rs +++ b/crates/matrix-sdk-base/src/client.rs @@ -35,7 +35,7 @@ use ruma::DeviceId; #[cfg(feature = "e2e-encryption")] use ruma::events::room::{history_visibility::HistoryVisibility, member::MembershipState}; use ruma::{ - MilliSecondsSinceUnixEpoch, OwnedRoomId, OwnedUserId, RoomId, UserId, + MilliSecondsSinceUnixEpoch, RoomId, UserId, api::client::{self as api, sync::sync_events::v5}, events::{ StateEvent, StateEventType, @@ -432,12 +432,12 @@ impl BaseClient { /// /// ```rust /// # use matrix_sdk_base::{BaseClient, store::StoreConfig, RoomState, ThreadingSupport}; - /// # use ruma::{OwnedRoomId, OwnedUserId, RoomId}; + /// # use ruma::{RoomId, UserId}; /// use matrix_sdk_common::cross_process_lock::CrossProcessLockConfig; /// # async { /// # let client = BaseClient::new(StoreConfig::new(CrossProcessLockConfig::multi_process("example")), ThreadingSupport::Disabled); - /// # async fn send_join_request() -> anyhow::Result { todo!() } - /// # async fn maybe_get_inviter(room_id: &RoomId) -> anyhow::Result> { todo!() } + /// # async fn send_join_request() -> anyhow::Result { todo!() } + /// # async fn maybe_get_inviter(room_id: &RoomId) -> anyhow::Result> { todo!() } /// # let room_id: &RoomId = todo!(); /// let maybe_inviter = maybe_get_inviter(room_id).await?; /// let room_id = send_join_request().await?; @@ -446,11 +446,7 @@ impl BaseClient { /// assert_eq!(room.state(), RoomState::Joined); /// # matrix_sdk_test::TestResult::Ok(()) }; /// ``` - pub async fn room_joined( - &self, - room_id: &RoomId, - inviter: Option, - ) -> Result { + pub async fn room_joined(&self, room_id: &RoomId, inviter: Option) -> Result { let room = self.state_store.get_or_create_room(room_id, RoomState::Joined); // If the state isn't `RoomState::Joined` then this means that we knew about @@ -624,8 +620,7 @@ impl BaseClient { let mut room_updates = RoomUpdates::default(); let mut notifications = Default::default(); - let mut updated_members_in_room: BTreeMap> = - BTreeMap::new(); + let mut updated_members_in_room: BTreeMap> = BTreeMap::new(); for (room_id, joined_room) in response.rooms.join { let joined_room_update = processors::room::sync_v2::update_joined_room( @@ -817,7 +812,7 @@ impl BaseClient { #[cfg(feature = "e2e-encryption")] let mut user_ids = BTreeSet::new(); - let mut ambiguity_map: HashMap> = Default::default(); + let mut ambiguity_map: HashMap> = Default::default(); for raw_event in &response.chunk { let member = match raw_event.deserialize() { @@ -978,7 +973,7 @@ impl BaseClient { self.room_key_recipient_strategy.clone(), ); - Ok(o.share_room_key(room_id, members.iter().map(Deref::deref), settings).await?) + Ok(o.share_room_key(room_id, members.iter(), settings).await?) } None => panic!("Olm machine wasn't started"), } @@ -1102,7 +1097,7 @@ impl BaseClient { #[derive(Debug, Default)] pub struct RequestedRequiredStates { default: Vec<(StateEventType, String)>, - for_rooms: HashMap>, + for_rooms: HashMap>, } impl RequestedRequiredStates { @@ -1112,7 +1107,7 @@ impl RequestedRequiredStates { /// `for_rooms` is the `required_state` per room. pub fn new( default: Vec<(StateEventType, String)>, - for_rooms: HashMap>, + for_rooms: HashMap>, ) -> Self { Self { default, for_rooms } } diff --git a/crates/matrix-sdk-base/src/deserialized_responses.rs b/crates/matrix-sdk-base/src/deserialized_responses.rs index b866afde2d3..19ef4c64b58 100644 --- a/crates/matrix-sdk-base/src/deserialized_responses.rs +++ b/crates/matrix-sdk-base/src/deserialized_responses.rs @@ -19,8 +19,7 @@ use std::{collections::BTreeMap, fmt, hash::Hash, iter, sync::LazyLock}; pub use matrix_sdk_common::deserialized_responses::*; use regex::Regex; use ruma::{ - EventId, MilliSecondsSinceUnixEpoch, MxcUri, OwnedEventId, OwnedRoomId, OwnedUserId, UInt, - UserId, + EventId, MilliSecondsSinceUnixEpoch, MxcUri, RoomId, UInt, UserId, events::{ AnyStrippedStateEvent, AnySyncStateEvent, AnySyncTimelineEvent, EventContentFromType, PossiblyRedactedStateEventContent, RedactContent, RedactedStateEventContent, @@ -43,22 +42,22 @@ use unicode_normalization::UnicodeNormalization; pub struct AmbiguityChange { /// The user ID of the member that is contained in the state key of the /// `m.room.member` event. - pub member_id: OwnedUserId, + pub member_id: UserId, /// Is the member that is contained in the state key of the `m.room.member` /// event itself ambiguous because of the event. pub member_ambiguous: bool, /// Has another user been disambiguated because of this event. - pub disambiguated_member: Option, + pub disambiguated_member: Option, /// Has another user become ambiguous because of this event. - pub ambiguated_member: Option, + pub ambiguated_member: Option, } impl AmbiguityChange { /// Get an iterator over the user IDs listed in this `AmbiguityChange`. pub fn user_ids(&self) -> impl Iterator { - iter::once(&*self.member_id) - .chain(self.disambiguated_member.as_deref()) - .chain(self.ambiguated_member.as_deref()) + iter::once(&self.member_id) + .chain(self.disambiguated_member.as_ref()) + .chain(self.ambiguated_member.as_ref()) } } @@ -68,7 +67,7 @@ impl AmbiguityChange { pub struct AmbiguityChanges { /// A map from room id to a map of an event id to the `AmbiguityChange` that /// the event with the given id caused. - pub changes: BTreeMap>, + pub changes: BTreeMap>, } static MXID_REGEX: LazyLock = LazyLock::new(|| { @@ -511,8 +510,8 @@ impl MemberEvent { /// display for this member event. pub fn avatar_url(&self) -> Option<&MxcUri> { match self { - Self::Sync(event) => event.as_original()?.content.avatar_url.as_deref(), - Self::Stripped(event) => event.content.avatar_url.as_deref(), + Self::Sync(event) => event.as_original()?.content.avatar_url.as_ref(), + Self::Stripped(event) => event.content.avatar_url.as_ref(), } } @@ -539,7 +538,7 @@ impl SyncOrStrippedState { pub fn power_levels( &self, rules: &AuthorizationRules, - creators: Vec, + creators: Vec, ) -> RoomPowerLevels { match self { Self::Sync(e) => e.power_levels(rules, creators), diff --git a/crates/matrix-sdk-base/src/event_cache/store/integration_tests.rs b/crates/matrix-sdk-base/src/event_cache/store/integration_tests.rs index dc9fcddef7c..3e35c08035c 100644 --- a/crates/matrix-sdk-base/src/event_cache/store/integration_tests.rs +++ b/crates/matrix-sdk-base/src/event_cache/store/integration_tests.rs @@ -1435,7 +1435,7 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore { // Now let's find the event. let event = self - .find_event(room_id, event_comte.event_id().unwrap().as_ref()) + .find_event(room_id, &event_comte.event_id().unwrap()) .await .expect("failed to query for finding an event") .expect("failed to find an event"); @@ -1444,7 +1444,7 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore { // Now let's try to find an event that exists, but not in the expected room. assert!( - self.find_event(room_id, event_gruyere.event_id().unwrap().as_ref()) + self.find_event(room_id, &event_gruyere.event_id().unwrap()) .await .expect("failed to query for finding an event") .is_none() @@ -1453,7 +1453,7 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore { // Clearing the rooms also clears the event's storage. self.clear_all_linked_chunks().await.expect("failed to clear all rooms chunks"); assert!( - self.find_event(room_id, event_comte.event_id().unwrap().as_ref()) + self.find_event(room_id, &event_comte.event_id().unwrap()) .await .expect("failed to query for finding an event") .is_none() @@ -1507,12 +1507,12 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore { assert!( relations .iter() - .any(|(ev, pos)| ev.event_id().as_deref() == Some(edit_eid1) && pos.is_none()) + .any(|(ev, pos)| ev.event_id().as_ref() == Some(edit_eid1) && pos.is_none()) ); assert!( relations .iter() - .any(|(ev, pos)| ev.event_id().as_deref() == Some(reaction_eid1) && pos.is_none()) + .any(|(ev, pos)| ev.event_id().as_ref() == Some(reaction_eid1) && pos.is_none()) ); // Finding relations with a filter only returns a subset. @@ -1521,7 +1521,7 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore { .await .unwrap(); assert_eq!(relations.len(), 1); - assert_eq!(relations[0].0.event_id().as_deref(), Some(edit_eid1)); + assert_eq!(relations[0].0.event_id().as_ref(), Some(edit_eid1)); let relations = self .find_event_relations( @@ -1532,8 +1532,8 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore { .await .unwrap(); assert_eq!(relations.len(), 2); - assert!(relations.iter().any(|r| r.0.event_id().as_deref() == Some(edit_eid1))); - assert!(relations.iter().any(|r| r.0.event_id().as_deref() == Some(reaction_eid1))); + assert!(relations.iter().any(|r| r.0.event_id().as_ref() == Some(edit_eid1))); + assert!(relations.iter().any(|r| r.0.event_id().as_ref() == Some(reaction_eid1))); // We can't find relations using the wrong room. let relations = self @@ -1562,7 +1562,7 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore { // The position is set for `reaction_eid1` now. assert!(relations.iter().any(|(ev, pos)| { - ev.event_id().as_deref() == Some(reaction_eid1) + ev.event_id().as_ref() == Some(reaction_eid1) && *pos == Some(Position::new(CId::new(0), 0)) })); @@ -1570,7 +1570,7 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore { assert!( relations .iter() - .any(|(ev, pos)| ev.event_id().as_deref() == Some(edit_eid1) && pos.is_none()) + .any(|(ev, pos)| ev.event_id().as_ref() == Some(edit_eid1) && pos.is_none()) ); } @@ -1718,14 +1718,14 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore { // Events can be found, when searched in their own rooms. let event = self - .find_event(room_id, event_comte.event_id().unwrap().as_ref()) + .find_event(room_id, &event_comte.event_id().unwrap()) .await .expect("failed to query for finding an event") .expect("failed to find an event"); assert_eq!(event.event_id(), event_comte.event_id()); let event = self - .find_event(another_room_id, event_gruyere.event_id().unwrap().as_ref()) + .find_event(another_room_id, &event_gruyere.event_id().unwrap()) .await .expect("failed to query for finding an event") .expect("failed to find an event"); @@ -1733,13 +1733,13 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore { // But they won't be returned when searching in the wrong room. assert!( - self.find_event(another_room_id, event_comte.event_id().unwrap().as_ref()) + self.find_event(another_room_id, &event_comte.event_id().unwrap()) .await .expect("failed to query for finding an event") .is_none() ); assert!( - self.find_event(room_id, event_gruyere.event_id().unwrap().as_ref()) + self.find_event(room_id, &event_gruyere.event_id().unwrap()) .await .expect("failed to query for finding an event") .is_none() @@ -1761,7 +1761,7 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore { // Add one event in a thread linked chunk. self.handle_linked_chunk_updates( - LinkedChunkId::Thread(room_id, thread_root1.event_id().unwrap().as_ref()), + LinkedChunkId::Thread(room_id, &thread_root1.event_id().unwrap()), vec![ Update::NewItemsChunk { previous: None, new: CId::new(0), next: None }, Update::PushItems { @@ -1775,7 +1775,7 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore { // Add one event in another thread linked chunk (same room). self.handle_linked_chunk_updates( - LinkedChunkId::Thread(room_id, thread_root2.event_id().unwrap().as_ref()), + LinkedChunkId::Thread(room_id, &thread_root2.event_id().unwrap()), vec![ Update::NewItemsChunk { previous: None, new: CId::new(0), next: None }, Update::PushItems { @@ -1802,22 +1802,22 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore { .unwrap(); // All the events can be found with `find_event()` for the room. - self.find_event(room_id, thread2_ev.event_id().unwrap().as_ref()) + self.find_event(room_id, &thread2_ev.event_id().unwrap()) .await .expect("failed to query for finding an event") .expect("failed to find thread1_ev"); - self.find_event(room_id, thread2_ev.event_id().unwrap().as_ref()) + self.find_event(room_id, &thread2_ev.event_id().unwrap()) .await .expect("failed to query for finding an event") .expect("failed to find thread2_ev"); - self.find_event(room_id, thread2_ev2.event_id().unwrap().as_ref()) + self.find_event(room_id, &thread2_ev2.event_id().unwrap()) .await .expect("failed to query for finding an event") .expect("failed to find thread2_ev2"); - self.find_event(room_id, room_ev.event_id().unwrap().as_ref()) + self.find_event(room_id, &room_ev.event_id().unwrap()) .await .expect("failed to query for finding an event") .expect("failed to find room_ev"); @@ -1825,7 +1825,7 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore { // Finding duplicates operates based on the linked chunk id. let dups = self .filter_duplicated_events( - LinkedChunkId::Thread(room_id, thread_root1.event_id().unwrap().as_ref()), + LinkedChunkId::Thread(room_id, &thread_root1.event_id().unwrap()), vec![thread1_ev.event_id().unwrap(), room_ev.event_id().unwrap()], ) .await @@ -1835,10 +1835,7 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore { // Loading all chunks operates based on the linked chunk id. let all_chunks = self - .load_all_chunks(LinkedChunkId::Thread( - room_id, - thread_root2.event_id().unwrap().as_ref(), - )) + .load_all_chunks(LinkedChunkId::Thread(room_id, &thread_root2.event_id().unwrap())) .await .unwrap(); assert_eq!(all_chunks.len(), 1); @@ -1853,7 +1850,7 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore { let metas = self .load_all_chunks_metadata(LinkedChunkId::Thread( room_id, - thread_root2.event_id().unwrap().as_ref(), + &thread_root2.event_id().unwrap(), )) .await .unwrap(); @@ -1863,10 +1860,7 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore { // Loading the last chunk operates based on the linked chunk id. let (last_chunk, _chunk_identifier_generator) = self - .load_last_chunk(LinkedChunkId::Thread( - room_id, - thread_root1.event_id().unwrap().as_ref(), - )) + .load_last_chunk(LinkedChunkId::Thread(room_id, &thread_root1.event_id().unwrap())) .await .unwrap(); let last_chunk = last_chunk.unwrap(); diff --git a/crates/matrix-sdk-base/src/event_cache/store/memory_store.rs b/crates/matrix-sdk-base/src/event_cache/store/memory_store.rs index 283e8a63004..9dec395f065 100644 --- a/crates/matrix-sdk-base/src/event_cache/store/memory_store.rs +++ b/crates/matrix-sdk-base/src/event_cache/store/memory_store.rs @@ -28,7 +28,7 @@ use matrix_sdk_common::{ RawChunk, Update, relational::RelationalLinkedChunk, }, }; -use ruma::{EventId, OwnedEventId, RoomId, events::relation::RelationType}; +use ruma::{EventId, RoomId, events::relation::RelationType}; use tracing::error; use super::{EventCacheStore, EventCacheStoreError, Result, extract_event_relation}; @@ -51,7 +51,7 @@ pub struct MemoryStore { #[derive(Debug)] struct MemoryStoreInner { leases: HashMap, - events: RelationalLinkedChunk, + events: RelationalLinkedChunk, } impl Default for MemoryStore { @@ -155,8 +155,8 @@ impl EventCacheStore for MemoryStore { async fn filter_duplicated_events( &self, linked_chunk_id: LinkedChunkId<'_>, - mut events: Vec, - ) -> Result, Self::Error> { + mut events: Vec, + ) -> Result, Self::Error> { if events.is_empty() { return Ok(Vec::new()); } @@ -171,7 +171,7 @@ impl EventCacheStore for MemoryStore { if let Some(known_event_id) = event.event_id() { // This event is a duplicate! if let Some(index) = - events.iter().position(|new_event_id| &known_event_id == new_event_id) + events.iter().position(|new_event_id| known_event_id == new_event_id) { duplicated_events.push((events.remove(index), position)); } diff --git a/crates/matrix-sdk-base/src/event_cache/store/mod.rs b/crates/matrix-sdk-base/src/event_cache/store/mod.rs index c0617e1850b..bd09f8401f0 100644 --- a/crates/matrix-sdk-base/src/event_cache/store/mod.rs +++ b/crates/matrix-sdk-base/src/event_cache/store/mod.rs @@ -32,7 +32,7 @@ use matrix_sdk_common::cross_process_lock::{ CrossProcessLockGuard, MappedCrossProcessLockState, TryLock, }; pub use matrix_sdk_store_encryption::Error as StoreEncryptionError; -use ruma::{OwnedEventId, events::AnySyncTimelineEvent, serde::Raw}; +use ruma::{EventId, events::AnySyncTimelineEvent, serde::Raw}; use tracing::trace; #[cfg(any(test, feature = "testing"))] @@ -224,10 +224,10 @@ impl TryLock for LockableEventCacheStore { /// If the event isn't in relation to another event, then this will return /// `None`. Otherwise, returns both the event id this event relates to, and the /// kind of relation as a string (e.g. `m.replace`). -pub fn extract_event_relation(event: &Raw) -> Option<(OwnedEventId, String)> { +pub fn extract_event_relation(event: &Raw) -> Option<(EventId, String)> { #[derive(serde::Deserialize)] struct RelatesTo { - event_id: OwnedEventId, + event_id: EventId, rel_type: String, } diff --git a/crates/matrix-sdk-base/src/event_cache/store/traits.rs b/crates/matrix-sdk-base/src/event_cache/store/traits.rs index 4348e983775..b9b6f98accb 100644 --- a/crates/matrix-sdk-base/src/event_cache/store/traits.rs +++ b/crates/matrix-sdk-base/src/event_cache/store/traits.rs @@ -23,7 +23,7 @@ use matrix_sdk_common::{ RawChunk, Update, }, }; -use ruma::{EventId, OwnedEventId, RoomId, events::relation::RelationType}; +use ruma::{EventId, RoomId, events::relation::RelationType}; use super::EventCacheStoreError; use crate::event_cache::{Event, Gap}; @@ -119,8 +119,8 @@ pub trait EventCacheStore: AsyncTraitDeps { async fn filter_duplicated_events( &self, linked_chunk_id: LinkedChunkId<'_>, - events: Vec, - ) -> Result, Self::Error>; + events: Vec, + ) -> Result, Self::Error>; /// Find an event by its ID in a room. /// @@ -259,8 +259,8 @@ impl EventCacheStore for EraseEventCacheStoreError { async fn filter_duplicated_events( &self, linked_chunk_id: LinkedChunkId<'_>, - events: Vec, - ) -> Result, Self::Error> { + events: Vec, + ) -> Result, Self::Error> { self.0.filter_duplicated_events(linked_chunk_id, events).await.map_err(Into::into) } diff --git a/crates/matrix-sdk-base/src/latest_event.rs b/crates/matrix-sdk-base/src/latest_event.rs index 59bb6898533..ace4a7a36e1 100644 --- a/crates/matrix-sdk-base/src/latest_event.rs +++ b/crates/matrix-sdk-base/src/latest_event.rs @@ -1,7 +1,7 @@ //! The Latest Event basic types. use matrix_sdk_common::deserialized_responses::TimelineEvent; -use ruma::{MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedUserId}; +use ruma::{EventId, MilliSecondsSinceUnixEpoch, UserId}; use serde::{Deserialize, Serialize}; use crate::store::SerializableEventContent; @@ -20,13 +20,13 @@ pub enum LatestEventValue { /// invited to join a room. RemoteInvite { /// The ID of the invite event. - event_id: Option, + event_id: Option, /// The timestamp of the invite event. timestamp: MilliSecondsSinceUnixEpoch, /// The user ID of the inviter. - inviter: Option, + inviter: Option, }, /// The latest event represents a local event that is sending. @@ -36,7 +36,7 @@ pub enum LatestEventValue { /// successfully. It should come quickly as a [`Self::Remote`]. LocalHasBeenSent { /// ID of the sent event. - event_id: OwnedEventId, + event_id: EventId, /// Value, as for other `Self::Local*` variants. value: LocalLatestEventValue, @@ -114,7 +114,7 @@ impl LatestEventValue { /// Get the event ID (if it exists) of the event representing the /// [`LatestEventValue`]. - pub fn event_id(&self) -> Option { + pub fn event_id(&self) -> Option { match self { Self::Remote(event) => event.event_id(), Self::RemoteInvite { event_id, .. } => event_id.clone(), diff --git a/crates/matrix-sdk-base/src/lib.rs b/crates/matrix-sdk-base/src/lib.rs index a7fd583ea5b..88244f22e3f 100644 --- a/crates/matrix-sdk-base/src/lib.rs +++ b/crates/matrix-sdk-base/src/lib.rs @@ -19,7 +19,7 @@ #![warn(missing_docs, missing_debug_implementations)] pub use matrix_sdk_common::*; -use ruma::{OwnedDeviceId, OwnedUserId}; +use ruma::{DeviceId, UserId}; use serde::{Deserialize, Serialize}; pub use crate::error::{Error, Result}; @@ -76,7 +76,7 @@ matrix_sdk_test_utils::init_tracing_for_tests!(); #[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)] pub struct SessionMeta { /// The ID of the session's user. - pub user_id: OwnedUserId, + pub user_id: UserId, /// The ID of the client device. - pub device_id: OwnedDeviceId, + pub device_id: DeviceId, } diff --git a/crates/matrix-sdk-base/src/media/mod.rs b/crates/matrix-sdk-base/src/media/mod.rs index b045b4e9e94..aee036e8fbf 100644 --- a/crates/matrix-sdk-base/src/media/mod.rs +++ b/crates/matrix-sdk-base/src/media/mod.rs @@ -139,8 +139,8 @@ impl MediaRequestParameters { /// Get the [`MxcUri`] from `Self`. pub fn uri(&self) -> &MxcUri { match &self.source { - MediaSource::Plain(url) => url.as_ref(), - MediaSource::Encrypted(file) => file.url.as_ref(), + MediaSource::Plain(url) => url, + MediaSource::Encrypted(file) => &file.url, } } } diff --git a/crates/matrix-sdk-base/src/media/store/media_service.rs b/crates/matrix-sdk-base/src/media/store/media_service.rs index b5130a9e9a2..7665267a6f3 100644 --- a/crates/matrix-sdk-base/src/media/store/media_service.rs +++ b/crates/matrix-sdk-base/src/media/store/media_service.rs @@ -408,7 +408,7 @@ mod tests { use matrix_sdk_common::locks::Mutex; use matrix_sdk_test::async_test; use ruma::{ - MxcUri, OwnedMxcUri, + MxcUri, events::room::MediaSource, mxc_uri, time::{Duration, SystemTime}, @@ -470,7 +470,7 @@ mod tests { key: String, /// The original URI of the media content. - uri: OwnedMxcUri, + uri: MxcUri, /// The media content. content: Vec, diff --git a/crates/matrix-sdk-base/src/media/store/memory_store.rs b/crates/matrix-sdk-base/src/media/store/memory_store.rs index 617725c9614..ff8127d167d 100644 --- a/crates/matrix-sdk-base/src/media/store/memory_store.rs +++ b/crates/matrix-sdk-base/src/media/store/memory_store.rs @@ -26,7 +26,7 @@ use matrix_sdk_common::{ }, ring_buffer::RingBuffer, }; -use ruma::{MxcUri, OwnedMxcUri, time::SystemTime}; +use ruma::{MxcUri, time::SystemTime}; use super::Result; use crate::media::{ @@ -58,7 +58,7 @@ struct MemoryMediaStoreInner { #[derive(Debug)] struct MediaContent { /// The URI of the content. - uri: OwnedMxcUri, + uri: MxcUri, /// The unique key of the content. key: String, diff --git a/crates/matrix-sdk-base/src/read_receipts.rs b/crates/matrix-sdk-base/src/read_receipts.rs index a8826ea4a9e..739ee7b84a8 100644 --- a/crates/matrix-sdk-base/src/read_receipts.rs +++ b/crates/matrix-sdk-base/src/read_receipts.rs @@ -127,7 +127,7 @@ use matrix_sdk_common::{ serde_helpers::extract_thread_root, }; use ruma::{ - EventId, OwnedEventId, OwnedUserId, RoomId, UserId, + EventId, RoomId, UserId, events::{ AnySyncMessageLikeEvent, AnySyncTimelineEvent, OriginalSyncMessageLikeEvent, SyncMessageLikeEvent, @@ -146,7 +146,7 @@ use crate::ThreadingSupport; struct LatestReadReceipt { /// The id of the event the read receipt is referring to. (Not the read /// receipt event id.) - event_id: OwnedEventId, + event_id: EventId, } /// Public data about read receipts collected during processing of that room. @@ -179,7 +179,7 @@ pub struct RoomReadReceipts { /// Note: this contains event ids of the event *targets* of the receipts, /// not the event ids of the receipt events themselves. #[serde(default = "new_nonempty_ring_buffer")] - pending: RingBuffer, + pending: RingBuffer, } impl Default for RoomReadReceipts { @@ -194,7 +194,7 @@ impl Default for RoomReadReceipts { } } -fn new_nonempty_ring_buffer() -> RingBuffer { +fn new_nonempty_ring_buffer() -> RingBuffer { // 10 pending read receipts per room should be enough for everyone. // SAFETY: `unwrap` is safe because 10 is not zero. RingBuffer::new(NonZeroUsize::new(10).unwrap()) @@ -288,10 +288,10 @@ impl RoomReadReceipts { /// order). struct ReceiptSelector { /// Mapping of known event IDs to their sync order. - event_id_to_pos: BTreeMap, + event_id_to_pos: BTreeMap, /// The event with the greatest sync order, for which we had a read-receipt, /// so far. - latest_event_with_receipt: Option, + latest_event_with_receipt: Option, /// The biggest sync order attached to the `best_receipt`. latest_event_pos: Option, } @@ -314,7 +314,7 @@ impl ReceiptSelector { /// `event_id`. fn create_sync_index<'a>( events: impl Iterator + 'a, - ) -> BTreeMap { + ) -> BTreeMap { // TODO: this should be cached and incrementally updated. BTreeMap::from_iter( events @@ -350,7 +350,7 @@ impl ReceiptSelector { /// Try to match pending receipts against new events. #[instrument(skip_all)] - fn handle_pending_receipts(&mut self, pending: &mut RingBuffer) { + fn handle_pending_receipts(&mut self, pending: &mut RingBuffer) { // Try to match stashed receipts against the new events. pending.retain(|event_id| { if let Some(event_pos) = self.event_id_to_pos.get(event_id) { @@ -382,7 +382,7 @@ impl ReceiptSelector { &mut self, user_id: &UserId, receipt_event: &ReceiptEventContent, - ) -> Vec { + ) -> Vec { let mut pending = Vec::new(); // Now consider new receipts. for (event_id, receipts) in &receipt_event.0 { @@ -411,7 +411,7 @@ impl ReceiptSelector { fn try_match_implicit(&mut self, user_id: &UserId, new_events: &[TimelineEvent]) { for ev in new_events { // Get the `sender` field, if any, or skip this event. - let Ok(Some(sender)) = ev.raw().get_field::("sender") else { continue }; + let Ok(Some(sender)) = ev.raw().get_field::("sender") else { continue }; if sender == user_id { // Get the event id, if any, or skip this event. let Some(event_id) = ev.event_id() else { continue }; @@ -479,7 +479,7 @@ pub(crate) fn compute_unread_counts( let new_receipt = { let mut selector = ReceiptSelector::new( &all_events, - read_receipts.latest_active.as_ref().map(|receipt| &*receipt.event_id), + read_receipts.latest_active.as_ref().map(|receipt| &receipt.event_id), ); selector.try_match_implicit(user_id, new_events); diff --git a/crates/matrix-sdk-base/src/response_processors/account_data/global.rs b/crates/matrix-sdk-base/src/response_processors/account_data/global.rs index 6ee86c9132b..31a2b05bcd0 100644 --- a/crates/matrix-sdk-base/src/response_processors/account_data/global.rs +++ b/crates/matrix-sdk-base/src/response_processors/account_data/global.rs @@ -20,9 +20,7 @@ use std::{ use matrix_sdk_common::timer; use ruma::{ RoomId, - events::{ - AnyGlobalAccountDataEvent, GlobalAccountDataEventType, direct::OwnedDirectUserIdentifier, - }, + events::{AnyGlobalAccountDataEvent, GlobalAccountDataEventType, direct::DirectUserIdentifier}, serde::Raw, }; use tracing::{debug, instrument, trace, warn}; @@ -86,7 +84,7 @@ impl Global { for event in events { let AnyGlobalAccountDataEvent::Direct(direct_event) = event else { continue }; - let mut new_dms = HashMap::<&RoomId, HashSet>::new(); + let mut new_dms = HashMap::<&RoomId, HashSet>::new(); for (user_identifier, rooms) in direct_event.content.iter() { for room_id in rooms { diff --git a/crates/matrix-sdk-base/src/response_processors/e2ee/tracked_users.rs b/crates/matrix-sdk-base/src/response_processors/e2ee/tracked_users.rs index 4749f215a8e..85b9830499a 100644 --- a/crates/matrix-sdk-base/src/response_processors/e2ee/tracked_users.rs +++ b/crates/matrix-sdk-base/src/response_processors/e2ee/tracked_users.rs @@ -16,7 +16,7 @@ use std::collections::BTreeSet; use matrix_sdk_common::timer; use matrix_sdk_crypto::OlmMachine; -use ruma::{OwnedUserId, RoomId}; +use ruma::{RoomId, UserId}; use crate::{EncryptionState, Result, RoomMemberships, store::BaseStateStore}; @@ -24,13 +24,13 @@ use crate::{EncryptionState, Result, RoomMemberships, store::BaseStateStore}; pub async fn update( olm_machine: Option<&OlmMachine>, room_encryption_state: EncryptionState, - user_ids_to_track: &BTreeSet, + user_ids_to_track: &BTreeSet, ) -> Result<()> { if room_encryption_state.is_encrypted() && let Some(olm) = olm_machine && !user_ids_to_track.is_empty() { - olm.update_tracked_users(user_ids_to_track.iter().map(AsRef::as_ref)).await? + olm.update_tracked_users(user_ids_to_track.iter()).await? } Ok(()) @@ -40,7 +40,7 @@ pub async fn update( /// encrypted. pub async fn update_or_set_if_room_is_newly_encrypted( olm_machine: Option<&OlmMachine>, - user_ids_to_track: &BTreeSet, + user_ids_to_track: &BTreeSet, new_room_encryption_state: EncryptionState, previous_room_encryption_state: EncryptionState, room_id: &RoomId, @@ -56,11 +56,11 @@ pub async fn update_or_set_if_room_is_newly_encrypted( // to also get all the existing users and mark them for // tracking. let user_ids = state_store.get_user_ids(room_id, RoomMemberships::ACTIVE).await?; - olm.update_tracked_users(user_ids.iter().map(AsRef::as_ref)).await? + olm.update_tracked_users(user_ids.iter()).await? } if !user_ids_to_track.is_empty() { - olm.update_tracked_users(user_ids_to_track.iter().map(AsRef::as_ref)).await?; + olm.update_tracked_users(user_ids_to_track.iter()).await?; } } diff --git a/crates/matrix-sdk-base/src/response_processors/mod.rs b/crates/matrix-sdk-base/src/response_processors/mod.rs index 2985db3b196..9fba598b1e4 100644 --- a/crates/matrix-sdk-base/src/response_processors/mod.rs +++ b/crates/matrix-sdk-base/src/response_processors/mod.rs @@ -27,11 +27,11 @@ pub mod verification; use std::collections::BTreeMap; -use ruma::OwnedRoomId; +use ruma::RoomId; use crate::{RoomInfoNotableUpdateReasons, StateChanges}; -type RoomInfoNotableUpdates = BTreeMap; +type RoomInfoNotableUpdates = BTreeMap; #[cfg_attr(test, derive(Clone))] #[derive(Default)] diff --git a/crates/matrix-sdk-base/src/response_processors/notification.rs b/crates/matrix-sdk-base/src/response_processors/notification.rs index ff2cac604f3..21eb8568691 100644 --- a/crates/matrix-sdk-base/src/response_processors/notification.rs +++ b/crates/matrix-sdk-base/src/response_processors/notification.rs @@ -15,7 +15,7 @@ use std::collections::BTreeMap; use ruma::{ - OwnedRoomId, + RoomId, push::{Action, PushConditionRoomCtx, Ruleset}, serde::Raw, }; @@ -28,14 +28,14 @@ use crate::{ /// and push rules. pub struct Notification<'a> { pub push_rules: &'a Ruleset, - pub notifications: &'a mut BTreeMap>, + pub notifications: &'a mut BTreeMap>, pub state_store: &'a BaseStateStore, } impl<'a> Notification<'a> { pub fn new( push_rules: &'a Ruleset, - notifications: &'a mut BTreeMap>, + notifications: &'a mut BTreeMap>, state_store: &'a BaseStateStore, ) -> Self { Self { push_rules, notifications, state_store } @@ -43,7 +43,7 @@ impl<'a> Notification<'a> { fn push_notification( &mut self, - room_id: OwnedRoomId, + room_id: RoomId, actions: Vec, event: RawAnySyncOrStrippedTimelineEvent, ) { diff --git a/crates/matrix-sdk-base/src/response_processors/room/msc4186/extensions.rs b/crates/matrix-sdk-base/src/response_processors/room/msc4186/extensions.rs index f2ce50c32cf..f6e33cf07f5 100644 --- a/crates/matrix-sdk-base/src/response_processors/room/msc4186/extensions.rs +++ b/crates/matrix-sdk-base/src/response_processors/room/msc4186/extensions.rs @@ -15,7 +15,7 @@ use std::collections::BTreeMap; use ruma::{ - OwnedRoomId, RoomId, + RoomId, api::client::sync::sync_events::v5 as http, events::{AnySyncEphemeralRoomEvent, SyncEphemeralRoomEvent, receipt::ReceiptEventContent}, serde::Raw, @@ -34,7 +34,7 @@ use crate::{ /// response. pub fn dispatch_typing_ephemeral_events( typing: &http::response::Typing, - joined_room_updates: &mut BTreeMap, + joined_room_updates: &mut BTreeMap, ) { for (room_id, raw) in &typing.rooms { joined_room_updates diff --git a/crates/matrix-sdk-base/src/response_processors/room/msc4186/mod.rs b/crates/matrix-sdk-base/src/response_processors/room/msc4186/mod.rs index 5c689a894d0..cacbfcdaa3e 100644 --- a/crates/matrix-sdk-base/src/response_processors/room/msc4186/mod.rs +++ b/crates/matrix-sdk-base/src/response_processors/room/msc4186/mod.rs @@ -20,7 +20,7 @@ use std::collections::BTreeSet; use matrix_sdk_common::timer; use ruma::{ - JsOption, OwnedRoomId, RoomId, UserId, + JsOption, RoomId, UserId, api::client::sync::sync_events::{ v3::{InviteState, InvitedRoom, KnockState, KnockedRoom}, v5 as http, @@ -59,7 +59,7 @@ pub async fn update_any_room( user_id: &UserId, room_creation_data: RoomCreationData<'_>, room_response: &http::response::Room, - rooms_account_data: &BTreeMap>>, + rooms_account_data: &BTreeMap>>, #[cfg(feature = "e2e-encryption")] e2ee: e2ee::E2EE<'_>, notification: notification::Notification<'_>, ) -> Result> { diff --git a/crates/matrix-sdk-base/src/response_processors/room/sync_v2.rs b/crates/matrix-sdk-base/src/response_processors/room/sync_v2.rs index ac5edc5f8e7..0355bff07b2 100644 --- a/crates/matrix-sdk-base/src/response_processors/room/sync_v2.rs +++ b/crates/matrix-sdk-base/src/response_processors/room/sync_v2.rs @@ -15,7 +15,7 @@ use std::collections::{BTreeMap, BTreeSet}; use ruma::{ - OwnedRoomId, OwnedUserId, RoomId, UserId, + RoomId, UserId, api::client::sync::sync_events::v3::{ InvitedRoom, JoinedRoom, KnockedRoom, LeftRoom, State as RumaState, }, @@ -39,7 +39,7 @@ pub async fn update_joined_room( context: &mut Context, room_creation_data: RoomCreationData<'_>, joined_room: JoinedRoom, - updated_members_in_room: &mut BTreeMap>, + updated_members_in_room: &mut BTreeMap>, notification: notification::Notification<'_>, #[cfg(feature = "e2e-encryption")] e2ee: e2ee::E2EE<'_>, ) -> Result { diff --git a/crates/matrix-sdk-base/src/response_processors/state_events.rs b/crates/matrix-sdk-base/src/response_processors/state_events.rs index 195f038bc06..e9216c0de99 100644 --- a/crates/matrix-sdk-base/src/response_processors/state_events.rs +++ b/crates/matrix-sdk-base/src/response_processors/state_events.rs @@ -34,7 +34,7 @@ pub mod sync { use as_variant::as_variant; use ruma::{ - OwnedUserId, RoomId, UserId, + RoomId, UserId, events::{ AnySyncStateEvent, AnySyncTimelineEvent, StateEventType, room::member::MembershipState, }, @@ -209,7 +209,7 @@ pub mod sync { fn insert(&mut self, user_id: &UserId); } - impl NewUsers for BTreeSet { + impl NewUsers for BTreeSet { fn insert(&mut self, user_id: &UserId) { self.insert(user_id.to_owned()); } @@ -488,7 +488,7 @@ pub fn is_tombstone_event_valid( loop { // We must check immediately if the `successor_room_id` is in `already_seen` in // case of a room is created and tombstones itself in a single sync. - if already_seen.contains(AsRef::::as_ref(&successor_room_id)) { + if already_seen.contains(&successor_room_id) { // Ahhh, there is a loop with `m.room.tombstone` events! error!(?room_id, ?tombstone, "`m.room.tombstone` event is invalid, it creates a loop"); return false; @@ -529,10 +529,10 @@ async fn decrypt_state_event( e2ee: &e2ee::E2EE<'_>, ) -> Option { use matrix_sdk_crypto::RoomEventDecryptionResult; - use ruma::OwnedEventId; + use ruma::EventId; use tracing::{trace, warn}; - let event_id = match raw_event.raw.get_field::("event_id") { + let event_id = match raw_event.raw.get_field::("event_id") { Ok(Some(event_id)) => event_id, Ok(None) => { warn!("Couldn't deserialize encrypted state event's ID: missing `event_id` field"); diff --git a/crates/matrix-sdk-base/src/response_processors/timeline.rs b/crates/matrix-sdk-base/src/response_processors/timeline.rs index bb757f22d5a..7e2f0b4b1de 100644 --- a/crates/matrix-sdk-base/src/response_processors/timeline.rs +++ b/crates/matrix-sdk-base/src/response_processors/timeline.rs @@ -198,7 +198,7 @@ fn update_push_room_context( user_id: &UserId, room_info: &RoomInfo, ) { - let room_id = &*room_info.room_id; + let room_id = &room_info.room_id; push_rules.member_count = UInt::new(room_info.active_members_count()).unwrap_or(UInt::MAX); diff --git a/crates/matrix-sdk-base/src/room/call.rs b/crates/matrix-sdk-base/src/room/call.rs index 93a57d55e53..ce35135fe1f 100644 --- a/crates/matrix-sdk-base/src/room/call.rs +++ b/crates/matrix-sdk-base/src/room/call.rs @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use ruma::OwnedUserId; +use ruma::UserId; use super::Room; @@ -23,7 +23,7 @@ impl Room { self.info.read().has_active_room_call() } - /// Returns a `Vec` of `OwnedUserId`'s that participate in the room call. + /// Returns a `Vec` of `UserId`'s that participate in the room call. /// /// MatrixRTC memberships with application `m.call` and scope `m.room` are /// considered. A user can occur twice if they join with two devices. @@ -31,7 +31,7 @@ impl Room { /// amount of sessions. /// /// The vector is ordered by oldest membership user to newest. - pub fn active_room_call_participants(&self) -> Vec { + pub fn active_room_call_participants(&self) -> Vec { self.info.read().active_room_call_participants() } } @@ -43,7 +43,7 @@ mod tests { use assign::assign; use matrix_sdk_test::{ALICE, BOB, CAROL, event_factory::EventFactory}; use ruma::{ - DeviceId, EventId, MilliSecondsSinceUnixEpoch, OwnedUserId, UserId, device_id, event_id, + DeviceId, EventId, MilliSecondsSinceUnixEpoch, UserId, device_id, event_id, events::{ AnySyncStateEvent, call::member::{ @@ -228,18 +228,18 @@ mod tests { let b_one = session_member_state_event( event_id!("$12345"), b, - Some(InitData { device_id: "DEVICE_0".into(), minutes_ago: 1 }), + Some(InitData { device_id: &"DEVICE_0".into(), minutes_ago: 1 }), ); let m_c1 = session_member_state_event( event_id!("$123456_0"), c, - Some(InitData { device_id: "DEVICE_0".into(), minutes_ago: 10 }), + Some(InitData { device_id: &"DEVICE_0".into(), minutes_ago: 10 }), ); let m_c2 = session_member_state_event( event_id!("$123456_1"), c, - Some(InitData { device_id: "DEVICE_1".into(), minutes_ago: 20 }), + Some(InitData { device_id: &"DEVICE_1".into(), minutes_ago: 20 }), ); // Intentionally use a non time sorted receive order1 receive_state_events(&room, vec![m_c1, m_c2, a_empty, b_one]); @@ -279,7 +279,7 @@ mod tests { receive_state_events(&room, vec![b_empty_membership, c_empty_membership]); // We have no active call anymore after emptying the memberships - assert_eq!(Vec::::new(), room.active_room_call_participants()); + assert_eq!(Vec::::new(), room.active_room_call_participants()); assert!(!room.has_active_room_call()); } } diff --git a/crates/matrix-sdk-base/src/room/create.rs b/crates/matrix-sdk-base/src/room/create.rs index 20d7479ee6d..b12f117f318 100644 --- a/crates/matrix-sdk-base/src/room/create.rs +++ b/crates/matrix-sdk-base/src/room/create.rs @@ -14,7 +14,7 @@ use matrix_sdk_common::ROOM_VERSION_RULES_FALLBACK; use ruma::{ - OwnedUserId, RoomVersionId, assign, + RoomVersionId, UserId, assign, events::{ EmptyStateKey, PossiblyRedactedStateEventContent, RedactContent, RedactedStateEventContent, StateEventContent, StateEventType, StaticEventContent, @@ -44,7 +44,7 @@ pub struct RoomCreateWithCreatorEventContent { /// /// While this should be optional since room version 11, we copy the sender /// of the event so we can still access it. - pub creator: OwnedUserId, + pub creator: UserId, /// Whether or not this room's data should be transferred to other /// homeservers. @@ -75,13 +75,13 @@ pub struct RoomCreateWithCreatorEventContent { /// Additional room creators, considered to have "infinite" power level, in /// room versions 12 onwards. #[serde(skip_serializing_if = "Vec::is_empty", default)] - pub additional_creators: Vec, + pub additional_creators: Vec, } impl RoomCreateWithCreatorEventContent { /// Constructs a `RoomCreateWithCreatorEventContent` with the given original /// content and sender. - pub fn from_event_content(content: RoomCreateEventContent, sender: OwnedUserId) -> Self { + pub fn from_event_content(content: RoomCreateEventContent, sender: UserId) -> Self { let RoomCreateEventContent { federate, room_version, @@ -100,7 +100,7 @@ impl RoomCreateWithCreatorEventContent { } } - fn into_event_content(self) -> (RoomCreateEventContent, OwnedUserId) { + fn into_event_content(self) -> (RoomCreateEventContent, UserId) { let Self { creator, federate, room_version, predecessor, room_type, additional_creators } = self; @@ -119,7 +119,7 @@ impl RoomCreateWithCreatorEventContent { /// Get the creators of the room from this content, according to the room /// version. - pub(crate) fn creators(&self) -> Vec { + pub(crate) fn creators(&self) -> Vec { let rules = self.room_version.rules().unwrap_or(ROOM_VERSION_RULES_FALLBACK); if rules.authorization.explicitly_privilege_room_creators { diff --git a/crates/matrix-sdk-base/src/room/display_name.rs b/crates/matrix-sdk-base/src/room/display_name.rs index 93aeef51e09..b47e550d312 100644 --- a/crates/matrix-sdk-base/src/room/display_name.rs +++ b/crates/matrix-sdk-base/src/room/display_name.rs @@ -17,7 +17,7 @@ use std::fmt; use as_variant::as_variant; use regex::Regex; use ruma::{ - OwnedMxcUri, OwnedUserId, RoomAliasId, UserId, + MxcUri, RoomAliasId, UserId, events::{SyncStateEvent, member_hints::MemberHintsEventContent}, }; use serde::{Deserialize, Serialize}; @@ -391,11 +391,11 @@ impl RoomSummary { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RoomHero { /// The user id of the hero. - pub user_id: OwnedUserId, + pub user_id: UserId, /// The display name of the hero. pub display_name: Option, /// The avatar url of the hero. - pub avatar_url: Option, + pub avatar_url: Option, } /// The number of heroes chosen to compute a room's name, if the room didn't diff --git a/crates/matrix-sdk-base/src/room/knock.rs b/crates/matrix-sdk-base/src/room/knock.rs index f5cc75f6cbc..ddaa65464e1 100644 --- a/crates/matrix-sdk-base/src/room/knock.rs +++ b/crates/matrix-sdk-base/src/room/knock.rs @@ -16,7 +16,7 @@ use std::collections::BTreeMap; use eyeball::{AsyncLock, ObservableWriteGuard}; use ruma::{ - OwnedEventId, OwnedUserId, + EventId, UserId, events::{ StateEventType, SyncStateEvent, room::member::{MembershipState, RoomMemberEventContent}, @@ -34,7 +34,7 @@ use crate::{ impl Room { /// Mark a list of requests to join the room as seen, given their state /// event ids. - pub async fn mark_knock_requests_as_seen(&self, user_ids: &[OwnedUserId]) -> StoreResult<()> { + pub async fn mark_knock_requests_as_seen(&self, user_ids: &[UserId]) -> StoreResult<()> { let raw_user_ids: Vec<&str> = user_ids.iter().map(|id| id.as_str()).collect(); let member_raw_events = self .store @@ -82,7 +82,7 @@ impl Room { let mut current_seen_events = current_seen_events_guard.clone().unwrap_or_default(); // Get and deserialize the member events for the seen knock requests - let keys: Vec = current_seen_events.values().map(|id| id.to_owned()).collect(); + let keys: Vec = current_seen_events.values().map(|id| id.to_owned()).collect(); let raw_member_events: Vec = self.store.get_state_events_for_keys_static(self.room_id(), &keys).await?; let member_events = raw_member_events @@ -127,14 +127,13 @@ impl Room { /// Get the list of seen knock request event ids in this room. pub async fn get_seen_knock_request_ids( &self, - ) -> Result, StoreError> { + ) -> Result, StoreError> { Ok(self.get_write_guarded_current_knock_request_ids().await?.clone().unwrap_or_default()) } async fn get_write_guarded_current_knock_request_ids( &self, - ) -> StoreResult>, AsyncLock>> - { + ) -> StoreResult>, AsyncLock>> { let mut guard = self.seen_knock_request_ids_map.write().await; // If there are no loaded request ids yet if guard.is_none() { @@ -153,8 +152,8 @@ impl Room { async fn update_seen_knock_request_ids( &self, - mut guard: ObservableWriteGuard<'_, Option>, AsyncLock>, - new_value: BTreeMap, + mut guard: ObservableWriteGuard<'_, Option>, AsyncLock>, + new_value: BTreeMap, ) -> StoreResult<()> { // Save the new values to the shared observable ObservableWriteGuard::set(&mut guard, Some(new_value.clone())); diff --git a/crates/matrix-sdk-base/src/room/members.rs b/crates/matrix-sdk-base/src/room/members.rs index 7d5bf112b27..0a2ff7eb9d5 100644 --- a/crates/matrix-sdk-base/src/room/members.rs +++ b/crates/matrix-sdk-base/src/room/members.rs @@ -21,7 +21,7 @@ use std::{ use bitflags::bitflags; use futures_util::future; use ruma::{ - Int, MxcUri, OwnedUserId, UserId, + Int, MxcUri, UserId, events::{ MessageLikeEventType, StateEventType, ignored_user_list::IgnoredUserListEventContent, @@ -276,7 +276,7 @@ impl RoomMember { /// Get the avatar url of the member, if there is one. pub fn avatar_url(&self) -> Option<&MxcUri> { if let Some(p) = self.profile.as_ref() { - p.content.avatar_url.as_deref() + p.content.avatar_url.as_ref() } else { self.event.avatar_url() } @@ -403,8 +403,8 @@ impl RoomMember { pub(crate) struct MemberRoomInfo<'a> { pub(crate) power_levels: Arc, pub(crate) max_power_level: i64, - pub(crate) users_display_names: HashMap<&'a DisplayName, BTreeSet>, - pub(crate) ignored_users: Option>, + pub(crate) users_display_names: HashMap<&'a DisplayName, BTreeSet>, + pub(crate) ignored_users: Option>, } /// The kind of room member updates that just happened. @@ -413,7 +413,7 @@ pub enum RoomMembersUpdate { /// The whole list room members was reloaded. FullReload, /// A few members were updated, their user ids are included. - Partial(BTreeSet), + Partial(BTreeSet), } bitflags! { diff --git a/crates/matrix-sdk-base/src/room/mod.rs b/crates/matrix-sdk-base/src/room/mod.rs index eb3ca6c20b7..976eda726bc 100644 --- a/crates/matrix-sdk-base/src/room/mod.rs +++ b/crates/matrix-sdk-base/src/room/mod.rs @@ -44,10 +44,9 @@ pub use room_info::{ RoomInfoNotableUpdateReasons, RoomRecencyStamp, apply_redaction, }; use ruma::{ - EventId, OwnedEventId, OwnedMxcUri, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, RoomId, - RoomVersionId, UserId, + EventId, MxcUri, RoomAliasId, RoomId, RoomVersionId, UserId, events::{ - direct::OwnedDirectUserIdentifier, + direct::DirectUserIdentifier, receipt::{Receipt, ReceiptThread, ReceiptType}, room::{ avatar, @@ -80,10 +79,10 @@ use crate::{ #[derive(Debug, Clone)] pub struct Room { /// The room ID. - pub(super) room_id: OwnedRoomId, + pub(super) room_id: RoomId, /// Our own user ID. - pub(super) own_user_id: OwnedUserId, + pub(super) own_user_id: UserId, pub(super) info: SharedObservable, @@ -98,8 +97,7 @@ pub struct Room { /// A map for ids of room membership events in the knocking state linked to /// the user id of the user affected by the member event, that the current /// user has marked as seen so they can be ignored. - pub seen_knock_request_ids_map: - SharedObservable>, AsyncLock>, + pub seen_knock_request_ids_map: SharedObservable>, AsyncLock>, /// A sender that will notify receivers when room member updates happen. pub room_member_updates_sender: broadcast::Sender, @@ -141,7 +139,7 @@ impl Room { } /// Get a copy of the room creators. - pub fn creators(&self) -> Option> { + pub fn creators(&self) -> Option> { self.info.read().creators() } @@ -221,7 +219,7 @@ impl Room { } /// Get the avatar url of this room. - pub fn avatar_url(&self) -> Option { + pub fn avatar_url(&self) -> Option { self.info.read().avatar_url().map(ToOwned::to_owned) } @@ -231,12 +229,12 @@ impl Room { } /// Get the canonical alias of this room. - pub fn canonical_alias(&self) -> Option { + pub fn canonical_alias(&self) -> Option { self.info.read().canonical_alias().map(ToOwned::to_owned) } /// Get the canonical alias of this room. - pub fn alt_aliases(&self) -> Vec { + pub fn alt_aliases(&self) -> Vec { self.info.read().alt_aliases().to_owned() } @@ -296,7 +294,7 @@ impl Room { /// only be considered as guidance. We leave members in this list to allow /// us to re-find a DM with a user even if they have left, since we may /// want to re-invite them. - pub fn direct_targets(&self) -> HashSet { + pub fn direct_targets(&self) -> HashSet { self.info.read().base_info.dm_targets.clone() } @@ -343,7 +341,7 @@ impl Room { } /// Get the service members in this room, if available. - pub fn service_members(&self) -> Option> { + pub fn service_members(&self) -> Option> { self.info.read().service_members().cloned() } @@ -430,7 +428,7 @@ impl Room { /// Get the list of users ids that are considered to be joined members of /// this room. - pub async fn joined_user_ids(&self) -> StoreResult> { + pub async fn joined_user_ids(&self) -> StoreResult> { self.store.get_user_ids(self.room_id(), RoomMemberships::JOIN).await } @@ -439,18 +437,18 @@ impl Room { self.info.read().heroes().to_vec() } - /// Get the receipt as an `OwnedEventId` and `Receipt` tuple for the given + /// Get the receipt as an `EventId` and `Receipt` tuple for the given /// `receipt_type`, `thread` and `user_id` in this room. pub async fn load_user_receipt( &self, receipt_type: ReceiptType, thread: ReceiptThread, user_id: &UserId, - ) -> StoreResult> { + ) -> StoreResult> { self.store.get_user_room_receipt_event(self.room_id(), receipt_type, thread, user_id).await } - /// Load from storage the receipts as a list of `OwnedUserId` and `Receipt` + /// Load from storage the receipts as a list of `UserId` and `Receipt` /// tuples for the given `receipt_type`, `thread` and `event_id` in this /// room. pub async fn load_event_receipts( @@ -458,7 +456,7 @@ impl Room { receipt_type: ReceiptType, thread: ReceiptThread, event_id: &EventId, - ) -> StoreResult> { + ) -> StoreResult> { self.store .get_event_room_receipt_events(self.room_id(), receipt_type, thread, event_id) .await @@ -495,14 +493,14 @@ impl Room { /// Get a `Stream` of loaded pinned events for this room. /// If no pinned events are found a single empty `Vec` will be returned. - pub fn pinned_event_ids_stream(&self) -> impl Stream> + use<> { + pub fn pinned_event_ids_stream(&self) -> impl Stream> + use<> { self.info .subscribe() .map(|i| i.base_info.pinned_events.map(|c| c.pinned).unwrap_or_default()) } /// Returns the current pinned event ids for this room. - pub fn pinned_event_ids(&self) -> Option> { + pub fn pinned_event_ids(&self) -> Option> { self.info.read().pinned_event_ids() } } diff --git a/crates/matrix-sdk-base/src/room/room_info.rs b/crates/matrix-sdk-base/src/room/room_info.rs index 7a7de02b4bd..7fb28294e56 100644 --- a/crates/matrix-sdk-base/src/room/room_info.rs +++ b/crates/matrix-sdk-base/src/room/room_info.rs @@ -22,8 +22,7 @@ use bitflags::bitflags; use eyeball::Subscriber; use matrix_sdk_common::{ROOM_VERSION_FALLBACK, ROOM_VERSION_RULES_FALLBACK}; use ruma::{ - EventId, MilliSecondsSinceUnixEpoch, MxcUri, OwnedEventId, OwnedMxcUri, OwnedRoomAliasId, - OwnedRoomId, OwnedUserId, RoomAliasId, RoomId, RoomVersionId, + EventId, MilliSecondsSinceUnixEpoch, MxcUri, RoomAliasId, RoomId, RoomVersionId, UserId, api::client::sync::sync_events::v3::RoomSummary as RumaSummary, assign, events::{ @@ -32,7 +31,7 @@ use ruma::{ call::member::{ CallMemberStateKey, MembershipData, PossiblyRedactedCallMemberEventContent, }, - direct::OwnedDirectUserIdentifier, + direct::DirectUserIdentifier, member_hints::PossiblyRedactedMemberHintsEventContent, room::{ avatar::{self, PossiblyRedactedRoomAvatarEventContent}, @@ -85,7 +84,7 @@ pub struct InviteAcceptanceDetails { pub invite_accepted_at: MilliSecondsSinceUnixEpoch, /// The user ID of the person that invited us. - pub inviter: OwnedUserId, + pub inviter: UserId, } impl Room { @@ -139,7 +138,7 @@ pub struct BaseRoomInfo { pub(crate) create: Option>, /// A list of user ids this room is considered as direct message, if this /// room is a DM. - pub(crate) dm_targets: HashSet, + pub(crate) dm_targets: HashSet, /// The `m.room.encryption` event content that enabled E2EE in this room. pub(crate) encryption: Option, /// The guest access policy of this room. @@ -480,44 +479,44 @@ impl BaseRoomInfo { .redaction; if let Some(ev) = &mut self.avatar - && ev.event_id.as_deref() == Some(redacts) + && ev.event_id.as_ref() == Some(redacts) { ev.redact(&redaction_rules); } else if let Some(ev) = &mut self.canonical_alias - && ev.event_id.as_deref() == Some(redacts) + && ev.event_id.as_ref() == Some(redacts) { ev.redact(&redaction_rules); } else if let Some(ev) = &mut self.create - && ev.event_id.as_deref() == Some(redacts) + && ev.event_id.as_ref() == Some(redacts) { ev.redact(&redaction_rules); } else if let Some(ev) = &mut self.guest_access - && ev.event_id.as_deref() == Some(redacts) + && ev.event_id.as_ref() == Some(redacts) { ev.redact(&redaction_rules); } else if let Some(ev) = &mut self.history_visibility - && ev.event_id.as_deref() == Some(redacts) + && ev.event_id.as_ref() == Some(redacts) { ev.redact(&redaction_rules); } else if let Some(ev) = &mut self.join_rules - && ev.event_id.as_deref() == Some(redacts) + && ev.event_id.as_ref() == Some(redacts) { ev.redact(&redaction_rules); } else if let Some(ev) = &mut self.name - && ev.event_id.as_deref() == Some(redacts) + && ev.event_id.as_ref() == Some(redacts) { ev.redact(&redaction_rules); } else if let Some(ev) = &mut self.tombstone - && ev.event_id.as_deref() == Some(redacts) + && ev.event_id.as_ref() == Some(redacts) { ev.redact(&redaction_rules); } else if let Some(ev) = &mut self.topic - && ev.event_id.as_deref() == Some(redacts) + && ev.event_id.as_ref() == Some(redacts) { ev.redact(&redaction_rules); } else { self.rtc_member_events - .retain(|_, member_event| member_event.event_id.as_deref() != Some(redacts)); + .retain(|_, member_event| member_event.event_id.as_ref() != Some(redacts)); } } @@ -572,7 +571,7 @@ pub struct RoomInfo { pub(crate) data_format_version: u8, /// The unique room id of the room. - pub(crate) room_id: OwnedRoomId, + pub(crate) room_id: RoomId, /// The state of the room. pub(crate) room_state: RoomState, @@ -874,11 +873,11 @@ impl RoomInfo { /// Returns the current room avatar. pub fn avatar_url(&self) -> Option<&MxcUri> { - self.base_info.avatar.as_ref().and_then(|e| e.content.url.as_deref()) + self.base_info.avatar.as_ref().and_then(|e| e.content.url.as_ref()) } /// Update the room avatar. - pub fn update_avatar(&mut self, url: Option) { + pub fn update_avatar(&mut self, url: Option) { self.base_info.avatar = url.map(|url| { let mut content = PossiblyRedactedRoomAvatarEventContent::new(); content.url = Some(url); @@ -985,11 +984,11 @@ impl RoomInfo { /// Get the canonical alias of this room. pub fn canonical_alias(&self) -> Option<&RoomAliasId> { - self.base_info.canonical_alias.as_ref()?.content.alias.as_deref() + self.base_info.canonical_alias.as_ref()?.content.alias.as_ref() } /// Get the alternative aliases of this room. - pub fn alt_aliases(&self) -> &[OwnedRoomAliasId] { + pub fn alt_aliases(&self) -> &[RoomAliasId] { self.base_info .canonical_alias .as_ref() @@ -1035,7 +1034,7 @@ impl RoomInfo { } /// Get the creators of this room. - pub fn creators(&self) -> Option> { + pub fn creators(&self) -> Option> { Some(self.base_info.create.as_ref()?.content.creators()) } @@ -1072,7 +1071,7 @@ impl RoomInfo { /// Return the service members for this room if the `m.member_hints` event /// is available - pub fn service_members(&self) -> Option<&BTreeSet> { + pub fn service_members(&self) -> Option<&BTreeSet> { self.base_info.member_hints.as_ref()?.content.service_members.as_ref() } @@ -1139,7 +1138,7 @@ impl RoomInfo { /// amount of sessions. /// /// The vector is ordered by oldest membership user to newest. - pub fn active_room_call_participants(&self) -> Vec { + pub fn active_room_call_participants(&self) -> Vec { self.active_room_call_memberships() .iter() .map(|(call_member_state_key, _)| call_member_state_key.user_id().to_owned()) @@ -1159,7 +1158,7 @@ impl RoomInfo { } /// Returns the current pinned event ids for this room. - pub fn pinned_event_ids(&self) -> Option> { + pub fn pinned_event_ids(&self) -> Option> { self.base_info.pinned_events.clone().map(|c| c.pinned) } @@ -1319,7 +1318,7 @@ pub fn apply_redaction( #[derive(Debug, Clone)] pub struct RoomInfoNotableUpdate { /// The room which was updated. - pub room_id: OwnedRoomId, + pub room_id: RoomId, /// The reason for this update. pub reasons: RoomInfoNotableUpdateReasons, diff --git a/crates/matrix-sdk-base/src/room/tombstone.rs b/crates/matrix-sdk-base/src/room/tombstone.rs index 704063e1c29..60b4c880ef2 100644 --- a/crates/matrix-sdk-base/src/room/tombstone.rs +++ b/crates/matrix-sdk-base/src/room/tombstone.rs @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use ruma::{OwnedRoomId, events::room::tombstone::PossiblyRedactedRoomTombstoneEventContent}; +use ruma::{RoomId, events::room::tombstone::PossiblyRedactedRoomTombstoneEventContent}; use super::Room; @@ -83,7 +83,7 @@ impl Room { #[derive(Debug)] pub struct SuccessorRoom { /// The ID of the next room replacing this (tombstoned) room. - pub room_id: OwnedRoomId, + pub room_id: RoomId, /// The reason why the room has been tombstoned. pub reason: Option, @@ -100,7 +100,7 @@ pub struct SuccessorRoom { #[derive(Debug)] pub struct PredecessorRoom { /// The ID of the old room. - pub room_id: OwnedRoomId, + pub room_id: RoomId, } #[cfg(test)] diff --git a/crates/matrix-sdk-base/src/sliding_sync.rs b/crates/matrix-sdk-base/src/sliding_sync.rs index 1040c74a261..bdfca2c801a 100644 --- a/crates/matrix-sdk-base/src/sliding_sync.rs +++ b/crates/matrix-sdk-base/src/sliding_sync.rs @@ -18,7 +18,7 @@ use matrix_sdk_common::deserialized_responses::ProcessedToDeviceEvent; use matrix_sdk_common::{deserialized_responses::TimelineEvent, timer}; use ruma::{ - OwnedRoomId, api::client::sync::sync_events::v5 as http, events::receipt::SyncReceiptEvent, + RoomId, api::client::sync::sync_events::v5 as http, events::receipt::SyncReceiptEvent, serde::Raw, }; use tracing::{instrument, trace}; @@ -239,7 +239,7 @@ impl BaseClient { #[doc(hidden)] pub async fn process_sliding_sync_receipts_extension_for_room( &self, - room_id: &OwnedRoomId, + room_id: &RoomId, response: &http::Response, new_sync_events: Vec, room_previous_events: Vec, @@ -308,12 +308,12 @@ mod tests { use assert_matches::assert_matches; use matrix_sdk_test::async_test; use ruma::{ - JsOption, MxcUri, OwnedRoomId, OwnedUserId, RoomAliasId, RoomId, UserId, + JsOption, MxcUri, RoomAliasId, RoomId, UserId, api::client::sync::sync_events::UnreadNotificationsCount, assign, event_id, events::{ GlobalAccountDataEventContent, StateEventContent, StateEventType, - direct::{DirectEventContent, DirectUserIdentifier, OwnedDirectUserIdentifier}, + direct::{DirectEventContent, DirectUserIdentifier}, room::{ avatar::RoomAvatarEventContent, canonical_alias::RoomCanonicalAliasEventContent, @@ -851,9 +851,7 @@ mod tests { create_dm(&client, room_id, user_a_id, user_b_id, MembershipState::Join).await; // (Sanity: B is a direct target, and is in Join state) - assert!( - direct_targets(&client, room_id).contains(<&DirectUserIdentifier>::from(user_b_id)) - ); + assert!(direct_targets(&client, room_id).contains(&DirectUserIdentifier::from(user_b_id))); assert_eq!(membership(&client, room_id, user_b_id).await, MembershipState::Join); // When B leaves @@ -862,9 +860,7 @@ mod tests { // Then B is still a direct target, and is in Leave state (B is a direct target // because we want to return to our old DM in the UI even if the other // user left, so we can reinvite them. See https://github.com/matrix-org/matrix-rust-sdk/issues/2017) - assert!( - direct_targets(&client, room_id).contains(<&DirectUserIdentifier>::from(user_b_id)) - ); + assert!(direct_targets(&client, room_id).contains(&DirectUserIdentifier::from(user_b_id))); assert_eq!(membership(&client, room_id, user_b_id).await, MembershipState::Leave); } @@ -880,9 +876,7 @@ mod tests { create_dm(&client, room_id, user_a_id, user_b_id, MembershipState::Invite).await; // (Sanity: B is a direct target, and is in Invite state) - assert!( - direct_targets(&client, room_id).contains(<&DirectUserIdentifier>::from(user_b_id)) - ); + assert!(direct_targets(&client, room_id).contains(&DirectUserIdentifier::from(user_b_id))); assert_eq!(membership(&client, room_id, user_b_id).await, MembershipState::Invite); // When B declines the invitation (i.e. leaves) @@ -891,9 +885,7 @@ mod tests { // Then B is still a direct target, and is in Leave state (B is a direct target // because we want to return to our old DM in the UI even if the other // user left, so we can reinvite them. See https://github.com/matrix-org/matrix-rust-sdk/issues/2017) - assert!( - direct_targets(&client, room_id).contains(<&DirectUserIdentifier>::from(user_b_id)) - ); + assert!(direct_targets(&client, room_id).contains(&DirectUserIdentifier::from(user_b_id))); assert_eq!(membership(&client, room_id, user_b_id).await, MembershipState::Leave); } @@ -911,9 +903,7 @@ mod tests { assert_eq!(membership(&client, room_id, user_a_id).await, MembershipState::Join); // (Sanity: B is a direct target, and is in Join state) - assert!( - direct_targets(&client, room_id).contains(<&DirectUserIdentifier>::from(user_b_id)) - ); + assert!(direct_targets(&client, room_id).contains(&DirectUserIdentifier::from(user_b_id))); assert_eq!(membership(&client, room_id, user_b_id).await, MembershipState::Join); let room = client.get_room(room_id).unwrap(); @@ -937,9 +927,7 @@ mod tests { assert_eq!(membership(&client, room_id, user_a_id).await, MembershipState::Join); // (Sanity: B is a direct target, and is in Join state) - assert!( - direct_targets(&client, room_id).contains(<&DirectUserIdentifier>::from(user_b_id)) - ); + assert!(direct_targets(&client, room_id).contains(&DirectUserIdentifier::from(user_b_id))); assert_eq!(membership(&client, room_id, user_b_id).await, MembershipState::Invite); let room = client.get_room(room_id).unwrap(); @@ -1950,8 +1938,7 @@ mod tests { let mut room_response = http::response::Room::new(); set_room_joined(&mut room_response, user_a_id); let mut response = response_with_room(room_id_1, room_response); - let mut direct_content: BTreeMap> = - BTreeMap::new(); + let mut direct_content: BTreeMap> = BTreeMap::new(); direct_content.insert(user_a_id.into(), vec![room_id_1.to_owned()]); direct_content.insert(user_b_id.into(), vec![room_id_2.to_owned()]); response @@ -2118,7 +2105,7 @@ mod tests { member.membership().clone() } - fn direct_targets(client: &BaseClient, room_id: &RoomId) -> HashSet { + fn direct_targets(client: &BaseClient, room_id: &RoomId) -> HashSet { let room = client.get_room(room_id).expect("Room not found!"); room.direct_targets() } @@ -2178,13 +2165,8 @@ mod tests { .expect("Failed to process sync"); } - fn set_direct_with( - response: &mut http::Response, - user_id: OwnedUserId, - room_ids: Vec, - ) { - let mut direct_content: BTreeMap> = - BTreeMap::new(); + fn set_direct_with(response: &mut http::Response, user_id: UserId, room_ids: Vec) { + let mut direct_content: BTreeMap> = BTreeMap::new(); direct_content.insert(user_id.into(), room_ids); response .extensions diff --git a/crates/matrix-sdk-base/src/store/ambiguity_map.rs b/crates/matrix-sdk-base/src/store/ambiguity_map.rs index 8080022c9a1..603a9e91856 100644 --- a/crates/matrix-sdk-base/src/store/ambiguity_map.rs +++ b/crates/matrix-sdk-base/src/store/ambiguity_map.rs @@ -18,7 +18,7 @@ use std::{ }; use ruma::{ - OwnedEventId, OwnedRoomId, OwnedUserId, RoomId, UserId, + EventId, RoomId, UserId, events::room::member::{MembershipState, SyncRoomMemberEvent}, }; use tracing::{instrument, trace}; @@ -33,13 +33,13 @@ use crate::{ #[derive(Debug, Clone)] struct DisplayNameUsers { display_name: DisplayName, - users: BTreeSet, + users: BTreeSet, } impl DisplayNameUsers { /// Remove the given [`UserId`] from the map, marking that the [`UserId`] /// doesn't use the display name anymore. - fn remove(&mut self, user_id: &UserId) -> Option { + fn remove(&mut self, user_id: &UserId) -> Option { self.users.remove(user_id); if self.user_count() == 1 { self.users.iter().next().cloned() } else { None } @@ -47,7 +47,7 @@ impl DisplayNameUsers { /// Add the given [`UserId`] from the map, marking that the [`UserId`] /// is using the display name. - fn add(&mut self, user_id: OwnedUserId) -> Option { + fn add(&mut self, user_id: UserId) -> Option { let ambiguous_user = if self.user_count() == 1 { self.users.iter().next().cloned() } else { None }; @@ -75,14 +75,14 @@ fn is_member_active(membership: &MembershipState) -> bool { #[derive(Debug)] pub(crate) struct AmbiguityCache { pub store: Arc, - pub cache: BTreeMap>>, - pub changes: BTreeMap>, + pub cache: BTreeMap>>, + pub changes: BTreeMap>, } #[instrument(ret(level = "trace"))] pub(crate) fn is_display_name_ambiguous( display_name: &DisplayName, - users_with_display_name: &BTreeSet, + users_with_display_name: &BTreeSet, ) -> bool { trace!("Checking if a display name is ambiguous"); display_name.is_inherently_ambiguous() || users_with_display_name.len() > 1 diff --git a/crates/matrix-sdk-base/src/store/integration_tests.rs b/crates/matrix-sdk-base/src/store/integration_tests.rs index 0feb7f865b9..b4e686f74e6 100644 --- a/crates/matrix-sdk-base/src/store/integration_tests.rs +++ b/crates/matrix-sdk-base/src/store/integration_tests.rs @@ -10,7 +10,7 @@ use assert_matches2::assert_let; use growable_bloom_filter::GrowableBloomBuilder; use matrix_sdk_test::{TestResult, event_factory::EventFactory}; use ruma::{ - EventId, MilliSecondsSinceUnixEpoch, OwnedUserId, RoomId, TransactionId, UserId, + EventId, MilliSecondsSinceUnixEpoch, RoomId, TransactionId, UserId, api::{ FeatureFlag, MatrixVersion, client::discovery::discover_homeserver::{HomeserverInfo, RtcFocusInfo}, @@ -465,10 +465,7 @@ impl StateStoreIntegrationTests for DynStateStore { // Empty user IDs list. let member_events = self - .get_state_events_for_keys_static::( - room_id, - &[], - ) + .get_state_events_for_keys_static::(room_id, &[]) .await; assert!(member_events?.is_empty()); let profiles = self.get_profiles(room_id, &[]).await; @@ -760,10 +757,7 @@ impl StateStoreIntegrationTests for DynStateStore { // Empty user IDs list. let member_events = self - .get_state_events_for_keys_static::( - room_id, - &[], - ) + .get_state_events_for_keys_static::(room_id, &[]) .await; assert!(member_events?.is_empty()); diff --git a/crates/matrix-sdk-base/src/store/memory_store.rs b/crates/matrix-sdk-base/src/store/memory_store.rs index 1b3bb31525d..5d74489d8d2 100644 --- a/crates/matrix-sdk-base/src/store/memory_store.rs +++ b/crates/matrix-sdk-base/src/store/memory_store.rs @@ -21,8 +21,8 @@ use async_trait::async_trait; use growable_bloom_filter::GrowableBloom; use matrix_sdk_common::{ROOM_VERSION_FALLBACK, ROOM_VERSION_RULES_FALLBACK}; use ruma::{ - CanonicalJsonObject, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedMxcUri, - OwnedRoomId, OwnedTransactionId, OwnedUserId, RoomId, TransactionId, UserId, + CanonicalJsonObject, EventId, MilliSecondsSinceUnixEpoch, MxcUri, RoomId, TransactionId, + UserId, canonical_json::{RedactedBecause, redact}, events::{ AnyGlobalAccountDataEvent, AnyRoomAccountDataEvent, AnyStrippedStateEvent, @@ -55,9 +55,9 @@ use crate::{ #[derive(Debug, Default)] #[allow(clippy::type_complexity)] struct MemoryStoreInner { - recently_visited_rooms: HashMap>, - composer_drafts: HashMap<(OwnedRoomId, Option), ComposerDraft>, - user_avatar_url: HashMap, + recently_visited_rooms: HashMap>, + composer_drafts: HashMap<(RoomId, Option), ComposerDraft>, + user_avatar_url: HashMap, sync_token: Option, supported_versions: Option>, well_known: Option>>, @@ -65,31 +65,28 @@ struct MemoryStoreInner { utd_hook_manager_data: Option, one_time_key_uploaded_error: bool, account_data: HashMap>, - profiles: HashMap>, - display_names: HashMap>>, - members: HashMap>, - room_info: HashMap, - room_state: - HashMap>>>, + profiles: HashMap>, + display_names: HashMap>>, + members: HashMap>, + room_info: HashMap, + room_state: HashMap>>>, room_account_data: - HashMap>>, + HashMap>>, stripped_room_state: - HashMap>>>, - stripped_members: HashMap>, - presence: HashMap>, - room_user_receipts: HashMap< - OwnedRoomId, - HashMap<(String, Option), HashMap>, - >, + HashMap>>>, + stripped_members: HashMap>, + presence: HashMap>, + room_user_receipts: + HashMap), HashMap>>, room_event_receipts: HashMap< - OwnedRoomId, - HashMap<(String, Option), HashMap>>, + RoomId, + HashMap<(String, Option), HashMap>>, >, custom: HashMap, Vec>, - send_queue_events: BTreeMap>, - dependent_send_queue_events: BTreeMap>, - seen_knock_requests: BTreeMap>, - thread_subscriptions: BTreeMap>, + send_queue_events: BTreeMap>, + dependent_send_queue_events: BTreeMap>, + seen_knock_requests: BTreeMap>, + thread_subscriptions: BTreeMap>, thread_subscriptions_catchup_tokens: Option>, } @@ -113,7 +110,7 @@ impl MemoryStore { receipt_type: ReceiptType, thread: ReceiptThread, user_id: &UserId, - ) -> Option<(OwnedEventId, Receipt)> { + ) -> Option<(EventId, Receipt)> { self.inner .read() .unwrap() @@ -130,7 +127,7 @@ impl MemoryStore { receipt_type: ReceiptType, thread: ReceiptThread, event_id: &EventId, - ) -> Option> { + ) -> Option> { Some( self.inner .read() @@ -479,7 +476,7 @@ impl StateStore for MemoryStore { } } - let make_redaction_rules = |room_info: &HashMap, room_id| { + let make_redaction_rules = |room_info: &HashMap, room_id| { room_info.get(room_id).map(|info| info.room_version_rules_or_default()).unwrap_or_else(|| { warn!( ?room_id, @@ -496,7 +493,7 @@ impl StateStore for MemoryStore { if let Some(room) = inner.room_state.get_mut(room_id) { for ref_room_mu in room.values_mut() { for raw_evt in ref_room_mu.values_mut() { - if let Ok(Some(event_id)) = raw_evt.get_field::("event_id") + if let Ok(Some(event_id)) = raw_evt.get_field::("event_id") && let Some(redaction) = redactions.get(&event_id) { let redacted = redact( @@ -523,10 +520,7 @@ impl StateStore for MemoryStore { Ok(self.inner.read().unwrap().presence.get(user_id).cloned()) } - async fn get_presence_events( - &self, - user_ids: &[OwnedUserId], - ) -> Result>> { + async fn get_presence_events(&self, user_ids: &[UserId]) -> Result>> { let presence = &self.inner.read().unwrap().presence; Ok(user_ids.iter().filter_map(|user_id| presence.get(user_id).cloned()).collect()) } @@ -550,7 +544,7 @@ impl StateStore for MemoryStore { event_type: StateEventType, ) -> Result> { fn get_events( - state_map: &HashMap>>>, + state_map: &HashMap>>>, room_id: &RoomId, event_type: &StateEventType, to_enum: fn(Raw) -> RawAnySyncOrStrippedState, @@ -623,7 +617,7 @@ impl StateStore for MemoryStore { async fn get_profiles<'a>( &self, room_id: &RoomId, - user_ids: &'a [OwnedUserId], + user_ids: &'a [UserId], ) -> Result> { if user_ids.is_empty() { return Ok(BTreeMap::new()); @@ -636,7 +630,7 @@ impl StateStore for MemoryStore { Ok(user_ids .iter() - .filter_map(|user_id| room_profiles.get(user_id).map(|p| (&**user_id, p.clone()))) + .filter_map(|user_id| room_profiles.get(user_id).map(|p| (user_id, p.clone()))) .collect()) } @@ -645,17 +639,17 @@ impl StateStore for MemoryStore { &self, room_id: &RoomId, memberships: RoomMemberships, - ) -> Result> { + ) -> Result> { /// Get the user IDs for the given room with the given memberships and /// stripped state. /// /// If `memberships` is empty, returns all user IDs in the room with the /// given stripped state. fn get_user_ids_inner( - members: &HashMap>, + members: &HashMap>, room_id: &RoomId, memberships: RoomMemberships, - ) -> Vec { + ) -> Vec { members .get(room_id) .map(|members| { @@ -695,7 +689,7 @@ impl StateStore for MemoryStore { &self, room_id: &RoomId, display_name: &DisplayName, - ) -> Result> { + ) -> Result> { Ok(self .inner .read() @@ -710,7 +704,7 @@ impl StateStore for MemoryStore { &self, room_id: &RoomId, display_names: &'a [DisplayName], - ) -> Result>> { + ) -> Result>> { if display_names.is_empty() { return Ok(HashMap::new()); } @@ -751,7 +745,7 @@ impl StateStore for MemoryStore { receipt_type: ReceiptType, thread: ReceiptThread, user_id: &UserId, - ) -> Result> { + ) -> Result> { Ok(self.get_user_room_receipt_event_impl(room_id, receipt_type, thread, user_id)) } @@ -761,7 +755,7 @@ impl StateStore for MemoryStore { receipt_type: ReceiptType, thread: ReceiptThread, event_id: &EventId, - ) -> Result> { + ) -> Result> { Ok(self .get_event_room_receipt_events_impl(room_id, receipt_type, thread, event_id) .unwrap_or_default()) @@ -802,7 +796,7 @@ impl StateStore for MemoryStore { async fn save_send_queue_request( &self, room_id: &RoomId, - transaction_id: OwnedTransactionId, + transaction_id: TransactionId, created_at: MilliSecondsSinceUnixEpoch, kind: QueuedRequestKind, priority: usize, @@ -903,7 +897,7 @@ impl StateStore for MemoryStore { Ok(()) } - async fn load_rooms_with_unsent_requests(&self) -> Result, Self::Error> { + async fn load_rooms_with_unsent_requests(&self) -> Result, Self::Error> { Ok(self.inner.read().unwrap().send_queue_events.keys().cloned().collect()) } diff --git a/crates/matrix-sdk-base/src/store/migration_helpers.rs b/crates/matrix-sdk-base/src/store/migration_helpers.rs index 309842458f5..c6a8e5bfa3e 100644 --- a/crates/matrix-sdk-base/src/store/migration_helpers.rs +++ b/crates/matrix-sdk-base/src/store/migration_helpers.rs @@ -18,9 +18,9 @@ use std::{collections::HashSet, sync::Arc}; use matrix_sdk_common::deserialized_responses::TimelineEvent; use ruma::{ - OwnedRoomId, OwnedUserId, RoomId, + RoomId, UserId, events::{ - direct::OwnedDirectUserIdentifier, + direct::DirectUserIdentifier, room::{ avatar::PossiblyRedactedRoomAvatarEventContent, canonical_alias::PossiblyRedactedRoomCanonicalAliasEventContent, @@ -58,7 +58,7 @@ use crate::{ /// 4. Replace the room info in the store. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct RoomInfoV1 { - room_id: OwnedRoomId, + room_id: RoomId, room_type: RoomState, notification_counts: UnreadNotificationsCount, summary: RoomSummary, @@ -142,7 +142,7 @@ fn encryption_state_default() -> bool { struct BaseRoomInfoV1 { avatar: Option>, canonical_alias: Option>, - dm_targets: HashSet, + dm_targets: HashSet, encryption: Option, guest_access: Option>, history_visibility: @@ -181,7 +181,7 @@ impl BaseRoomInfoV1 { let mut converted_dm_targets = HashSet::new(); for dm_target in dm_targets { - converted_dm_targets.insert(OwnedDirectUserIdentifier::from(dm_target)); + converted_dm_targets.insert(DirectUserIdentifier::from(dm_target)); } Box::new(BaseRoomInfo { diff --git a/crates/matrix-sdk-base/src/store/mod.rs b/crates/matrix-sdk-base/src/store/mod.rs index bd7cb7649a8..a83c706d249 100644 --- a/crates/matrix-sdk-base/src/store/mod.rs +++ b/crates/matrix-sdk-base/src/store/mod.rs @@ -46,7 +46,7 @@ use matrix_sdk_crypto::store::{DynCryptoStore, IntoCryptoStore}; pub use matrix_sdk_store_encryption::Error as StoreEncryptionError; use observable_map::ObservableMap; use ruma::{ - EventId, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId, UserId, + EventId, RoomId, UserId, events::{ AnyGlobalAccountDataEvent, AnyRoomAccountDataEvent, AnyStrippedStateEvent, AnySyncStateEvent, EmptyStateKey, GlobalAccountDataEventType, RedactContent, @@ -188,7 +188,7 @@ pub(crate) struct BaseStateStore { pub(super) sync_token: Arc>>, /// All rooms the store knows about. - rooms: Arc>>, + rooms: Arc>>, /// A lock to synchronize access to the store, such that data by the sync is /// never overwritten. @@ -196,7 +196,7 @@ pub(crate) struct BaseStateStore { /// Which rooms have already logged a log line about missing room info, in /// the context of response processors? - pub(crate) already_logged_missing_room: Arc>>, + pub(crate) already_logged_missing_room: Arc>>, } impl BaseStateStore { @@ -467,7 +467,7 @@ pub enum RoomLoadSettings { /// /// Please, be careful with this option. Read the documentation of /// [`RoomLoadSettings`]. - One(OwnedRoomId), + One(RoomId), } /// The subscription status of a thread. @@ -546,45 +546,42 @@ pub struct StateChanges { /// A mapping of event type string to `AnyBasicEvent`. pub account_data: BTreeMap>, /// A mapping of `UserId` to `PresenceEvent`. - pub presence: BTreeMap>, + pub presence: BTreeMap>, /// A mapping of `RoomId` to a map of users and their /// `MinimalRoomMemberEvent`. - pub profiles: BTreeMap>, + pub profiles: BTreeMap>, /// A mapping of room profiles to delete. /// /// These are deleted *before* other room profiles are inserted. - pub profiles_to_delete: BTreeMap>, + pub profiles_to_delete: BTreeMap>, /// A mapping of `RoomId` to a map of event type string to a state key and /// `AnySyncStateEvent`. - pub state: - BTreeMap>>>, + pub state: BTreeMap>>>, /// A mapping of `RoomId` to a map of event type string to `AnyBasicEvent`. pub room_account_data: - BTreeMap>>, + BTreeMap>>, - /// A map of `OwnedRoomId` to `RoomInfo`. - pub room_infos: BTreeMap, + /// A map of `RoomId` to `RoomInfo`. + pub room_infos: BTreeMap, /// A map of `RoomId` to `ReceiptEventContent`. - pub receipts: BTreeMap, + pub receipts: BTreeMap, - /// A map of `RoomId` to maps of `OwnedEventId` to be redacted by + /// A map of `RoomId` to maps of `EventId` to be redacted by /// `SyncRoomRedactionEvent`. - pub redactions: BTreeMap>>, + pub redactions: BTreeMap>>, /// A mapping of `RoomId` to a map of event type to a map of state key to /// `StrippedState`. - pub stripped_state: BTreeMap< - OwnedRoomId, - BTreeMap>>, - >, + pub stripped_state: + BTreeMap>>>, /// A map from room id to a map of a display name and a set of user ids that /// share that display name in the given room. - pub ambiguity_maps: BTreeMap>>, + pub ambiguity_maps: BTreeMap>>, } impl StateChanges { diff --git a/crates/matrix-sdk-base/src/store/send_queue.rs b/crates/matrix-sdk-base/src/store/send_queue.rs index ebbfefe9fbf..b0b7a7ba7e2 100644 --- a/crates/matrix-sdk-base/src/store/send_queue.rs +++ b/crates/matrix-sdk-base/src/store/send_queue.rs @@ -18,8 +18,7 @@ use std::{collections::BTreeMap, fmt, ops::Deref}; use as_variant::as_variant; use ruma::{ - MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedEventId, OwnedTransactionId, OwnedUserId, - TransactionId, UInt, + DeviceId, EventId, MilliSecondsSinceUnixEpoch, TransactionId, UInt, UserId, events::{ AnyMessageLikeEventContent, MessageLikeEventContent as _, RawExt as _, room::{MediaSource, message::RoomMessageEventContent}, @@ -109,7 +108,7 @@ pub enum QueuedRequestKind { thumbnail_source: Option, /// To which media event transaction does this upload relate? - related_to: OwnedTransactionId, + related_to: TransactionId, /// Accumulated list of infos for previously uploaded files and /// thumbnails if used during a gallery transaction. Otherwise empty. @@ -132,7 +131,7 @@ pub struct QueuedRequest { pub kind: QueuedRequestKind, /// Unique transaction id for the queued request, acting as a key. - pub transaction_id: OwnedTransactionId, + pub transaction_id: TransactionId, /// Error returned when the request couldn't be sent and is stuck in the /// unrecoverable state. @@ -177,7 +176,7 @@ pub enum QueueWedgeError { #[error("There are insecure devices in the room")] InsecureDevices { /// The insecure devices as a Map of userID to deviceID. - user_device_map: BTreeMap>, + user_device_map: BTreeMap>, }, /// This error occurs when a previously verified user is not anymore, and @@ -185,7 +184,7 @@ pub enum QueueWedgeError { #[error("Some users that were previously verified are not anymore")] IdentityViolations { /// The users that are expected to be verified but are not. - users: Vec, + users: Vec, }, /// It is required to set up cross-signing and properly verify the current @@ -242,7 +241,7 @@ pub enum DependentQueuedRequestKind { cache_key: MediaRequestParameters, /// To which media transaction id does this upload relate to? - related_to: OwnedTransactionId, + related_to: TransactionId, /// Whether the depended upon request was a thumbnail or a file upload. #[serde(default = "default_parent_is_thumbnail_upload")] @@ -258,7 +257,7 @@ pub enum DependentQueuedRequestKind { local_echo: Box, /// Transaction id for the file upload. - file_upload: OwnedTransactionId, + file_upload: TransactionId, /// Information about the thumbnail, if present. thumbnail_info: Option, @@ -289,7 +288,7 @@ fn default_parent_is_thumbnail_upload() -> bool { #[derive(Clone, Debug, Serialize, Deserialize)] pub struct FinishUploadThumbnailInfo { /// Transaction id for the thumbnail upload. - pub txn: OwnedTransactionId, + pub txn: TransactionId, /// Thumbnail's width. #[serde(default, skip_serializing_if = "Option::is_none")] pub width: Option, @@ -305,7 +304,7 @@ pub struct FinishUploadThumbnailInfo { #[derive(Clone, Debug, Serialize, Deserialize)] pub struct FinishGalleryItemInfo { /// Transaction id for the file upload. - pub file_upload: OwnedTransactionId, + pub file_upload: TransactionId, /// Information about the thumbnail, if present. pub thumbnail_info: Option, } @@ -319,7 +318,7 @@ pub struct FinishGalleryItemInfo { #[repr(transparent)] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(transparent)] -pub struct ChildTransactionId(OwnedTransactionId); +pub struct ChildTransactionId(TransactionId); impl ChildTransactionId { /// Returns a new [`ChildTransactionId`]. @@ -343,14 +342,14 @@ impl From for ChildTransactionId { } } -impl From for OwnedTransactionId { +impl From for TransactionId { fn from(val: ChildTransactionId) -> Self { val.0 } } -impl From for ChildTransactionId { - fn from(val: OwnedTransactionId) -> Self { +impl From for ChildTransactionId { + fn from(val: TransactionId) -> Self { Self(val) } } @@ -410,7 +409,7 @@ pub enum SentRequestKey { /// The parent transaction returned an event when it succeeded. Event { /// The event ID returned by the server. - event_id: OwnedEventId, + event_id: EventId, /// The sent event. event: Raw, @@ -425,7 +424,7 @@ pub enum SentRequestKey { impl SentRequestKey { /// Converts the current parent key into an event id, if possible. - pub fn into_event_id(self) -> Option { + pub fn into_event_id(self) -> Option { as_variant!(self, Self::Event { event_id, .. } => event_id) } @@ -456,7 +455,7 @@ pub struct DependentQueuedRequest { /// Note: this is the transaction id used for the depended-on request, i.e. /// the one that was originally sent and that's being modified with this /// dependent request. - pub parent_transaction_id: OwnedTransactionId, + pub parent_transaction_id: TransactionId, /// If the parent request has been sent, the parent's request identifier /// returned by the server once the local echo has been sent out. diff --git a/crates/matrix-sdk-base/src/store/traits.rs b/crates/matrix-sdk-base/src/store/traits.rs index 956347792c2..5d8b7ce2f26 100644 --- a/crates/matrix-sdk-base/src/store/traits.rs +++ b/crates/matrix-sdk-base/src/store/traits.rs @@ -24,8 +24,7 @@ use async_trait::async_trait; use growable_bloom_filter::GrowableBloom; use matrix_sdk_common::AsyncTraitDeps; use ruma::{ - EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedMxcUri, OwnedRoomId, - OwnedTransactionId, OwnedUserId, RoomId, TransactionId, UserId, + EventId, MilliSecondsSinceUnixEpoch, MxcUri, RoomId, TransactionId, UserId, api::{ SupportedVersions, client::discovery::discover_homeserver::{ @@ -119,7 +118,7 @@ pub trait StateStore: AsyncTraitDeps { /// * `user_ids` - The IDs of the users to fetch the presence events for. async fn get_presence_events( &self, - user_ids: &[OwnedUserId], + user_ids: &[UserId], ) -> Result>, Self::Error>; /// Get a state event out of the state store. @@ -189,7 +188,7 @@ pub trait StateStore: AsyncTraitDeps { async fn get_profiles<'a>( &self, room_id: &RoomId, - user_ids: &'a [OwnedUserId], + user_ids: &'a [UserId], ) -> Result, Self::Error>; /// Get the user ids of members for a given room with the given memberships, @@ -198,7 +197,7 @@ pub trait StateStore: AsyncTraitDeps { &self, room_id: &RoomId, memberships: RoomMemberships, - ) -> Result, Self::Error>; + ) -> Result, Self::Error>; /// Get a set of pure `RoomInfo`s the store knows about. async fn get_room_infos( @@ -218,7 +217,7 @@ pub trait StateStore: AsyncTraitDeps { &self, room_id: &RoomId, display_name: &DisplayName, - ) -> Result, Self::Error>; + ) -> Result, Self::Error>; /// Get all the users that use the given display names in the given room. /// @@ -231,7 +230,7 @@ pub trait StateStore: AsyncTraitDeps { &self, room_id: &RoomId, display_names: &'a [DisplayName], - ) -> Result>, Self::Error>; + ) -> Result>, Self::Error>; /// Get an event out of the account data store. /// @@ -276,7 +275,7 @@ pub trait StateStore: AsyncTraitDeps { receipt_type: ReceiptType, thread: ReceiptThread, user_id: &UserId, - ) -> Result, Self::Error>; + ) -> Result, Self::Error>; /// Get events out of the event room receipt store. /// @@ -297,7 +296,7 @@ pub trait StateStore: AsyncTraitDeps { receipt_type: ReceiptType, thread: ReceiptThread, event_id: &EventId, - ) -> Result, Self::Error>; + ) -> Result, Self::Error>; /// Get arbitrary data from the custom store /// @@ -367,7 +366,7 @@ pub trait StateStore: AsyncTraitDeps { async fn save_send_queue_request( &self, room_id: &RoomId, - transaction_id: OwnedTransactionId, + transaction_id: TransactionId, created_at: MilliSecondsSinceUnixEpoch, request: QueuedRequestKind, priority: usize, @@ -422,7 +421,7 @@ pub trait StateStore: AsyncTraitDeps { ) -> Result<(), Self::Error>; /// Loads all the rooms which have any pending requests in their send queue. - async fn load_rooms_with_unsent_requests(&self) -> Result, Self::Error>; + async fn load_rooms_with_unsent_requests(&self) -> Result, Self::Error>; /// Add a new entry to the list of dependent send queue requests for a /// parent request. @@ -571,7 +570,7 @@ impl StateStore for EraseStateStoreError { async fn get_presence_events( &self, - user_ids: &[OwnedUserId], + user_ids: &[UserId], ) -> Result>, Self::Error> { self.0.get_presence_events(user_ids).await.map_err(Into::into) } @@ -613,7 +612,7 @@ impl StateStore for EraseStateStoreError { async fn get_profiles<'a>( &self, room_id: &RoomId, - user_ids: &'a [OwnedUserId], + user_ids: &'a [UserId], ) -> Result, Self::Error> { self.0.get_profiles(room_id, user_ids).await.map_err(Into::into) } @@ -622,7 +621,7 @@ impl StateStore for EraseStateStoreError { &self, room_id: &RoomId, memberships: RoomMemberships, - ) -> Result, Self::Error> { + ) -> Result, Self::Error> { self.0.get_user_ids(room_id, memberships).await.map_err(Into::into) } @@ -637,7 +636,7 @@ impl StateStore for EraseStateStoreError { &self, room_id: &RoomId, display_name: &DisplayName, - ) -> Result, Self::Error> { + ) -> Result, Self::Error> { self.0.get_users_with_display_name(room_id, display_name).await.map_err(Into::into) } @@ -645,7 +644,7 @@ impl StateStore for EraseStateStoreError { &self, room_id: &RoomId, display_names: &'a [DisplayName], - ) -> Result>, Self::Error> { + ) -> Result>, Self::Error> { self.0.get_users_with_display_names(room_id, display_names).await.map_err(Into::into) } @@ -670,7 +669,7 @@ impl StateStore for EraseStateStoreError { receipt_type: ReceiptType, thread: ReceiptThread, user_id: &UserId, - ) -> Result, Self::Error> { + ) -> Result, Self::Error> { self.0 .get_user_room_receipt_event(room_id, receipt_type, thread, user_id) .await @@ -683,7 +682,7 @@ impl StateStore for EraseStateStoreError { receipt_type: ReceiptType, thread: ReceiptThread, event_id: &EventId, - ) -> Result, Self::Error> { + ) -> Result, Self::Error> { self.0 .get_event_room_receipt_events(room_id, receipt_type, thread, event_id) .await @@ -713,7 +712,7 @@ impl StateStore for EraseStateStoreError { async fn save_send_queue_request( &self, room_id: &RoomId, - transaction_id: OwnedTransactionId, + transaction_id: TransactionId, created_at: MilliSecondsSinceUnixEpoch, content: QueuedRequestKind, priority: usize, @@ -760,7 +759,7 @@ impl StateStore for EraseStateStoreError { .map_err(Into::into) } - async fn load_rooms_with_unsent_requests(&self) -> Result, Self::Error> { + async fn load_rooms_with_unsent_requests(&self) -> Result, Self::Error> { self.0.load_rooms_with_unsent_requests().await.map_err(Into::into) } @@ -1145,10 +1144,10 @@ pub enum StateStoreDataValue { Filter(String), /// The user avatar url - UserAvatarUrl(OwnedMxcUri), + UserAvatarUrl(MxcUri), /// A list of recently visited room identifiers for the current user - RecentlyVisitedRooms(Vec), + RecentlyVisitedRooms(Vec), /// Persistent data for /// `matrix_sdk_ui::unable_to_decrypt_hook::UtdHookManager`. @@ -1165,7 +1164,7 @@ pub enum StateStoreDataValue { ComposerDraft(ComposerDraft), /// A list of knock request ids marked as seen in a room. - SeenKnockRequests(BTreeMap), + SeenKnockRequests(BTreeMap), /// A list of tokens to continue thread subscriptions catchup. /// @@ -1311,12 +1310,12 @@ pub enum ComposerDraftType { /// The draft is a reply to an event. Reply { /// The ID of the event being replied to. - event_id: OwnedEventId, + event_id: EventId, }, /// The draft is an edit of an event. Edit { /// The ID of the event being edited. - event_id: OwnedEventId, + event_id: EventId, }, } @@ -1332,12 +1331,12 @@ impl StateStoreDataValue { } /// Get this value if it is a user avatar url. - pub fn into_user_avatar_url(self) -> Option { + pub fn into_user_avatar_url(self) -> Option { as_variant!(self, Self::UserAvatarUrl) } /// Get this value if it is a list of recently visited rooms. - pub fn into_recently_visited_rooms(self) -> Option> { + pub fn into_recently_visited_rooms(self) -> Option> { as_variant!(self, Self::RecentlyVisitedRooms) } @@ -1362,7 +1361,7 @@ impl StateStoreDataValue { } /// Get this value if it is the data for the ignored join requests. - pub fn into_seen_knock_requests(self) -> Option> { + pub fn into_seen_knock_requests(self) -> Option> { as_variant!(self, Self::SeenKnockRequests) } diff --git a/crates/matrix-sdk-base/src/sync.rs b/crates/matrix-sdk-base/src/sync.rs index c1431405351..8d2346061d1 100644 --- a/crates/matrix-sdk-base/src/sync.rs +++ b/crates/matrix-sdk-base/src/sync.rs @@ -24,7 +24,7 @@ pub use ruma::api::client::sync::sync_events::v3::{ InvitedRoom as InvitedRoomUpdate, KnockedRoom as KnockedRoomUpdate, }; use ruma::{ - OwnedEventId, OwnedRoomId, + EventId, RoomId, api::client::sync::sync_events::UnreadNotificationsCount as RumaUnreadNotificationsCount, events::{ AnyGlobalAccountDataEvent, AnyRoomAccountDataEvent, AnySyncEphemeralRoomEvent, @@ -58,7 +58,7 @@ pub struct SyncResponse { /// Messages sent directly between devices. pub to_device: Vec, /// New notifications per room. - pub notifications: BTreeMap>, + pub notifications: BTreeMap>, } #[cfg(not(tarpaulin_include))] @@ -77,20 +77,20 @@ impl fmt::Debug for SyncResponse { #[derive(Clone, Default)] pub struct RoomUpdates { /// The rooms that the user has left or been banned from. - pub left: BTreeMap, + pub left: BTreeMap, /// The rooms that the user has joined. - pub joined: BTreeMap, + pub joined: BTreeMap, /// The rooms that the user has been invited to. - pub invited: BTreeMap, + pub invited: BTreeMap, /// The rooms that the user has knocked on. - pub knocked: BTreeMap, + pub knocked: BTreeMap, } impl RoomUpdates { /// Iterate over all room IDs, from [`RoomUpdates::left`], /// [`RoomUpdates::joined`], [`RoomUpdates::invited`] and /// [`RoomUpdates::knocked`]. - pub fn iter_all_room_ids(&self) -> impl Iterator { + pub fn iter_all_room_ids(&self) -> impl Iterator { self.left .keys() .chain(self.joined.keys()) @@ -218,7 +218,7 @@ pub struct JoinedRoomUpdate { /// /// This is a map of event ID of the `m.room.member` event to the /// details of the ambiguity change. - pub ambiguity_changes: BTreeMap, + pub ambiguity_changes: BTreeMap, } #[cfg(not(tarpaulin_include))] @@ -242,7 +242,7 @@ impl JoinedRoomUpdate { account_data: Vec>, ephemeral: Vec>, unread_notifications: UnreadNotificationsCount, - ambiguity_changes: BTreeMap, + ambiguity_changes: BTreeMap, ) -> Self { Self { unread_notifications, timeline, state, account_data, ephemeral, ambiguity_changes } } @@ -290,7 +290,7 @@ pub struct LeftRoomUpdate { /// /// This is a map of event ID of the `m.room.member` event to the /// details of the ambiguity change. - pub ambiguity_changes: BTreeMap, + pub ambiguity_changes: BTreeMap, } impl LeftRoomUpdate { @@ -298,7 +298,7 @@ impl LeftRoomUpdate { timeline: Timeline, state: State, account_data: Vec>, - ambiguity_changes: BTreeMap, + ambiguity_changes: BTreeMap, ) -> Self { Self { timeline, state, account_data, ambiguity_changes } } @@ -375,7 +375,7 @@ impl fmt::Debug for State { } } -struct DebugInvitedRoomUpdates<'a>(&'a BTreeMap); +struct DebugInvitedRoomUpdates<'a>(&'a BTreeMap); #[cfg(not(tarpaulin_include))] impl fmt::Debug for DebugInvitedRoomUpdates<'_> { @@ -384,7 +384,7 @@ impl fmt::Debug for DebugInvitedRoomUpdates<'_> { } } -struct DebugKnockedRoomUpdates<'a>(&'a BTreeMap); +struct DebugKnockedRoomUpdates<'a>(&'a BTreeMap); #[cfg(not(tarpaulin_include))] impl fmt::Debug for DebugKnockedRoomUpdates<'_> { diff --git a/crates/matrix-sdk-base/src/utils.rs b/crates/matrix-sdk-base/src/utils.rs index 3615518aec0..d42a21d0f10 100644 --- a/crates/matrix-sdk-base/src/utils.rs +++ b/crates/matrix-sdk-base/src/utils.rs @@ -1,5 +1,5 @@ use ruma::{ - OwnedEventId, + EventId, events::{ AnySyncStateEvent, AnySyncTimelineEvent, PossiblyRedactedStateEventContent, RedactContent, RedactedStateEventContent, StateEventType, StaticEventContent, StaticStateEventContent, @@ -32,7 +32,7 @@ pub struct MinimalStateEvent, + pub event_id: Option, } impl MinimalStateEvent @@ -88,7 +88,7 @@ where #[derive(Serialize, Deserialize)] struct MinimalStateEventSerdeHelperInner { content: C, - event_id: Option, + event_id: Option, } impl From> for MinimalStateEvent @@ -349,7 +349,7 @@ mod tests { ) .unwrap(); assert_eq!(event.content.name.as_deref(), Some("My Room")); - assert_eq!(event.event_id.as_deref(), Some(event_id)); + assert_eq!(event.event_id.as_ref(), Some(event_id)); let event = serde_json::from_str::>( @@ -357,7 +357,7 @@ mod tests { ) .unwrap(); assert_eq!(event.content.name, None); - assert_eq!(event.event_id.as_deref(), Some(event_id)); + assert_eq!(event.event_id.as_ref(), Some(event_id)); // The new format works. let event = @@ -366,7 +366,7 @@ mod tests { ) .unwrap(); assert_eq!(event.content.name.as_deref(), Some("My Room")); - assert_eq!(event.event_id.as_deref(), Some(event_id)); + assert_eq!(event.event_id.as_ref(), Some(event_id)); let event = serde_json::from_str::>( @@ -374,6 +374,6 @@ mod tests { ) .unwrap(); assert_eq!(event.content.name, None); - assert_eq!(event.event_id.as_deref(), Some(event_id)); + assert_eq!(event.event_id.as_ref(), Some(event_id)); } } diff --git a/crates/matrix-sdk-common/src/deserialized_responses.rs b/crates/matrix-sdk-common/src/deserialized_responses.rs index 4dd8bd5a805..bb5e3cc8f08 100644 --- a/crates/matrix-sdk-common/src/deserialized_responses.rs +++ b/crates/matrix-sdk-common/src/deserialized_responses.rs @@ -15,7 +15,7 @@ use std::{collections::BTreeMap, fmt, ops::Not, sync::Arc}; use ruma::{ - DeviceKeyAlgorithm, MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedEventId, OwnedUserId, + DeviceId, DeviceKeyAlgorithm, EventId, MilliSecondsSinceUnixEpoch, UserId, events::{ AnySyncMessageLikeEvent, AnySyncTimelineEvent, AnyTimelineEvent, AnyToDeviceEvent, MessageLikeEventType, room::encrypted::EncryptedEventScheme, @@ -321,9 +321,9 @@ pub enum AlgorithmInfo { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ForwarderInfo { /// The user ID of the forwarder. - pub user_id: OwnedUserId, + pub user_id: UserId, /// The device ID of the forwarder. - pub device_id: OwnedDeviceId, + pub device_id: DeviceId, } /// Struct containing information on how an event was decrypted. @@ -331,10 +331,10 @@ pub struct ForwarderInfo { pub struct EncryptionInfo { /// The user ID of the event sender, note this is untrusted data unless the /// `verification_state` is `Verified` as well. - pub sender: OwnedUserId, + pub sender: UserId, /// The device ID of the device that sent us the event, note this is /// untrusted data unless `verification_state` is `Verified` as well. - pub sender_device: Option, + pub sender_device: Option, /// If the keys for this message were shared-on-invite as part of an /// [MSC4268] key bundle, information about the forwarder. /// @@ -371,8 +371,8 @@ impl<'de> Deserialize<'de> for EncryptionInfo { // EncryptionInfo the session_id was not in AlgorithmInfo #[derive(Deserialize)] struct Helper { - pub sender: OwnedUserId, - pub sender_device: Option, + pub sender: UserId, + pub sender_device: Option, pub forwarder: Option, pub algorithm_info: AlgorithmInfo, pub verification_state: VerificationState, @@ -419,7 +419,7 @@ impl<'de> Deserialize<'de> for EncryptionInfo { pub struct ThreadSummary { /// The event id for the latest reply to the thread. #[serde(skip_serializing_if = "Option::is_none")] - pub latest_reply: Option, + pub latest_reply: Option, /// The number of replies to the thread. /// @@ -722,7 +722,7 @@ impl TimelineEvent { match latest_event.get_field::("type") { Ok(None) => { - let event_id = latest_event.get_field::("event_id").ok().flatten(); + let event_id = latest_event.get_field::("event_id").ok().flatten(); warn!( ?event_id, "couldn't deserialize bundled latest thread event: missing `type` field \ @@ -758,7 +758,7 @@ impl TimelineEvent { ))), Err(err) => { - let event_id = latest_event.get_field::("event_id").ok().flatten(); + let event_id = latest_event.get_field::("event_id").ok().flatten(); warn!(?event_id, "couldn't deserialize bundled latest thread event's type: {err}"); None } @@ -780,7 +780,7 @@ impl TimelineEvent { /// Get the event id of this [`TimelineEvent`] if the event has any valid /// id. - pub fn event_id(&self) -> Option { + pub fn event_id(&self) -> Option { self.kind.event_id() } @@ -921,8 +921,8 @@ impl TimelineEventKind { /// Get the event id of this `TimelineEventKind` if the event has any valid /// id. - pub fn event_id(&self) -> Option { - self.raw().get_field::("event_id").ok().flatten() + pub fn event_id(&self) -> Option { + self.raw().get_field::("event_id").ok().flatten() } /// Whether we could not decrypt the event (i.e. it is a UTD). @@ -1825,7 +1825,7 @@ mod tests { let timeline_event = TimelineEvent::from_plaintext(raw); assert_matches!(timeline_event.thread_summary, ThreadSummaryStatus::Some(ThreadSummary { num_replies, latest_reply }) => { assert_eq!(num_replies, 2); - assert_eq!(latest_reply.as_deref(), Some(event_id!("$latest_event:example.com"))); + assert_eq!(latest_reply.as_ref(), Some(event_id!("$latest_event:example.com"))); }); assert!(timeline_event.bundled_latest_thread_event.is_some()); diff --git a/crates/matrix-sdk-common/src/linked_chunk/mod.rs b/crates/matrix-sdk-common/src/linked_chunk/mod.rs index e13134e1c2c..6f02d441131 100644 --- a/crates/matrix-sdk-common/src/linked_chunk/mod.rs +++ b/crates/matrix-sdk-common/src/linked_chunk/mod.rs @@ -106,7 +106,7 @@ use std::{ pub use as_vector::*; pub use order_tracker::OrderTracker; -use ruma::{EventId, OwnedEventId, OwnedRoomId, RoomId}; +use ruma::{EventId, RoomId}; use serde::{Deserialize, Serialize}; pub use updates::*; @@ -185,9 +185,9 @@ impl PartialEq> for OwnedLinkedChunkId { /// An identifier for a linked chunk; owned variant. #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum OwnedLinkedChunkId { - Room(OwnedRoomId), - Thread(OwnedRoomId, OwnedEventId), - PinnedEvents(OwnedRoomId), + Room(RoomId), + Thread(RoomId, EventId), + PinnedEvents(RoomId), } impl Display for OwnedLinkedChunkId { @@ -199,13 +199,11 @@ impl Display for OwnedLinkedChunkId { impl OwnedLinkedChunkId { pub fn as_ref(&self) -> LinkedChunkId<'_> { match self { - OwnedLinkedChunkId::Room(room_id) => LinkedChunkId::Room(room_id.as_ref()), + OwnedLinkedChunkId::Room(room_id) => LinkedChunkId::Room(room_id), OwnedLinkedChunkId::Thread(room_id, event_id) => { - LinkedChunkId::Thread(room_id.as_ref(), event_id.as_ref()) - } - OwnedLinkedChunkId::PinnedEvents(room_id) => { - LinkedChunkId::PinnedEvents(room_id.as_ref()) + LinkedChunkId::Thread(room_id, event_id) } + OwnedLinkedChunkId::PinnedEvents(room_id) => LinkedChunkId::PinnedEvents(room_id), } } diff --git a/crates/matrix-sdk-common/src/linked_chunk/relational.rs b/crates/matrix-sdk-common/src/linked_chunk/relational.rs index ed2a3fa2389..94f250b3ab7 100644 --- a/crates/matrix-sdk-common/src/linked_chunk/relational.rs +++ b/crates/matrix-sdk-common/src/linked_chunk/relational.rs @@ -20,7 +20,7 @@ use std::{ hash::Hash, }; -use ruma::{OwnedEventId, OwnedRoomId, RoomId}; +use ruma::{EventId, RoomId}; use thiserror::Error; use super::{ChunkContent, ChunkIdentifierGenerator, RawChunk}; @@ -110,7 +110,7 @@ pub trait IndexableItem { } impl IndexableItem for TimelineEvent { - type ItemId = OwnedEventId; + type ItemId = EventId; fn id(&self) -> Self::ItemId { self.event_id() @@ -414,7 +414,7 @@ where } /// Save a single item "out-of-band" in the relational linked chunk. - pub fn save_item(&mut self, room_id: OwnedRoomId, item: Item) { + pub fn save_item(&mut self, room_id: RoomId, item: Item) { let id = item.id(); let linked_chunk_id = OwnedLinkedChunkId::Room(room_id); diff --git a/crates/matrix-sdk-common/src/serde_helpers.rs b/crates/matrix-sdk-common/src/serde_helpers.rs index 4da53fa25b8..46f121796a9 100644 --- a/crates/matrix-sdk-common/src/serde_helpers.rs +++ b/crates/matrix-sdk-common/src/serde_helpers.rs @@ -16,7 +16,7 @@ //! to access some fields. use ruma::{ - MilliSecondsSinceUnixEpoch, OwnedEventId, + EventId, MilliSecondsSinceUnixEpoch, events::{ AnyMessageLikeEventContent, AnySyncMessageLikeEvent, AnySyncTimelineEvent, relation::{BundledThread, RelationType}, @@ -32,7 +32,7 @@ struct RelatesTo { #[serde(rename = "rel_type")] rel_type: RelationType, #[serde(rename = "event_id")] - event_id: Option, + event_id: Option, } #[allow(missing_debug_implementations)] @@ -51,7 +51,7 @@ struct SimplifiedContent { /// during deserialization. pub fn extract_thread_root_from_content( content: Raw, -) -> Option { +) -> Option { let relates_to = content.deserialize_as_unchecked::().ok()?.relates_to?; match relates_to.rel_type { RelationType::Thread => relates_to.event_id, @@ -66,7 +66,7 @@ pub fn extract_thread_root_from_content( /// /// Returns `None` if we couldn't find a thread root, or if there was an issue /// during deserialization. -pub fn extract_thread_root(event: &Raw) -> Option { +pub fn extract_thread_root(event: &Raw) -> Option { extract_thread_root_from_content(event.get_field("content").ok().flatten()?) } @@ -79,7 +79,7 @@ pub fn extract_thread_root(event: &Raw) -> Option) -> Option { +pub fn extract_edit_target(event: &Raw) -> Option { let relates_to = event.get_field::("content").ok().flatten()?.relates_to?; match relates_to.rel_type { RelationType::Replacement => relates_to.event_id, @@ -89,7 +89,7 @@ pub fn extract_edit_target(event: &Raw) -> Option) -> Option<(RelationType, OwnedEventId)> { +pub fn extract_relation(event: &Raw) -> Option<(RelationType, EventId)> { let relates_to = event.get_field::("content").ok().flatten()?.relates_to?; Some((relates_to.rel_type, relates_to.event_id?)) } @@ -120,7 +120,7 @@ pub fn extract_bundled_thread_summary( let count = bundled_thread.count.try_into().unwrap_or(u32::MAX); let latest_reply = - bundled_thread.latest_event.get_field::("event_id").ok().flatten(); + bundled_thread.latest_event.get_field::("event_id").ok().flatten(); ( ThreadSummaryStatus::Some(ThreadSummary { num_replies: count, latest_reply }), @@ -189,7 +189,7 @@ mod tests { .cast_unchecked(); let observed_thread_root = extract_thread_root(&event); - assert_eq!(observed_thread_root.as_deref(), Some(thread_root)); + assert_eq!(observed_thread_root.as_ref(), Some(thread_root)); let observed_relation = extract_relation(&event).unwrap(); assert_eq!(observed_relation, (RelationType::Thread, thread_root.to_owned())); diff --git a/crates/matrix-sdk-crypto/src/backups/mod.rs b/crates/matrix-sdk-crypto/src/backups/mod.rs index 3ec40dbce68..0c98a85bbb9 100644 --- a/crates/matrix-sdk-crypto/src/backups/mod.rs +++ b/crates/matrix-sdk-crypto/src/backups/mod.rs @@ -29,8 +29,8 @@ use std::{ }; use ruma::{ - DeviceId, DeviceKeyAlgorithm, OwnedDeviceId, OwnedRoomId, OwnedTransactionId, RoomId, - TransactionId, api::client::backup::RoomKeyBackup, serde::Raw, + DeviceId, DeviceKeyAlgorithm, RoomId, TransactionId, api::client::backup::RoomKeyBackup, + serde::Raw, }; use tokio::sync::RwLock; use tracing::{debug, info, instrument, trace, warn}; @@ -67,9 +67,9 @@ type SessionId = String; #[derive(Debug, Clone)] struct PendingBackup { - request_id: OwnedTransactionId, + request_id: TransactionId, request: KeysBackupRequest, - sessions: BTreeMap>>, + sessions: BTreeMap>>, } /// The result of a signature verification of a signed JSON object. @@ -83,7 +83,7 @@ pub struct SignatureVerification { pub user_identity_signature: SignatureState, /// The result of the signature verification using public keys of other /// devices we own. - pub other_signatures: BTreeMap, + pub other_signatures: BTreeMap, } impl SignatureVerification { @@ -219,7 +219,7 @@ impl BackupMachine { signatures: &Signatures, auth_data: &str, compute_all_signatures: bool, - ) -> Result, CryptoStoreError> { + ) -> Result, CryptoStoreError> { let mut result = BTreeMap::new(); if let Some(user_signatures) = signatures.get(&self.store.static_account().user_id) { @@ -233,7 +233,7 @@ impl BackupMachine { let state = self .test_ed25519_device_signature( - device_key_id.key_name(), + &device_key_id.key_name(), signatures, auth_data, ) @@ -448,7 +448,7 @@ impl BackupMachine { /// out to backup the room keys. pub async fn backup( &self, - ) -> Result, CryptoStoreError> { + ) -> Result, CryptoStoreError> { let mut request = self.pending_backup.write().await; if let Some(request) = &*request { @@ -478,7 +478,7 @@ impl BackupMachine { .flat_map(|(room_id, sender_key_to_session_ids)| { std::iter::repeat(room_id).zip(sender_key_to_session_ids.values().flatten()) }) - .map(|(room_id, session_id)| (room_id.as_ref(), session_id.as_str())) + .map(|(room_id, session_id)| (room_id, session_id.as_str())) .collect(); trace!(request_id = ?r.request_id, keys = ?r.sessions, "Marking room keys as backed up"); @@ -556,12 +556,10 @@ impl BackupMachine { async fn backup_keys( sessions: Vec, backup_key: &MegolmV1BackupKey, - ) -> ( - BTreeMap, - BTreeMap>>, - ) { - let mut backup: BTreeMap = BTreeMap::new(); - let mut session_record: BTreeMap>> = + ) -> (BTreeMap, BTreeMap>>) + { + let mut backup: BTreeMap = BTreeMap::new(); + let mut session_record: BTreeMap>> = BTreeMap::new(); for session in sessions { @@ -602,7 +600,7 @@ impl BackupMachine { #[deprecated(note = "Use the OlmMachine::store::import_room_keys method instead")] pub async fn import_backed_up_room_keys( &self, - room_keys: BTreeMap>, + room_keys: BTreeMap>, progress_listener: impl Fn(usize, usize), ) -> Result { let mut decrypted_room_keys = vec![]; diff --git a/crates/matrix-sdk-crypto/src/error.rs b/crates/matrix-sdk-crypto/src/error.rs index 8ed4ee11dc0..891b64a15a8 100644 --- a/crates/matrix-sdk-crypto/src/error.rs +++ b/crates/matrix-sdk-crypto/src/error.rs @@ -15,7 +15,7 @@ use std::collections::BTreeMap; use matrix_sdk_common::deserialized_responses::{VerificationLevel, WithheldCode}; -use ruma::{CanonicalJsonError, IdParseError, OwnedDeviceId, OwnedRoomId, OwnedUserId}; +use ruma::{CanonicalJsonError, DeviceId, IdParseError, RoomId, UserId}; use serde::{Serializer, ser::SerializeMap}; use serde_json::Error as SerdeError; use thiserror::Error; @@ -58,12 +58,12 @@ pub enum OlmError { #[error( "decryption failed likely because an Olm session from {0} with sender key {1} was wedged" )] - SessionWedged(OwnedUserId, Curve25519PublicKey), + SessionWedged(UserId, Curve25519PublicKey), /// An Olm message got replayed while the Olm ratchet has already moved /// forward. #[error("decryption failed because an Olm message from {0} with sender key {1} was replayed")] - ReplayedMessage(OwnedUserId, Curve25519PublicKey), + ReplayedMessage(UserId, Curve25519PublicKey), /// Encryption failed because the device does not have a valid Olm session /// with us. @@ -208,7 +208,7 @@ pub enum EventError { "the sender of the plaintext doesn't match the sender of the encrypted \ message, got {0}, expected {1}" )] - MismatchedSender(OwnedUserId, OwnedUserId), + MismatchedSender(UserId, UserId), /// The public key that was part of the message doesn't match the key we /// have stored. @@ -224,7 +224,7 @@ pub enum EventError { "the room id of the room key doesn't match the room id of the \ decrypted event: expected {0}, got {1:?}" )] - MismatchedRoom(OwnedRoomId, Option), + MismatchedRoom(RoomId, Option), /// The event includes `sender_device_keys` as per [MSC4147], but the /// signature was invalid, or the ed25519 or curve25519 key did not @@ -313,14 +313,14 @@ pub enum SessionCreationError { "Failed to create a new Olm session for {0} {1}, the requested \ one-time key isn't a signed curve key" )] - OneTimeKeyNotSigned(OwnedUserId, OwnedDeviceId), + OneTimeKeyNotSigned(UserId, DeviceId), /// The signed one-time key is missing. #[error( "Tried to create a new Olm session for {0} {1}, but the signed \ one-time key is missing" )] - OneTimeKeyMissing(OwnedUserId, OwnedDeviceId), + OneTimeKeyMissing(UserId, DeviceId), /// Failed to verify the one-time key signatures. #[error( @@ -341,7 +341,7 @@ pub enum SessionCreationError { "Tried to create an Olm session for {0} {1}, but the device is missing \ a curve25519 key" )] - DeviceMissingCurveKey(OwnedUserId, OwnedDeviceId), + DeviceMissingCurveKey(UserId, DeviceId), /// Error deserializing the one-time key. #[error("Error deserializing the one-time key: {0}")] @@ -401,7 +401,7 @@ pub enum SessionRecipientCollectionError { /// [`LocalTrust::BlackListed`] (see [`Device::set_local_trust`]), and /// then retry the encryption operation. #[error("one or more verified users have unsigned devices")] - VerifiedUserHasUnsignedDevice(BTreeMap>), + VerifiedUserHasUnsignedDevice(BTreeMap>), /// One or more users was previously verified, but they have changed their /// identity. @@ -422,7 +422,7 @@ pub enum SessionRecipientCollectionError { /// /// The caller can then retry the encryption operation. #[error("one or more users that were verified have changed their identity")] - VerifiedUserChangedIdentity(Vec), + VerifiedUserChangedIdentity(Vec), /// Cross-signing has not been configured on our own identity. /// diff --git a/crates/matrix-sdk-crypto/src/gossiping/machine.rs b/crates/matrix-sdk-crypto/src/gossiping/machine.rs index fe5ee7f224d..5f0c600cc03 100644 --- a/crates/matrix-sdk-crypto/src/gossiping/machine.rs +++ b/crates/matrix-sdk-crypto/src/gossiping/machine.rs @@ -31,8 +31,7 @@ use std::{ use matrix_sdk_common::locks::RwLock as StdRwLock; use ruma::{ - DeviceId, OneTimeKeyAlgorithm, OwnedDeviceId, OwnedTransactionId, OwnedUserId, RoomId, - TransactionId, UserId, + DeviceId, OneTimeKeyAlgorithm, RoomId, TransactionId, UserId, api::client::keys::claim_keys::v3::Request as KeysClaimRequest, events::secret::request::{ RequestAction, SecretName, ToDeviceSecretRequestEvent as SecretRequestEvent, @@ -72,10 +71,10 @@ pub(crate) struct GossipMachineInner { store: Store, #[cfg(feature = "automatic-room-key-forwarding")] outbound_group_sessions: GroupSessionCache, - outgoing_requests: StdRwLock>, + outgoing_requests: StdRwLock>, incoming_key_requests: StdRwLock>, wait_queue: WaitQueue, - users_for_key_claim: Arc>>>, + users_for_key_claim: Arc>>>, /// Whether we should respond to incoming `m.room_key_request` messages. room_key_forwarding_enabled: AtomicBool, @@ -91,7 +90,7 @@ impl GossipMachine { store: Store, identity_manager: IdentityManager, #[allow(unused)] outbound_group_sessions: GroupSessionCache, - users_for_key_claim: Arc>>>, + users_for_key_claim: Arc>>>, ) -> Self { let room_key_forwarding_enabled = AtomicBool::new(cfg!(feature = "automatic-room-key-forwarding")); diff --git a/crates/matrix-sdk-crypto/src/gossiping/mod.rs b/crates/matrix-sdk-crypto/src/gossiping/mod.rs index 75f2edb103c..b3737ffd163 100644 --- a/crates/matrix-sdk-crypto/src/gossiping/mod.rs +++ b/crates/matrix-sdk-crypto/src/gossiping/mod.rs @@ -22,7 +22,7 @@ use std::{ pub(crate) use machine::GossipMachine; use matrix_sdk_common::locks::RwLock as StdRwLock; use ruma::{ - DeviceId, OwnedDeviceId, OwnedTransactionId, OwnedUserId, TransactionId, UserId, + DeviceId, TransactionId, UserId, events::{ AnyToDeviceEventContent, ToDeviceEventType, room_key_request::{Action, ToDeviceRoomKeyRequestEventContent}, @@ -89,9 +89,9 @@ pub enum KeyForwardDecision { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct GossipRequest { /// The user we requested the secret from - pub request_recipient: OwnedUserId, + pub request_recipient: UserId, /// The unique id of the secret request. - pub request_id: OwnedTransactionId, + pub request_id: TransactionId, /// The info of the requested secret. pub info: SecretInfo, /// Has the request been sent out. @@ -137,7 +137,7 @@ impl From for SecretInfo { impl GossipRequest { /// Create an outgoing secret request for the given secret. - pub(crate) fn from_secret_name(own_user_id: OwnedUserId, secret_name: SecretName) -> Self { + pub(crate) fn from_secret_name(own_user_id: UserId, secret_name: SecretName) -> Self { Self { request_recipient: own_user_id, request_id: TransactionId::new(), @@ -289,17 +289,13 @@ impl RequestEvent { #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] struct RequestInfo { - sender: OwnedUserId, - requesting_device_id: OwnedDeviceId, - request_id: OwnedTransactionId, + sender: UserId, + requesting_device_id: DeviceId, + request_id: TransactionId, } impl RequestInfo { - fn new( - sender: OwnedUserId, - requesting_device_id: OwnedDeviceId, - request_id: OwnedTransactionId, - ) -> Self { + fn new(sender: UserId, requesting_device_id: DeviceId, request_id: TransactionId) -> Self { Self { sender, requesting_device_id, request_id } } } @@ -314,7 +310,7 @@ struct WaitQueue { #[derive(Debug, Default)] struct WaitQueueInner { requests_waiting_for_session: BTreeMap, - requests_ids_waiting: BTreeMap<(OwnedUserId, OwnedDeviceId), BTreeSet>, + requests_ids_waiting: BTreeMap<(UserId, DeviceId), BTreeSet>, } impl WaitQueue { diff --git a/crates/matrix-sdk-crypto/src/identities/device.rs b/crates/matrix-sdk-crypto/src/identities/device.rs index 84543b7497b..481ae7c0f56 100644 --- a/crates/matrix-sdk-crypto/src/identities/device.rs +++ b/crates/matrix-sdk-crypto/src/identities/device.rs @@ -23,8 +23,7 @@ use std::{ use matrix_sdk_common::locks::RwLock; use ruma::{ - DeviceId, DeviceKeyAlgorithm, DeviceKeyId, MilliSecondsSinceUnixEpoch, OwnedDeviceId, - OwnedDeviceKeyId, UInt, UserId, + DeviceId, DeviceKeyAlgorithm, DeviceKeyId, MilliSecondsSinceUnixEpoch, UInt, UserId, api::client::keys::upload_signatures::v3::Request as SignatureUploadRequest, events::{AnyToDeviceEventContent, key::verification::VerificationMethod}, serde::Raw, @@ -519,7 +518,7 @@ impl Device { /// A read only view over all devices belonging to a user. #[derive(Debug)] pub struct UserDevices { - pub(crate) inner: HashMap, + pub(crate) inner: HashMap, pub(crate) verification_machine: VerificationMachine, pub(crate) own_identity: Option, pub(crate) device_owner_identity: Option, @@ -560,7 +559,7 @@ impl UserDevices { /// Iterator over all the device ids of the user devices. pub fn keys(&self) -> impl Iterator { - self.inner.keys().map(Deref::deref) + self.inner.keys() } /// Iterator over all the devices of the user devices. @@ -646,7 +645,7 @@ impl DeviceData { } /// Get a map containing all the device keys. - pub fn keys(&self) -> &BTreeMap { + pub fn keys(&self) -> &BTreeMap { &self.device_keys.keys } diff --git a/crates/matrix-sdk-crypto/src/identities/manager.rs b/crates/matrix-sdk-crypto/src/identities/manager.rs index c93a2f14b1c..45693f1c1d7 100644 --- a/crates/matrix-sdk-crypto/src/identities/manager.rs +++ b/crates/matrix-sdk-crypto/src/identities/manager.rs @@ -14,7 +14,6 @@ use std::{ collections::{BTreeMap, BTreeSet, HashMap, HashSet}, - ops::Deref, sync::Arc, time::Duration, }; @@ -23,8 +22,8 @@ use futures_util::future::join_all; use itertools::Itertools; use matrix_sdk_common::{executor::spawn, failures_cache::FailuresCache}; use ruma::{ - OwnedDeviceId, OwnedServerName, OwnedTransactionId, OwnedUserId, ServerName, TransactionId, - UserId, api::client::keys::get_keys::v3::Response as KeysQueryResponse, serde::Raw, + DeviceId, ServerName, TransactionId, UserId, + api::client::keys::get_keys::v3::Response as KeysQueryResponse, serde::Raw, }; use tokio::sync::Mutex; use tracing::{Level, debug, enabled, info, instrument, trace, warn}; @@ -69,7 +68,7 @@ pub(crate) struct IdentityManager { /// `/keys/query` response. /// /// See also [`crate::session_manager::SessionManager::failures`]. - failures: FailuresCache, + failures: FailuresCache, store: Store, pub(crate) key_query_manager: Arc, @@ -88,12 +87,12 @@ struct KeysQueryRequestDetails { /// A single batch of queries returned by the Store is broken up into one or /// more actual KeysQueryRequests, each with their own request id. We /// record the outstanding request ids here. - request_ids: HashSet, + request_ids: HashSet, } // Helper type to handle key query response struct KeySetInfo { - user_id: OwnedUserId, + user_id: UserId, master_key: MasterPubkey, self_signing: SelfSigningPubkey, } @@ -147,14 +146,15 @@ impl IdentityManager { .keys() .filter_map(|k| ServerName::parse(k).ok()) .filter(|s| s != self.user_id().server_name()); - let successful_servers = response.device_keys.keys().map(|u| u.server_name()); + let successful_servers = + response.device_keys.keys().map(|u| u.server_name()).collect::>(); // Append the new failed servers and remove any successful servers. We // need to explicitly remove the successful servers because the cache // doesn't automatically remove entries that elapse. Instead, the effect // is that elapsed servers will be retried and their delays incremented. self.failures.extend(failed_servers); - self.failures.remove(successful_servers); + self.failures.remove(successful_servers.iter()); let devices = self.handle_devices_from_key_query(response.device_keys.clone()).await?; let (identities, cross_signing_identity) = self.handle_cross_signing_keys(response).await?; @@ -206,10 +206,7 @@ impl IdentityManager { self.key_query_manager .synced(&cache) .await? - .mark_tracked_users_as_up_to_date( - response.device_keys.keys().map(Deref::deref), - sequence_number, - ) + .mark_tracked_users_as_up_to_date(response.device_keys.keys(), sequence_number) .await?; } @@ -292,14 +289,14 @@ impl IdentityManager { async fn update_user_devices( store: Store, - user_id: OwnedUserId, - device_map: BTreeMap>, + user_id: UserId, + device_map: BTreeMap>, ) -> StoreResult { let own_device_id = store.static_account().device_id().to_owned(); let mut changes = DeviceChanges::default(); - let current_devices: HashSet = device_map.keys().cloned().collect(); + let current_devices: HashSet = device_map.keys().cloned().collect(); let tasks = device_map.into_iter().filter_map(|(device_id, device_keys)| match device_keys .deserialize_as::( @@ -339,14 +336,14 @@ impl IdentityManager { } } - let current_devices: HashSet<&OwnedDeviceId> = current_devices.iter().collect(); + let current_devices: HashSet<&DeviceId> = current_devices.iter().collect(); let stored_devices = store.get_device_data_for_user(&user_id).await?; - let stored_devices_set: HashSet<&OwnedDeviceId> = stored_devices.keys().collect(); + let stored_devices_set: HashSet<&DeviceId> = stored_devices.keys().collect(); let deleted_devices_set = stored_devices_set.difference(¤t_devices); let own_user_id = store.static_account().user_id(); for device_id in deleted_devices_set { - if user_id == *own_user_id && *device_id == &own_device_id { + if user_id == *own_user_id && *device_id == own_device_id { let identity_keys = store.static_account().identity_keys(); warn!( @@ -376,10 +373,7 @@ impl IdentityManager { /// they are new, one of their properties has changed or they got deleted. async fn handle_devices_from_key_query( &self, - device_keys_map: BTreeMap< - OwnedUserId, - BTreeMap>, - >, + device_keys_map: BTreeMap>>, ) -> StoreResult { let mut changes = DeviceChanges::default(); @@ -804,7 +798,7 @@ impl IdentityManager { pub(crate) fn build_key_query_for_users<'a>( &self, users: impl IntoIterator, - ) -> (OwnedTransactionId, KeysQueryRequest) { + ) -> (TransactionId, KeysQueryRequest) { // Since this is an "out-of-band" request, we just make up a transaction ID and // do not store the details in `self.keys_query_request_details`. // @@ -828,7 +822,7 @@ impl IdentityManager { /// [`receive_keys_query_response`]: Self::receive_keys_query_response pub async fn users_for_key_query( &self, - ) -> StoreResult> { + ) -> StoreResult> { // Forget about any previous key queries in flight. *self.keys_query_request_details.lock().await = None; @@ -858,7 +852,7 @@ impl IdentityManager { // a TTL cache, remembers users for which a previous `/key/query` request has // failed. We don't retry a `/keys/query` for such users for a // certain amount of time. - let users = users.into_iter().filter(|u| !self.failures.contains(u.server_name())); + let users = users.into_iter().filter(|u| !self.failures.contains(&u.server_name())); // We don't want to create a single `/keys/query` request with an infinite // amount of users. Some servers will likely bail out after a @@ -926,7 +920,7 @@ impl IdentityManager { pub async fn get_user_devices_for_encryption( &self, users: impl Iterator, - ) -> StoreResult>> { + ) -> StoreResult>> { // How long we wait for /keys/query to complete. const KEYS_QUERY_WAIT_TIME: Duration = Duration::from_secs(5); @@ -971,7 +965,7 @@ impl IdentityManager { // In that case, we'll end up waiting for the *next* `users_for_key_query` call, // which might not be for 30 seconds or so. (And by then, it might be `failed` // again.) - if self.failures.contains(user_id.server_name()) { + if self.failures.contains(&user_id.server_name()) { users_with_no_devices_on_failed_servers.push(user_id); continue; } @@ -992,7 +986,7 @@ impl IdentityManager { // // We don't actually update the `devices_by_user` map here since that could // require concurrent access to it. Instead each task returns a - // `(OwnedUserId, HashMap)` pair (or rather, an `Option` of one) so that we can + // `(UserId, HashMap)` pair (or rather, an `Option` of one) so that we can // add the results to the map. let results = join_all( users_with_no_devices_on_unfailed_servers @@ -1032,7 +1026,7 @@ impl IdentityManager { &self, timeout_duration: Duration, user_id: &'a UserId, - ) -> Result)>, CryptoStoreError> { + ) -> Result)>, CryptoStoreError> { let cache = self.store.cache().await?; match self .key_query_manager @@ -1165,7 +1159,7 @@ impl IdentityManager { .synced(&store_cache) .await? .mark_tracked_users_as_changed( - tracked_users.iter().map(|tracked_user| tracked_user.user_id.as_ref()), + tracked_users.iter().map(|tracked_user| &tracked_user.user_id), ) .await?; @@ -1647,8 +1641,7 @@ pub(crate) mod tests { let devices = manager.store.get_user_devices(our_user).await.unwrap(); assert_eq!(devices.devices().count(), 1); - let device = - manager.store.get_device_data(our_user, device_id!(device_id())).await.unwrap(); + let device = manager.store.get_device_data(our_user, device_id()).await.unwrap(); assert!(device.is_some()); } @@ -1656,7 +1649,7 @@ pub(crate) mod tests { #[async_test] async fn test_private_identity_invalidation_after_public_keys_change() { let user_id = user_id!("@example1:localhost"); - let manager = manager_test_helper(user_id, "DEVICEID".into()).await; + let manager = manager_test_helper(user_id, &"DEVICEID".into()).await; let identity_request = { let private_identity = manager.store.private_identity(); @@ -1821,7 +1814,7 @@ pub(crate) mod tests { // a failure should stop us querying for the user's keys. let response = key_query_with_failures(); manager.receive_keys_query_response(&reqid, &response).await.unwrap(); - assert!(manager.failures.contains(alice.server_name())); + assert!(manager.failures.contains(&alice.server_name())); assert!( !manager .users_for_key_query() @@ -1832,7 +1825,7 @@ pub(crate) mod tests { ); // clearing the failure flag should make the user reappear in the query list. - manager.failures.remove([alice.server_name().to_owned()].iter()); + manager.failures.remove([alice.server_name()].iter()); assert!( manager .users_for_key_query() diff --git a/crates/matrix-sdk-crypto/src/identities/room_identity_state.rs b/crates/matrix-sdk-crypto/src/identities/room_identity_state.rs index 3fdcd11f9ea..ee6424b11f1 100644 --- a/crates/matrix-sdk-crypto/src/identities/room_identity_state.rs +++ b/crates/matrix-sdk-crypto/src/identities/room_identity_state.rs @@ -16,7 +16,7 @@ use std::{collections::HashMap, ops::Deref}; use matrix_sdk_common::BoxFuture; use ruma::{ - OwnedUserId, UserId, + UserId, events::{ SyncStateEvent, room::member::{MembershipState, SyncRoomMemberEvent}, @@ -140,8 +140,8 @@ impl RoomIdentityState { // redactions. if let SyncStateEvent::Original(event) = sync_room_member_event.deref() { // Ignore invalid user IDs - let user_id: Result<&UserId, _> = event.state_key.as_str().try_into(); - if let Ok(user_id) = user_id { + let user_id: Result = event.state_key.as_str().try_into(); + if let Ok(user_id) = &user_id { // Ignore non-existent users, and changes to our own identity if let Some(user_identity @ UserIdentity::Other(_)) = self.room.user_identity(user_id).await @@ -239,7 +239,7 @@ impl RoomIdentityState { #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct IdentityStatusChange { /// The user ID of the user whose identity status changed - pub user_id: OwnedUserId, + pub user_id: UserId, /// The new state of the identity of the user pub changed_to: IdentityState, @@ -288,7 +288,7 @@ pub enum RoomIdentityChange { /// Only stores users who _not_ in the Pinned stated. #[derive(Debug)] struct KnownStates { - known_states: HashMap, + known_states: HashMap, } impl KnownStates { @@ -332,10 +332,7 @@ mod tests { use matrix_sdk_common::BoxFuture; use matrix_sdk_test::{async_test, event_factory::EventFactory}; - use ruma::{ - OwnedUserId, UserId, device_id, events::room::member::MembershipState, owned_user_id, - user_id, - }; + use ruma::{UserId, device_id, events::room::member::MembershipState, owned_user_id, user_id}; use super::{IdentityState, RoomIdentityChange, RoomIdentityProvider, RoomIdentityState}; use crate::{ @@ -976,7 +973,7 @@ mod tests { #[derive(Clone, Debug)] struct FakeRoom { - users: Arc>>, + users: Arc>>, } impl FakeRoom { @@ -1065,7 +1062,7 @@ mod tests { } struct IdentityChangeSpec { - user_id: OwnedUserId, + user_id: UserId, changed_to: IdentityState, new: bool, own: bool, diff --git a/crates/matrix-sdk-crypto/src/identities/user.rs b/crates/matrix-sdk-crypto/src/identities/user.rs index 591f270c735..cd51b71450b 100644 --- a/crates/matrix-sdk-crypto/src/identities/user.rs +++ b/crates/matrix-sdk-crypto/src/identities/user.rs @@ -24,7 +24,7 @@ use std::{ use as_variant::as_variant; use matrix_sdk_common::locks::RwLock; use ruma::{ - DeviceId, EventId, OwnedDeviceId, OwnedUserId, RoomId, UserId, + DeviceId, EventId, RoomId, UserId, api::client::keys::upload_signatures::v3::Request as SignatureUploadRequest, events::{key::verification::VerificationMethod, room::message::MessageType}, }; @@ -592,7 +592,7 @@ impl UserIdentityData { #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(try_from = "OtherUserIdentityDataSerializer", into = "OtherUserIdentityDataSerializer")] pub struct OtherUserIdentityData { - user_id: OwnedUserId, + user_id: UserId, pub(crate) master_key: Arc, self_signing_key: Arc, pinned_master_key: Arc>, @@ -617,14 +617,14 @@ struct OtherUserIdentityDataSerializer { #[derive(Debug, Deserialize, Serialize)] struct OtherUserIdentityDataSerializerV0 { - user_id: OwnedUserId, + user_id: UserId, master_key: MasterPubkey, self_signing_key: SelfSigningPubkey, } #[derive(Debug, Deserialize, Serialize)] struct OtherUserIdentityDataSerializerV1 { - user_id: OwnedUserId, + user_id: UserId, master_key: MasterPubkey, self_signing_key: SelfSigningPubkey, pinned_master_key: MasterPubkey, @@ -632,7 +632,7 @@ struct OtherUserIdentityDataSerializerV1 { #[derive(Debug, Deserialize, Serialize)] struct OtherUserIdentityDataSerializerV2 { - user_id: OwnedUserId, + user_id: UserId, master_key: MasterPubkey, self_signing_key: SelfSigningPubkey, pinned_master_key: MasterPubkey, @@ -913,7 +913,7 @@ impl OtherUserIdentityData { /// the identity. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct OwnUserIdentityData { - user_id: OwnedUserId, + user_id: UserId, master_key: Arc, self_signing_key: Arc, user_signing_key: Arc, @@ -1166,9 +1166,9 @@ impl OwnUserIdentityData { fn filter_devices_to_request( &self, - devices: HashMap, + devices: HashMap, own_device_id: &DeviceId, - ) -> Vec { + ) -> Vec { devices .into_iter() .filter_map(|(device_id, device)| { diff --git a/crates/matrix-sdk-crypto/src/lib.rs b/crates/matrix-sdk-crypto/src/lib.rs index cf1b06362b1..93a70d9adf1 100644 --- a/crates/matrix-sdk-crypto/src/lib.rs +++ b/crates/matrix-sdk-crypto/src/lib.rs @@ -51,7 +51,7 @@ pub use identities::room_identity_state::{ IdentityState, IdentityStatusChange, RoomIdentityChange, RoomIdentityProvider, RoomIdentityState, }; -use ruma::OwnedRoomId; +use ruma::RoomId; /// Return type for the room key importing. #[derive(Debug, Clone, PartialEq, Eq)] @@ -64,14 +64,14 @@ pub struct RoomKeyImportResult { /// /// It's a map from room id to a map of the sender key to a set of session /// ids. - pub keys: BTreeMap>>, + pub keys: BTreeMap>>, } impl RoomKeyImportResult { pub(crate) fn new( imported_count: usize, total_count: usize, - keys: BTreeMap>>, + keys: BTreeMap>>, ) -> Self { Self { imported_count, total_count, keys } } @@ -367,7 +367,7 @@ pub enum RoomEventDecryptionResult { /// let user_id = user_id!("@alice:localhost"); /// let device_id = "DEVICEID".into(); /// -/// let machine = OlmMachine::new(user_id, device_id).await; +/// let machine = OlmMachine::new(user_id, &device_id).await; /// # Ok(()) /// # } /// ``` @@ -386,7 +386,7 @@ pub enum RoomEventDecryptionResult { /// /// let store = SqliteCryptoStore::open("/home/example/matrix-client/", None).await?; /// -/// let machine = OlmMachine::with_store(user_id, device_id, store).await; +/// let machine = OlmMachine::with_store(user_id, &device_id, store).await; /// # Ok(()) /// # } /// ``` @@ -773,12 +773,11 @@ pub enum RoomEventDecryptionResult { /// /// ```no_run /// # use anyhow::Result; -/// # use std::ops::Deref; /// # use matrix_sdk_crypto::{ /// # DecryptionSettings, EncryptionSyncChanges, OlmMachine, TrustRequirement /// # }; /// # use ruma::api::client::sync::sync_events::v3::{Response, State, JoinedRoom}; -/// # use ruma::{OwnedUserId, serde::Raw, events::AnySyncStateEvent}; +/// # use ruma::{UserId, serde::Raw, events::AnySyncStateEvent}; /// # #[tokio::main] /// # async fn main() -> Result<()> { /// # struct Client { @@ -794,7 +793,7 @@ pub enum RoomEventDecryptionResult { /// # fn is_member_event_of_a_joined_user(event: &Raw) -> bool { /// # true /// # } -/// # fn get_user_id(event: &Raw) -> OwnedUserId { +/// # fn get_user_id(event: &Raw) -> UserId { /// # unimplemented!(); /// # } /// # fn is_room_encrypted(room: &JoinedRoom) -> bool { @@ -846,7 +845,7 @@ pub enum RoomEventDecryptionResult { /// // Mark all the users that we consider to be in a end-to-end encrypted room with us to be /// // tracked. We need to know about all the devices each user has so we can later encrypt /// // messages for each of their devices. -/// client.olm_machine.update_tracked_users(users.iter().map(Deref::deref)).await?; +/// client.olm_machine.update_tracked_users(users.iter()).await?; /// /// // Process the rest of the sync response here. /// @@ -885,7 +884,6 @@ pub enum RoomEventDecryptionResult { /// /// ```no_run /// # use std::collections::{BTreeMap, HashSet}; -/// # use std::ops::Deref; /// # use anyhow::Result; /// # use ruma::UserId; /// # use ruma::api::client::keys::claim_keys::v3::{Response, Request}; @@ -896,11 +894,11 @@ pub enum RoomEventDecryptionResult { /// # } /// # #[tokio::main] /// # async fn main() -> Result<()> { -/// # let users: HashSet<&UserId> = HashSet::new(); +/// # let users: HashSet = HashSet::new(); /// # let machine: OlmMachine = unimplemented!(); /// // Mark all the users that are part of an encrypted room as tracked /// if let Some((request_id, request)) = -/// machine.get_missing_sessions(users.iter().map(Deref::deref)).await? +/// machine.get_missing_sessions(users.iter()).await? /// { /// let response = send_request(&request).await?; /// machine.mark_request_as_sent(&request_id, &response).await?; @@ -931,7 +929,6 @@ pub enum RoomEventDecryptionResult { /// /// ```no_run /// # use std::collections::{BTreeMap, HashSet}; -/// # use std::ops::Deref; /// # use anyhow::Result; /// # use ruma::UserId; /// # use ruma::api::client::keys::claim_keys::v3::{Response, Request}; @@ -942,14 +939,14 @@ pub enum RoomEventDecryptionResult { /// # } /// # #[tokio::main] /// # async fn main() -> Result<()> { -/// # let users: HashSet<&UserId> = HashSet::new(); +/// # let users: HashSet = HashSet::new(); /// # let room_id = unimplemented!(); /// # let settings = EncryptionSettings::default(); /// # let machine: OlmMachine = unimplemented!(); /// // Let's share a room key with our group. /// let requests = machine.share_room_key( /// room_id, -/// users.iter().map(Deref::deref), +/// users.iter(), /// EncryptionSettings::default(), /// ).await?; /// @@ -996,7 +993,6 @@ pub enum RoomEventDecryptionResult { /// /// ```no_run /// # use std::collections::{BTreeMap, HashSet}; -/// # use std::ops::Deref; /// # use anyhow::Result; /// # use serde_json::json; /// # use ruma::{UserId, RoomId, serde::Raw}; @@ -1014,7 +1010,7 @@ pub enum RoomEventDecryptionResult { /// # async fn acquire_per_room_lock(room_id: &RoomId) -> MutexGuard<()> { /// # unimplemented!(); /// # } -/// # async fn get_joined_members(room_id: &RoomId) -> Vec<&UserId> { +/// # async fn get_joined_members(room_id: &RoomId) -> Vec { /// # unimplemented!(); /// # } /// # fn is_room_encrypted(room_id: &RoomId) -> bool { @@ -1022,16 +1018,16 @@ pub enum RoomEventDecryptionResult { /// # } /// # #[tokio::main] /// # async fn main() -> Result<()> { -/// # let users: HashSet<&UserId> = HashSet::new(); +/// # let users: HashSet = HashSet::new(); /// # let machine: OlmMachine = unimplemented!(); /// struct Client { /// session_establishment_lock: tokio::sync::Mutex<()>, /// olm_machine: OlmMachine, /// } /// -/// async fn establish_sessions(client: &Client, users: &[&UserId]) -> Result<()> { +/// async fn establish_sessions(client: &Client, users: &[UserId]) -> Result<()> { /// if let Some((request_id, request)) = -/// client.olm_machine.get_missing_sessions(users.iter().map(Deref::deref)).await? +/// client.olm_machine.get_missing_sessions(users.iter()).await? /// { /// let response = send_request(&request).await?; /// client.olm_machine.mark_request_as_sent(&request_id, &response).await?; @@ -1040,12 +1036,12 @@ pub enum RoomEventDecryptionResult { /// Ok(()) /// } /// -/// async fn share_room_key(machine: &OlmMachine, room_id: &RoomId, users: &[&UserId]) -> Result<()> { +/// async fn share_room_key(machine: &OlmMachine, room_id: &RoomId, users: &[UserId]) -> Result<()> { /// let _lock = acquire_per_room_lock(room_id).await; /// /// let requests = machine.share_room_key( /// room_id, -/// users.iter().map(Deref::deref), +/// users.iter(), /// EncryptionSettings::default(), /// ).await?; /// diff --git a/crates/matrix-sdk-crypto/src/machine/mod.rs b/crates/matrix-sdk-crypto/src/machine/mod.rs index 4acab22e670..9f1d78da27b 100644 --- a/crates/matrix-sdk-crypto/src/machine/mod.rs +++ b/crates/matrix-sdk-crypto/src/machine/mod.rs @@ -37,8 +37,8 @@ use matrix_sdk_common::{ #[cfg(feature = "experimental-encrypted-state-events")] use ruma::events::{AnyStateEventContent, StateEventContent}; use ruma::{ - DeviceId, DeviceKeyAlgorithm, MilliSecondsSinceUnixEpoch, OneTimeKeyAlgorithm, OwnedDeviceId, - OwnedDeviceKeyId, OwnedTransactionId, OwnedUserId, RoomId, TransactionId, UInt, UserId, + DeviceId, DeviceKeyAlgorithm, DeviceKeyId, MilliSecondsSinceUnixEpoch, OneTimeKeyAlgorithm, + RoomId, TransactionId, UInt, UserId, api::client::{ dehydrated_device::DehydratedDeviceData, keys::{ @@ -134,9 +134,9 @@ pub struct OlmMachine { pub struct OlmMachineInner { /// The unique user id that owns this account. - user_id: OwnedUserId, + user_id: UserId, /// The unique device ID of the device that holds this account. - device_id: OwnedDeviceId, + device_id: DeviceId, /// The private part of our cross signing identity. /// Used to sign devices and other users, might be missing if some other /// device bootstrapped cross signing or cross signing isn't bootstrapped at @@ -477,7 +477,7 @@ impl OlmMachine { /// /// See [`update_tracked_users`](#method.update_tracked_users) for more /// information. - pub async fn tracked_users(&self) -> StoreResult> { + pub async fn tracked_users(&self) -> StoreResult> { let cache = self.store().cache().await?; Ok(self.inner.identity_manager.key_query_manager.synced(&cache).await?.tracked_users()) } @@ -584,7 +584,7 @@ impl OlmMachine { pub fn query_keys_for_users<'a>( &self, users: impl IntoIterator, - ) -> (OwnedTransactionId, KeysQueryRequest) { + ) -> (TransactionId, KeysQueryRequest) { self.inner.identity_manager.build_key_query_for_users(users) } @@ -737,7 +737,7 @@ impl OlmMachine { /// need to be uploaded. Otherwise, returns `None`. pub async fn upload_device_keys( &self, - ) -> StoreResult> { + ) -> StoreResult> { let cache = self.store().cache().await?; let account = cache.account().await?; @@ -792,7 +792,7 @@ impl OlmMachine { pub async fn get_missing_sessions( &self, users: impl Iterator, - ) -> StoreResult> { + ) -> StoreResult> { self.inner.session_manager.get_missing_sessions(users).await } @@ -1790,7 +1790,7 @@ impl OlmMachine { .identity_manager .receive_device_changes( transaction.cache(), - sync_changes.changed_devices.changed.iter().map(|u| u.as_ref()), + sync_changes.changed_devices.changed.iter(), ) .await { @@ -1864,7 +1864,7 @@ impl OlmMachine { &self, session: &InboundGroupSession, sender: &UserId, - ) -> MegolmResult<(VerificationState, Option)> { + ) -> MegolmResult<(VerificationState, Option)> { let sender_data = self.get_or_update_sender_data(session, sender).await?; // If the user ID in the sender data doesn't match that in the event envelope, @@ -2778,7 +2778,7 @@ impl OlmMachine { async fn sign_with_master_key( &self, message: &str, - ) -> Result<(OwnedDeviceKeyId, Ed25519Signature), SignatureError> { + ) -> Result<(DeviceKeyId, Ed25519Signature), SignatureError> { let identity = &*self.inner.user_identity.lock().await; let key_id = identity.master_key_id().await.ok_or(SignatureError::MissingSigningKey)?; @@ -3064,7 +3064,7 @@ impl OlmMachine { fn sender_data_to_verification_state( sender_data: SenderData, session_has_been_imported: bool, -) -> (VerificationState, Option) { +) -> (VerificationState, Option) { match sender_data { SenderData::UnknownDevice { owner_check_failed: false, .. } => { let device_link_problem = if session_has_been_imported { diff --git a/crates/matrix-sdk-crypto/src/machine/test_helpers.rs b/crates/matrix-sdk-crypto/src/machine/test_helpers.rs index a159437da4c..fa6aeb9c9aa 100644 --- a/crates/matrix-sdk-crypto/src/machine/test_helpers.rs +++ b/crates/matrix-sdk-crypto/src/machine/test_helpers.rs @@ -21,7 +21,7 @@ use as_variant::as_variant; use matrix_sdk_common::deserialized_responses::ProcessedToDeviceEvent; use matrix_sdk_test::{ruma_response_from_json, test_json}; use ruma::{ - DeviceId, OwnedOneTimeKeyId, TransactionId, UserId, + DeviceId, OneTimeKeyId, TransactionId, UserId, api::client::keys::{ claim_keys, get_keys::{self, v3::Response as KeysQueryResponse}, @@ -52,7 +52,7 @@ use crate::{ }; /// These keys need to be periodically uploaded to the server. -type OneTimeKeys = BTreeMap>; +type OneTimeKeys = BTreeMap>; fn alice_device_id() -> &'static DeviceId { device_id!("JLAFKJWSCS") @@ -289,7 +289,7 @@ pub async fn build_session_for_pair( alice: OlmMachine, bob: OlmMachine, mut one_time_keys: BTreeMap< - ruma::OwnedKeyId, + ruma::KeyId, Raw, >, ) -> (OlmMachine, OlmMachine) { @@ -356,7 +356,7 @@ pub async fn create_session( machine: &OlmMachine, user_id: &UserId, device_id: &DeviceId, - key_id: OwnedOneTimeKeyId, + key_id: OneTimeKeyId, one_time_key: Raw, ) { let one_time_keys = BTreeMap::from([( diff --git a/crates/matrix-sdk-crypto/src/machine/tests/mod.rs b/crates/matrix-sdk-crypto/src/machine/tests/mod.rs index 096dcdc9334..ead50116832 100644 --- a/crates/matrix-sdk-crypto/src/machine/tests/mod.rs +++ b/crates/matrix-sdk-crypto/src/machine/tests/mod.rs @@ -462,7 +462,7 @@ async fn test_session_encryption_info_can_be_fetched() { // Then the expected info is returned assert_eq!(encryption_info.sender, alice_id()); - assert_eq!(encryption_info.sender_device.as_deref(), Some(alice_device_id())); + assert_eq!(encryption_info.sender_device.as_ref(), Some(alice_device_id())); assert_matches!( &encryption_info.algorithm_info, AlgorithmInfo::MegolmV1AesSha2 { curve25519_key, .. } @@ -1496,7 +1496,7 @@ async fn test_room_key_with_fake_identity_keys() { #[async_test] async fn test_importing_private_cross_signing_keys_verifies_the_public_identity() { async fn create_additional_machine(machine: &OlmMachine) -> OlmMachine { - let second_machine = OlmMachine::new(machine.user_id(), "ADDITIONAL_MACHINE".into()).await; + let second_machine = OlmMachine::new(machine.user_id(), &"ADDITIONAL_MACHINE".into()).await; let identity = machine .get_identity(machine.user_id(), None) diff --git a/crates/matrix-sdk-crypto/src/olm/account.rs b/crates/matrix-sdk-crypto/src/olm/account.rs index 9088c869477..c0473ba19ff 100644 --- a/crates/matrix-sdk-crypto/src/olm/account.rs +++ b/crates/matrix-sdk-crypto/src/olm/account.rs @@ -29,8 +29,7 @@ use matrix_sdk_common::deserialized_responses::{ use ruma::api::client::dehydrated_device::DehydratedDeviceV1; use ruma::{ CanonicalJsonValue, DeviceId, DeviceKeyAlgorithm, DeviceKeyId, MilliSecondsSinceUnixEpoch, - OneTimeKeyAlgorithm, OneTimeKeyId, OwnedDeviceId, OwnedDeviceKeyId, OwnedOneTimeKeyId, - OwnedUserId, RoomId, SecondsSinceUnixEpoch, UInt, UserId, + OneTimeKeyAlgorithm, OneTimeKeyId, RoomId, SecondsSinceUnixEpoch, UInt, UserId, api::client::{ dehydrated_device::{DehydratedDeviceData, DehydratedDeviceV2}, keys::{ @@ -167,9 +166,9 @@ impl OlmMessageHash { #[cfg_attr(not(tarpaulin_include), derive(Debug))] pub struct StaticAccountData { /// The user_id this account belongs to. - pub user_id: OwnedUserId, + pub user_id: UserId, /// The device_id of this entry. - pub device_id: OwnedDeviceId, + pub device_id: DeviceId, /// The associated identity keys. pub identity_keys: Arc, /// Whether the account is for a dehydrated device. @@ -259,7 +258,7 @@ impl StaticAccountData { } /// Get the key ID of our Ed25519 signing key. - pub fn signing_key_id(&self) -> OwnedDeviceKeyId { + pub fn signing_key_id(&self) -> DeviceKeyId { DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, self.device_id()) } @@ -379,9 +378,9 @@ impl Deref for Account { #[allow(missing_debug_implementations)] pub struct PickledAccount { /// The user id of the account owner. - pub user_id: OwnedUserId, + pub user_id: UserId, /// The device ID of the account owner. - pub device_id: OwnedDeviceId, + pub device_id: DeviceId, /// The pickled version of the Olm account. pub pickle: AccountPickle, /// Was the account shared. @@ -414,7 +413,7 @@ impl fmt::Debug for Account { } } -pub type OneTimeKeys = BTreeMap>; +pub type OneTimeKeys = BTreeMap>; pub type FallbackKeys = OneTimeKeys; impl Account { @@ -464,7 +463,7 @@ impl Account { /// encoded as base64 will be used for the device ID. pub fn new(user_id: &UserId) -> Self { let account = InnerAccount::new(); - let device_id: OwnedDeviceId = + let device_id: DeviceId = base64_encode(account.identity_keys().curve25519.as_bytes()).into(); Self::new_helper(account, user_id, &device_id) @@ -473,7 +472,7 @@ impl Account { /// Create a new random Olm Account for a dehydrated device pub fn new_dehydrated(user_id: &UserId) -> Self { let account = InnerAccount::new(); - let device_id: OwnedDeviceId = + let device_id: DeviceId = base64_encode(account.identity_keys().curve25519.as_bytes()).into(); let mut ret = Self::new_helper(account, user_id, &device_id); @@ -911,7 +910,7 @@ impl Account { keys_map.insert( OneTimeKeyId::from_parts( OneTimeKeyAlgorithm::SignedCurve25519, - key_id.to_base64().as_str().into(), + &key_id.to_base64().into(), ), signed_key.into_raw(), ); @@ -1909,7 +1908,6 @@ fn satisfies_sender_trust_requirement( mod tests { use std::{ collections::{BTreeMap, BTreeSet}, - ops::Deref, time::Duration, }; @@ -1946,10 +1944,9 @@ mod tests { let (_, second_one_time_keys, _) = account.keys_for_upload(); assert!(!second_one_time_keys.is_empty()); - let one_time_key_ids: BTreeSet<&OneTimeKeyId> = - one_time_keys.keys().map(Deref::deref).collect(); + let one_time_key_ids: BTreeSet<&OneTimeKeyId> = one_time_keys.keys().collect(); let second_one_time_key_ids: BTreeSet<&OneTimeKeyId> = - second_one_time_keys.keys().map(Deref::deref).collect(); + second_one_time_keys.keys().collect(); assert_eq!(one_time_key_ids, second_one_time_key_ids); @@ -1967,7 +1964,7 @@ mod tests { assert!(!fourth_one_time_keys.is_empty()); let fourth_one_time_key_ids: BTreeSet<&OneTimeKeyId> = - fourth_one_time_keys.keys().map(Deref::deref).collect(); + fourth_one_time_keys.keys().collect(); assert_ne!(one_time_key_ids, fourth_one_time_key_ids); Ok(()) diff --git a/crates/matrix-sdk-crypto/src/olm/group_sessions/forwarder_data.rs b/crates/matrix-sdk-crypto/src/olm/group_sessions/forwarder_data.rs index d66fe609c6b..4cb45f57342 100644 --- a/crates/matrix-sdk-crypto/src/olm/group_sessions/forwarder_data.rs +++ b/crates/matrix-sdk-crypto/src/olm/group_sessions/forwarder_data.rs @@ -64,9 +64,7 @@ impl ForwarderData { pub fn user_id(&self) -> &UserId { match &self { ForwarderData::SenderUnverified(known_sender_data) - | ForwarderData::SenderVerified(known_sender_data) => { - known_sender_data.user_id.as_ref() - } + | ForwarderData::SenderVerified(known_sender_data) => &known_sender_data.user_id, } } @@ -75,7 +73,7 @@ impl ForwarderData { match &self { ForwarderData::SenderUnverified(known_sender_data) | ForwarderData::SenderVerified(known_sender_data) => { - known_sender_data.device_id.as_deref() + known_sender_data.device_id.as_ref() } } } diff --git a/crates/matrix-sdk-crypto/src/olm/group_sessions/inbound.rs b/crates/matrix-sdk-crypto/src/olm/group_sessions/inbound.rs index f529b869d4a..ba9bccd8774 100644 --- a/crates/matrix-sdk-crypto/src/olm/group_sessions/inbound.rs +++ b/crates/matrix-sdk-crypto/src/olm/group_sessions/inbound.rs @@ -23,7 +23,7 @@ use std::{ }; use ruma::{ - DeviceKeyAlgorithm, OwnedRoomId, RoomId, events::room::history_visibility::HistoryVisibility, + DeviceKeyAlgorithm, RoomId, events::room::history_visibility::HistoryVisibility, serde::JsonObject, }; use serde::{Deserialize, Serialize}; @@ -196,7 +196,7 @@ pub struct InboundGroupSession { pub forwarder_data: Option, /// The Room this GroupSession belongs to - pub room_id: OwnedRoomId, + pub room_id: RoomId, /// A flag recording whether the `InboundGroupSession` was received directly /// as a `m.room_key` event or indirectly via a forward or file import. @@ -637,7 +637,7 @@ impl InboundGroupSession { // Check that we have a room id and that the event wasn't forwarded from // another room. - if room_id.as_deref() != Some(self.room_id()) { + if room_id.as_ref() != Some(self.room_id()) { return Err(EventError::MismatchedRoom(self.room_id().to_owned(), room_id).into()); } @@ -714,7 +714,7 @@ pub struct PickledInboundGroupSession { #[serde(default)] pub forwarder_data: Option, /// The id of the room that the session is used in. - pub room_id: OwnedRoomId, + pub room_id: RoomId, /// Flag remembering if the session was directly sent to us by the sender /// or if it was imported. pub imported: bool, diff --git a/crates/matrix-sdk-crypto/src/olm/group_sessions/mod.rs b/crates/matrix-sdk-crypto/src/olm/group_sessions/mod.rs index a1dec499de2..a8d08bff961 100644 --- a/crates/matrix-sdk-crypto/src/olm/group_sessions/mod.rs +++ b/crates/matrix-sdk-crypto/src/olm/group_sessions/mod.rs @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use ruma::{DeviceKeyAlgorithm, OwnedRoomId}; +use ruma::{DeviceKeyAlgorithm, RoomId}; use serde::{Deserialize, Serialize}; mod forwarder_data; @@ -79,7 +79,7 @@ pub struct ExportedRoomKey { pub algorithm: EventEncryptionAlgorithm, /// The room where the session is used. - pub room_id: OwnedRoomId, + pub room_id: RoomId, /// The Curve25519 key of the device which initiated the session originally. #[serde(deserialize_with = "deserialize_curve_key", serialize_with = "serialize_curve_key")] @@ -118,7 +118,7 @@ impl ExportedRoomKey { /// /// This can be used when importing the keys from a backup into the store. pub fn from_backed_up_room_key( - room_id: OwnedRoomId, + room_id: RoomId, session_id: String, room_key: BackedUpRoomKey, ) -> Self { @@ -145,7 +145,7 @@ impl ExportedRoomKey { } impl RoomKeyExport for &ExportedRoomKey { - fn room_id(&self) -> &ruma::RoomId { + fn room_id(&self) -> &RoomId { &self.room_id } diff --git a/crates/matrix-sdk-crypto/src/olm/group_sessions/outbound.rs b/crates/matrix-sdk-crypto/src/olm/group_sessions/outbound.rs index a6b04d22c40..c8d35f2934f 100644 --- a/crates/matrix-sdk-crypto/src/olm/group_sessions/outbound.rs +++ b/crates/matrix-sdk-crypto/src/olm/group_sessions/outbound.rs @@ -28,8 +28,7 @@ use matrix_sdk_common::{deserialized_responses::WithheldCode, locks::RwLock as S #[cfg(feature = "experimental-encrypted-state-events")] use ruma::events::AnyStateEventContent; use ruma::{ - DeviceId, OwnedDeviceId, OwnedRoomId, OwnedTransactionId, OwnedUserId, RoomId, - SecondsSinceUnixEpoch, TransactionId, UserId, + DeviceId, RoomId, SecondsSinceUnixEpoch, TransactionId, UserId, events::{ AnyMessageLikeEventContent, room::{encryption::RoomEncryptionEventContent, history_visibility::HistoryVisibility}, @@ -172,10 +171,10 @@ pub struct OutboundGroupSessionEncryptionResult { #[derive(Clone)] pub struct OutboundGroupSession { inner: Arc>, - device_id: OwnedDeviceId, + device_id: DeviceId, account_identity_keys: Arc, session_id: Arc, - room_id: OwnedRoomId, + room_id: RoomId, pub(crate) creation_time: SecondsSinceUnixEpoch, message_count: Arc, shared: Arc, @@ -189,9 +188,9 @@ pub struct OutboundGroupSession { /// /// Holds the `ShareInfo` for all the user/device pairs that will receive the /// room key. -pub type ShareInfoSet = BTreeMap>; +pub type ShareInfoSet = BTreeMap>; -type ToShareMap = BTreeMap, ShareInfoSet)>; +type ToShareMap = BTreeMap, ShareInfoSet)>; /// Struct holding info about the share state of a outbound group session. #[derive(Clone, Debug, Serialize, Deserialize)] @@ -282,8 +281,7 @@ impl SharingView<'_> { ) -> impl Iterator + use<'a, 'b, 'c> { set.range::(user_ids).flat_map(move |(uid, d)| { - d.range::(device_ids) - .map(|(id, info)| (uid.as_ref(), id.as_ref(), info)) + d.range::(device_ids).map(move |(id, info)| (uid, id, info)) }) } @@ -341,7 +339,7 @@ impl OutboundGroupSession { /// * `settings` - Settings determining the algorithm and rotation period of /// the outbound group session. pub fn new( - device_id: OwnedDeviceId, + device_id: DeviceId, identity_keys: Arc, room_id: &RoomId, settings: EncryptionSettings, @@ -378,7 +376,7 @@ impl OutboundGroupSession { /// of crypto-store implementations. **Do not use this outside of tests**. pub fn add_request( &self, - request_id: OwnedTransactionId, + request_id: TransactionId, request: Arc, share_infos: ShareInfoSet, ) { @@ -415,15 +413,13 @@ impl OutboundGroupSession { pub fn mark_request_as_sent( &self, request_id: &TransactionId, - ) -> BTreeMap> { + ) -> BTreeMap> { let mut no_olm_devices = BTreeMap::new(); let removed = self.to_share_with_set.write().remove(request_id); if let Some((to_device, request)) = removed { - let recipients: BTreeMap<&UserId, BTreeSet<&DeviceId>> = request - .iter() - .map(|(u, d)| (u.as_ref(), d.keys().map(|d| d.as_ref()).collect())) - .collect(); + let recipients: BTreeMap<&UserId, BTreeSet<&DeviceId>> = + request.iter().map(|(u, d)| (u, d.keys().collect())).collect(); info!( ?request_id, @@ -433,7 +429,7 @@ impl OutboundGroupSession { ); for (user_id, info) in request { - let no_olms: BTreeSet = info + let no_olms: BTreeSet = info .iter() .filter(|(_, info)| matches!(info, ShareInfo::Withheld(WithheldCode::NoOlm))) .map(|(d, _)| d.to_owned()) @@ -765,7 +761,7 @@ impl OutboundGroupSession { } /// Get the list of request ids this session is waiting for to be sent out. - pub(crate) fn pending_request_ids(&self) -> Vec { + pub(crate) fn pending_request_ids(&self) -> Vec { self.to_share_with_set.read().keys().cloned().collect() } @@ -787,7 +783,7 @@ impl OutboundGroupSession { /// * `pickle_mode` - The mode that was used to pickle the session, either /// an unencrypted mode or an encrypted using passphrase. pub fn from_pickle( - device_id: OwnedDeviceId, + device_id: DeviceId, identity_keys: Arc, pickle: PickledOutboundGroupSession, ) -> Result { @@ -858,7 +854,7 @@ pub struct PickledOutboundGroupSession { /// The settings this session adheres to. pub settings: Arc, /// The room id this session is used for. - pub room_id: OwnedRoomId, + pub room_id: RoomId, /// The timestamp when this session was created. pub creation_time: SecondsSinceUnixEpoch, /// The number of messages this session has already encrypted. @@ -868,9 +864,9 @@ pub struct PickledOutboundGroupSession { /// Has the session been invalidated. pub invalidated: bool, /// The set of users the session has been already shared with. - pub shared_with_set: BTreeMap>, + pub shared_with_set: BTreeMap>, /// Requests that need to be sent out to share the session. - pub requests: BTreeMap, ShareInfoSet)>, + pub requests: BTreeMap, ShareInfoSet)>, } #[cfg(test)] diff --git a/crates/matrix-sdk-crypto/src/olm/group_sessions/sender_data.rs b/crates/matrix-sdk-crypto/src/olm/group_sessions/sender_data.rs index d34b39209f5..406ccbc1540 100644 --- a/crates/matrix-sdk-crypto/src/olm/group_sessions/sender_data.rs +++ b/crates/matrix-sdk-crypto/src/olm/group_sessions/sender_data.rs @@ -14,7 +14,7 @@ use std::{cmp::Ordering, fmt}; -use ruma::{DeviceId, OwnedDeviceId, OwnedUserId, UserId}; +use ruma::{DeviceId, UserId}; use serde::{Deserialize, Deserializer, Serialize, de, de::Visitor}; use tracing::error; use vodozemac::Ed25519PublicKey; @@ -29,12 +29,12 @@ use crate::{ #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] pub struct KnownSenderData { /// The user ID of the user who established this session. - pub user_id: OwnedUserId, + pub user_id: UserId, /// The device ID of the device that send the session. /// This is an `Option` for backwards compatibility, but we should always /// populate it on creation. - pub device_id: Option, + pub device_id: Option, /// The cross-signing key of the user who established this session. #[serde( @@ -332,7 +332,7 @@ impl SenderData { /// /// For `SenderData::UnknownDevice`, we don't record any information about /// the owner of the sender, so returns `None`. - pub(crate) fn user_id(&self) -> Option { + pub(crate) fn user_id(&self) -> Option { match &self { SenderData::UnknownDevice { .. } => None, SenderData::DeviceInfo { device_keys, .. } => Some(device_keys.user_id.clone()), @@ -384,8 +384,8 @@ enum SenderDataReader { // If we read this older variant, it gets changed to SenderUnverified or // SenderVerified, depending on the master_key_verified flag. SenderKnown { - user_id: OwnedUserId, - device_id: Option, + user_id: UserId, + device_id: Option, master_key: Box, master_key_verified: bool, }, diff --git a/crates/matrix-sdk-crypto/src/olm/group_sessions/sender_data_finder.rs b/crates/matrix-sdk-crypto/src/olm/group_sessions/sender_data_finder.rs index c60b766718d..dd203539956 100644 --- a/crates/matrix-sdk-crypto/src/olm/group_sessions/sender_data_finder.rs +++ b/crates/matrix-sdk-crypto/src/olm/group_sessions/sender_data_finder.rs @@ -330,7 +330,7 @@ mod tests { use assert_matches2::assert_let; use matrix_sdk_test::async_test; - use ruma::{DeviceId, OwnedUserId, RoomId, UserId, device_id, room_id, user_id}; + use ruma::{DeviceId, RoomId, UserId, device_id, room_id, user_id}; use tokio::sync::Mutex; use vodozemac::{Curve25519PublicKey, Ed25519PublicKey, megolm::SessionKey}; @@ -897,7 +897,7 @@ mod tests { } struct TestUser { - user_id: OwnedUserId, + user_id: UserId, account: Account, private_identity: Arc>, user_identity: UserIdentityData, diff --git a/crates/matrix-sdk-crypto/src/olm/signing/mod.rs b/crates/matrix-sdk-crypto/src/olm/signing/mod.rs index 7a86b518a7f..196a4ff9c57 100644 --- a/crates/matrix-sdk-crypto/src/olm/signing/mod.rs +++ b/crates/matrix-sdk-crypto/src/olm/signing/mod.rs @@ -21,7 +21,7 @@ use std::sync::{ pub use pk_signing::{MasterSigning, PickledSignings, SelfSigning, SigningError, UserSigning}; use ruma::{ - DeviceKeyAlgorithm, DeviceKeyId, OwnedDeviceId, OwnedDeviceKeyId, OwnedUserId, UserId, + DeviceId, DeviceKeyAlgorithm, DeviceKeyId, UserId, api::client::keys::upload_signatures::v3::{Request as SignatureUploadRequest, SignedKeys}, events::secret::request::SecretName, }; @@ -51,7 +51,7 @@ use crate::{ /// It can be used to sign devices or other identities. #[derive(Clone, Debug)] pub struct PrivateCrossSigningIdentity { - user_id: OwnedUserId, + user_id: UserId, shared: Arc, pub(crate) master_key: Arc>>, pub(crate) user_signing_key: Arc>>, @@ -89,7 +89,7 @@ impl DiffResult { #[allow(missing_debug_implementations)] pub struct PickledCrossSigningIdentity { /// The user id of the identity owner. - pub user_id: OwnedUserId, + pub user_id: UserId, /// Have the public keys of the identity been shared. pub shared: bool, /// The pickled signing keys @@ -141,9 +141,9 @@ impl PrivateCrossSigningIdentity { } /// Get the key ID of the master key. - pub async fn master_key_id(&self) -> Option { + pub async fn master_key_id(&self) -> Option { let master_key = self.master_public_key().await?.get_first_key()?.to_base64(); - let master_key = OwnedDeviceId::from(master_key); + let master_key = DeviceId::from(master_key); Some(DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, &master_key)) } @@ -543,7 +543,7 @@ impl PrivateCrossSigningIdentity { /// created it. #[cfg(any(test, feature = "testing"))] #[allow(dead_code)] - pub fn new(user_id: OwnedUserId) -> Self { + pub fn new(user_id: UserId) -> Self { let master = MasterSigning::new(user_id.to_owned()); Self::new_helper(&user_id, master) } @@ -678,7 +678,7 @@ mod tests { fn test_signature_verification() { let signing = Signing::new(); let user_id = user_id(); - let key_id = DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, "DEVICEID".into()); + let key_id = DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, &"DEVICEID".into()); let json = json!({ "hello": "world" diff --git a/crates/matrix-sdk-crypto/src/olm/signing/pk_signing.rs b/crates/matrix-sdk-crypto/src/olm/signing/pk_signing.rs index 07d0880c52b..d899bb5dde7 100644 --- a/crates/matrix-sdk-crypto/src/olm/signing/pk_signing.rs +++ b/crates/matrix-sdk-crypto/src/olm/signing/pk_signing.rs @@ -13,7 +13,7 @@ // limitations under the License. use ruma::{ - CanonicalJsonValue, DeviceKeyAlgorithm, DeviceKeyId, OwnedUserId, + CanonicalJsonValue, DeviceKeyAlgorithm, DeviceKeyId, UserId, canonical_json::to_canonical_value, encryption::KeyUsage, }; use serde::{Deserialize, Serialize}; @@ -101,7 +101,7 @@ pub struct PickledSelfSigning { } impl MasterSigning { - pub fn new(user_id: OwnedUserId) -> Self { + pub fn new(user_id: UserId) -> Self { let inner = Signing::new(); let public_key = inner .cross_signing_key(user_id, KeyUsage::Master) @@ -165,7 +165,7 @@ impl MasterSigning { self.inner.to_base64() } - pub fn from_base64(user_id: OwnedUserId, key: &str) -> Result { + pub fn from_base64(user_id: UserId, key: &str) -> Result { let inner = Signing::from_base64(key)?; let public_key = inner .cross_signing_key(user_id, KeyUsage::Master) @@ -194,7 +194,7 @@ impl MasterSigning { self.public_key.user_id().to_owned(), DeviceKeyId::from_parts( DeviceKeyAlgorithm::Ed25519, - self.inner.public_key.to_base64().as_str().into(), + &self.inner.public_key.to_base64().into(), ), signature, ); @@ -216,7 +216,7 @@ impl UserSigning { self.inner.to_base64() } - pub fn from_base64(user_id: OwnedUserId, key: &str) -> Result { + pub fn from_base64(user_id: UserId, key: &str) -> Result { let inner = Signing::from_base64(key)?; let public_key = inner .cross_signing_key(user_id, KeyUsage::UserSigning) @@ -251,7 +251,7 @@ impl UserSigning { self.public_key.user_id().to_owned(), DeviceKeyId::from_parts( DeviceKeyAlgorithm::Ed25519, - self.inner.public_key.to_base64().as_str().into(), + &self.inner.public_key.to_base64().into(), ), signature, ); @@ -281,7 +281,7 @@ impl SelfSigning { self.inner.to_base64() } - pub fn from_base64(user_id: OwnedUserId, key: &str) -> Result { + pub fn from_base64(user_id: UserId, key: &str) -> Result { let inner = Signing::from_base64(key)?; let public_key = inner .cross_signing_key(user_id, KeyUsage::SelfSigning) @@ -299,7 +299,7 @@ impl SelfSigning { self.public_key.user_id().to_owned(), DeviceKeyId::from_parts( DeviceKeyAlgorithm::Ed25519, - self.inner.public_key.to_base64().as_str().into(), + &self.inner.public_key.to_base64().into(), ), signature, ); @@ -375,11 +375,11 @@ impl Signing { self.public_key } - pub fn cross_signing_key(&self, user_id: OwnedUserId, usage: KeyUsage) -> CrossSigningKey { + pub fn cross_signing_key(&self, user_id: UserId, usage: KeyUsage) -> CrossSigningKey { let keys = SigningKeys::from([( DeviceKeyId::from_parts( DeviceKeyAlgorithm::Ed25519, - self.public_key().to_base64().as_str().into(), + &self.public_key().to_base64().into(), ), self.inner.public_key().into(), )]); diff --git a/crates/matrix-sdk-crypto/src/session_manager/group_sessions/mod.rs b/crates/matrix-sdk-crypto/src/session_manager/group_sessions/mod.rs index b2837ec327b..ad8d4df421a 100644 --- a/crates/matrix-sdk-crypto/src/session_manager/group_sessions/mod.rs +++ b/crates/matrix-sdk-crypto/src/session_manager/group_sessions/mod.rs @@ -30,8 +30,7 @@ use matrix_sdk_common::{ #[cfg(feature = "experimental-encrypted-state-events")] use ruma::events::AnyStateEventContent; use ruma::{ - DeviceId, OwnedDeviceId, OwnedRoomId, OwnedTransactionId, OwnedUserId, RoomId, TransactionId, - UserId, + DeviceId, RoomId, TransactionId, UserId, events::{AnyMessageLikeEventContent, AnyToDeviceEventContent, ToDeviceEventType}, serde::Raw, to_device::DeviceIdOrAllDevices, @@ -68,10 +67,10 @@ use crate::{ #[derive(Clone, Debug)] pub(crate) struct GroupSessionCache { store: Store, - sessions: Arc>>, + sessions: Arc>>, /// A map from the request id to the group session that the request belongs /// to. Used to mark requests belonging to the session as shared. - sessions_being_shared: Arc>>, + sessions_being_shared: Arc>>, } impl GroupSessionCache { @@ -136,7 +135,7 @@ impl GroupSessionCache { self.sessions_being_shared.write().remove(id) } - fn mark_as_being_shared(&self, id: OwnedTransactionId, session: OutboundGroupSession) { + fn mark_as_being_shared(&self, id: TransactionId, session: OutboundGroupSession) { self.sessions_being_shared.write().insert(id, session); } } @@ -326,10 +325,7 @@ impl GroupSessionManager { store: Arc, group_session: OutboundGroupSession, devices: Vec, - ) -> OlmResult<( - EncryptForDevicesResult, - BTreeMap>, - )> { + ) -> OlmResult<(EncryptForDevicesResult, BTreeMap>)> { // Use a named type instead of a tuple with rather long type name pub struct DeviceResult { device: DeviceData, @@ -1005,7 +1001,7 @@ struct EncryptForDevicesResult { #[derive(Debug, Default)] struct EncryptForDevicesResultBuilder { /// The payloads of the to-device messages - messages: BTreeMap>>, + messages: BTreeMap>>, /// The devices which lack an Olm session and therefore need a withheld code no_olm_devices: Vec<(DeviceData, WithheldCode)>, @@ -1083,7 +1079,6 @@ mod tests { use std::{ collections::{BTreeMap, BTreeSet}, iter, - ops::Deref, sync::Arc, }; @@ -1091,7 +1086,7 @@ mod tests { use matrix_sdk_common::deserialized_responses::{ProcessedToDeviceEvent, WithheldCode}; use matrix_sdk_test::{async_test, ruma_response_from_json}; use ruma::{ - DeviceId, OneTimeKeyAlgorithm, OwnedMxcUri, TransactionId, UInt, UserId, + DeviceId, MxcUri, OneTimeKeyAlgorithm, TransactionId, UInt, UserId, api::client::{ keys::{claim_keys, get_keys, upload_keys}, to_device::send_event_to_device::v3::Response as ToDeviceResponse, @@ -1237,7 +1232,7 @@ mod tests { let room_id = room_id!("!test:localhost"); let keys_claim = keys_claim_response(); - let users = keys_claim.one_time_keys.keys().map(Deref::deref); + let users = keys_claim.one_time_keys.keys(); let requests = machine.share_room_key(room_id, users, EncryptionSettings::default()).await.unwrap(); @@ -1264,7 +1259,7 @@ mod tests { let room_id = room_id!("!test:localhost"); let keys_claim = keys_claim_response(); - let users = keys_claim.one_time_keys.keys().map(Deref::deref); + let users = keys_claim.one_time_keys.keys(); let requests = machine.share_room_key(room_id, users, EncryptionSettings::default()).await.unwrap(); @@ -1317,7 +1312,7 @@ mod tests { let machine = machine().await; let keys_claim = keys_claim_response(); - let users = keys_claim.one_time_keys.keys().map(Deref::deref); + let users = keys_claim.one_time_keys.keys(); let first_room_id = room_id!("!test:localhost"); @@ -1348,7 +1343,7 @@ mod tests { // The fact that an olm was sent should be remembered even if sharing another // session in an other room. let second_room_id = room_id!("!other:localhost"); - let users = keys_claim.one_time_keys.keys().map(Deref::deref); + let users = keys_claim.one_time_keys.keys(); let requests = machine .share_room_key(second_room_id, users, EncryptionSettings::default()) .await @@ -1369,7 +1364,7 @@ mod tests { let late_joiner = user_id!("@bob:localhost"); let keys_claim = keys_claim_response(); - let mut users: BTreeSet<_> = keys_claim.one_time_keys.keys().map(Deref::deref).collect(); + let mut users: BTreeSet<_> = keys_claim.one_time_keys.keys().collect(); users.insert(late_joiner); let requests = machine @@ -1395,7 +1390,7 @@ mod tests { let room_id = room_id!("!test:localhost"); let keys_claim = keys_claim_response(); - let users = keys_claim.one_time_keys.keys().map(Deref::deref); + let users = keys_claim.one_time_keys.keys(); let outbound = machine.inner.group_session_manager.get_outbound_group_session(room_id).unwrap(); @@ -1494,7 +1489,7 @@ mod tests { assert!(recipients[user_id].is_empty()); let device_id = "AFGUOBTZWM".into(); - let device = machine.get_device(user_id, device_id, None).await.unwrap().unwrap(); + let device = machine.get_device(user_id, &device_id, None).await.unwrap().unwrap(); device.set_local_trust(LocalTrust::Verified).await.unwrap(); let users = [user_id].into_iter(); @@ -1539,7 +1534,7 @@ mod tests { let room_id = room_id!("!test:localhost"); let keys_claim = keys_claim_response(); - let users = keys_claim.one_time_keys.keys().map(Deref::deref); + let users = keys_claim.one_time_keys.keys(); let settings = EncryptionSettings { sharing_strategy: CollectStrategy::OnlyTrustedDevices, ..Default::default() @@ -1548,10 +1543,10 @@ mod tests { // Trust only one let user_id = user_id!("@example:localhost"); let device_id = "MWFXPINOAO".into(); - let device = machine.get_device(user_id, device_id, None).await.unwrap().unwrap(); + let device = machine.get_device(user_id, &device_id, None).await.unwrap().unwrap(); device.set_local_trust(LocalTrust::Verified).await.unwrap(); machine - .get_device(user_id, "MWVTUXDNNM".into(), None) + .get_device(user_id, &"MWVTUXDNNM".into(), None) .await .unwrap() .unwrap() @@ -1640,7 +1635,7 @@ mod tests { let response = ToDeviceResponse::new(); - let device = machine.get_device(bob_id, "BOBDEVICE".into(), None).await.unwrap().unwrap(); + let device = machine.get_device(bob_id, &"BOBDEVICE".into(), None).await.unwrap().unwrap(); // The device should be marked as having the `m.no_olm` code received only after // the request has been marked as sent. @@ -1650,7 +1645,7 @@ mod tests { machine.mark_request_as_sent(&request.txn_id, &response).await.unwrap(); } - let device = machine.get_device(bob_id, "BOBDEVICE".into(), None).await.unwrap().unwrap(); + let device = machine.get_device(bob_id, &"BOBDEVICE".into(), None).await.unwrap().unwrap(); assert!(device.was_withheld_code_sent()); } @@ -1841,7 +1836,7 @@ mod tests { let content = RoomKeyBundleContent { room_id: owned_room_id!("!room:id"), file: (EncryptedFileInit { - url: OwnedMxcUri::from("test"), + url: MxcUri::from("test"), key: JsonWebKey::from(JsonWebKeyInit { kty: "oct".to_owned(), key_ops: vec!["encrypt".to_owned(), "decrypt".to_owned()], diff --git a/crates/matrix-sdk-crypto/src/session_manager/group_sessions/share_strategy.rs b/crates/matrix-sdk-crypto/src/session_manager/group_sessions/share_strategy.rs index ea7e0d6c3ea..3ca2681ad5b 100644 --- a/crates/matrix-sdk-crypto/src/session_manager/group_sessions/share_strategy.rs +++ b/crates/matrix-sdk-crypto/src/session_manager/group_sessions/share_strategy.rs @@ -19,7 +19,7 @@ use std::{ use itertools::{Either, Itertools}; use matrix_sdk_common::deserialized_responses::WithheldCode; -use ruma::{DeviceId, OwnedDeviceId, OwnedUserId, UserId}; +use ruma::{DeviceId, UserId}; use serde::{Deserialize, Serialize}; use tracing::{debug, instrument, trace}; @@ -137,7 +137,7 @@ pub(crate) struct CollectRecipientsResult { /// If true the outbound group session should be rotated pub should_rotate: bool, /// The map of user|device that should receive the session - pub devices: BTreeMap>, + pub devices: BTreeMap>, /// The map of user|device that won't receive the key with the withheld /// code. pub withheld_devices: Vec<(DeviceData, WithheldCode)>, @@ -209,7 +209,7 @@ pub(crate) async fn collect_recipients_for_share_strategy( trace!(?users, ?share_strategy, "Calculating group session recipients"); let mut result = CollectRecipientsResult::default(); - let mut verified_users_with_new_identities: Vec = Default::default(); + let mut verified_users_with_new_identities: Vec = Default::default(); // If we have an outbound session, check if a user is missing from the set of // users that should get the session but is in the set of users that @@ -243,7 +243,7 @@ pub(crate) async fn collect_recipients_for_share_strategy( } } CollectStrategy::ErrorOnVerifiedUserProblem => { - let mut unsigned_devices_of_verified_users: BTreeMap> = + let mut unsigned_devices_of_verified_users: BTreeMap> = Default::default(); for user_id in users { @@ -461,13 +461,12 @@ pub(crate) async fn split_devices_for_share_strategy( ) -> OlmResult<(Vec, Vec<(DeviceData, WithheldCode)>)> { let own_identity = store.get_user_identity(store.user_id()).await?.and_then(|i| i.into_own()); - let mut verified_users_with_new_identities: BTreeSet = Default::default(); + let mut verified_users_with_new_identities: BTreeSet = Default::default(); let mut allowed_devices: Vec = Default::default(); let mut blocked_devices: Vec<(DeviceData, WithheldCode)> = Default::default(); - let mut user_identities_cache: BTreeMap> = - Default::default(); + let mut user_identities_cache: BTreeMap> = Default::default(); let mut get_user_identity = async move |user_id| -> OlmResult<_> { match user_identities_cache.get(user_id) { Some(user_identity) => Ok(user_identity.clone()), @@ -503,7 +502,7 @@ pub(crate) async fn split_devices_for_share_strategy( // associated user has a verification violation. If so, we add the // device to `unsigned_devices_of_verified_users`, which will be // returned with the error. - let mut unsigned_devices_of_verified_users: BTreeMap> = + let mut unsigned_devices_of_verified_users: BTreeMap> = Default::default(); let mut add_device_to_unsigned_devices_map = |user_id: &UserId, device: &DeviceData| { let device_id = device.device_id().to_owned(); @@ -732,7 +731,7 @@ enum ErrorOnVerifiedUserProblemResult { /// We found devices that should cause the transmission to fail, due to /// being an unsigned device belonging to a verified user. Only /// populated when `error_on_verified_user_problem` is set. - UnsignedDevicesOfVerifiedUser(Vec), + UnsignedDevicesOfVerifiedUser(Vec), /// There were no unsigned devices of verified users. Devices(RecipientDevicesForUser), @@ -741,7 +740,7 @@ enum ErrorOnVerifiedUserProblemResult { /// Partition the list of a user's devices according to whether they should /// receive the key, for [`CollectStrategy::AllDevices`]. fn split_devices_for_user_for_all_devices_strategy( - user_devices: HashMap, + user_devices: HashMap, own_identity: &Option, device_owner_identity: &Option, ) -> RecipientDevicesForUser { @@ -818,7 +817,7 @@ fn should_withhold_to_dehydrated_device( /// the devices that should receive the room key, and those that should /// receive a withheld code. fn split_devices_for_user_for_error_on_verified_user_problem_strategy( - user_devices: HashMap, + user_devices: HashMap, own_identity: &Option, device_owner_identity: &Option, ) -> ErrorOnVerifiedUserProblemResult { @@ -826,7 +825,7 @@ fn split_devices_for_user_for_error_on_verified_user_problem_strategy( // We construct unsigned_devices_of_verified_users lazily, because chances are // we won't need it. - let mut unsigned_devices_of_verified_users: Option> = None; + let mut unsigned_devices_of_verified_users: Option> = None; for d in user_devices.into_values() { match handle_device_for_user_for_error_on_verified_user_problem_strategy( @@ -889,7 +888,7 @@ fn handle_device_for_user_for_error_on_verified_user_problem_strategy( } fn split_devices_for_user_for_identity_based_strategy( - user_devices: HashMap, + user_devices: HashMap, device_owner_identity: &Option, ) -> RecipientDevicesForUser { match device_owner_identity { @@ -946,7 +945,7 @@ fn withheld_code_for_device_with_owner_for_identity_based_strategy( /// Partition the list of a user's devices according to whether they should /// receive the key, for [`CollectStrategy::OnlyTrustedDevices`]. fn split_devices_for_user_for_only_trusted_devices( - user_devices: HashMap, + user_devices: HashMap, own_identity: &Option, device_owner_identity: &Option, ) -> RecipientDevicesForUser { @@ -3125,7 +3124,7 @@ mod tests { machine .inner .group_session_manager - .mark_request_as_sent(r.as_ref().txn_id.as_ref()) + .mark_request_as_sent(&r.as_ref().txn_id) .await .unwrap(); } diff --git a/crates/matrix-sdk-crypto/src/session_manager/sessions.rs b/crates/matrix-sdk-crypto/src/session_manager/sessions.rs index 2cd3b413fee..6dd20fa8e23 100644 --- a/crates/matrix-sdk-crypto/src/session_manager/sessions.rs +++ b/crates/matrix-sdk-crypto/src/session_manager/sessions.rs @@ -20,8 +20,8 @@ use std::{ use matrix_sdk_common::{failures_cache::FailuresCache, locks::RwLock as StdRwLock}; use ruma::{ - DeviceId, OneTimeKeyAlgorithm, OwnedDeviceId, OwnedOneTimeKeyId, OwnedServerName, - OwnedTransactionId, OwnedUserId, SecondsSinceUnixEpoch, ServerName, TransactionId, UserId, + DeviceId, OneTimeKeyAlgorithm, OneTimeKeyId, SecondsSinceUnixEpoch, ServerName, TransactionId, + UserId, api::client::keys::claim_keys::v3::{ Request as KeysClaimRequest, Response as KeysClaimResponse, }, @@ -55,24 +55,24 @@ pub(crate) struct SessionManager { /// According to the doc on [`crate::OlmMachine::get_missing_sessions`], /// there should only be one such request active at a time, so we only need /// to keep a record of the most recent. - current_key_claim_request: Arc>>, + current_key_claim_request: Arc>>, /// A map of user/devices that we need to automatically claim keys for. /// Submodules can insert user/device pairs into this map and the /// user/device paris will be added to the list of users when /// [`get_missing_sessions`](#method.get_missing_sessions) is called. - users_for_key_claim: Arc>>>, - wedged_devices: Arc>>>, + users_for_key_claim: Arc>>>, + wedged_devices: Arc>>>, key_request_machine: GossipMachine, - outgoing_to_device_requests: Arc>>, + outgoing_to_device_requests: Arc>>, /// Servers that have previously appeared in the `failures` section of a /// `/keys/claim` response. /// /// See also [`crate::identities::IdentityManager::failures`]. - failures: FailuresCache, + failures: FailuresCache, - failed_devices: Arc>>>, + failed_devices: Arc>>>, } impl SessionManager { @@ -80,7 +80,7 @@ impl SessionManager { const UNWEDGING_INTERVAL: Duration = Duration::from_secs(60 * 60); pub fn new( - users_for_key_claim: Arc>>>, + users_for_key_claim: Arc>>>, key_request_machine: GossipMachine, store: Store, ) -> Self { @@ -204,11 +204,11 @@ impl SessionManager { pub async fn get_missing_sessions( &self, users: impl Iterator, - ) -> StoreResult> { + ) -> StoreResult> { let mut missing_session_devices_by_user: BTreeMap<_, BTreeMap<_, _>> = BTreeMap::new(); let mut timed_out_devices_by_user: BTreeMap<_, BTreeSet<_>> = BTreeMap::new(); - let unfailed_users = users.filter(|u| !self.failures.contains(u.server_name())); + let unfailed_users = users.filter(|u| !self.failures.contains(&u.server_name())); // Get the current list of devices for each user. let devices_by_user = Box::pin( @@ -220,8 +220,8 @@ impl SessionManager { #[derive(Debug, Default)] struct UserFailedDeviceInfo { - non_olm_devices: BTreeMap>, - bad_key_devices: BTreeSet, + non_olm_devices: BTreeMap>, + bad_key_devices: BTreeSet, } let mut failed_devices_by_user: BTreeMap<_, UserFailedDeviceInfo> = BTreeMap::new(); @@ -336,16 +336,13 @@ impl SessionManager { fn handle_otk_exhaustion_failure( &self, request_id: &TransactionId, - failed_servers: &BTreeSet, - one_time_keys: &BTreeMap< - &OwnedUserId, - BTreeMap<&OwnedDeviceId, BTreeSet<&OwnedOneTimeKeyId>>, - >, + failed_servers: &BTreeSet, + one_time_keys: &BTreeMap<&UserId, BTreeMap<&DeviceId, BTreeSet<&OneTimeKeyId>>>, ) { // First check that the response is for the request we were expecting. let request = { let mut guard = self.current_key_claim_request.write(); - let expected_request_id = guard.as_ref().map(|e| e.0.as_ref()); + let expected_request_id = guard.as_ref().map(|e| &e.0); if Some(request_id) == expected_request_id { // We have a confirmed match. Clear the expectation, but hang onto the details @@ -390,7 +387,7 @@ impl SessionManager { .filter(|(user_id, _)| { // Skip over users whose homeservers were in the "failed servers" list: we don't // want to mark individual devices as broken *as well as* the server. - !failed_servers.contains(user_id.server_name()) + !failed_servers.contains(&user_id.server_name()) }) .collect(); @@ -456,7 +453,8 @@ impl SessionManager { .filter_map(|s| ServerName::parse(s).ok()) .filter(|s| s != self.store.static_account().user_id.server_name()) .collect(); - let successful_servers = response.one_time_keys.keys().map(|u| u.server_name()); + let successful_servers = + response.one_time_keys.keys().map(|u| u.server_name()).collect::>(); // Add the user/device pairs that don't have any one-time keys to the failures // cache. @@ -464,7 +462,7 @@ impl SessionManager { // Add the failed servers to the failures cache. self.failures.extend(failed_servers); // Remove the servers we successfully contacted from the failures cache. - self.failures.remove(successful_servers); + self.failures.remove(successful_servers.iter()); // Finally, create some 1-to-1 sessions. self.create_sessions(response).await @@ -586,14 +584,13 @@ impl SessionManager { #[cfg(test)] mod tests { - use std::{collections::BTreeMap, iter, ops::Deref, sync::Arc, time::Duration}; + use std::{collections::BTreeMap, iter, sync::Arc, time::Duration}; use matrix_sdk_common::{executor::spawn, locks::RwLock as StdRwLock}; use matrix_sdk_test::{async_test, ruma_response_from_json}; use ruma::{ - DeviceId, OwnedUserId, UserId, - api::client::keys::claim_keys::v3::Response as KeyClaimResponse, device_id, - owned_server_name, user_id, + DeviceId, UserId, api::client::keys::claim_keys::v3::Response as KeyClaimResponse, + device_id, owned_server_name, user_id, }; use serde_json::json; use tokio::sync::Mutex; @@ -749,9 +746,7 @@ mod tests { let bob_user_id = bob.user_id().to_owned(); #[allow(unknown_lints, clippy::redundant_async_block)] // false positive - spawn( - async move { manager.get_missing_sessions(iter::once(bob_user_id.deref())).await }, - ) + spawn(async move { manager.get_missing_sessions(iter::once(&bob_user_id)).await }) }; // the initial `/keys/query` completes, and we start another @@ -784,7 +779,7 @@ mod tests { let (manager, identity_manager) = session_manager_test_helper().await; // We start tracking Bob's devices. - let other_user_id = OwnedUserId::try_from("@bob:example.com").unwrap(); + let other_user_id = UserId::try_from("@bob:example.com").unwrap(); { let cache = manager.store.cache().await.unwrap(); identity_manager @@ -792,7 +787,7 @@ mod tests { .synced(&cache) .await .unwrap() - .update_tracked_users(iter::once(other_user_id.as_ref())) + .update_tracked_users(iter::once(&other_user_id)) .await .unwrap(); } @@ -809,7 +804,7 @@ mod tests { // timeout so that we can detect the call blocking. let result = tokio::time::timeout( Duration::from_millis(10), - manager.get_missing_sessions(iter::once(other_user_id.as_ref())), + manager.get_missing_sessions(iter::once(&other_user_id)), ) .await .expect("get_missing_sessions blocked rather than completing quickly") @@ -886,7 +881,7 @@ mod tests { #[async_test] async fn test_failure_handling() { let alice = user_id!("@alice:example.org"); - let alice_account = Account::with_device_id(alice, "DEVICEID".into()); + let alice_account = Account::with_device_id(alice, &"DEVICEID".into()); let alice_device = DeviceData::from_account(&alice_account); let (manager, _identity_manager) = session_manager_test_helper().await; @@ -969,7 +964,7 @@ mod tests { let response = ruma_response_from_json(&response_json); let alice = user_id!("@alice:example.org"); - let mut alice_account = Account::with_device_id(alice, "DEVICEID".into()); + let mut alice_account = Account::with_device_id(alice, &"DEVICEID".into()); let alice_device = DeviceData::from_account(&alice_account); let (manager, _identity_manager) = session_manager_test_helper().await; diff --git a/crates/matrix-sdk-crypto/src/store/caches.rs b/crates/matrix-sdk-crypto/src/store/caches.rs index d122d28d029..612d358e867 100644 --- a/crates/matrix-sdk-crypto/src/store/caches.rs +++ b/crates/matrix-sdk-crypto/src/store/caches.rs @@ -28,7 +28,7 @@ use std::{ }; use matrix_sdk_common::locks::RwLock as StdRwLock; -use ruma::{DeviceId, OwnedDeviceId, OwnedUserId, UserId}; +use ruma::{DeviceId, UserId}; use serde::{Deserialize, Serialize}; use tokio::sync::{Mutex, MutexGuard, OwnedRwLockReadGuard, RwLock}; use tracing::{Span, field::display, instrument, trace}; @@ -88,7 +88,7 @@ impl SessionStore { /// In-memory store holding the devices of users. #[derive(Debug, Default)] pub struct DeviceStore { - entries: StdRwLock>>, + entries: StdRwLock>>, } impl DeviceStore { @@ -124,7 +124,7 @@ impl DeviceStore { } /// Get a read-only view over all devices of the given user. - pub fn user_devices(&self, user_id: &UserId) -> HashMap { + pub fn user_devices(&self, user_id: &UserId) -> HashMap { self.entries .write() .entry(user_id.to_owned()) @@ -180,7 +180,7 @@ impl SequenceNumber { #[derive(Debug)] pub(super) struct KeysQueryWaiter { /// The user that we are waiting for - user: OwnedUserId, + user: UserId, /// The sequence number of the last invalidation of the users's device list /// when we started waiting (ie, any `/keys/query` result with the same or @@ -207,7 +207,7 @@ pub(super) struct UsersForKeyQuery { /// The users pending a lookup, together with the sequence number at which /// they were added to the list - user_map: HashMap, + user_map: HashMap, /// A list of tasks waiting for key queries to complete. /// @@ -298,7 +298,7 @@ impl UsersForKeyQuery { /// Fetch the list of users waiting for a key query, and the current /// sequence number - pub(super) fn users_for_key_query(&self) -> (HashSet, SequenceNumber) { + pub(super) fn users_for_key_query(&self) -> (HashSet, SequenceNumber) { // we return the sequence number of the last invalidation let sequence_number = self.next_sequence_number.previous(); (self.user_map.keys().cloned().collect(), sequence_number) @@ -333,7 +333,7 @@ impl UsersForKeyQuery { #[derive(Debug)] pub(crate) struct StoreCache { pub(super) store: Arc, - pub(super) tracked_users: StdRwLock>, + pub(super) tracked_users: StdRwLock>, pub(super) loaded_tracked_users: RwLock, pub(super) account: Mutex>, } @@ -457,7 +457,7 @@ mod tests { let user_devices = store.user_devices(device.user_id()); - assert_eq!(&**user_devices.keys().next().unwrap(), device.device_id()); + assert_eq!(user_devices.keys().next().unwrap(), device.device_id()); assert_eq!(user_devices.values().next().unwrap(), &device); let loaded_device = user_devices.get(device.device_id()).unwrap(); diff --git a/crates/matrix-sdk-crypto/src/store/crypto_store_wrapper.rs b/crates/matrix-sdk-crypto/src/store/crypto_store_wrapper.rs index cddbfce28f7..5c0eeaa0d32 100644 --- a/crates/matrix-sdk-crypto/src/store/crypto_store_wrapper.rs +++ b/crates/matrix-sdk-crypto/src/store/crypto_store_wrapper.rs @@ -3,7 +3,7 @@ use std::{future, ops::Deref, sync::Arc}; use futures_core::Stream; use futures_util::StreamExt; use matrix_sdk_common::cross_process_lock::{CrossProcessLock, CrossProcessLockConfig}; -use ruma::{DeviceId, OwnedDeviceId, OwnedUserId, UserId}; +use ruma::{DeviceId, UserId}; use tokio::sync::{Mutex, broadcast}; use tokio_stream::wrappers::{BroadcastStream, errors::BroadcastStreamRecvError}; use tracing::{debug, trace, warn}; @@ -25,8 +25,8 @@ use crate::{ /// [`crate::verification::VerificationStore`]. #[derive(Debug)] pub(crate) struct CryptoStoreWrapper { - user_id: OwnedUserId, - device_id: OwnedDeviceId, + user_id: UserId, + device_id: DeviceId, store: Arc, @@ -107,7 +107,7 @@ impl CryptoStoreWrapper { // processing the changes let own_identity_was_verified_before_change = self .store - .get_user_identity(self.user_id.as_ref()) + .get_user_identity(&self.user_id) .await? .as_ref() .and_then(|i| i.own()) @@ -223,7 +223,7 @@ impl CryptoStoreWrapper { for tracked_user in tracked_users { if let Some(other_identity) = self .store - .get_user_identity(tracked_user.user_id.as_ref()) + .get_user_identity(&tracked_user.user_id) .await? .as_ref() .and_then(|i| i.other()) diff --git a/crates/matrix-sdk-crypto/src/store/error.rs b/crates/matrix-sdk-crypto/src/store/error.rs index e40126a5c0d..a47301bb7ea 100644 --- a/crates/matrix-sdk-crypto/src/store/error.rs +++ b/crates/matrix-sdk-crypto/src/store/error.rs @@ -14,7 +14,7 @@ use std::{convert::Infallible, fmt::Debug, io::Error as IoError}; -use ruma::{IdParseError, OwnedDeviceId, OwnedUserId}; +use ruma::{DeviceId, IdParseError, UserId}; use serde_json::Error as SerdeError; use thiserror::Error; @@ -39,9 +39,9 @@ pub enum CryptoStoreError { )] MismatchedAccount { /// The expected user/device id pair. - expected: (OwnedUserId, OwnedDeviceId), + expected: (UserId, DeviceId), /// The user/device id pair that was loaded from the store. - got: (OwnedUserId, OwnedDeviceId), + got: (UserId, DeviceId), }, /// An IO error occurred. diff --git a/crates/matrix-sdk-crypto/src/store/integration_tests.rs b/crates/matrix-sdk-crypto/src/store/integration_tests.rs index ee47be59488..69c64cb547b 100644 --- a/crates/matrix-sdk-crypto/src/store/integration_tests.rs +++ b/crates/matrix-sdk-crypto/src/store/integration_tests.rs @@ -789,13 +789,13 @@ macro_rules! cryptostore_integration_tests { let (_account, store) = get_loaded_store(dir.clone()).await; let alice_device_1 = DeviceData::from_account(&Account::with_device_id( - "@alice:localhost".try_into().unwrap(), - "FIRSTDEVICE".into(), + &"@alice:localhost".try_into().unwrap(), + &"FIRSTDEVICE".into(), )); let alice_device_2 = DeviceData::from_account(&Account::with_device_id( - "@alice:localhost".try_into().unwrap(), - "SECONDDEVICE".into(), + &"@alice:localhost".try_into().unwrap(), + &"SECONDDEVICE".into(), )); let json = json!({ @@ -895,11 +895,11 @@ macro_rules! cryptostore_integration_tests { let dir = "user_saving"; let user_id = user_id!("@example:localhost"); - let device_id: &DeviceId = "WSKKLTJZCL".into(); + let device_id: DeviceId = "WSKKLTJZCL".into(); let store = get_store(dir, None, true).await; - let account = Account::with_device_id(&user_id, device_id); + let account = Account::with_device_id(&user_id, &device_id); store.save_pending_changes(PendingChanges { account: Some(account), }) .await @@ -1364,7 +1364,7 @@ macro_rules! cryptostore_integration_tests { }.into(); let file = ruma::events::room::EncryptedFileInit { - url: ruma::OwnedMxcUri::from(bundle_uri), + url: ruma::MxcUri::from(bundle_uri), key: jwk, iv: ruma::serde::Base64::new(vec![0u8; 0]), hashes: Default::default(), diff --git a/crates/matrix-sdk-crypto/src/store/memorystore.rs b/crates/matrix-sdk-crypto/src/store/memorystore.rs index c40b88c0dd1..a0eab8f191b 100644 --- a/crates/matrix-sdk-crypto/src/store/memorystore.rs +++ b/crates/matrix-sdk-crypto/src/store/memorystore.rs @@ -26,10 +26,7 @@ use matrix_sdk_common::{ }, locks::RwLock as StdRwLock, }; -use ruma::{ - DeviceId, OwnedDeviceId, OwnedRoomId, OwnedTransactionId, OwnedUserId, RoomId, TransactionId, - UserId, events::secret::request::SecretName, -}; +use ruma::{DeviceId, RoomId, TransactionId, UserId, events::secret::request::SecretName}; use tokio::sync::{Mutex, RwLock}; use tracing::warn; use vodozemac::Curve25519PublicKey; @@ -85,33 +82,32 @@ pub struct MemoryStore { account: StdRwLock>, // Map of sender_key to map of session_id to serialized pickle sessions: StdRwLock>>, - inbound_group_sessions: StdRwLock>>, + inbound_group_sessions: StdRwLock>>, /// Map room id -> session id -> backup order number /// The latest backup in which this session is stored. Equivalent to /// `backed_up_to` in [`IndexedDbCryptoStore`] inbound_group_sessions_backed_up_to: - StdRwLock>>, + StdRwLock>>, - outbound_group_sessions: StdRwLock>, + outbound_group_sessions: StdRwLock>, private_identity: StdRwLock>, - tracked_users: StdRwLock>, + tracked_users: StdRwLock>, olm_hashes: StdRwLock>>, devices: DeviceStore, - identities: StdRwLock>, - outgoing_key_requests: StdRwLock>, - key_requests_by_info: StdRwLock>, - direct_withheld_info: StdRwLock>>, + identities: StdRwLock>, + outgoing_key_requests: StdRwLock>, + key_requests_by_info: StdRwLock>, + direct_withheld_info: StdRwLock>>, custom_values: StdRwLock>>, leases: StdRwLock>, secret_inbox: StdRwLock>>, backup_keys: RwLock, dehydrated_device_pickle_key: RwLock>, next_batch_token: RwLock>, - room_settings: StdRwLock>, - room_key_bundles: - StdRwLock>>, - room_key_backups_fully_downloaded: StdRwLock>, + room_settings: StdRwLock>, + room_key_bundles: StdRwLock>>, + room_key_backups_fully_downloaded: StdRwLock>, save_changes_lock: Arc>, } @@ -642,7 +638,7 @@ impl CryptoStore for MemoryStore { async fn save_tracked_users(&self, tracked_users: &[(&UserId, bool)]) -> Result<()> { self.tracked_users.write().extend(tracked_users.iter().map(|(user_id, dirty)| { - let user_id: OwnedUserId = user_id.to_owned().into(); + let user_id: UserId = user_id.to_owned().into(); (user_id.clone(), TrackedUser { user_id, dirty: *dirty }) })); Ok(()) @@ -656,10 +652,7 @@ impl CryptoStore for MemoryStore { Ok(self.devices.get(user_id, device_id)) } - async fn get_user_devices( - &self, - user_id: &UserId, - ) -> Result> { + async fn get_user_devices(&self, user_id: &UserId) -> Result> { Ok(self.devices.user_devices(user_id)) } @@ -1114,7 +1107,7 @@ mod tests { let user_devices = store.get_user_devices(device.user_id()).await.unwrap(); - assert_eq!(&**user_devices.keys().next().unwrap(), device.device_id()); + assert_eq!(user_devices.keys().next().unwrap(), device.device_id()); assert_eq!(user_devices.values().next().unwrap(), &device); let loaded_device = user_devices.get(device.device_id()).unwrap(); @@ -1295,9 +1288,7 @@ mod integration_tests { use async_trait::async_trait; use matrix_sdk_common::cross_process_lock::CrossProcessLockGeneration; - use ruma::{ - DeviceId, OwnedDeviceId, RoomId, TransactionId, UserId, events::secret::request::SecretName, - }; + use ruma::{DeviceId, RoomId, TransactionId, UserId, events::secret::request::SecretName}; use vodozemac::Curve25519PublicKey; use super::MemoryStore; @@ -1519,7 +1510,7 @@ mod integration_tests { async fn get_user_devices( &self, user_id: &UserId, - ) -> Result, Self::Error> { + ) -> Result, Self::Error> { self.0.get_user_devices(user_id).await } diff --git a/crates/matrix-sdk-crypto/src/store/mod.rs b/crates/matrix-sdk-crypto/src/store/mod.rs index 9addcba2837..6c6c06b9cac 100644 --- a/crates/matrix-sdk-crypto/src/store/mod.rs +++ b/crates/matrix-sdk-crypto/src/store/mod.rs @@ -51,10 +51,7 @@ use as_variant::as_variant; use futures_core::Stream; use futures_util::StreamExt; use itertools::{Either, Itertools}; -use ruma::{ - DeviceId, OwnedDeviceId, OwnedUserId, RoomId, UserId, encryption::KeyUsage, - events::secret::request::SecretName, -}; +use ruma::{DeviceId, RoomId, UserId, encryption::KeyUsage, events::secret::request::SecretName}; use serde::{Serialize, de::DeserializeOwned}; use thiserror::Error; use tokio::sync::{Mutex, Notify, OwnedRwLockWriteGuard, RwLock}; @@ -338,12 +335,12 @@ impl SyncedKeyQueryManager<'_> { /// A pair `(users, sequence_number)`, where `users` is the list of users to /// be queried, and `sequence_number` is the current sequence number, /// which should be returned in `mark_tracked_users_as_up_to_date`. - pub async fn users_for_key_query(&self) -> (HashSet, SequenceNumber) { + pub async fn users_for_key_query(&self) -> (HashSet, SequenceNumber) { self.manager.users_for_key_query.lock().await.users_for_key_query() } /// See the docs for [`crate::OlmMachine::tracked_users()`]. - pub fn tracked_users(&self) -> HashSet { + pub fn tracked_users(&self) -> HashSet { self.cache.tracked_users.read().iter().cloned().collect() } @@ -779,7 +776,7 @@ impl Store { pub(crate) async fn get_device_data_for_user_filtered( &self, user_id: &UserId, - ) -> Result> { + ) -> Result> { self.inner.store.get_user_devices(user_id).await.map(|mut d| { if user_id == self.user_id() { d.remove(self.device_id()); @@ -799,7 +796,7 @@ impl Store { pub(crate) async fn get_device_data_for_user( &self, user_id: &UserId, - ) -> Result> { + ) -> Result> { self.inner.store.get_user_devices(user_id).await } diff --git a/crates/matrix-sdk-crypto/src/store/traits.rs b/crates/matrix-sdk-crypto/src/store/traits.rs index bdfacbbed1d..523cb63e5df 100644 --- a/crates/matrix-sdk-crypto/src/store/traits.rs +++ b/crates/matrix-sdk-crypto/src/store/traits.rs @@ -16,9 +16,7 @@ use std::{collections::HashMap, fmt, sync::Arc}; use async_trait::async_trait; use matrix_sdk_common::{AsyncTraitDeps, cross_process_lock::CrossProcessLockGeneration}; -use ruma::{ - DeviceId, OwnedDeviceId, RoomId, TransactionId, UserId, events::secret::request::SecretName, -}; +use ruma::{DeviceId, RoomId, TransactionId, UserId, events::secret::request::SecretName}; use vodozemac::Curve25519PublicKey; use super::{ @@ -267,7 +265,7 @@ pub trait CryptoStore: AsyncTraitDeps { async fn get_user_devices( &self, user_id: &UserId, - ) -> Result, Self::Error>; + ) -> Result, Self::Error>; /// Get the device for the current client. /// @@ -552,10 +550,7 @@ impl CryptoStore for EraseCryptoStoreError { self.0.get_device(user_id, device_id).await.map_err(Into::into) } - async fn get_user_devices( - &self, - user_id: &UserId, - ) -> Result> { + async fn get_user_devices(&self, user_id: &UserId) -> Result> { self.0.get_user_devices(user_id).await.map_err(Into::into) } diff --git a/crates/matrix-sdk-crypto/src/store/types.rs b/crates/matrix-sdk-crypto/src/store/types.rs index a334b360f95..9bacbe35ed4 100644 --- a/crates/matrix-sdk-crypto/src/store/types.rs +++ b/crates/matrix-sdk-crypto/src/store/types.rs @@ -22,7 +22,7 @@ use std::{ time::Duration, }; -use ruma::{OwnedDeviceId, OwnedRoomId, OwnedUserId}; +use ruma::{DeviceId, RoomId, UserId}; use serde::{Deserialize, Serialize}; use vodozemac::{Curve25519PublicKey, base64_encode}; use zeroize::{Zeroize, ZeroizeOnDrop}; @@ -78,8 +78,8 @@ pub struct Changes { pub identities: IdentityChanges, pub devices: DeviceChanges, /// Stores when a `m.room_key.withheld` is received - pub withheld_session_info: BTreeMap>, - pub room_settings: HashMap, + pub withheld_session_info: BTreeMap>, + pub room_settings: HashMap, pub secrets: Vec, pub next_batch_token: Option, @@ -89,7 +89,7 @@ pub struct Changes { /// The set of rooms for which we have requested all room keys from the /// backup in advance of constructing a room key bundle. - pub room_key_backups_fully_downloaded: HashSet, + pub room_key_backups_fully_downloaded: HashSet, } /// Information about an [MSC4268] room key bundle. @@ -98,7 +98,7 @@ pub struct Changes { #[derive(Clone, Debug, Serialize, Deserialize)] pub struct StoredRoomKeyBundleData { /// The user that sent us this data. - pub sender_user: OwnedUserId, + pub sender_user: UserId, /// The [`Curve25519PublicKey`] of the device that sent us this data. pub sender_key: Curve25519PublicKey, @@ -115,7 +115,7 @@ pub struct StoredRoomKeyBundleData { #[derive(Clone, Debug, Serialize, Deserialize)] pub struct TrackedUser { /// The user ID of the user. - pub user_id: OwnedUserId, + pub user_id: UserId, /// The outdate/dirty flag of the user, remembers if the list of devices for /// the user is considered to be out of date. If the list of devices is /// out of date, a `/keys/query` request should be sent out for this @@ -173,9 +173,9 @@ impl IdentityChanges { pub(super) fn into_maps( self, ) -> ( - BTreeMap, - BTreeMap, - BTreeMap, + BTreeMap, + BTreeMap, + BTreeMap, ) { let new: BTreeMap<_, _> = self .new @@ -216,9 +216,9 @@ pub struct DeviceUpdates { /// A device being in this list does not necessarily mean that the device /// was just created, it just means that it's the first time we're /// seeing this device. - pub new: BTreeMap>, + pub new: BTreeMap>, /// The list of changed devices. - pub changed: BTreeMap>, + pub changed: BTreeMap>, } /// Updates about [`UserIdentity`]s which got received over the `/keys/query` @@ -230,11 +230,11 @@ pub struct IdentityUpdates { /// A identity being in this list does not necessarily mean that the /// identity was just created, it just means that it's the first time /// we're seeing this identity. - pub new: BTreeMap, + pub new: BTreeMap, /// The list of changed identities. - pub changed: BTreeMap, + pub changed: BTreeMap, /// The list of unchanged identities. - pub unchanged: BTreeMap, + pub unchanged: BTreeMap, } /// The private part of a backup key. @@ -462,7 +462,7 @@ pub struct RoomKeyInfo { pub algorithm: EventEncryptionAlgorithm, /// The room where the key is used. - pub room_id: OwnedRoomId, + pub room_id: RoomId, /// The Curve25519 key of the device which initiated the session originally. pub sender_key: Curve25519PublicKey, @@ -486,7 +486,7 @@ impl From<&InboundGroupSession> for RoomKeyInfo { #[derive(Clone, Debug, Deserialize, Serialize)] pub struct RoomKeyWithheldInfo { /// The room where the key is used. - pub room_id: OwnedRoomId, + pub room_id: RoomId, /// The ID of the session that the key is for. pub session_id: String, @@ -506,7 +506,7 @@ pub struct RoomKeyWithheldEntry { /// `m.room_key.withheld` to-device event or an [MSC4268] room key bundle. /// /// [MSC4268]: https://github.com/matrix-org/matrix-spec-proposals/pull/4268 - pub sender: OwnedUserId, + pub sender: UserId, /// The content of the entry, which provides details about the reason the /// key was withheld. pub content: RoomKeyWithheldContent, @@ -528,13 +528,13 @@ impl From for RoomKeyWithheldEntry { #[derive(Debug, Clone)] pub struct RoomKeyBundleInfo { /// The user ID of the person that sent us the historic room key bundle. - pub sender: OwnedUserId, + pub sender: UserId, /// The [`Curve25519PublicKey`] of the device that sent us this data. pub sender_key: Curve25519PublicKey, /// The ID of the room the bundle should be used in. - pub room_id: OwnedRoomId, + pub room_id: RoomId, } impl From<&StoredRoomKeyBundleData> for RoomKeyBundleInfo { diff --git a/crates/matrix-sdk-crypto/src/types/backup.rs b/crates/matrix-sdk-crypto/src/types/backup.rs index 82a790f3b34..9853351be1a 100644 --- a/crates/matrix-sdk-crypto/src/types/backup.rs +++ b/crates/matrix-sdk-crypto/src/types/backup.rs @@ -165,7 +165,7 @@ mod tests { signatures: Signatures(BTreeMap::from([( owned_user_id!("@alice:localhost"), BTreeMap::from([( - KeyId::from_parts(DeviceKeyAlgorithm::Ed25519, "ABCDEFG".into()), + KeyId::from_parts(DeviceKeyAlgorithm::Ed25519, &"ABCDEFG".into()), Ok(Signature::from(Ed25519Signature::from_slice(&[0u8; 64]).unwrap())), )]), )])), diff --git a/crates/matrix-sdk-crypto/src/types/cross_signing/common.rs b/crates/matrix-sdk-crypto/src/types/cross_signing/common.rs index db66a753f60..94baf0acb0f 100644 --- a/crates/matrix-sdk-crypto/src/types/cross_signing/common.rs +++ b/crates/matrix-sdk-crypto/src/types/cross_signing/common.rs @@ -23,7 +23,7 @@ use std::collections::BTreeMap; use as_variant::as_variant; use ruma::{ - DeviceKeyAlgorithm, DeviceKeyId, OwnedDeviceKeyId, OwnedUserId, UserId, + DeviceKeyAlgorithm, DeviceKeyId, UserId, encryption::KeyUsage, serde::{JsonCastable, Raw}, }; @@ -38,7 +38,7 @@ use crate::types::{Signatures, SigningKeys}; #[derive(Clone, Debug, Deserialize, Serialize)] pub struct CrossSigningKey { /// The ID of the user the key belongs to. - pub user_id: OwnedUserId, + pub user_id: UserId, /// What the key is used for. pub usage: Vec, @@ -46,7 +46,7 @@ pub struct CrossSigningKey { /// The public key. /// /// The object must have exactly one property. - pub keys: SigningKeys, + pub keys: SigningKeys, /// Signatures of the key. /// @@ -62,9 +62,9 @@ impl CrossSigningKey { /// Creates a new `CrossSigningKey` with the given user ID, usage, keys and /// signatures. pub fn new( - user_id: OwnedUserId, + user_id: UserId, usage: Vec, - keys: SigningKeys, + keys: SigningKeys, signatures: Signatures, ) -> Self { Self { user_id, usage, keys, signatures, other: BTreeMap::new() } @@ -83,7 +83,7 @@ impl CrossSigningKey { /// /// [cross_signing_key_spec]: https//spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3keysdevice_signingupload pub fn get_first_key_and_id(&self) -> Option<(&DeviceKeyId, Ed25519PublicKey)> { - self.keys.iter().find_map(|(id, key)| Some((id.as_ref(), key.ed25519()?))) + self.keys.iter().find_map(|(id, key)| Some((id, key.ed25519()?))) } } diff --git a/crates/matrix-sdk-crypto/src/types/cross_signing/master.rs b/crates/matrix-sdk-crypto/src/types/cross_signing/master.rs index 75421cbcc82..a921808fba7 100644 --- a/crates/matrix-sdk-crypto/src/types/cross_signing/master.rs +++ b/crates/matrix-sdk-crypto/src/types/cross_signing/master.rs @@ -14,7 +14,7 @@ use std::collections::btree_map::Iter; -use ruma::{DeviceKeyId, OwnedDeviceKeyId, UserId, encryption::KeyUsage}; +use ruma::{DeviceKeyId, UserId, encryption::KeyUsage}; use serde::{Deserialize, Serialize}; use vodozemac::Ed25519PublicKey; @@ -40,7 +40,7 @@ impl MasterPubkey { } /// Get the keys map of containing the master keys. - pub fn keys(&self) -> &SigningKeys { + pub fn keys(&self) -> &SigningKeys { &self.0.keys } @@ -119,8 +119,8 @@ impl MasterPubkey { } impl<'a> IntoIterator for &'a MasterPubkey { - type Item = (&'a OwnedDeviceKeyId, &'a SigningKey); - type IntoIter = Iter<'a, OwnedDeviceKeyId, SigningKey>; + type Item = (&'a DeviceKeyId, &'a SigningKey); + type IntoIter = Iter<'a, DeviceKeyId, SigningKey>; fn into_iter(self) -> Self::IntoIter { self.keys().iter() diff --git a/crates/matrix-sdk-crypto/src/types/cross_signing/mod.rs b/crates/matrix-sdk-crypto/src/types/cross_signing/mod.rs index 4556af96cb6..d668f306753 100644 --- a/crates/matrix-sdk-crypto/src/types/cross_signing/mod.rs +++ b/crates/matrix-sdk-crypto/src/types/cross_signing/mod.rs @@ -128,7 +128,7 @@ mod tests { let mut other_key: CrossSigningKey = raw.deserialize_as().unwrap(); other_key.signatures.add_signature( user_id.to_owned(), - DeviceKeyId::from_parts(ruma::DeviceKeyAlgorithm::Ed25519, "DEVICEID".into()), + DeviceKeyId::from_parts(ruma::DeviceKeyAlgorithm::Ed25519, &"DEVICEID".into()), signature, ); let other_key = other_key.try_into().unwrap(); diff --git a/crates/matrix-sdk-crypto/src/types/cross_signing/self_signing.rs b/crates/matrix-sdk-crypto/src/types/cross_signing/self_signing.rs index 784aec3837a..c96ea1c7590 100644 --- a/crates/matrix-sdk-crypto/src/types/cross_signing/self_signing.rs +++ b/crates/matrix-sdk-crypto/src/types/cross_signing/self_signing.rs @@ -1,6 +1,6 @@ use std::collections::btree_map::Iter; -use ruma::{OwnedDeviceKeyId, UserId, encryption::KeyUsage}; +use ruma::{DeviceKeyId, UserId, encryption::KeyUsage}; use serde::{Deserialize, Serialize}; use vodozemac::Ed25519PublicKey; @@ -25,7 +25,7 @@ impl SelfSigningPubkey { } /// Get the keys map of containing the self signing keys. - pub fn keys(&self) -> &SigningKeys { + pub fn keys(&self) -> &SigningKeys { &self.0.keys } @@ -66,8 +66,8 @@ impl SelfSigningPubkey { } impl<'a> IntoIterator for &'a SelfSigningPubkey { - type Item = (&'a OwnedDeviceKeyId, &'a SigningKey); - type IntoIter = Iter<'a, OwnedDeviceKeyId, SigningKey>; + type Item = (&'a DeviceKeyId, &'a SigningKey); + type IntoIter = Iter<'a, DeviceKeyId, SigningKey>; fn into_iter(self) -> Self::IntoIter { self.keys().iter() diff --git a/crates/matrix-sdk-crypto/src/types/cross_signing/user_signing.rs b/crates/matrix-sdk-crypto/src/types/cross_signing/user_signing.rs index c5081fa358a..229fdb11cfc 100644 --- a/crates/matrix-sdk-crypto/src/types/cross_signing/user_signing.rs +++ b/crates/matrix-sdk-crypto/src/types/cross_signing/user_signing.rs @@ -1,6 +1,6 @@ use std::collections::btree_map::Iter; -use ruma::{OwnedDeviceKeyId, UserId, encryption::KeyUsage}; +use ruma::{DeviceKeyId, UserId, encryption::KeyUsage}; use serde::{Deserialize, Serialize}; use vodozemac::Ed25519PublicKey; @@ -26,7 +26,7 @@ impl UserSigningPubkey { } /// Get the keys map of containing the user signing keys. - pub fn keys(&self) -> &SigningKeys { + pub fn keys(&self) -> &SigningKeys { &self.0.keys } @@ -60,8 +60,8 @@ impl UserSigningPubkey { } impl<'a> IntoIterator for &'a UserSigningPubkey { - type Item = (&'a OwnedDeviceKeyId, &'a SigningKey); - type IntoIter = Iter<'a, OwnedDeviceKeyId, SigningKey>; + type Item = (&'a DeviceKeyId, &'a SigningKey); + type IntoIter = Iter<'a, DeviceKeyId, SigningKey>; fn into_iter(self) -> Self::IntoIter { self.keys().iter() diff --git a/crates/matrix-sdk-crypto/src/types/device_keys.rs b/crates/matrix-sdk-crypto/src/types/device_keys.rs index a475c3a3c81..0c8c75fbc22 100644 --- a/crates/matrix-sdk-crypto/src/types/device_keys.rs +++ b/crates/matrix-sdk-crypto/src/types/device_keys.rs @@ -22,7 +22,7 @@ use std::collections::BTreeMap; use js_option::JsOption; use ruma::{ - DeviceKeyAlgorithm, DeviceKeyId, OwnedDeviceId, OwnedDeviceKeyId, OwnedUserId, + DeviceId, DeviceKeyAlgorithm, DeviceKeyId, UserId, serde::{JsonCastable, Raw}, }; use serde::{Deserialize, Serialize}; @@ -56,18 +56,18 @@ pub struct DeviceKeys { /// The ID of the user the device belongs to. /// /// Must match the user ID used when logging in. - pub user_id: OwnedUserId, + pub user_id: UserId, /// The ID of the device these keys belong to. /// /// Must match the device ID used when logging in. - pub device_id: OwnedDeviceId, + pub device_id: DeviceId, /// The encryption algorithms supported by this device. pub algorithms: Vec, /// Public identity keys. - pub keys: BTreeMap, + pub keys: BTreeMap, /// Signatures for the device key object. pub signatures: Signatures, @@ -89,10 +89,10 @@ impl DeviceKeys { /// Creates a new `DeviceKeys` from the given user id, device ID, /// algorithms, keys and signatures. pub fn new( - user_id: OwnedUserId, - device_id: OwnedDeviceId, + user_id: UserId, + device_id: DeviceId, algorithms: Vec, - keys: BTreeMap, + keys: BTreeMap, signatures: Signatures, ) -> Self { Self { @@ -211,10 +211,10 @@ impl From for DeviceKey { /// [`DeviceKey`]s. #[derive(Clone, Debug, Deserialize, Serialize)] struct DeviceKeyHelper { - pub user_id: OwnedUserId, - pub device_id: OwnedDeviceId, + pub user_id: UserId, + pub device_id: DeviceId, pub algorithms: Vec, - pub keys: BTreeMap, + pub keys: BTreeMap, #[serde(default, skip_serializing_if = "JsOption::is_undefined")] pub dehydrated: JsOption, pub signatures: Signatures, @@ -228,7 +228,7 @@ impl TryFrom for DeviceKeys { type Error = vodozemac::KeyError; fn try_from(value: DeviceKeyHelper) -> Result { - let keys: Result, vodozemac::KeyError> = value + let keys: Result, vodozemac::KeyError> = value .keys .into_iter() .map(|(k, v)| { @@ -261,7 +261,7 @@ impl TryFrom for DeviceKeys { impl From for DeviceKeyHelper { fn from(value: DeviceKeys) -> Self { - let keys: BTreeMap = + let keys: BTreeMap = value.keys.into_iter().map(|(k, v)| (k, v.to_base64())).collect(); Self { @@ -281,7 +281,7 @@ impl From for DeviceKeyHelper { mod tests { use std::str::FromStr; - use ruma::{OwnedDeviceKeyId, device_id, user_id}; + use ruma::{DeviceKeyId, device_id, user_id}; use serde_json::json; use vodozemac::{Curve25519PublicKey, Curve25519SecretKey}; @@ -352,7 +352,7 @@ mod tests { // Change one of the fields and verify that the signature check fails. let new_curve_key = Curve25519SecretKey::new(); - let key_id = OwnedDeviceKeyId::from_str("curve25519:BNYQQWUMXO").unwrap(); + let key_id = DeviceKeyId::from_str("curve25519:BNYQQWUMXO").unwrap(); device_keys.keys.insert(key_id, Curve25519PublicKey::from(&new_curve_key).into()); assert!(device_keys.check_self_signature().is_err()); diff --git a/crates/matrix-sdk-crypto/src/types/events/forwarded_room_key.rs b/crates/matrix-sdk-crypto/src/types/events/forwarded_room_key.rs index 1b63d5fb5f1..97c8bdac074 100644 --- a/crates/matrix-sdk-crypto/src/types/events/forwarded_room_key.rs +++ b/crates/matrix-sdk-crypto/src/types/events/forwarded_room_key.rs @@ -16,7 +16,7 @@ use std::collections::BTreeMap; -use ruma::{DeviceKeyAlgorithm, OwnedRoomId}; +use ruma::{DeviceKeyAlgorithm, RoomId}; use serde::{Deserialize, Serialize}; use serde_json::Value; use vodozemac::{Curve25519PublicKey, Ed25519PublicKey, megolm::ExportedSessionKey}; @@ -89,7 +89,7 @@ impl EventType for ForwardedRoomKeyContent { #[derive(Deserialize, Serialize)] pub struct ForwardedMegolmV1AesSha2Content { /// The room where the key is used. - pub room_id: OwnedRoomId, + pub room_id: RoomId, /// The ID of the session that the key is for. pub session_id: String, @@ -141,7 +141,7 @@ pub struct ForwardedMegolmV1AesSha2Content { #[derive(Deserialize, Serialize)] pub struct ForwardedMegolmV2AesSha2Content { /// The room where the key is used. - pub room_id: OwnedRoomId, + pub room_id: RoomId, /// The ID of the session that the key is for. pub session_id: String, diff --git a/crates/matrix-sdk-crypto/src/types/events/olm_v1.rs b/crates/matrix-sdk-crypto/src/types/events/olm_v1.rs index 78df1eb91dc..08f89edc677 100644 --- a/crates/matrix-sdk-crypto/src/types/events/olm_v1.rs +++ b/crates/matrix-sdk-crypto/src/types/events/olm_v1.rs @@ -17,7 +17,7 @@ use std::fmt::Debug; -use ruma::{OwnedUserId, UserId}; +use ruma::UserId; use serde::{Deserialize, Serialize}; use serde_json::value::RawValue; use vodozemac::Ed25519PublicKey; @@ -187,9 +187,9 @@ where C: EventType + Debug + Sized + Serialize, { /// The sender of the event, as set by the sender of the event. - pub sender: OwnedUserId, + pub sender: UserId, /// The intended recipient of the event, as set by the sender of the event. - pub recipient: OwnedUserId, + pub recipient: UserId, /// The sender's signing keys of the encrypted event. pub keys: OlmV1Keys, /// The recipient's signing keys of the encrypted event. @@ -280,9 +280,9 @@ impl DecryptedOlmV1Event { #[derive(Clone, Debug, Deserialize, Serialize)] pub struct ToDeviceCustomEvent { /// The sender of the encrypted to-device event. - pub sender: OwnedUserId, + pub sender: UserId, /// The recipient of the encrypted to-device event. - pub recipient: OwnedUserId, + pub recipient: UserId, /// The sender's signing keys of the encrypted event. pub keys: OlmV1Keys, /// The recipient's signing keys of the encrypted event. diff --git a/crates/matrix-sdk-crypto/src/types/events/room/encrypted.rs b/crates/matrix-sdk-crypto/src/types/events/room/encrypted.rs index 6a178534402..e5a5c30ae73 100644 --- a/crates/matrix-sdk-crypto/src/types/events/room/encrypted.rs +++ b/crates/matrix-sdk-crypto/src/types/events/room/encrypted.rs @@ -16,7 +16,7 @@ use std::collections::BTreeMap; -use ruma::{OwnedDeviceId, RoomId, events::AnyToDeviceEventContent, serde::JsonCastable}; +use ruma::{DeviceId, RoomId, events::AnyToDeviceEventContent, serde::JsonCastable}; use serde::{Deserialize, Serialize}; use serde_json::Value; use vodozemac::{Curve25519PublicKey, megolm::MegolmMessage, olm::OlmMessage}; @@ -323,7 +323,7 @@ pub struct MegolmV1AesSha2Content { /// The ID of the sending device. #[serde(skip_serializing_if = "Option::is_none")] - pub device_id: Option, + pub device_id: Option, /// The ID of the session used to encrypt the message. pub session_id: String, diff --git a/crates/matrix-sdk-crypto/src/types/events/room/mod.rs b/crates/matrix-sdk-crypto/src/types/events/room/mod.rs index 582bbfe7f9e..d7b80861273 100644 --- a/crates/matrix-sdk-crypto/src/types/events/room/mod.rs +++ b/crates/matrix-sdk-crypto/src/types/events/room/mod.rs @@ -16,7 +16,7 @@ use std::{collections::BTreeMap, fmt::Debug}; -use ruma::{EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedUserId, UserId}; +use ruma::{EventId, MilliSecondsSinceUnixEpoch, UserId}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -31,10 +31,10 @@ where C: EventType + Debug + Sized + Serialize, { /// Contains the fully-qualified ID of the user who sent this event. - pub sender: OwnedUserId, + pub sender: UserId, /// The globally unique identifier for this event. - pub event_id: OwnedEventId, + pub event_id: EventId, /// Present if and only if this event is a state event. #[cfg(feature = "experimental-encrypted-state-events")] diff --git a/crates/matrix-sdk-crypto/src/types/events/room_key.rs b/crates/matrix-sdk-crypto/src/types/events/room_key.rs index dbf9a82e2c4..d0e603ccd37 100644 --- a/crates/matrix-sdk-crypto/src/types/events/room_key.rs +++ b/crates/matrix-sdk-crypto/src/types/events/room_key.rs @@ -16,7 +16,7 @@ use std::collections::BTreeMap; -use ruma::{OwnedRoomId, RoomId, serde::Raw}; +use ruma::{RoomId, serde::Raw}; use serde::{Deserialize, Serialize}; use serde_json::{Value, value::to_raw_value}; use vodozemac::megolm::SessionKey; @@ -111,7 +111,7 @@ impl RoomKeyContent { #[derive(Deserialize, Serialize)] pub struct MegolmV1AesSha2Content { /// The room where the key is used. - pub room_id: OwnedRoomId, + pub room_id: RoomId, /// The ID of the session that the key is for. pub session_id: String, /// The key to be exchanged. Can be used to create a [`InboundGroupSession`] @@ -134,7 +134,7 @@ pub struct MegolmV1AesSha2Content { impl MegolmV1AesSha2Content { /// Create a new `m.megolm.v1.aes-sha2` `m.room_key` content. pub fn new( - room_id: OwnedRoomId, + room_id: RoomId, session_id: String, session_key: SessionKey, shared_history: bool, diff --git a/crates/matrix-sdk-crypto/src/types/events/room_key_bundle.rs b/crates/matrix-sdk-crypto/src/types/events/room_key_bundle.rs index 1443385ccc3..fd1f09fa3ac 100644 --- a/crates/matrix-sdk-crypto/src/types/events/room_key_bundle.rs +++ b/crates/matrix-sdk-crypto/src/types/events/room_key_bundle.rs @@ -17,7 +17,7 @@ //! //! [MSC4268]: https://github.com/matrix-org/matrix-spec-proposals/pull/4268 -use ruma::{OwnedRoomId, events::room::EncryptedFile}; +use ruma::{RoomId, events::room::EncryptedFile}; use serde::{Deserialize, Serialize}; use super::EventType; @@ -30,7 +30,7 @@ use super::EventType; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct RoomKeyBundleContent { /// The room that these keys are for. - pub room_id: OwnedRoomId, + pub room_id: RoomId, /// The location and encryption info of the key bundle. pub file: EncryptedFile, diff --git a/crates/matrix-sdk-crypto/src/types/events/room_key_request.rs b/crates/matrix-sdk-crypto/src/types/events/room_key_request.rs index e397862c639..7074f01090d 100644 --- a/crates/matrix-sdk-crypto/src/types/events/room_key_request.rs +++ b/crates/matrix-sdk-crypto/src/types/events/room_key_request.rs @@ -16,10 +16,7 @@ use std::collections::BTreeMap; -use ruma::{ - OwnedDeviceId, OwnedRoomId, OwnedTransactionId, RoomId, events::AnyToDeviceEventContent, - serde::JsonCastable, -}; +use ruma::{DeviceId, RoomId, TransactionId, events::AnyToDeviceEventContent, serde::JsonCastable}; use serde::{Deserialize, Serialize}; use serde_json::Value; use vodozemac::Curve25519PublicKey; @@ -47,11 +44,11 @@ pub struct RoomKeyRequestContent { #[serde(flatten)] pub action: Action, /// The ID of the device that is requesting the room key. - pub requesting_device_id: OwnedDeviceId, + pub requesting_device_id: DeviceId, /// A random string uniquely identifying the request for a key. If the key /// is requested multiple times, it should be reused. It should also reused /// in order to cancel a request. - pub request_id: OwnedTransactionId, + pub request_id: TransactionId, } impl RoomKeyRequestContent { @@ -59,8 +56,8 @@ impl RoomKeyRequestContent { /// set to request a room key with the given `RequestedKeyInfo`. pub fn new_request( info: RequestedKeyInfo, - requesting_device_id: OwnedDeviceId, - request_id: OwnedTransactionId, + requesting_device_id: DeviceId, + request_id: TransactionId, ) -> Self { Self { action: Action::Request(info), requesting_device_id, request_id } } @@ -206,7 +203,7 @@ impl From for SupportedKeyInfo { #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] pub struct MegolmV1AesSha2Content { /// The room where the key is used. - pub room_id: OwnedRoomId, + pub room_id: RoomId, /// The Curve25519 key of the device which initiated the session originally. #[serde(default, with = "serde_curve_key_option", skip_serializing_if = "Option::is_none")] @@ -221,7 +218,7 @@ pub struct MegolmV1AesSha2Content { #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] pub struct MegolmV2AesSha2Content { /// The room where the key is used. - pub room_id: OwnedRoomId, + pub room_id: RoomId, /// The ID of the session that the key is for. pub session_id: String, diff --git a/crates/matrix-sdk-crypto/src/types/events/room_key_withheld.rs b/crates/matrix-sdk-crypto/src/types/events/room_key_withheld.rs index fa8016ad8b1..12d4898528d 100644 --- a/crates/matrix-sdk-crypto/src/types/events/room_key_withheld.rs +++ b/crates/matrix-sdk-crypto/src/types/events/room_key_withheld.rs @@ -17,9 +17,7 @@ use std::collections::BTreeMap; use matrix_sdk_common::deserialized_responses::WithheldCode; -use ruma::{ - OwnedDeviceId, OwnedRoomId, RoomId, events::AnyToDeviceEventContent, serde::JsonCastable, -}; +use ruma::{DeviceId, RoomId, events::AnyToDeviceEventContent, serde::JsonCastable}; use serde::{Deserialize, Serialize}; use serde_json::Value; use vodozemac::Curve25519PublicKey; @@ -102,10 +100,10 @@ impl RoomKeyWithheldContent { pub fn new( algorithm: EventEncryptionAlgorithm, code: WithheldCode, - room_id: OwnedRoomId, + room_id: RoomId, session_id: String, sender_key: Curve25519PublicKey, - from_device: OwnedDeviceId, + from_device: DeviceId, ) -> Self { let from_device = Some(from_device); @@ -215,7 +213,7 @@ pub enum MegolmV1AesSha2WithheldContent { #[derive(Clone, PartialEq, Eq, Deserialize, Serialize)] pub struct CommonWithheldCodeContent { /// The room where the key is used. - pub room_id: OwnedRoomId, + pub room_id: RoomId, /// The ID of the session. pub session_id: String, @@ -227,7 +225,7 @@ pub struct CommonWithheldCodeContent { /// The device ID of the device sending the m.room_key.withheld message /// MSC3735. #[serde(skip_serializing_if = "Option::is_none")] - pub from_device: Option, + pub from_device: Option, #[serde(flatten)] other: BTreeMap, @@ -236,10 +234,10 @@ pub struct CommonWithheldCodeContent { impl CommonWithheldCodeContent { /// Create a new common withheld code content. pub fn new( - room_id: OwnedRoomId, + room_id: RoomId, session_id: String, sender_key: Curve25519PublicKey, - device_id: OwnedDeviceId, + device_id: DeviceId, ) -> Self { Self { room_id, @@ -316,7 +314,7 @@ pub struct NoOlmWithheldContent { /// The device ID of the device sending the m.room_key.withheld message /// MSC3735. #[serde(skip_serializing_if = "Option::is_none")] - pub from_device: Option, + pub from_device: Option, #[serde(flatten)] other: BTreeMap, diff --git a/crates/matrix-sdk-crypto/src/types/events/secret_send.rs b/crates/matrix-sdk-crypto/src/types/events/secret_send.rs index 7fc7f0e7420..9aee25f96df 100644 --- a/crates/matrix-sdk-crypto/src/types/events/secret_send.rs +++ b/crates/matrix-sdk-crypto/src/types/events/secret_send.rs @@ -16,7 +16,7 @@ use std::collections::BTreeMap; -use ruma::{OwnedTransactionId, events::secret::request::SecretName}; +use ruma::{TransactionId, events::secret::request::SecretName}; use serde::{Deserialize, Serialize}; use serde_json::Value; use zeroize::Zeroize; @@ -34,7 +34,7 @@ pub type SecretSendEvent = ToDeviceEvent; #[derive(Clone, Serialize, Deserialize)] pub struct SecretSendContent { /// The ID of the request that this a response to. - pub request_id: OwnedTransactionId, + pub request_id: TransactionId, /// The contents of the secret. pub secret: String, /// The name of the secret, typically not part of the event but can be @@ -49,7 +49,7 @@ pub struct SecretSendContent { impl SecretSendContent { /// Create a new `m.secret.send` content. - pub fn new(request_id: OwnedTransactionId, secret: String) -> Self { + pub fn new(request_id: TransactionId, secret: String) -> Self { Self { request_id, secret, secret_name: None, other: Default::default() } } } diff --git a/crates/matrix-sdk-crypto/src/types/events/to_device.rs b/crates/matrix-sdk-crypto/src/types/events/to_device.rs index d69af1842fa..7069b47f67a 100644 --- a/crates/matrix-sdk-crypto/src/types/events/to_device.rs +++ b/crates/matrix-sdk-crypto/src/types/events/to_device.rs @@ -15,7 +15,7 @@ use std::{collections::BTreeMap, fmt::Debug}; use ruma::{ - OwnedUserId, UserId, + UserId, events::{ ToDeviceEventContent, ToDeviceEventType, key::verification::{ @@ -242,7 +242,7 @@ impl JsonCastable for ToDeviceEvents {} #[derive(Clone, Debug, Deserialize, Serialize)] pub struct ToDeviceCustomEvent { /// The sender of the to-device event. - pub sender: OwnedUserId, + pub sender: UserId, /// The content of the to-device event. pub content: BTreeMap, /// The type of the to-device event. @@ -260,7 +260,7 @@ where C: EventType + Debug + Sized + Serialize, { /// The sender of the to-device event. - pub sender: OwnedUserId, + pub sender: UserId, /// The content of the to-device event. pub content: C, /// Any other unknown data of the to-device event. @@ -269,7 +269,7 @@ where impl ToDeviceEvent { /// Create a new `ToDeviceEvent`. - pub fn new(sender: OwnedUserId, content: C) -> ToDeviceEvent { + pub fn new(sender: UserId, content: C) -> ToDeviceEvent { ToDeviceEvent { sender, content, other: Default::default() } } } @@ -311,7 +311,7 @@ where { #[derive(Deserialize)] struct Helper { - sender: OwnedUserId, + sender: UserId, content: C, // We're deserializing the `type` field here so it doesn't end up in `other`. #[allow(dead_code)] diff --git a/crates/matrix-sdk-crypto/src/types/mod.rs b/crates/matrix-sdk-crypto/src/types/mod.rs index 4c7e72b82c1..14cb57e6aa8 100644 --- a/crates/matrix-sdk-crypto/src/types/mod.rs +++ b/crates/matrix-sdk-crypto/src/types/mod.rs @@ -35,10 +35,7 @@ use std::{ use as_variant::as_variant; use matrix_sdk_common::deserialized_responses::PrivOwnedStr; -use ruma::{ - DeviceKeyAlgorithm, DeviceKeyId, OwnedDeviceKeyId, OwnedUserId, RoomId, UserId, - serde::StringEnum, -}; +use ruma::{DeviceKeyAlgorithm, DeviceKeyId, RoomId, UserId, serde::StringEnum}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use vodozemac::{Curve25519PublicKey, Ed25519PublicKey, Ed25519Signature, KeyError}; use zeroize::{Zeroize, ZeroizeOnDrop}; @@ -213,9 +210,7 @@ impl From for Signature { /// Signatures for a signed object. #[derive(Debug, Clone, PartialEq, Eq)] -pub struct Signatures( - BTreeMap>>, -); +pub struct Signatures(BTreeMap>>); impl Signatures { /// Create a new, empty, signatures collection. @@ -227,8 +222,8 @@ impl Signatures { /// the collection. pub fn add_signature( &mut self, - signer: OwnedUserId, - key_id: OwnedDeviceKeyId, + signer: UserId, + key_id: DeviceKeyId, signature: Ed25519Signature, ) -> Option> { self.0.entry(signer).or_default().insert(key_id, Ok(signature.into())) @@ -244,7 +239,7 @@ impl Signatures { pub fn get( &self, signer: &UserId, - ) -> Option<&BTreeMap>> { + ) -> Option<&BTreeMap>> { self.0.get(signer) } @@ -271,10 +266,9 @@ impl Default for Signatures { } impl IntoIterator for Signatures { - type Item = (OwnedUserId, BTreeMap>); + type Item = (UserId, BTreeMap>); - type IntoIter = - IntoIter>>; + type IntoIter = IntoIter>>; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() @@ -286,7 +280,7 @@ impl<'de> Deserialize<'de> for Signatures { where D: Deserializer<'de>, { - let map: BTreeMap> = + let map: BTreeMap> = Deserialize::deserialize(deserializer)?; let map = map @@ -320,7 +314,7 @@ impl Serialize for Signatures { where S: Serializer, { - let signatures: BTreeMap<&OwnedUserId, BTreeMap<&OwnedDeviceKeyId, String>> = self + let signatures: BTreeMap<&UserId, BTreeMap<&DeviceKeyId, String>> = self .0 .iter() .map(|(u, m)| { @@ -412,14 +406,14 @@ impl From<[(K, SigningKey); N]> for SigningKeys { } } -// Helper trait to generalize between a `OwnedDeviceKeyId` and a +// Helper trait to generalize between a `DeviceKeyId` and a // `DeviceKeyAlgorithm` so that we can support Deserialize for // `SigningKeys` trait Algorithm { fn algorithm(&self) -> DeviceKeyAlgorithm; } -impl Algorithm for OwnedDeviceKeyId { +impl Algorithm for DeviceKeyId { fn algorithm(&self) -> DeviceKeyAlgorithm { DeviceKeyId::algorithm(self) } diff --git a/crates/matrix-sdk-crypto/src/types/requests/keys_backup.rs b/crates/matrix-sdk-crypto/src/types/requests/keys_backup.rs index ca4678367e7..e5948e369b0 100644 --- a/crates/matrix-sdk-crypto/src/types/requests/keys_backup.rs +++ b/crates/matrix-sdk-crypto/src/types/requests/keys_backup.rs @@ -14,7 +14,7 @@ use std::collections::BTreeMap; -use ruma::{OwnedRoomId, api::client::backup::RoomKeyBackup}; +use ruma::{RoomId, api::client::backup::RoomKeyBackup}; /// A request that will back up a batch of room keys to the server. #[derive(Clone, Debug)] @@ -23,5 +23,5 @@ pub struct KeysBackupRequest { pub version: String, /// The map from room id to a backed up room key that we're going to upload /// to the server. - pub rooms: BTreeMap, + pub rooms: BTreeMap, } diff --git a/crates/matrix-sdk-crypto/src/types/requests/keys_query.rs b/crates/matrix-sdk-crypto/src/types/requests/keys_query.rs index 02ba70598b1..c41da4809af 100644 --- a/crates/matrix-sdk-crypto/src/types/requests/keys_query.rs +++ b/crates/matrix-sdk-crypto/src/types/requests/keys_query.rs @@ -14,7 +14,7 @@ use std::{collections::BTreeMap, time::Duration}; -use ruma::{OwnedDeviceId, OwnedUserId}; +use ruma::{DeviceId, UserId}; /// Customized version of `ruma_client_api::keys::get_keys::v3::Request`, /// without any references. @@ -26,11 +26,11 @@ pub struct KeysQueryRequest { /// The keys to be downloaded. An empty list indicates all devices for /// the corresponding user. - pub device_keys: BTreeMap>, + pub device_keys: BTreeMap>, } impl KeysQueryRequest { - pub(crate) fn new(users: impl Iterator) -> Self { + pub(crate) fn new(users: impl Iterator) -> Self { let device_keys = users.map(|u| (u, Vec::new())).collect(); Self { timeout: None, device_keys } diff --git a/crates/matrix-sdk-crypto/src/types/requests/mod.rs b/crates/matrix-sdk-crypto/src/types/requests/mod.rs index 11d48156d9f..fb326e13f12 100644 --- a/crates/matrix-sdk-crypto/src/types/requests/mod.rs +++ b/crates/matrix-sdk-crypto/src/types/requests/mod.rs @@ -16,7 +16,7 @@ use std::sync::Arc; -use ruma::{OwnedTransactionId, TransactionId}; +use ruma::TransactionId; mod enums; mod keys_backup; @@ -40,7 +40,7 @@ pub use verification::*; pub struct OutgoingRequest { /// The unique id of a request, needs to be passed when receiving a /// response. - pub(crate) request_id: OwnedTransactionId, + pub(crate) request_id: TransactionId, /// The underlying outgoing request. pub(crate) request: Arc, } diff --git a/crates/matrix-sdk-crypto/src/types/requests/room_message.rs b/crates/matrix-sdk-crypto/src/types/requests/room_message.rs index fa050ba4c4b..63bfdc8c491 100644 --- a/crates/matrix-sdk-crypto/src/types/requests/room_message.rs +++ b/crates/matrix-sdk-crypto/src/types/requests/room_message.rs @@ -12,20 +12,20 @@ // See the License for the specific language governing permissions and // limitations under the License. -use ruma::{OwnedRoomId, OwnedTransactionId, events::AnyMessageLikeEventContent}; +use ruma::{RoomId, TransactionId, events::AnyMessageLikeEventContent}; /// Customized owned request type for sending out room messages. #[derive(Clone, Debug)] pub struct RoomMessageRequest { /// The room to send the event to. - pub room_id: OwnedRoomId, + pub room_id: RoomId, /// The transaction ID for this event. /// /// Clients should generate an ID unique across requests with the /// same access token; it will be used by the server to ensure /// idempotency of requests. - pub txn_id: OwnedTransactionId, + pub txn_id: TransactionId, /// The event content to send. pub content: Box, diff --git a/crates/matrix-sdk-crypto/src/types/requests/to_device.rs b/crates/matrix-sdk-crypto/src/types/requests/to_device.rs index 901190d3789..1c233527eb1 100644 --- a/crates/matrix-sdk-crypto/src/types/requests/to_device.rs +++ b/crates/matrix-sdk-crypto/src/types/requests/to_device.rs @@ -15,7 +15,7 @@ use std::{collections::BTreeMap, iter}; use ruma::{ - OwnedDeviceId, OwnedTransactionId, OwnedUserId, TransactionId, UserId, + DeviceId, TransactionId, UserId, events::{AnyToDeviceEventContent, ToDeviceEventContent, ToDeviceEventType}, serde::Raw, to_device::DeviceIdOrAllDevices, @@ -31,7 +31,7 @@ pub struct ToDeviceRequest { /// A request identifier unique to the access token used to send the /// request. - pub txn_id: OwnedTransactionId, + pub txn_id: TransactionId, /// A map of users to devices to a content for a message event to be /// sent to the user's device. Individual message events can be sent @@ -39,8 +39,7 @@ pub struct ToDeviceRequest { /// The content's type for this field will be updated in a future /// release, until then you can create a value using /// `serde_json::value::to_raw_value`. - pub messages: - BTreeMap>>, + pub messages: BTreeMap>>, } impl ToDeviceRequest { @@ -72,9 +71,9 @@ impl ToDeviceRequest { pub(crate) fn for_recipients( recipient: &UserId, - recipient_devices: Vec, + recipient_devices: Vec, content: &AnyToDeviceEventContent, - txn_id: OwnedTransactionId, + txn_id: TransactionId, ) -> Self { let event_type = content.event_type(); let raw_content = Raw::new(content).expect("Failed to serialize to-device event"); @@ -103,7 +102,7 @@ impl ToDeviceRequest { recipient_device: impl Into, content: Raw, event_type: ToDeviceEventType, - txn_id: OwnedTransactionId, + txn_id: TransactionId, ) -> Self { let user_messages = iter::once((recipient_device.into(), content)).collect(); let messages = iter::once((recipient.to_owned(), user_messages)).collect(); @@ -115,7 +114,7 @@ impl ToDeviceRequest { recipient: &UserId, recipient_device: impl Into, content: &AnyToDeviceEventContent, - txn_id: OwnedTransactionId, + txn_id: TransactionId, ) -> Self { let event_type = content.event_type(); let raw_content = Raw::new(content).expect("Failed to serialize to-device event"); diff --git a/crates/matrix-sdk-crypto/src/types/room_history.rs b/crates/matrix-sdk-crypto/src/types/room_history.rs index 7345cc90002..657f09298a1 100644 --- a/crates/matrix-sdk-crypto/src/types/room_history.rs +++ b/crates/matrix-sdk-crypto/src/types/room_history.rs @@ -20,7 +20,7 @@ limitations under the License. use std::fmt::Debug; -use ruma::{DeviceKeyAlgorithm, OwnedRoomId}; +use ruma::{DeviceKeyAlgorithm, RoomId}; use serde::{Deserialize, Serialize}; use vodozemac::{Curve25519PublicKey, megolm::ExportedSessionKey}; @@ -67,7 +67,7 @@ pub struct HistoricRoomKey { pub algorithm: EventEncryptionAlgorithm, /// The room where the session is used. - pub room_id: OwnedRoomId, + pub room_id: RoomId, /// The Curve25519 key of the device which initiated the session originally, /// according to the device that sent us this key. @@ -99,7 +99,7 @@ impl Debug for HistoricRoomKey { } impl RoomKeyExport for &HistoricRoomKey { - fn room_id(&self) -> &ruma::RoomId { + fn room_id(&self) -> &RoomId { &self.room_id } diff --git a/crates/matrix-sdk-crypto/src/verification/cache.rs b/crates/matrix-sdk-crypto/src/verification/cache.rs index 9802b8e4627..0b99fa26437 100644 --- a/crates/matrix-sdk-crypto/src/verification/cache.rs +++ b/crates/matrix-sdk-crypto/src/verification/cache.rs @@ -16,7 +16,7 @@ use std::{collections::BTreeMap, sync::Arc}; use as_variant::as_variant; use matrix_sdk_common::locks::RwLock as StdRwLock; -use ruma::{DeviceId, OwnedTransactionId, OwnedUserId, TransactionId, UserId}; +use ruma::{DeviceId, TransactionId, UserId}; #[cfg(feature = "qrcode")] use tracing::debug; use tracing::{trace, warn}; @@ -51,15 +51,15 @@ fn test_send_sync_for_room() { #[derive(Debug, Default)] struct VerificationCacheInner { - verification: StdRwLock>>, - outgoing_requests: StdRwLock>, - flow_ids_waiting_for_response: StdRwLock>, + verification: StdRwLock>>, + outgoing_requests: StdRwLock>, + flow_ids_waiting_for_response: StdRwLock>, } #[derive(Debug)] pub struct RequestInfo { pub flow_id: FlowId, - pub request_id: OwnedTransactionId, + pub request_id: TransactionId, } impl VerificationCache { diff --git a/crates/matrix-sdk-crypto/src/verification/event_enums.rs b/crates/matrix-sdk-crypto/src/verification/event_enums.rs index 0d120cb5f9c..f50cca1486c 100644 --- a/crates/matrix-sdk-crypto/src/verification/event_enums.rs +++ b/crates/matrix-sdk-crypto/src/verification/event_enums.rs @@ -16,7 +16,7 @@ use std::collections::BTreeMap; use as_variant::as_variant; use ruma::{ - CanonicalJsonValue, DeviceId, MilliSecondsSinceUnixEpoch, OwnedRoomId, UserId, + CanonicalJsonValue, DeviceId, MilliSecondsSinceUnixEpoch, RoomId, UserId, events::{ AnyMessageLikeEvent, AnyMessageLikeEventContent, AnyToDeviceEventContent, MessageLikeEvent, key::verification::{ @@ -166,28 +166,28 @@ impl TryFrom<&AnyMessageLikeEvent> for FlowId { fn try_from(value: &AnyMessageLikeEvent) -> Result { match value { AnyMessageLikeEvent::KeyVerificationReady(MessageLikeEvent::Original(e)) => { - Ok(FlowId::from((&*e.room_id, &*e.content.relates_to.event_id))) + Ok(FlowId::from((&e.room_id, &e.content.relates_to.event_id))) } AnyMessageLikeEvent::RoomMessage(MessageLikeEvent::Original(e)) => { - Ok(FlowId::from((&*e.room_id, &*e.event_id))) + Ok(FlowId::from((&e.room_id, &e.event_id))) } AnyMessageLikeEvent::KeyVerificationStart(MessageLikeEvent::Original(e)) => { - Ok(FlowId::from((&*e.room_id, &*e.content.relates_to.event_id))) + Ok(FlowId::from((&e.room_id, &e.content.relates_to.event_id))) } AnyMessageLikeEvent::KeyVerificationCancel(MessageLikeEvent::Original(e)) => { - Ok(FlowId::from((&*e.room_id, &*e.content.relates_to.event_id))) + Ok(FlowId::from((&e.room_id, &e.content.relates_to.event_id))) } AnyMessageLikeEvent::KeyVerificationAccept(MessageLikeEvent::Original(e)) => { - Ok(FlowId::from((&*e.room_id, &*e.content.relates_to.event_id))) + Ok(FlowId::from((&e.room_id, &e.content.relates_to.event_id))) } AnyMessageLikeEvent::KeyVerificationKey(MessageLikeEvent::Original(e)) => { - Ok(FlowId::from((&*e.room_id, &*e.content.relates_to.event_id))) + Ok(FlowId::from((&e.room_id, &e.content.relates_to.event_id))) } AnyMessageLikeEvent::KeyVerificationMac(MessageLikeEvent::Original(e)) => { - Ok(FlowId::from((&*e.room_id, &*e.content.relates_to.event_id))) + Ok(FlowId::from((&e.room_id, &e.content.relates_to.event_id))) } AnyMessageLikeEvent::KeyVerificationDone(MessageLikeEvent::Original(e)) => { - Ok(FlowId::from((&*e.room_id, &*e.content.relates_to.event_id))) + Ok(FlowId::from((&e.room_id, &e.content.relates_to.event_id))) } _ => Err(()), } @@ -567,7 +567,7 @@ impl CancelContent<'_> { #[derive(Clone, Debug)] pub enum OwnedStartContent { ToDevice(ToDeviceKeyVerificationStartEventContent), - Room(OwnedRoomId, KeyVerificationStartEventContent), + Room(RoomId, KeyVerificationStartEventContent), } impl OwnedStartContent { @@ -609,8 +609,8 @@ impl OwnedStartContent { } } -impl From<(OwnedRoomId, KeyVerificationStartEventContent)> for OwnedStartContent { - fn from(tuple: (OwnedRoomId, KeyVerificationStartEventContent)) -> Self { +impl From<(RoomId, KeyVerificationStartEventContent)> for OwnedStartContent { + fn from(tuple: (RoomId, KeyVerificationStartEventContent)) -> Self { Self::Room(tuple.0, tuple.1) } } @@ -624,7 +624,7 @@ impl From for OwnedStartContent { #[derive(Clone, Debug)] pub enum OwnedAcceptContent { ToDevice(ToDeviceKeyVerificationAcceptEventContent), - Room(OwnedRoomId, KeyVerificationAcceptEventContent), + Room(RoomId, KeyVerificationAcceptEventContent), } impl From for OwnedAcceptContent { @@ -633,8 +633,8 @@ impl From for OwnedAcceptContent { } } -impl From<(OwnedRoomId, KeyVerificationAcceptEventContent)> for OwnedAcceptContent { - fn from(content: (OwnedRoomId, KeyVerificationAcceptEventContent)) -> Self { +impl From<(RoomId, KeyVerificationAcceptEventContent)> for OwnedAcceptContent { + fn from(content: (RoomId, KeyVerificationAcceptEventContent)) -> Self { Self::Room(content.0, content.1) } } @@ -650,7 +650,7 @@ impl OwnedAcceptContent { #[derive(Clone, Debug)] pub enum OutgoingContent { - Room(OwnedRoomId, Box), + Room(RoomId, Box), ToDevice(Box), } @@ -673,14 +673,14 @@ impl From for OutgoingContent { } } -impl From<(OwnedRoomId, AnyMessageLikeEventContent)> for OutgoingContent { - fn from(content: (OwnedRoomId, AnyMessageLikeEventContent)) -> Self { +impl From<(RoomId, AnyMessageLikeEventContent)> for OutgoingContent { + fn from(content: (RoomId, AnyMessageLikeEventContent)) -> Self { OutgoingContent::Room(content.0, Box::new(content.1)) } } -impl From<(OwnedRoomId, Box)> for OutgoingContent { - fn from(content: (OwnedRoomId, Box)) -> Self { +impl From<(RoomId, Box)> for OutgoingContent { + fn from(content: (RoomId, Box)) -> Self { OutgoingContent::Room(content.0, content.1) } } diff --git a/crates/matrix-sdk-crypto/src/verification/machine.rs b/crates/matrix-sdk-crypto/src/verification/machine.rs index 4201c2a588d..2d5ee58fc9f 100644 --- a/crates/matrix-sdk-crypto/src/verification/machine.rs +++ b/crates/matrix-sdk-crypto/src/verification/machine.rs @@ -16,8 +16,8 @@ use std::{collections::HashMap, sync::Arc}; use matrix_sdk_common::locks::RwLock as StdRwLock; use ruma::{ - DeviceId, EventId, MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedUserId, RoomId, - SecondsSinceUnixEpoch, TransactionId, UInt, UserId, + DeviceId, EventId, MilliSecondsSinceUnixEpoch, RoomId, SecondsSinceUnixEpoch, TransactionId, + UInt, UserId, events::{ AnyToDeviceEvent, AnyToDeviceEventContent, ToDeviceEvent, key::verification::VerificationMethod, @@ -48,7 +48,7 @@ use crate::{ pub struct VerificationMachine { pub(crate) store: VerificationStore, verifications: VerificationCache, - requests: Arc>>>, + requests: Arc>>>, } impl VerificationMachine { @@ -75,7 +75,7 @@ impl VerificationMachine { pub(crate) fn request_to_device_verification( &self, user_id: &UserId, - recipient_devices: Vec, + recipient_devices: Vec, methods: Option>, ) -> (VerificationRequest, OutgoingVerificationRequest) { let flow_id = FlowId::from(TransactionId::new()); diff --git a/crates/matrix-sdk-crypto/src/verification/mod.rs b/crates/matrix-sdk-crypto/src/verification/mod.rs index 00ad8dda987..d54c115c765 100644 --- a/crates/matrix-sdk-crypto/src/verification/mod.rs +++ b/crates/matrix-sdk-crypto/src/verification/mod.rs @@ -33,8 +33,7 @@ use ruma::events::key::verification::done::{ KeyVerificationDoneEventContent, ToDeviceKeyVerificationDoneEventContent, }; use ruma::{ - DeviceId, EventId, OwnedDeviceId, OwnedEventId, OwnedRoomId, OwnedTransactionId, RoomId, - UserId, + DeviceId, EventId, RoomId, TransactionId, UserId, api::client::keys::upload_signatures::v3::Request as SignatureUploadRequest, events::{ AnyMessageLikeEventContent, AnyToDeviceEventContent, @@ -161,7 +160,7 @@ impl VerificationStore { pub async fn get_user_devices( &self, user_id: &UserId, - ) -> Result, CryptoStoreError> { + ) -> Result, CryptoStoreError> { self.inner.get_user_devices(user_id).await } @@ -408,10 +407,10 @@ impl Cancelled { #[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd)] pub enum FlowId { /// The flow ID comes from a to-device request. - ToDevice(OwnedTransactionId), + ToDevice(TransactionId), /// The flow ID comes from a room event. - InRoom(OwnedRoomId, OwnedEventId), + InRoom(RoomId, EventId), } impl FlowId { @@ -429,14 +428,14 @@ impl FlowId { } } -impl From for FlowId { - fn from(transaction_id: OwnedTransactionId) -> Self { +impl From for FlowId { + fn from(transaction_id: TransactionId) -> Self { Self::ToDevice(transaction_id) } } -impl From<(OwnedRoomId, OwnedEventId)> for FlowId { - fn from(ids: (OwnedRoomId, OwnedEventId)) -> Self { +impl From<(RoomId, EventId)> for FlowId { + fn from(ids: (RoomId, EventId)) -> Self { Self::InRoom(ids.0, ids.1) } } diff --git a/crates/matrix-sdk-crypto/src/verification/qrcode.rs b/crates/matrix-sdk-crypto/src/verification/qrcode.rs index 7af54fa7b10..9bec9b892b5 100644 --- a/crates/matrix-sdk-crypto/src/verification/qrcode.rs +++ b/crates/matrix-sdk-crypto/src/verification/qrcode.rs @@ -24,7 +24,7 @@ use matrix_sdk_qrcode::{ }; use rand::{RngCore, thread_rng}; use ruma::{ - DeviceId, OwnedDeviceId, OwnedUserId, RoomId, TransactionId, UserId, + DeviceId, RoomId, TransactionId, UserId, api::client::keys::upload_signatures::v3::Request as SignatureUploadRequest, events::{ AnyMessageLikeEventContent, AnyToDeviceEventContent, @@ -76,11 +76,11 @@ pub enum ScanError { /// One of the users that is participating in this verification doesn't have /// a valid cross signing identity. #[error("The user {0} is missing a valid cross signing identity")] - MissingCrossSigningIdentity(OwnedUserId), + MissingCrossSigningIdentity(UserId), /// The device of the user that is participating in this verification /// doesn't have a valid device key. #[error("The user's {0} device {1} is not E2E capable")] - MissingDeviceKeys(OwnedUserId, OwnedDeviceId), + MissingDeviceKeys(UserId, DeviceId), /// The ID uniquely identifying this verification flow didn't match to the /// one that has been scanned. #[error("The unique verification flow id did not match (expected {expected}, found {found})")] @@ -566,8 +566,8 @@ impl QrVerification { pub(crate) async fn from_scan( store: VerificationStore, - other_user_id: OwnedUserId, - other_device_id: OwnedDeviceId, + other_user_id: UserId, + other_device_id: DeviceId, flow_id: FlowId, qr_code: QrVerificationData, we_started: bool, @@ -752,7 +752,7 @@ struct Confirmed {} #[derive(Clone, Debug)] struct Reciprocated { - own_device_id: OwnedDeviceId, + own_device_id: DeviceId, secret: Base64, } diff --git a/crates/matrix-sdk-crypto/src/verification/requests.rs b/crates/matrix-sdk-crypto/src/verification/requests.rs index 07b07f15785..cfd294d9468 100644 --- a/crates/matrix-sdk-crypto/src/verification/requests.rs +++ b/crates/matrix-sdk-crypto/src/verification/requests.rs @@ -21,8 +21,7 @@ use futures_util::StreamExt; #[cfg(feature = "qrcode")] use matrix_sdk_qrcode::QrVerificationData; use ruma::{ - DeviceId, MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedUserId, RoomId, TransactionId, - UserId, + DeviceId, MilliSecondsSinceUnixEpoch, RoomId, TransactionId, UserId, events::{ AnyMessageLikeEventContent, AnyToDeviceEventContent, key::verification::{ @@ -153,11 +152,11 @@ pub struct VerificationRequest { verification_cache: VerificationCache, account: StaticAccountData, flow_id: Arc, - other_user_id: OwnedUserId, + other_user_id: UserId, inner: SharedObservable, creation_time: Arc, we_started: bool, - recipient_devices: Arc>, + recipient_devices: Arc>, } /// A handle to a request so child verification flows can cancel the request. @@ -199,7 +198,7 @@ impl VerificationRequest { store: VerificationStore, flow_id: FlowId, other_user: &UserId, - recipient_devices: Vec, + recipient_devices: Vec, methods: Option>, ) -> Self { let account = store.account.clone(); @@ -285,7 +284,7 @@ impl VerificationRequest { } /// The id of the other device that is participating in this verification. - pub fn other_device_id(&self) -> Option { + pub fn other_device_id(&self) -> Option { match &*self.inner.read() { InnerRequest::Requested(r) => Some(r.state.other_device_data.device_id().to_owned()), InnerRequest::Ready(r) => Some(r.state.other_device_data.device_id().to_owned()), @@ -655,10 +654,10 @@ impl VerificationRequest { let cancel_content = cancelled.as_content(self.flow_id()); let OutgoingContent::ToDevice(c) = cancel_content else { return None }; - let recip_devices: Vec = self + let recip_devices: Vec = self .recipient_devices .iter() - .filter(|&d| filter_device.is_none_or(|device| **d != *device)) + .filter(|&d| filter_device.is_none_or(|device| *d != *device)) .cloned() .collect(); @@ -1004,7 +1003,7 @@ struct RequestState { flow_id: Arc, /// The id of the user which is participating in this verification request. - pub other_user_id: OwnedUserId, + pub other_user_id: UserId, /// The verification request state we are in. state: S, @@ -1615,7 +1614,7 @@ impl RequestState { struct Passive { /// The device ID of the device that responded to the verification request. #[allow(dead_code)] - pub other_device_id: OwnedDeviceId, + pub other_device_id: DeviceId, } #[derive(Clone, Debug)] diff --git a/crates/matrix-sdk-crypto/src/verification/sas/helpers.rs b/crates/matrix-sdk-crypto/src/verification/sas/helpers.rs index 62ecc062c8d..94711549d74 100644 --- a/crates/matrix-sdk-crypto/src/verification/sas/helpers.rs +++ b/crates/matrix-sdk-crypto/src/verification/sas/helpers.rs @@ -15,7 +15,7 @@ use std::collections::BTreeMap; use ruma::{ - DeviceKeyAlgorithm, DeviceKeyId, OwnedDeviceKeyId, UserId, + DeviceKeyAlgorithm, DeviceKeyId, UserId, events::{ AnyMessageLikeEventContent, AnyToDeviceEventContent, key::verification::{ @@ -223,7 +223,7 @@ pub fn receive_mac_event( "Checking a SAS MAC", ); - let key_id: OwnedDeviceKeyId = match key_id.as_str().try_into() { + let key_id: DeviceKeyId = match key_id.as_str().try_into() { Ok(id) => id, Err(_) => continue, }; diff --git a/crates/matrix-sdk-crypto/src/verification/sas/mod.rs b/crates/matrix-sdk-crypto/src/verification/sas/mod.rs index d2af9c83991..cd746ccbf60 100644 --- a/crates/matrix-sdk-crypto/src/verification/sas/mod.rs +++ b/crates/matrix-sdk-crypto/src/verification/sas/mod.rs @@ -24,7 +24,7 @@ use futures_core::Stream; use futures_util::StreamExt; use inner_sas::InnerSas; use ruma::{ - DeviceId, OwnedEventId, OwnedRoomId, OwnedTransactionId, RoomId, TransactionId, UserId, + DeviceId, EventId, RoomId, TransactionId, UserId, api::client::keys::upload_signatures::v3::Request as SignatureUploadRequest, events::{ AnyMessageLikeEventContent, AnyToDeviceEventContent, @@ -358,7 +358,7 @@ impl Sas { /// sent out through the server to the other device. pub(crate) fn start( identities: IdentitiesBeingVerified, - transaction_id: OwnedTransactionId, + transaction_id: TransactionId, we_started: bool, request_handle: Option, short_auth_strings: Option>, @@ -380,8 +380,8 @@ impl Sas { /// sent out through the server to the other device. #[allow(clippy::too_many_arguments)] pub(crate) fn start_in_room( - flow_id: OwnedEventId, - room_id: OwnedRoomId, + flow_id: EventId, + room_id: RoomId, identities: IdentitiesBeingVerified, we_started: bool, request_handle: RequestHandle, diff --git a/crates/matrix-sdk-crypto/src/verification/sas/sas_state.rs b/crates/matrix-sdk-crypto/src/verification/sas/sas_state.rs index 12ab996acda..5f68cb75d5c 100644 --- a/crates/matrix-sdk-crypto/src/verification/sas/sas_state.rs +++ b/crates/matrix-sdk-crypto/src/verification/sas/sas_state.rs @@ -16,7 +16,7 @@ use std::{matches, sync::Arc, time::Duration}; use matrix_sdk_common::locks::Mutex; use ruma::{ - DeviceId, OwnedTransactionId, TransactionId, UserId, + DeviceId, TransactionId, UserId, events::{ AnyMessageLikeEventContent, AnyToDeviceEventContent, key::verification::{ @@ -389,7 +389,7 @@ pub struct Started { pub struct Accepted { pub accepted_protocols: AcceptedProtocols, start_content: Arc, - pub request_id: OwnedTransactionId, + pub request_id: TransactionId, commitment: Base64, } @@ -410,7 +410,7 @@ pub struct WeAccepted { pub struct KeyReceived { sas: Arc>, we_started: bool, - pub request_id: OwnedTransactionId, + pub request_id: TransactionId, pub accepted_protocols: AcceptedProtocols, } diff --git a/crates/matrix-sdk-indexeddb/src/crypto_store/migrations/mod.rs b/crates/matrix-sdk-indexeddb/src/crypto_store/migrations/mod.rs index d1e10ba6daf..979d79c8123 100644 --- a/crates/matrix-sdk-indexeddb/src/crypto_store/migrations/mod.rs +++ b/crates/matrix-sdk-indexeddb/src/crypto_store/migrations/mod.rs @@ -285,7 +285,7 @@ mod tests { }; use matrix_sdk_store_encryption::StoreCipher; use matrix_sdk_test::async_test; - use ruma::{OwnedRoomId, RoomId, owned_device_id, owned_user_id, room_id}; + use ruma::{RoomId, owned_device_id, owned_user_id, room_id}; use serde::Serialize; use tracing_subscriber::util::SubscriberInitExt; use wasm_bindgen::JsValue; @@ -519,7 +519,7 @@ mod tests { 24, 25, 26, 27, 28, 29, 30, 31, ]) .unwrap(); - let room_id: OwnedRoomId = format!("!a{i}:b.co").try_into().unwrap(); + let room_id: RoomId = format!("!a{i}:b.co").try_into().unwrap(); let encryption_algorithm = EventEncryptionAlgorithm::MegolmV1AesSha2; let history_visibility = None; diff --git a/crates/matrix-sdk-indexeddb/src/crypto_store/mod.rs b/crates/matrix-sdk-indexeddb/src/crypto_store/mod.rs index c7b6fc2e11d..dc67574987d 100644 --- a/crates/matrix-sdk-indexeddb/src/crypto_store/mod.rs +++ b/crates/matrix-sdk-indexeddb/src/crypto_store/mod.rs @@ -51,7 +51,7 @@ use matrix_sdk_crypto::{ }; use matrix_sdk_store_encryption::StoreCipher; use ruma::{ - DeviceId, MilliSecondsSinceUnixEpoch, OwnedDeviceId, RoomId, TransactionId, UserId, + DeviceId, MilliSecondsSinceUnixEpoch, RoomId, TransactionId, UserId, events::secret::request::SecretName, }; use serde::{Deserialize, Serialize}; @@ -1300,7 +1300,7 @@ impl_crypto_store! { async fn get_user_devices( &self, user_id: &UserId, - ) -> Result> { + ) -> Result> { let range = self.serializer.encode_to_range(keys::DEVICES, user_id); Ok(self .inner diff --git a/crates/matrix-sdk-indexeddb/src/event_cache_store/mod.rs b/crates/matrix-sdk-indexeddb/src/event_cache_store/mod.rs index efa87d9f030..ac9ab4571dd 100644 --- a/crates/matrix-sdk-indexeddb/src/event_cache_store/mod.rs +++ b/crates/matrix-sdk-indexeddb/src/event_cache_store/mod.rs @@ -29,9 +29,7 @@ use matrix_sdk_base::{ }, timer, }; -use ruma::{ - EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, RoomId, events::relation::RelationType, -}; +use ruma::{EventId, MilliSecondsSinceUnixEpoch, RoomId, events::relation::RelationType}; use tracing::{error, instrument, trace}; use web_sys::IdbTransactionMode; @@ -434,8 +432,8 @@ impl EventCacheStore for IndexeddbEventCacheStore { async fn filter_duplicated_events( &self, linked_chunk_id: LinkedChunkId<'_>, - events: Vec, - ) -> Result, IndexeddbEventCacheStoreError> { + events: Vec, + ) -> Result, IndexeddbEventCacheStoreError> { let _timer = timer!("method"); if events.is_empty() { diff --git a/crates/matrix-sdk-indexeddb/src/event_cache_store/types.rs b/crates/matrix-sdk-indexeddb/src/event_cache_store/types.rs index 69afee898e3..3a63818167c 100644 --- a/crates/matrix-sdk-indexeddb/src/event_cache_store/types.rs +++ b/crates/matrix-sdk-indexeddb/src/event_cache_store/types.rs @@ -20,7 +20,7 @@ use matrix_sdk_base::{ event_cache::store::extract_event_relation, linked_chunk::{ChunkIdentifier, LinkedChunkId, OwnedLinkedChunkId}, }; -use ruma::{OwnedEventId, RoomId}; +use ruma::{EventId, RoomId}; use serde::{Deserialize, Serialize}; /// Representation of a time-based lock on the entire @@ -101,8 +101,8 @@ impl Event { } } - /// The [`OwnedEventId`] of the underlying event. - pub fn event_id(&self) -> Option { + /// The [`EventId`] of the underlying event. + pub fn event_id(&self) -> Option { match self { Event::InBand(e) => e.event_id(), Event::OutOfBand(e) => e.event_id(), @@ -117,10 +117,10 @@ impl Event { } } - /// The [`OwnedEventId`] and + /// The [`EventId`] and /// [`RelationType`](ruma::events::relation::RelationType) of the underlying /// event as a [`String`]. - pub fn relation(&self) -> Option<(OwnedEventId, String)> { + pub fn relation(&self) -> Option<(EventId, String)> { match self { Event::InBand(e) => e.relation(), Event::OutOfBand(e) => e.relation(), @@ -160,16 +160,16 @@ impl

GenericEvent

{ self.linked_chunk_id.room_id() } - /// The [`OwnedEventId`] of the underlying event. - pub fn event_id(&self) -> Option { + /// The [`EventId`] of the underlying event. + pub fn event_id(&self) -> Option { self.content.event_id() } /// The event that the underlying event relates to, if any. /// - /// Returns the related [`OwnedEventId`] and the + /// Returns the related [`EventId`] and the /// [`RelationType`](ruma::events::relation::RelationType) as a [`String`]. - pub fn relation(&self) -> Option<(OwnedEventId, String)> { + pub fn relation(&self) -> Option<(EventId, String)> { extract_event_relation(self.content.raw()) } } diff --git a/crates/matrix-sdk-indexeddb/src/serializer/safe_encode/traits.rs b/crates/matrix-sdk-indexeddb/src/serializer/safe_encode/traits.rs index a5c276e50e3..08873c115a2 100644 --- a/crates/matrix-sdk-indexeddb/src/serializer/safe_encode/traits.rs +++ b/crates/matrix-sdk-indexeddb/src/serializer/safe_encode/traits.rs @@ -7,8 +7,7 @@ use base64::{ use indexed_db_futures::KeyRange; use matrix_sdk_store_encryption::StoreCipher; use ruma::{ - DeviceId, EventId, MxcUri, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId, TransactionId, - UserId, + DeviceId, EventId, MxcUri, RoomId, TransactionId, UserId, events::{ GlobalAccountDataEventType, RoomAccountDataEventType, StateEventType, receipt::ReceiptType, }, @@ -273,25 +272,12 @@ impl SafeEncode for RoomId { self.as_str().as_encoded_string() } } - -impl SafeEncode for OwnedRoomId { - fn as_encoded_string(&self) -> String { - self.as_str().as_encoded_string() - } -} - impl SafeEncode for UserId { fn as_encoded_string(&self) -> String { self.as_str().as_encoded_string() } } -impl SafeEncode for OwnedUserId { - fn as_encoded_string(&self) -> String { - self.as_str().as_encoded_string() - } -} - impl SafeEncode for DeviceId { fn as_encoded_string(&self) -> String { self.as_str().as_encoded_string() @@ -304,12 +290,6 @@ impl SafeEncode for EventId { } } -impl SafeEncode for OwnedEventId { - fn as_encoded_string(&self) -> String { - self.as_str().as_encoded_string() - } -} - impl SafeEncode for MxcUri { fn as_encoded_string(&self) -> String { self.as_str().as_encoded_string() diff --git a/crates/matrix-sdk-indexeddb/src/state_store/migrations.rs b/crates/matrix-sdk-indexeddb/src/state_store/migrations.rs index aa80a2c70c8..9fe8d47db21 100644 --- a/crates/matrix-sdk-indexeddb/src/state_store/migrations.rs +++ b/crates/matrix-sdk-indexeddb/src/state_store/migrations.rs @@ -861,7 +861,7 @@ mod tests { }; use matrix_sdk_test::{async_test, event_factory::EventFactory}; use ruma::{ - EventId, MilliSecondsSinceUnixEpoch, OwnedUserId, RoomId, UserId, + EventId, MilliSecondsSinceUnixEpoch, RoomId, UserId, events::{ AnySyncStateEvent, StateEventType, room::{ @@ -1570,11 +1570,11 @@ mod tests { room_state_store: &ObjectStore<'_>, room_id: &RoomId, name: Option<&str>, - create_creator: Option, + create_creator: Option, create_sender: Option<&UserId>, ) -> Result<()> { let room_info_json = - room_info_v1_json(room_id, RoomState::Joined, name, create_creator.as_deref()); + room_info_v1_json(room_id, RoomState::Joined, name, create_creator.as_ref()); room_infos_store .put(&serialize_value(None, &room_info_json)?) diff --git a/crates/matrix-sdk-indexeddb/src/state_store/mod.rs b/crates/matrix-sdk-indexeddb/src/state_store/mod.rs index e66b83b769b..5f11ba47575 100644 --- a/crates/matrix-sdk-indexeddb/src/state_store/mod.rs +++ b/crates/matrix-sdk-indexeddb/src/state_store/mod.rs @@ -39,8 +39,8 @@ use matrix_sdk_base::{ }; use matrix_sdk_store_encryption::{Error as EncryptionError, StoreCipher}; use ruma::{ - CanonicalJsonObject, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedMxcUri, - OwnedRoomId, OwnedTransactionId, OwnedUserId, RoomId, TransactionId, UserId, + CanonicalJsonObject, EventId, MilliSecondsSinceUnixEpoch, MxcUri, RoomId, TransactionId, + UserId, canonical_json::{RedactedBecause, redact}, events::{ AnyGlobalAccountDataEvent, AnyRoomAccountDataEvent, AnySyncStateEvent, @@ -411,7 +411,7 @@ impl IndexeddbStateStore { room_id: &RoomId, memberships: RoomMemberships, stripped: bool, - ) -> Result> { + ) -> Result> { let store_name = if stripped { keys::STRIPPED_USER_IDS } else { keys::USER_IDS }; let tx = self.inner.transaction(store_name).with_mode(TransactionMode::Readonly).build()?; @@ -514,12 +514,12 @@ impl IndexeddbStateStore { #[derive(Serialize, Deserialize)] struct PersistedQueuedRequest { /// In which room is this event going to be sent. - pub room_id: OwnedRoomId, + pub room_id: RoomId, // All these fields are the same as in [`QueuedRequest`]. /// Kind. Optional because it might be missing from previous formats. kind: Option, - transaction_id: OwnedTransactionId, + transaction_id: TransactionId, pub error: Option, @@ -640,11 +640,11 @@ impl_state_store!({ .transpose()? .map(StateStoreDataValue::Filter), StateStoreDataKey::UserAvatarUrl(_) => value - .map(|f| self.deserialize_value::(&f)) + .map(|f| self.deserialize_value::(&f)) .transpose()? .map(StateStoreDataValue::UserAvatarUrl), StateStoreDataKey::RecentlyVisitedRooms(_) => value - .map(|f| self.deserialize_value::>(&f)) + .map(|f| self.deserialize_value::>(&f)) .transpose()? .map(StateStoreDataValue::RecentlyVisitedRooms), StateStoreDataKey::UtdHookManagerData => value @@ -660,7 +660,7 @@ impl_state_store!({ .transpose()? .map(StateStoreDataValue::ComposerDraft), StateStoreDataKey::SeenKnockRequests(_) => value - .map(|f| self.deserialize_value::>(&f)) + .map(|f| self.deserialize_value::>(&f)) .transpose()? .map(StateStoreDataValue::SeenKnockRequests), StateStoreDataKey::ThreadSubscriptionsCatchupTokens => value @@ -982,10 +982,10 @@ impl_state_store!({ ), }; - if let Some((old_event, _)) = - room_user_receipts.get(&key).await?.and_then(|f| { - self.deserialize_value::<(OwnedEventId, Receipt)>(&f).ok() - }) + if let Some((old_event, _)) = room_user_receipts + .get(&key) + .await? + .and_then(|f| self.deserialize_value::<(EventId, Receipt)>(&f).ok()) { let key = match receipt.thread.as_str() { Some(thread_id) => self.encode_key( @@ -1044,7 +1044,7 @@ impl_state_store!({ }; let raw_evt = self.deserialize_value::>(&value)?; - if let Ok(Some(event_id)) = raw_evt.get_field::("event_id") + if let Ok(Some(event_id)) = raw_evt.get_field::("event_id") && let Some(redaction) = redactions.get(&event_id) { let redaction_rules = match &redaction_rules { @@ -1096,10 +1096,7 @@ impl_state_store!({ .transpose() } - async fn get_presence_events( - &self, - user_ids: &[OwnedUserId], - ) -> Result>> { + async fn get_presence_events(&self, user_ids: &[UserId]) -> Result>> { if user_ids.is_empty() { return Ok(Vec::new()); } @@ -1258,7 +1255,7 @@ impl_state_store!({ async fn get_profiles<'a>( &self, room_id: &RoomId, - user_ids: &'a [OwnedUserId], + user_ids: &'a [UserId], ) -> Result> { if user_ids.is_empty() { return Ok(BTreeMap::new()); @@ -1276,7 +1273,7 @@ impl_state_store!({ .map(|f| self.deserialize_value(&f)) .transpose()? { - profiles.insert(user_id.as_ref(), profile); + profiles.insert(user_id, profile); } } @@ -1312,7 +1309,7 @@ impl_state_store!({ &self, room_id: &RoomId, display_name: &DisplayName, - ) -> Result> { + ) -> Result> { self.inner .transaction(keys::DISPLAY_NAMES) .with_mode(TransactionMode::Readonly) @@ -1326,7 +1323,7 @@ impl_state_store!({ ), )) .await? - .map(|f| self.deserialize_value::>(&f)) + .map(|f| self.deserialize_value::>(&f)) .unwrap_or_else(|| Ok(Default::default())) } @@ -1334,7 +1331,7 @@ impl_state_store!({ &self, room_id: &RoomId, display_names: &'a [DisplayName], - ) -> Result>> { + ) -> Result>> { let mut map = HashMap::new(); if display_names.is_empty() { @@ -1362,7 +1359,7 @@ impl_state_store!({ ), ) .await? - .map(|f| self.deserialize_value::>(&f)) + .map(|f| self.deserialize_value::>(&f)) .transpose()? { map.insert(display_name, user_ids); @@ -1409,7 +1406,7 @@ impl_state_store!({ receipt_type: ReceiptType, thread: ReceiptThread, user_id: &UserId, - ) -> Result> { + ) -> Result> { let key = match thread.as_str() { Some(thread_id) => self .encode_key(keys::ROOM_USER_RECEIPTS, (room_id, receipt_type, thread_id, user_id)), @@ -1432,7 +1429,7 @@ impl_state_store!({ receipt_type: ReceiptType, thread: ReceiptThread, event_id: &EventId, - ) -> Result> { + ) -> Result> { let range = match thread.as_str() { Some(thread_id) => self.encode_to_range( keys::ROOM_EVENT_RECEIPTS, @@ -1542,7 +1539,7 @@ impl_state_store!({ &self, room_id: &RoomId, memberships: RoomMemberships, - ) -> Result> { + ) -> Result> { let ids = self.get_user_ids_inner(room_id, memberships, true).await?; if !ids.is_empty() { return Ok(ids); @@ -1553,7 +1550,7 @@ impl_state_store!({ async fn save_send_queue_request( &self, room_id: &RoomId, - transaction_id: OwnedTransactionId, + transaction_id: TransactionId, created_at: MilliSecondsSinceUnixEpoch, kind: QueuedRequestKind, priority: usize, @@ -1740,7 +1737,7 @@ impl_state_store!({ Ok(()) } - async fn load_rooms_with_unsent_requests(&self) -> Result> { + async fn load_rooms_with_unsent_requests(&self) -> Result> { let tx = self .inner .transaction(keys::ROOM_SEND_QUEUE) @@ -2050,7 +2047,7 @@ impl_state_store!({ /// A room member. #[derive(Debug, Serialize, Deserialize)] struct RoomMember { - user_id: OwnedUserId, + user_id: UserId, membership: MembershipState, } @@ -2070,19 +2067,16 @@ impl From<&StrippedRoomMemberEvent> for RoomMember { mod migration_tests { use assert_matches2::assert_matches; use matrix_sdk_base::store::{QueuedRequestKind, SerializableEventContent}; - use ruma::{ - OwnedRoomId, OwnedTransactionId, TransactionId, - events::room::message::RoomMessageEventContent, room_id, - }; + use ruma::{RoomId, TransactionId, events::room::message::RoomMessageEventContent, room_id}; use serde::{Deserialize, Serialize}; use crate::state_store::PersistedQueuedRequest; #[derive(Serialize, Deserialize)] struct OldPersistedQueuedRequest { - room_id: OwnedRoomId, + room_id: RoomId, event: SerializableEventContent, - transaction_id: OwnedTransactionId, + transaction_id: TransactionId, is_wedged: bool, } diff --git a/crates/matrix-sdk-search/src/index/builder.rs b/crates/matrix-sdk-search/src/index/builder.rs index ed3fef8540b..6cb25d3f12e 100644 --- a/crates/matrix-sdk-search/src/index/builder.rs +++ b/crates/matrix-sdk-search/src/index/builder.rs @@ -1,6 +1,6 @@ use std::{fs, path::PathBuf, sync::Arc}; -use ruma::OwnedRoomId; +use ruma::RoomId; use tantivy::{ Index, directory::{MmapDirectory, error::OpenDirectoryError}, @@ -19,15 +19,12 @@ pub struct RoomIndexBuilder {} impl RoomIndexBuilder { /// Make an index on disk - pub fn new_on_disk>( - path: PathBuf, - room_id: R, - ) -> PhysicalRoomIndexBuilder { + pub fn new_on_disk>(path: PathBuf, room_id: R) -> PhysicalRoomIndexBuilder { PhysicalRoomIndexBuilder::new(path, room_id.into()) } /// Make an index in memory - pub fn new_in_memory>(room_id: R) -> MemoryRoomIndexBuilder { + pub fn new_in_memory>(room_id: R) -> MemoryRoomIndexBuilder { MemoryRoomIndexBuilder::new(room_id.into()) } } @@ -35,12 +32,12 @@ impl RoomIndexBuilder { /// Incomplete builder for [`RoomIndex`] on disk. pub struct PhysicalRoomIndexBuilder { path: PathBuf, - room_id: OwnedRoomId, + room_id: RoomId, } impl PhysicalRoomIndexBuilder { /// Make an new [`PhysicalRoomIndexBuilder`] - pub(crate) fn new(path: PathBuf, room_id: OwnedRoomId) -> PhysicalRoomIndexBuilder { + pub(crate) fn new(path: PathBuf, room_id: RoomId) -> PhysicalRoomIndexBuilder { PhysicalRoomIndexBuilder { path, room_id } } @@ -65,7 +62,7 @@ impl PhysicalRoomIndexBuilder { /// Complete builder for [`RoomIndex`] on disk. pub struct UnencryptedPhysicalRoomIndexBuilder { path: PathBuf, - room_id: OwnedRoomId, + room_id: RoomId, } impl UnencryptedPhysicalRoomIndexBuilder { @@ -96,7 +93,7 @@ impl UnencryptedPhysicalRoomIndexBuilder { /// Complete builder for [`RoomIndex`] on disk. pub struct EncryptedPhysicalRoomIndexBuilder { path: PathBuf, - room_id: OwnedRoomId, + room_id: RoomId, password: Zeroizing, } @@ -128,12 +125,12 @@ impl EncryptedPhysicalRoomIndexBuilder { /// Builder for [`RoomIndex`] in memory pub struct MemoryRoomIndexBuilder { - room_id: OwnedRoomId, + room_id: RoomId, } impl MemoryRoomIndexBuilder { /// Make an new [`MemoryIndexBuilder`] - pub(crate) fn new(room_id: OwnedRoomId) -> MemoryRoomIndexBuilder { + pub(crate) fn new(room_id: RoomId) -> MemoryRoomIndexBuilder { MemoryRoomIndexBuilder { room_id } } diff --git a/crates/matrix-sdk-search/src/index/mod.rs b/crates/matrix-sdk-search/src/index/mod.rs index 2ce7b2b1667..53ad547d2f4 100644 --- a/crates/matrix-sdk-search/src/index/mod.rs +++ b/crates/matrix-sdk-search/src/index/mod.rs @@ -17,9 +17,7 @@ pub mod builder; use std::{collections::HashSet, fmt}; -use ruma::{ - EventId, OwnedEventId, OwnedRoomId, RoomId, events::room::message::OriginalSyncRoomMessageEvent, -}; +use ruma::{EventId, RoomId, events::room::message::OriginalSyncRoomMessageEvent}; use tantivy::{ Index, IndexReader, TantivyDocument, collector::TopDocs, directory::error::OpenDirectoryError, query::QueryParser, schema::Value, @@ -40,11 +38,11 @@ pub enum RoomIndexOperation { Add(OriginalSyncRoomMessageEvent), /// Remove all documents in the index where /// `MatrixSearchIndexSchema::deletion_key()` matches this event id. - Remove(OwnedEventId), + Remove(EventId), /// Replace all documents in the index where /// `MatrixSearchIndexSchema::deletion_key()` matches this event id with /// the new event. - Edit(OwnedEventId, OriginalSyncRoomMessageEvent), + Edit(EventId, OriginalSyncRoomMessageEvent), /// Do nothing. Noop, } @@ -55,9 +53,9 @@ pub struct RoomIndex { index: Index, schema: RoomMessageSchema, query_parser: QueryParser, - room_id: OwnedRoomId, - uncommitted_adds: HashSet, - uncommitted_removes: HashSet, + room_id: RoomId, + uncommitted_adds: HashSet, + uncommitted_removes: HashSet, } impl fmt::Debug for RoomIndex { @@ -136,7 +134,7 @@ impl RoomIndex { query: &str, max_number_of_results: usize, pagination_offset: Option, - ) -> Result, IndexError> { + ) -> Result, IndexError> { let query = self.query_parser.parse_query(query)?; let searcher = self.get_reader()?.searcher(); @@ -144,13 +142,13 @@ impl RoomIndex { let results = searcher .search(&query, &TopDocs::with_limit(max_number_of_results).and_offset(offset))?; - let mut ret: Vec = Vec::new(); + let mut ret: Vec = Vec::new(); let pk = self.schema.primary_key(); for (_score, doc_address) in results { let retrieved_doc: TantivyDocument = searcher.doc(doc_address)?; match retrieved_doc.get_first(pk).and_then(|maybe_value| maybe_value.as_str()) { - Some(value) => match OwnedEventId::try_from(value) { + Some(value) => match EventId::try_from(value) { Ok(event_id) => ret.push(event_id), Err(err) => error!("error while parsing event_id from search result: {err:?}"), }, @@ -161,10 +159,7 @@ impl RoomIndex { Ok(ret) } - fn get_events_to_be_removed( - &self, - event_id: &EventId, - ) -> Result, IndexError> { + fn get_events_to_be_removed(&self, event_id: &EventId) -> Result, IndexError> { self.search( format!("{}:\"{event_id}\"", self.schema.get_field_name(self.schema.deletion_key())) .as_str(), @@ -189,7 +184,7 @@ impl RoomIndex { fn remove( &mut self, writer: &mut SearchIndexWriter, - event_id: OwnedEventId, + event_id: EventId, ) -> Result<(), IndexError> { let events = self.get_events_to_be_removed(&event_id)?; diff --git a/crates/matrix-sdk-sqlite/migrations/event_cache_store/003_events.sql b/crates/matrix-sdk-sqlite/migrations/event_cache_store/003_events.sql index c3f8e07a098..418ebd33bd1 100644 --- a/crates/matrix-sdk-sqlite/migrations/event_cache_store/003_events.sql +++ b/crates/matrix-sdk-sqlite/migrations/event_cache_store/003_events.sql @@ -34,7 +34,7 @@ CREATE TABLE "events" ( -- Which room does this event belong to? (hashed key shared with linked_chunks) "room_id" BLOB NOT NULL, - -- `OwnedEventId` for events, can be null if malformed. + -- `EventId` for events, can be null if malformed. "event_id" TEXT, -- JSON serialized `TimelineEvent` (encrypted value). "content" BLOB NOT NULL, diff --git a/crates/matrix-sdk-sqlite/migrations/event_cache_store/006_events.sql b/crates/matrix-sdk-sqlite/migrations/event_cache_store/006_events.sql index b8ce6e04e92..a23129e9112 100644 --- a/crates/matrix-sdk-sqlite/migrations/event_cache_store/006_events.sql +++ b/crates/matrix-sdk-sqlite/migrations/event_cache_store/006_events.sql @@ -48,7 +48,7 @@ CREATE TABLE "events" ( -- Which chunk does this event refer to? Corresponds to a `ChunkIdentifier`. "chunk_id" INTEGER NOT NULL, - -- `OwnedEventId` for events. + -- `EventId` for events. "event_id" BLOB NOT NULL, -- JSON serialized `TimelineEvent` (encrypted value). "content" BLOB NOT NULL, diff --git a/crates/matrix-sdk-sqlite/migrations/event_cache_store/007_event_chunks.sql b/crates/matrix-sdk-sqlite/migrations/event_cache_store/007_event_chunks.sql index 6134cf3b3f6..e8e19525969 100644 --- a/crates/matrix-sdk-sqlite/migrations/event_cache_store/007_event_chunks.sql +++ b/crates/matrix-sdk-sqlite/migrations/event_cache_store/007_event_chunks.sql @@ -14,7 +14,7 @@ CREATE TABLE "events" ( -- The room in which the event is located. "room_id" BLOB NOT NULL, - -- The `OwnedEventId` of this event. + -- The `EventId` of this event. "event_id" BLOB NOT NULL, -- JSON serialized `TimelineEvent` (encrypted value). @@ -41,7 +41,7 @@ CREATE TABLE "event_chunks" ( -- Which chunk does this event refer to? Corresponds to a `ChunkIdentifier`. "chunk_id" INTEGER NOT NULL, - -- `OwnedEventId` for events. + -- `EventId` for events. "event_id" BLOB NOT NULL, -- Position (index) in the chunk. "position" INTEGER NOT NULL, diff --git a/crates/matrix-sdk-sqlite/migrations/event_cache_store/008_linked_chunk_id.sql b/crates/matrix-sdk-sqlite/migrations/event_cache_store/008_linked_chunk_id.sql index c15d737fea7..337aa7ce470 100644 --- a/crates/matrix-sdk-sqlite/migrations/event_cache_store/008_linked_chunk_id.sql +++ b/crates/matrix-sdk-sqlite/migrations/event_cache_store/008_linked_chunk_id.sql @@ -33,7 +33,7 @@ CREATE TABLE "event_chunks" ( -- Which chunk does this event refer to? Corresponds to a `ChunkIdentifier`. "chunk_id" INTEGER NOT NULL, - -- `OwnedEventId` for events. + -- `EventId` for events. "event_id" BLOB NOT NULL, -- Position (index) in the chunk. "position" INTEGER NOT NULL, diff --git a/crates/matrix-sdk-sqlite/migrations/event_cache_store/012_store_event_type.sql b/crates/matrix-sdk-sqlite/migrations/event_cache_store/012_store_event_type.sql index c0aeb40b5fa..bd5eac01943 100644 --- a/crates/matrix-sdk-sqlite/migrations/event_cache_store/012_store_event_type.sql +++ b/crates/matrix-sdk-sqlite/migrations/event_cache_store/012_store_event_type.sql @@ -16,7 +16,7 @@ CREATE TABLE "events" ( -- The room in which the event is located. "room_id" BLOB NOT NULL, - -- The `OwnedEventId` of this event. + -- The `EventId` of this event. "event_id" BLOB NOT NULL, -- The event type of this event. diff --git a/crates/matrix-sdk-sqlite/migrations/event_cache_store/014_event_chunks_event_id_index.sql b/crates/matrix-sdk-sqlite/migrations/event_cache_store/014_event_chunks_event_id_index.sql index 2924b305716..a8fa6b43e45 100644 --- a/crates/matrix-sdk-sqlite/migrations/event_cache_store/014_event_chunks_event_id_index.sql +++ b/crates/matrix-sdk-sqlite/migrations/event_cache_store/014_event_chunks_event_id_index.sql @@ -14,7 +14,7 @@ CREATE TABLE "event_chunks" ( -- Which chunk does this event refer to? Corresponds to a `ChunkIdentifier`. "chunk_id" INTEGER NOT NULL, - -- `OwnedEventId` for events. + -- `EventId` for events. "event_id" BLOB NOT NULL, -- Position (index) in the chunk. "position" INTEGER NOT NULL, diff --git a/crates/matrix-sdk-sqlite/src/crypto_store.rs b/crates/matrix-sdk-sqlite/src/crypto_store.rs index baa8bf988a8..f5bf5ba7532 100644 --- a/crates/matrix-sdk-sqlite/src/crypto_store.rs +++ b/crates/matrix-sdk-sqlite/src/crypto_store.rs @@ -37,7 +37,7 @@ use matrix_sdk_crypto::{ }; use matrix_sdk_store_encryption::StoreCipher; use ruma::{ - DeviceId, MilliSecondsSinceUnixEpoch, OwnedDeviceId, RoomId, TransactionId, UserId, + DeviceId, MilliSecondsSinceUnixEpoch, RoomId, TransactionId, UserId, events::secret::request::SecretName, }; use rusqlite::{OptionalExtension, named_params, params_from_iter}; @@ -1340,10 +1340,7 @@ impl CryptoStore for SqliteCryptoStore { .transpose()?) } - async fn get_user_devices( - &self, - user_id: &UserId, - ) -> Result> { + async fn get_user_devices(&self, user_id: &UserId) -> Result> { let user_id = self.encode_key("device", user_id.as_bytes()); self.read() .await? diff --git a/crates/matrix-sdk-sqlite/src/event_cache_store.rs b/crates/matrix-sdk-sqlite/src/event_cache_store.rs index 00ba2d9ab79..e6f49e8b457 100644 --- a/crates/matrix-sdk-sqlite/src/event_cache_store.rs +++ b/crates/matrix-sdk-sqlite/src/event_cache_store.rs @@ -31,9 +31,7 @@ use matrix_sdk_base::{ timer, }; use matrix_sdk_store_encryption::StoreCipher; -use ruma::{ - EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, RoomId, events::relation::RelationType, -}; +use ruma::{EventId, MilliSecondsSinceUnixEpoch, RoomId, events::relation::RelationType}; use rusqlite::{ OptionalExtension, ToSql, Transaction, TransactionBehavior, params, params_from_iter, }; @@ -1218,8 +1216,8 @@ impl EventCacheStore for SqliteEventCacheStore { async fn filter_duplicated_events( &self, linked_chunk_id: LinkedChunkId<'_>, - events: Vec, - ) -> Result, Self::Error> { + events: Vec, + ) -> Result, Self::Error> { let _timer = timer!("method"); // If there's no events for which we want to check duplicates, we can return @@ -1461,7 +1459,7 @@ fn find_event_relations_transaction( store: SqliteEventCacheStore, hashed_room_id: Key, hashed_linked_chunk_id: Key, - event_id: OwnedEventId, + event_id: EventId, filters: Option>, txn: &Transaction<'_>, ) -> Result)>> { @@ -1899,11 +1897,11 @@ mod tests { // Verify the event is in both. assert_matches!(&room_chunks[0].content, ChunkContent::Items(events) => { assert_eq!(events.len(), 1); - assert_eq!(events[0].event_id().as_deref(), Some(event_id!("$thread_reply"))); + assert_eq!(events[0].event_id().as_ref(), Some(event_id!("$thread_reply"))); }); assert_matches!(&thread_chunks[0].content, ChunkContent::Items(events) => { assert_eq!(events.len(), 1); - assert_eq!(events[0].event_id().as_deref(), Some(event_id!("$thread_reply"))); + assert_eq!(events[0].event_id().as_ref(), Some(event_id!("$thread_reply"))); }); } } @@ -2006,7 +2004,7 @@ mod encrypted_tests { // The event needs to be the edit event, otherwise something is wrong. let (found_event, _) = &results[0]; assert_eq!( - found_event.event_id().as_deref(), + found_event.event_id().as_ref(), Some(edit_id), "The single event we found should be the edit event" ); diff --git a/crates/matrix-sdk-sqlite/src/state_store.rs b/crates/matrix-sdk-sqlite/src/state_store.rs index d2f20ee9123..8687f4d724e 100644 --- a/crates/matrix-sdk-sqlite/src/state_store.rs +++ b/crates/matrix-sdk-sqlite/src/state_store.rs @@ -20,8 +20,7 @@ use matrix_sdk_base::{ }; use matrix_sdk_store_encryption::StoreCipher; use ruma::{ - CanonicalJsonObject, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, - OwnedTransactionId, OwnedUserId, RoomId, TransactionId, UInt, UserId, + CanonicalJsonObject, EventId, MilliSecondsSinceUnixEpoch, RoomId, TransactionId, UInt, UserId, canonical_json::{RedactedBecause, redact}, events::{ AnyGlobalAccountDataEvent, AnyRoomAccountDataEvent, AnySyncStateEvent, @@ -1483,10 +1482,7 @@ impl StateStore for SqliteStateStore { .transpose() } - async fn get_presence_events( - &self, - user_ids: &[OwnedUserId], - ) -> Result>> { + async fn get_presence_events(&self, user_ids: &[UserId]) -> Result>> { if user_ids.is_empty() { return Ok(Vec::new()); } @@ -1589,7 +1585,7 @@ impl StateStore for SqliteStateStore { async fn get_profiles<'a>( &self, room_id: &RoomId, - user_ids: &'a [OwnedUserId], + user_ids: &'a [UserId], ) -> Result> { if user_ids.is_empty() { return Ok(BTreeMap::new()); @@ -1598,7 +1594,7 @@ impl StateStore for SqliteStateStore { let room_id = self.encode_key(keys::PROFILE, room_id); let mut user_ids_map = user_ids .iter() - .map(|u| (self.encode_key(keys::PROFILE, u), u.as_ref())) + .map(|u| (self.encode_key(keys::PROFILE, u), u)) .collect::>(); let user_ids = user_ids_map.keys().cloned().collect(); @@ -1622,7 +1618,7 @@ impl StateStore for SqliteStateStore { &self, room_id: &RoomId, membership: RoomMemberships, - ) -> Result> { + ) -> Result> { let room_id = self.encode_key(keys::MEMBER, room_id); let memberships = membership .as_vec() @@ -1655,7 +1651,7 @@ impl StateStore for SqliteStateStore { &self, room_id: &RoomId, display_name: &DisplayName, - ) -> Result> { + ) -> Result> { let room_id = self.encode_key(keys::DISPLAY_NAME, room_id); let names = vec![self.encode_key( keys::DISPLAY_NAME, @@ -1678,7 +1674,7 @@ impl StateStore for SqliteStateStore { &self, room_id: &RoomId, display_names: &'a [DisplayName], - ) -> Result>> { + ) -> Result>> { let mut result = HashMap::new(); if display_names.is_empty() { @@ -1755,7 +1751,7 @@ impl StateStore for SqliteStateStore { receipt_type: ReceiptType, thread: ReceiptThread, user_id: &UserId, - ) -> Result> { + ) -> Result> { let room_id = self.encode_key(keys::RECEIPT, room_id); let receipt_type = self.encode_key(keys::RECEIPT, receipt_type.to_string()); // We cannot have a NULL primary key so we rely on serialization instead of the @@ -1779,7 +1775,7 @@ impl StateStore for SqliteStateStore { receipt_type: ReceiptType, thread: ReceiptThread, event_id: &EventId, - ) -> Result> { + ) -> Result> { let room_id = self.encode_key(keys::RECEIPT, room_id); let receipt_type = self.encode_key(keys::RECEIPT, receipt_type.to_string()); // We cannot have a NULL primary key so we rely on serialization instead of the @@ -1879,7 +1875,7 @@ impl StateStore for SqliteStateStore { async fn save_send_queue_request( &self, room_id: &RoomId, - transaction_id: OwnedTransactionId, + transaction_id: TransactionId, created_at: MilliSecondsSinceUnixEpoch, content: QueuedRequestKind, priority: usize, @@ -2015,7 +2011,7 @@ impl StateStore for SqliteStateStore { .await } - async fn load_rooms_with_unsent_requests(&self) -> Result, Self::Error> { + async fn load_rooms_with_unsent_requests(&self) -> Result, Self::Error> { // If the values were not encrypted, we could use `SELECT DISTINCT` here, but we // have to manually do the deduplication: indeed, for all X, encrypt(X) // != encrypted(X), since we use a nonce in the encryption process. @@ -2033,7 +2029,7 @@ impl StateStore for SqliteStateStore { Ok(res .into_iter() .map(|entry| self.deserialize_value(&entry)) - .collect::, _>>()? + .collect::, _>>()? .into_iter() .collect()) } @@ -2303,8 +2299,8 @@ impl StateStore for SqliteStateStore { #[derive(Debug, Clone, Serialize, Deserialize)] struct ReceiptData { receipt: Receipt, - event_id: OwnedEventId, - user_id: OwnedUserId, + event_id: EventId, + user_id: UserId, } #[cfg(test)] @@ -2439,7 +2435,7 @@ mod migration_tests { }; use matrix_sdk_test::async_test; use ruma::{ - EventId, MilliSecondsSinceUnixEpoch, OwnedTransactionId, RoomId, TransactionId, UserId, + EventId, MilliSecondsSinceUnixEpoch, RoomId, TransactionId, UserId, events::{ StateEventType, room::{MediaSource, create::RoomCreateEventContent, message::RoomMessageEventContent}, @@ -2803,7 +2799,7 @@ mod migration_tests { UploadFileWithThumbnail { content_type: String, cache_key: MediaRequestParameters, - related_to: OwnedTransactionId, + related_to: TransactionId, }, } diff --git a/crates/matrix-sdk-sqlite/src/utils.rs b/crates/matrix-sdk-sqlite/src/utils.rs index 6e91013a96c..80d5ee308ed 100644 --- a/crates/matrix-sdk-sqlite/src/utils.rs +++ b/crates/matrix-sdk-sqlite/src/utils.rs @@ -24,7 +24,7 @@ use async_trait::async_trait; use deadpool_sync::InteractError; use itertools::Itertools; use matrix_sdk_store_encryption::StoreCipher; -use ruma::{OwnedEventId, OwnedRoomId, serde::Raw, time::SystemTime}; +use ruma::{EventId, RoomId, serde::Raw, time::SystemTime}; use rusqlite::{OptionalExtension, Params, Row, Statement, Transaction, limits::Limit}; use serde::{Serialize, de::DeserializeOwned}; use tracing::{error, trace, warn}; @@ -663,10 +663,10 @@ pub(crate) trait EncryptableStore { ); if let Some(raw) = raw_json { - if let Some(room_id) = raw.get_field::("room_id").ok().flatten() { + if let Some(room_id) = raw.get_field::("room_id").ok().flatten() { warn!("Found a room id in the source data to deserialize: {room_id}"); } - if let Some(event_id) = raw.get_field::("event_id").ok().flatten() { + if let Some(event_id) = raw.get_field::("event_id").ok().flatten() { warn!("Found an event id in the source data to deserialize: {event_id}"); } } diff --git a/crates/matrix-sdk-ui/src/notification_client.rs b/crates/matrix-sdk-ui/src/notification_client.rs index 985ea28b946..5e44b880b93 100644 --- a/crates/matrix-sdk-ui/src/notification_client.rs +++ b/crates/matrix-sdk-ui/src/notification_client.rs @@ -14,7 +14,6 @@ use std::{ collections::BTreeMap, - ops::Deref, sync::{Arc, Mutex}, time::Duration, }; @@ -26,7 +25,7 @@ use matrix_sdk::{ use matrix_sdk_base::{RoomState, StoreError, deserialized_responses::TimelineEvent}; use matrix_sdk_common::cross_process_lock::CrossProcessLockConfig; use ruma::{ - EventId, OwnedEventId, OwnedRoomId, RoomId, UserId, + EventId, RoomId, UserId, api::client::sync::sync_events::v5 as http, assign, events::{ @@ -376,7 +375,7 @@ impl NotificationClient { async fn try_sliding_sync( &self, requests: &[NotificationItemsRequest], - ) -> Result)>, Error> { + ) -> Result)>, Error> { const MAX_SLIDING_SYNC_ATTEMPTS: u64 = 3; // Serialize all the calls to this method by taking a lock at the beginning, // that will be dropped later. @@ -400,7 +399,7 @@ impl NotificationClient { let timeline_event_handler = self.client.add_event_handler({ let requests = requests.clone(); move |raw: Raw| async move { - match &raw.get_field::("event_id") { + match &raw.get_field::("event_id") { Ok(Some(event_id)) => { let Some(request) = &requests.iter().find(|request| request.event_ids.contains(event_id)) @@ -449,7 +448,7 @@ impl NotificationClient { // Try to match the event by event_id, as it's the most precise. In theory, we // shouldn't receive it, so that's a first attempt. - match &raw.get_field::("event_id") { + match &raw.get_field::("event_id") { Ok(Some(event_id)) => { let request = &requests.iter().find(|request| request.event_ids.contains(event_id)); @@ -529,7 +528,7 @@ impl NotificationClient { .await?; sync.subscribe_to_rooms( - &room_ids.iter().map(|id| id.deref()).collect::>(), + &room_ids.iter().collect::>(), Some(assign!(http::request::RoomSubscription::default(), { required_state, timeline_limit: uint!(16) @@ -811,11 +810,11 @@ pub enum NotificationStatus { #[derive(Debug, Clone)] pub struct NotificationItemsRequest { - pub room_id: OwnedRoomId, - pub event_ids: Vec, + pub room_id: RoomId, + pub event_ids: Vec, } -type BatchNotificationFetchingResult = BTreeMap>; +type BatchNotificationFetchingResult = BTreeMap>; /// The Notification event as it was fetched from remote for the /// given `event_id`, represented as Raw but decrypted, thus only @@ -850,7 +849,7 @@ impl NotificationEvent { /// Returns the root event id of the thread the notification event is in, if /// any. - fn thread_id(&self) -> Option { + fn thread_id(&self) -> Option { let NotificationEvent::Timeline(sync_timeline_event) = &self else { return None; }; @@ -911,7 +910,7 @@ pub struct NotificationItem { /// It is set if and only if the push actions could be determined. pub is_noisy: Option, pub has_mention: Option, - pub thread_id: Option, + pub thread_id: Option, /// The push actions for this notification (notify, sound, highlight, etc.). pub actions: Option>, diff --git a/crates/matrix-sdk-ui/src/room_list_service/filters/identifiers.rs b/crates/matrix-sdk-ui/src/room_list_service/filters/identifiers.rs index 5c4dc38f5d3..f5d9dc12ebe 100644 --- a/crates/matrix-sdk-ui/src/room_list_service/filters/identifiers.rs +++ b/crates/matrix-sdk-ui/src/room_list_service/filters/identifiers.rs @@ -12,13 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -use ruma::OwnedRoomId; +use ruma::RoomId; use super::Filter; /// Create a new filter that will filter out rooms that are not part of the /// given identifiers array -pub fn new_filter(identifiers: Vec) -> impl Filter { +pub fn new_filter(identifiers: Vec) -> impl Filter { move |room| -> bool { identifiers.contains(&room.room_id().to_owned()) } } diff --git a/crates/matrix-sdk-ui/src/room_list_service/mod.rs b/crates/matrix-sdk-ui/src/room_list_service/mod.rs index bd6a046b53d..f7e20def504 100644 --- a/crates/matrix-sdk-ui/src/room_list_service/mod.rs +++ b/crates/matrix-sdk-ui/src/room_list_service/mod.rs @@ -67,7 +67,7 @@ use matrix_sdk::{ }; pub use room_list::*; use ruma::{ - OwnedRoomId, RoomId, UInt, + RoomId, UInt, api::{FeatureFlag, client::sync::sync_events::v5 as http}, assign, events::StateEventType, @@ -532,7 +532,7 @@ pub enum Error { /// The requested room doesn't exist. #[error("Room `{0}` not found")] - RoomNotFound(OwnedRoomId), + RoomNotFound(RoomId), #[error(transparent)] EventCache(#[from] EventCacheError), diff --git a/crates/matrix-sdk-ui/src/spaces/graph.rs b/crates/matrix-sdk-ui/src/spaces/graph.rs index 99da2d5ffb3..80a98cc8f43 100644 --- a/crates/matrix-sdk-ui/src/spaces/graph.rs +++ b/crates/matrix-sdk-ui/src/spaces/graph.rs @@ -14,17 +14,17 @@ use std::collections::{BTreeMap, BTreeSet}; -use ruma::{OwnedRoomId, RoomId}; +use ruma::RoomId; #[derive(Debug)] struct SpaceGraphNode { - id: OwnedRoomId, - parents: BTreeSet, - children: BTreeSet, + id: RoomId, + parents: BTreeSet, + children: BTreeSet, } impl SpaceGraphNode { - fn new(id: OwnedRoomId) -> Self { + fn new(id: RoomId) -> Self { Self { id, parents: BTreeSet::new(), children: BTreeSet::new() } } } @@ -34,7 +34,7 @@ impl SpaceGraphNode { /// retrieving top-level parents/roots. #[derive(Debug)] pub(super) struct SpaceGraph { - nodes: BTreeMap, + nodes: BTreeMap, } impl Default for SpaceGraph { @@ -52,31 +52,23 @@ impl SpaceGraph { /// Returns the root nodes of the graph, which are nodes without any /// parents. pub(super) fn root_nodes(&self) -> Vec<&RoomId> { - self.nodes - .values() - .filter(|node| node.parents.is_empty()) - .map(|node| node.id.as_ref()) - .collect() + self.nodes.values().filter(|node| node.parents.is_empty()).map(|node| &node.id).collect() } /// Returns the children of a given node. If the node does not exist, it /// returns an empty vector. pub(super) fn children_of(&self, node_id: &RoomId) -> Vec<&RoomId> { - self.nodes - .get(node_id) - .map_or(vec![], |node| node.children.iter().map(|id| id.as_ref()).collect()) + self.nodes.get(node_id).map_or(vec![], |node| node.children.iter().collect()) } /// Returns the parents of a given node. If the node does not exist, it /// returns an empty vector. pub(super) fn parents_of(&self, node_id: &RoomId) -> Vec<&RoomId> { - self.nodes - .get(node_id) - .map_or(vec![], |node| node.parents.iter().map(|id| id.as_ref()).collect()) + self.nodes.get(node_id).map_or(vec![], |node| node.parents.iter().collect()) } /// Adds a node to the graph. If the node already exists, it does nothing. - pub(super) fn add_node(&mut self, node_id: OwnedRoomId) { + pub(super) fn add_node(&mut self, node_id: RoomId) { self.nodes.entry(node_id.clone()).or_insert(SpaceGraphNode::new(node_id)); } @@ -87,7 +79,7 @@ impl SpaceGraph { /// Adds a directed edge from `parent_id` to `child_id`, creating nodes if /// they do not already exist in the graph. - pub(super) fn add_edge(&mut self, parent_id: OwnedRoomId, child_id: OwnedRoomId) { + pub(super) fn add_edge(&mut self, parent_id: RoomId, child_id: RoomId) { let parent_entry = self.nodes.entry(parent_id.clone()).or_insert(SpaceGraphNode::new(parent_id.clone())); parent_entry.children.insert(child_id.clone()); @@ -101,7 +93,7 @@ impl SpaceGraph { /// /// Does a BFS starting from the given node tracking the visited nodes /// and returning them in the reverse order. - pub(super) fn flattened_bottom_up_subtree(&self, node_id: &RoomId) -> Vec { + pub(super) fn flattened_bottom_up_subtree(&self, node_id: &RoomId) -> Vec { if !self.has_node(node_id) { return Vec::new(); } @@ -147,10 +139,10 @@ impl SpaceGraph { fn dfs_remove_cycles( &self, - node_id: &OwnedRoomId, - visited: &mut BTreeSet, - stack: &mut BTreeSet, - edges_to_remove: &mut Vec<(OwnedRoomId, OwnedRoomId)>, + node_id: &RoomId, + visited: &mut BTreeSet, + stack: &mut BTreeSet, + edges_to_remove: &mut Vec<(RoomId, RoomId)>, ) { if !visited.insert(node_id.clone()) { return; @@ -233,7 +225,7 @@ mod tests { let mut roots = graph.root_nodes(); roots.sort_by_key(|key| key.to_string()); - let expected: Vec<&OwnedRoomId> = vec![&a, &x]; + let expected: Vec<&RoomId> = vec![&a, &x]; assert_eq!(roots, expected); } diff --git a/crates/matrix-sdk-ui/src/spaces/leave.rs b/crates/matrix-sdk-ui/src/spaces/leave.rs index a53165d7c70..6aa5a372959 100644 --- a/crates/matrix-sdk-ui/src/spaces/leave.rs +++ b/crates/matrix-sdk-ui/src/spaces/leave.rs @@ -13,7 +13,7 @@ // limitations under the License. use matrix_sdk::{Client, ROOM_VERSION_RULES_FALLBACK, RoomState, room::RoomMemberRole}; -use ruma::{Int, OwnedRoomId, events::room::member::MembershipState}; +use ruma::{Int, RoomId, events::room::member::MembershipState}; use tracing::info; use crate::spaces::{Error, SpaceRoom}; @@ -44,7 +44,7 @@ pub struct LeaveSpaceHandle { } impl LeaveSpaceHandle { - pub(crate) async fn new(client: Client, room_ids: Vec) -> Self { + pub(crate) async fn new(client: Client, room_ids: Vec) -> Self { let mut rooms = Vec::new(); for room_id in &room_ids { @@ -88,7 +88,7 @@ impl LeaveSpaceHandle { == RoomMemberRole::Administrator } }) - .map(|p: (ruma::OwnedUserId, i64)| p.0) + .map(|p: (ruma::UserId, i64)| p.0) .chain(privileged_creator_ids.into_iter()); let mut joined_owner_ids = Vec::new(); diff --git a/crates/matrix-sdk-ui/src/spaces/mod.rs b/crates/matrix-sdk-ui/src/spaces/mod.rs index 0154c12a786..90cb541832d 100644 --- a/crates/matrix-sdk-ui/src/spaces/mod.rs +++ b/crates/matrix-sdk-ui/src/spaces/mod.rs @@ -38,7 +38,7 @@ use matrix_sdk::{ task_monitor::BackgroundTaskHandle, }; use ruma::{ - OwnedRoomId, RoomId, + RoomId, events::{ self, StateEventType, SyncStateEvent, space::{child::SpaceChildEventContent, parent::SpaceParentEventContent}, @@ -65,11 +65,11 @@ pub enum Error { /// The requested room was not found. #[error("Room `{0}` not found")] - RoomNotFound(OwnedRoomId), + RoomNotFound(RoomId), /// The space parent/child state was missing. #[error("Missing `{0}` for `{1}`")] - MissingState(StateEventType, OwnedRoomId), + MissingState(StateEventType, RoomId), /// Failed to set either of the m.space.parent or m.space.child state /// events. @@ -326,7 +326,7 @@ impl SpaceService { } /// Returns a `SpaceRoomList` for the given space ID. - pub async fn space_room_list(&self, space_id: OwnedRoomId) -> SpaceRoomList { + pub async fn space_room_list(&self, space_id: RoomId) -> SpaceRoomList { SpaceRoomList::new(self.client.clone(), space_id).await } @@ -360,8 +360,8 @@ impl SpaceService { pub async fn add_child_to_space( &self, - child_id: OwnedRoomId, - space_id: OwnedRoomId, + child_id: RoomId, + space_id: RoomId, ) -> Result<(), Error> { let user_id = self.client.user_id().ok_or(Error::UserIdNotFound)?; let space_room = @@ -397,8 +397,8 @@ impl SpaceService { pub async fn remove_child_from_space( &self, - child_id: OwnedRoomId, - space_id: OwnedRoomId, + child_id: RoomId, + space_id: RoomId, ) -> Result<(), Error> { let user_id = self.client.user_id().ok_or(Error::UserIdNotFound)?; let space_room = @@ -499,7 +499,7 @@ impl SpaceService { let mut graph = SpaceGraph::new(); // And also store `m.space.child` ordering info for later use - let mut space_child_states = HashMap::::new(); + let mut space_child_states = HashMap::::new(); // Iterate over all joined spaces and populate the graph with edges based // on `m.space.parent` and `m.space.child` state events. @@ -616,7 +616,7 @@ impl SpaceService { client: &Client, graph: &SpaceGraph, top_level_space_rooms: Vec<&Room>, - space_child_states: HashMap, + space_child_states: HashMap, ) -> Vec { let mut filters = Vec::new(); for top_level_space in top_level_space_rooms { @@ -674,7 +674,7 @@ pub struct SpaceFilter { /// The room identifiers of the descendants of this space. /// For top level spaces (level 0) these will be direct descendants while /// for first level spaces they will be all other descendants, recursively. - pub descendants: Vec, + pub descendants: Vec, } #[cfg(test)] diff --git a/crates/matrix-sdk-ui/src/spaces/room.rs b/crates/matrix-sdk-ui/src/spaces/room.rs index 6e03f7f8070..062da0b4106 100644 --- a/crates/matrix-sdk-ui/src/spaces/room.rs +++ b/crates/matrix-sdk-ui/src/spaces/room.rs @@ -16,8 +16,7 @@ use std::cmp::Ordering; use matrix_sdk::{Room, RoomHero, RoomState}; use ruma::{ - MilliSecondsSinceUnixEpoch, OwnedMxcUri, OwnedRoomAliasId, OwnedRoomId, OwnedServerName, - OwnedSpaceChildOrder, + MilliSecondsSinceUnixEpoch, MxcUri, RoomAliasId, RoomId, ServerName, SpaceChildOrder, events::{ room::{guest_access::GuestAccess, history_visibility::HistoryVisibility}, space::child::HierarchySpaceChildEvent, @@ -30,9 +29,9 @@ use ruma::{ #[derive(Debug, Clone, PartialEq)] pub struct SpaceRoom { /// The ID of the room. - pub room_id: OwnedRoomId, + pub room_id: RoomId, /// The canonical alias of the room, if any. - pub canonical_alias: Option, + pub canonical_alias: Option, /// The name of the room, if any. pub name: Option, /// Calculated display name based on the room's name, aliases, and members. @@ -40,7 +39,7 @@ pub struct SpaceRoom { /// The topic of the room, if any. pub topic: Option, /// The URL for the room's avatar, if one is set. - pub avatar_url: Option, + pub avatar_url: Option, /// The type of room from `m.room.create`, if any. pub room_type: Option, /// The number of members joined to the room. @@ -64,7 +63,7 @@ pub struct SpaceRoom { /// A list of room members considered to be heroes. pub heroes: Option>, /// The via parameters of the room. - pub via: Vec, + pub via: Vec, } impl SpaceRoom { @@ -74,11 +73,11 @@ impl SpaceRoom { summary: &RoomSummary, known_room: Option, children_count: u64, - via: Vec, + via: Vec, ) -> Self { let display_name = matrix_sdk_base::Room::compute_display_name_with_fields( summary.name.clone(), - summary.canonical_alias.as_deref(), + summary.canonical_alias.as_ref(), known_room.as_ref().map(|r| r.heroes().to_vec()).unwrap_or_default(), summary.num_joined_members.into(), ) @@ -167,7 +166,7 @@ impl SpaceRoom { #[derive(Clone, Debug)] pub(crate) struct SpaceRoomChildState { - pub(crate) order: Option, + pub(crate) order: Option, pub(crate) origin_server_ts: MilliSecondsSinceUnixEpoch, } @@ -185,7 +184,7 @@ mod tests { use std::cmp::Ordering; use matrix_sdk_test::async_test; - use ruma::{MilliSecondsSinceUnixEpoch, OwnedRoomId, SpaceChildOrder, owned_room_id, uint}; + use ruma::{MilliSecondsSinceUnixEpoch, RoomId, SpaceChildOrder, owned_room_id, uint}; use crate::spaces::{SpaceRoom, room::SpaceRoomChildState}; @@ -317,7 +316,7 @@ mod tests { ); } - fn make_space_room(room_id: OwnedRoomId) -> SpaceRoom { + fn make_space_room(room_id: RoomId) -> SpaceRoom { SpaceRoom { room_id, canonical_alias: None, diff --git a/crates/matrix-sdk-ui/src/spaces/room_list.rs b/crates/matrix-sdk-ui/src/spaces/room_list.rs index 7f0c85306f0..0e8aa0efcef 100644 --- a/crates/matrix-sdk-ui/src/spaces/room_list.rs +++ b/crates/matrix-sdk-ui/src/spaces/room_list.rs @@ -23,7 +23,7 @@ use matrix_sdk::{ Client, Error, locks::Mutex, paginators::PaginationToken, task_monitor::BackgroundTaskHandle, }; use ruma::{ - OwnedRoomId, + RoomId, api::client::space::get_hierarchy, events::space::child::{HierarchySpaceChildEvent, SpaceChildEventContent}, uint, @@ -104,11 +104,11 @@ pub enum SpaceRoomListPaginationState { pub struct SpaceRoomList { client: Client, - space_id: OwnedRoomId, + space_id: RoomId, space: SharedObservable>, - children_state: Mutex>>, + children_state: Mutex>>, token: AsyncMutex, @@ -123,7 +123,7 @@ pub struct SpaceRoomList { impl SpaceRoomList { /// Creates a new `SpaceRoomList` for the given space identifier. - pub async fn new(client: Client, space_id: OwnedRoomId) -> Self { + pub async fn new(client: Client, space_id: RoomId) -> Self { let rooms = Arc::new(Mutex::new(ObservableVector::::new())); let all_room_updates_receiver = client.subscribe_to_all_room_updates(); @@ -150,7 +150,7 @@ impl SpaceRoomList { if let Some((position, room)) = mutable_rooms .clone() .iter() - .find_position(|room| &room.room_id == updated_room_id) + .find_position(|room| room.room_id == updated_room_id) && let Some(updated_room) = client.get_room(updated_room_id) { mutable_rooms.set( @@ -297,8 +297,7 @@ impl SpaceRoomList { result.rooms.into_iter().partition(|f| f.summary.room_id == self.space_id); if let Some(room) = space.first() { - let mut children_state = - HashMap::::new(); + let mut children_state = HashMap::::new(); for child_state in &room.children_state { match child_state.deserialize() { Ok(child) => { @@ -381,7 +380,7 @@ impl SpaceRoomList { fn compare_rooms( a: &SpaceRoom, b: &SpaceRoom, - children_state: &HashMap, + children_state: &HashMap, ) -> Ordering { let a_state = children_state.get(&a.room_id); let b_state = children_state.get(&b.room_id); @@ -402,7 +401,7 @@ mod tests { JoinedRoomBuilder, LeftRoomBuilder, async_test, event_factory::EventFactory, }; use ruma::{ - OwnedRoomId, RoomId, + RoomId, events::space::child::HierarchySpaceChildEvent, owned_room_id, owned_server_name, room::{JoinRuleSummary, RoomSummary}, @@ -758,7 +757,7 @@ mod tests { #[async_test] async fn test_room_list_sorting() { - let mut children_state = HashMap::::new(); + let mut children_state = HashMap::::new(); // Rooms not present in the `children_state` should be sorted by their room ID assert_eq!( @@ -933,10 +932,10 @@ mod tests { } fn make_space_room( - room_id: OwnedRoomId, + room_id: RoomId, order: Option<&str>, origin_server_ts: Option, - children_state: &mut HashMap, + children_state: &mut HashMap, ) -> SpaceRoom { if let Some(origin_server_ts) = origin_server_ts { children_state.insert( diff --git a/crates/matrix-sdk-ui/src/timeline/algorithms.rs b/crates/matrix-sdk-ui/src/timeline/algorithms.rs index 275df374275..c2d9c4a92dd 100644 --- a/crates/matrix-sdk-ui/src/timeline/algorithms.rs +++ b/crates/matrix-sdk-ui/src/timeline/algorithms.rs @@ -106,7 +106,7 @@ pub(super) fn rfind_event_by_item_id<'a>( rfind_event_item(items, |item| match &item.kind { EventTimelineItemKind::Local(local) => local.transaction_id == *txn_id, EventTimelineItemKind::Remote(remote) => { - remote.transaction_id.as_deref() == Some(txn_id) + remote.transaction_id.as_ref() == Some(txn_id) } }) } diff --git a/crates/matrix-sdk-ui/src/timeline/controller/aggregations.rs b/crates/matrix-sdk-ui/src/timeline/controller/aggregations.rs index a44210ea381..5ce00a13ddc 100644 --- a/crates/matrix-sdk-ui/src/timeline/controller/aggregations.rs +++ b/crates/matrix-sdk-ui/src/timeline/controller/aggregations.rs @@ -42,7 +42,7 @@ use std::{borrow::Cow, collections::HashMap, sync::Arc}; use as_variant::as_variant; use matrix_sdk::deserialized_responses::EncryptionInfo; use ruma::{ - MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedTransactionId, OwnedUserId, + EventId, MilliSecondsSinceUnixEpoch, TransactionId, UserId, events::{ AnySyncTimelineEvent, poll::unstable_start::NewUnstablePollStartEventContentWithoutRelation, @@ -87,7 +87,7 @@ pub(in crate::timeline) struct PendingEdit { /// If provided, this is the identifier of a remote event item that included /// this bundled edit. - pub bundled_item_owner: Option, + pub bundled_item_owner: Option, } /// Which kind of aggregation (related event) is this? @@ -96,7 +96,7 @@ pub(crate) enum AggregationKind { /// This is a response to a poll. PollResponse { /// Sender of the poll's response. - sender: OwnedUserId, + sender: UserId, /// Timestamp at which the response has beens ent. timestamp: MilliSecondsSinceUnixEpoch, /// All the answers to the poll sent by the sender. @@ -117,7 +117,7 @@ pub(crate) enum AggregationKind { /// The reaction "key" displayed by the client, often an emoji. key: String, /// Sender of the reaction. - sender: OwnedUserId, + sender: UserId, /// Timestamp at which the reaction has been sent. timestamp: MilliSecondsSinceUnixEpoch, /// The send status of the reaction this is, with handles to abort it if @@ -531,7 +531,7 @@ impl Aggregations { /// Mark a target event as being sent (i.e. it transitions from an local /// transaction id to its remote event id counterpart), by updating the /// internal mappings. - pub fn mark_target_as_sent(&mut self, txn_id: OwnedTransactionId, event_id: OwnedEventId) { + pub fn mark_target_as_sent(&mut self, txn_id: TransactionId, event_id: EventId) { let from = TimelineEventItemId::TransactionId(txn_id); let to = TimelineEventItemId::EventId(event_id); @@ -558,8 +558,8 @@ impl Aggregations { /// passing the context to apply an aggregation here. pub fn mark_aggregation_as_sent( &mut self, - txn_id: OwnedTransactionId, - event_id: OwnedEventId, + txn_id: TransactionId, + event_id: EventId, items: &mut ObservableItemsTransaction<'_>, rules: &RoomVersionRules, ) -> bool { @@ -670,7 +670,7 @@ fn edit_item(item: &mut Cow<'_, EventTimelineItem>, edit: PendingEdit) -> bool { let PendingEdit { kind: edit_kind, edit_json, encryption_info, bundled_item_owner: _ } = edit; if let Some(event_json) = &edit_json { - let Some(edit_sender) = event_json.get_field::("sender").ok().flatten() else { + let Some(edit_sender) = event_json.get_field::("sender").ok().flatten() else { info!("edit event didn't have a sender; likely a malformed event"); return false; }; diff --git a/crates/matrix-sdk-ui/src/timeline/controller/decryption_retry_task.rs b/crates/matrix-sdk-ui/src/timeline/controller/decryption_retry_task.rs index 83102aafba8..882bcf050fc 100644 --- a/crates/matrix-sdk-ui/src/timeline/controller/decryption_retry_task.rs +++ b/crates/matrix-sdk-ui/src/timeline/controller/decryption_retry_task.rs @@ -123,7 +123,7 @@ mod tests { use matrix_sdk::deserialized_responses::{AlgorithmInfo, EncryptionInfo, VerificationState}; use matrix_sdk_base::crypto::types::events::UtdCause; use ruma::{ - MilliSecondsSinceUnixEpoch, OwnedTransactionId, + MilliSecondsSinceUnixEpoch, TransactionId, events::room::{ encrypted::{ EncryptedEventScheme, MegolmV1AesSha2Content, MegolmV1AesSha2ContentInit, @@ -227,7 +227,7 @@ mod tests { fn local_event() -> Arc { let event_kind = EventTimelineItemKind::Local(LocalEventTimelineItem { send_state: EventSendState::NotSentYet { progress: None }, - transaction_id: OwnedTransactionId::from("trans"), + transaction_id: TransactionId::from("trans"), send_handle: None, }); diff --git a/crates/matrix-sdk-ui/src/timeline/controller/metadata.rs b/crates/matrix-sdk-ui/src/timeline/controller/metadata.rs index e0b4f2fd051..5463fe2345d 100644 --- a/crates/matrix-sdk-ui/src/timeline/controller/metadata.rs +++ b/crates/matrix-sdk-ui/src/timeline/controller/metadata.rs @@ -20,7 +20,7 @@ use std::{ use imbl::Vector; use matrix_sdk::deserialized_responses::EncryptionInfo; use ruma::{ - EventId, OwnedEventId, OwnedUserId, + EventId, UserId, events::{ AnyMessageLikeEventContent, AnySyncMessageLikeEvent, AnySyncTimelineEvent, BundledMessageLikeRelations, poll::unstable_start::UnstablePollStartEventContent, @@ -86,8 +86,8 @@ pub(in crate::timeline) struct TimelineMetadata { /// This value is constant over the lifetime of the metadata. pub room_version_rules: RoomVersionRules, - /// The own [`OwnedUserId`] of the client who opened the timeline. - pub(crate) own_user_id: OwnedUserId, + /// The own [`UserId`] of the client who opened the timeline. + pub(crate) own_user_id: UserId, // **** DYNAMIC FIELDS **** /// The next internal identifier for timeline items, used for both local and @@ -107,11 +107,11 @@ pub(in crate::timeline) struct TimelineMetadata { /// Given an event, what are all the events that are replies to it? /// /// Only works for remote events *and* replies which are remote-echoed. - pub replies: HashMap>, + pub replies: HashMap>, /// Identifier of the fully-read event, helping knowing where to introduce /// the read marker. - pub fully_read_event: Option, + pub fully_read_event: Option, /// Whether we have a fully read-marker item in the timeline, that's up to /// date with the room's read marker. @@ -129,7 +129,7 @@ pub(in crate::timeline) struct TimelineMetadata { impl TimelineMetadata { pub(in crate::timeline) fn new( - own_user_id: OwnedUserId, + own_user_id: UserId, room_version_rules: RoomVersionRules, internal_id_prefix: Option, unable_to_decrypt_hook: Option>, @@ -317,7 +317,7 @@ impl TimelineMetadata { bundled_edit_encryption_info: Option>, timeline_items: &Vector>, is_thread_focus: bool, - ) -> (Option, Option) { + ) -> (Option, Option) { if let AnySyncTimelineEvent::MessageLike(ev) = event && let Some(content) = ev.original_content() { @@ -344,7 +344,7 @@ impl TimelineMetadata { remote_ctx: Option>, timeline_items: &Vector>, is_thread_focus: bool, - ) -> (Option, Option) { + ) -> (Option, Option) { match content { AnyMessageLikeEventContent::Sticker(content) => { let (in_reply_to, thread_root) = Self::extract_reply_and_thread_root( @@ -448,7 +448,7 @@ impl TimelineMetadata { relates_to: Option, timeline_items: &Vector>, is_thread_focus: bool, - ) -> (Option, Option) { + ) -> (Option, Option) { let mut thread_root = None; let in_reply_to = relates_to.and_then(|relation| match relation { @@ -510,11 +510,11 @@ pub(in crate::timeline) enum RelativePosition { #[derive(Debug, Clone)] pub(in crate::timeline) struct EventMeta { /// The ID of the event. - pub event_id: OwnedEventId, + pub event_id: EventId, /// If this event is part of a thread, this will contain its thread root /// event id. - pub thread_root_id: Option, + pub thread_root_id: Option, /// Whether the event is among the timeline items. pub visible: bool, @@ -588,10 +588,10 @@ pub(in crate::timeline) struct EventMeta { impl EventMeta { pub fn new( - event_id: OwnedEventId, + event_id: EventId, visible: bool, can_show_read_receipts: bool, - thread_root_id: Option, + thread_root_id: Option, ) -> Self { Self { event_id, diff --git a/crates/matrix-sdk-ui/src/timeline/controller/mod.rs b/crates/matrix-sdk-ui/src/timeline/controller/mod.rs index 350399eaeb6..d65146ef0ff 100644 --- a/crates/matrix-sdk-ui/src/timeline/controller/mod.rs +++ b/crates/matrix-sdk-ui/src/timeline/controller/mod.rs @@ -33,7 +33,7 @@ use matrix_sdk::{ #[cfg(test)] use ruma::events::receipt::ReceiptEventContent; use ruma::{ - EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedTransactionId, TransactionId, UserId, + EventId, MilliSecondsSinceUnixEpoch, TransactionId, UserId, api::client::receipt::create_receipt::v3::ReceiptType as SendReceiptType, events::{ AnyMessageLikeEventContent, AnySyncEphemeralRoomEvent, AnySyncMessageLikeEvent, @@ -116,7 +116,7 @@ pub(in crate::timeline) enum TimelineFocusKind { /// A live timeline for a thread. Thread { /// The root event for the current thread. - root_event_id: OwnedEventId, + root_event_id: EventId, }, PinnedEvents, @@ -566,7 +566,7 @@ impl TimelineController

{ let events_in_thread = events.into_iter().filter(|event| { extract_thread_root(event.raw()) .is_some_and(|event_thread_root| event_thread_root == thread_root) - || event.event_id().as_deref() == Some(thread_root) + || event.event_id().as_ref() == Some(thread_root) }); self.replace_with_initial_remote_events( @@ -759,7 +759,7 @@ impl TimelineController

{ /// The root of the current thread, for a live thread timeline or a /// permalink to a thread message. - pub(super) fn thread_root(&self) -> Option { + pub(super) fn thread_root(&self) -> Option { self.focus.thread_root().map(ToOwned::to_owned) } @@ -1034,7 +1034,7 @@ impl TimelineController

{ } } - pub(super) async fn handle_fully_read_marker(&self, fully_read_event_id: OwnedEventId) { + pub(super) async fn handle_fully_read_marker(&self, fully_read_event_id: EventId) { self.state.write().await.handle_fully_read_marker(fully_read_event_id); } @@ -1054,7 +1054,7 @@ impl TimelineController

{ #[instrument(skip_all)] pub(super) async fn handle_local_event( &self, - txn_id: OwnedTransactionId, + txn_id: TransactionId, content: AnyMessageLikeEventContent, send_handle: Option, ) { @@ -1402,7 +1402,7 @@ impl TimelineController

{ pub(super) async fn latest_user_read_receipt( &self, user_id: &UserId, - ) -> Option<(OwnedEventId, Receipt)> { + ) -> Option<(EventId, Receipt)> { let receipt_thread = self.focus.receipt_thread(); self.state @@ -1417,7 +1417,7 @@ impl TimelineController

{ pub(super) async fn latest_user_read_receipt_timeline_event_id( &self, user_id: &UserId, - ) -> Option { + ) -> Option { self.state.read().await.latest_user_read_receipt_timeline_event_id(user_id) } @@ -1469,7 +1469,7 @@ impl TimelineController

{ &self, reaction_key: String, send_handle: SendReactionHandle, - applies_to: OwnedTransactionId, + applies_to: TransactionId, ) { let mut state = self.state.write().await; let mut tr = state.transaction(); @@ -1771,7 +1771,7 @@ impl TimelineController { /// Returns the latest event identifier, even if it's not visible, or if /// it's folded into another timeline item. - pub(crate) async fn latest_event_id(&self) -> Option { + pub(crate) async fn latest_event_id(&self) -> Option { let state = self.state.read().await; let filter_out_thread_events = match self.focus() { TimelineFocusKind::Thread { .. } => false, diff --git a/crates/matrix-sdk-ui/src/timeline/controller/read_receipts.rs b/crates/matrix-sdk-ui/src/timeline/controller/read_receipts.rs index 5c2d41bf189..67b2c0e8a33 100644 --- a/crates/matrix-sdk-ui/src/timeline/controller/read_receipts.rs +++ b/crates/matrix-sdk-ui/src/timeline/controller/read_receipts.rs @@ -17,7 +17,7 @@ use std::{cmp::Ordering, collections::HashMap}; use futures_core::Stream; use indexmap::IndexMap; use ruma::{ - EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedUserId, UserId, + EventId, MilliSecondsSinceUnixEpoch, UserId, events::receipt::{Receipt, ReceiptEventContent, ReceiptThread, ReceiptType}, }; use tokio::sync::watch; @@ -36,13 +36,13 @@ pub(super) struct ReadReceipts { /// Map of public read receipts on events. /// /// Event ID => User ID => Read receipt of the user. - by_event: HashMap>, + by_event: HashMap>, /// In-memory cache of all latest read receipts by user. /// /// User ID => Receipt type => Read receipt of the user of the given /// type. - latest_by_user: HashMap>, + latest_by_user: HashMap>, /// A sender to notify of changes to the receipts of our own user. own_user_read_receipts_changed_sender: watch::Sender<()>, @@ -69,7 +69,7 @@ impl ReadReceipts { &self, user_id: &UserId, receipt_type: &ReceiptType, - ) -> Option<&(OwnedEventId, Receipt)> { + ) -> Option<&(EventId, Receipt)> { self.latest_by_user.get(user_id).and_then(|map| map.get(receipt_type)) } @@ -77,9 +77,9 @@ impl ReadReceipts { /// given user. fn upsert_latest( &mut self, - user_id: OwnedUserId, + user_id: UserId, receipt_type: ReceiptType, - read_receipt: (OwnedEventId, Receipt), + read_receipt: (EventId, Receipt), ) { self.latest_by_user.entry(user_id).or_default().insert(receipt_type, read_receipt); } @@ -252,17 +252,12 @@ impl ReadReceipts { } /// Returns the cached receipts by user for a given `event_id`. - fn get_event_receipts(&self, event_id: &EventId) -> Option<&IndexMap> { + fn get_event_receipts(&self, event_id: &EventId) -> Option<&IndexMap> { self.by_event.get(event_id) } /// Mark the given event as seen by the user with the given receipt. - fn add_event_receipt_for_user( - &mut self, - event_id: OwnedEventId, - user_id: OwnedUserId, - receipt: Receipt, - ) { + fn add_event_receipt_for_user(&mut self, event_id: EventId, user_id: UserId, receipt: Receipt) { self.by_event.entry(event_id).or_default().insert(user_id, receipt); } @@ -287,7 +282,7 @@ impl ReadReceipts { event_id: &EventId, timeline_items: &mut ObservableItemsTransaction<'_>, at_end: bool, - ) -> IndexMap { + ) -> IndexMap { let mut all_receipts = self.get_event_receipts(event_id).cloned().unwrap_or_default(); if at_end { @@ -386,12 +381,12 @@ struct ReadReceiptTimelineUpdate { /// if any. old_item_pos: Option, /// The old event that had the receipt of the user, if any. - old_event_id: Option, + old_event_id: Option, /// The position of the timeline item that has the new receipt of the user, /// if any. new_item_pos: Option, /// The new event that has the receipt of the user, if any. - new_event_id: Option, + new_event_id: Option, } impl ReadReceiptTimelineUpdate { @@ -448,7 +443,7 @@ impl ReadReceiptTimelineUpdate { fn add_new_receipt( self, items: &mut ObservableItemsTransaction<'_>, - user_id: OwnedUserId, + user_id: UserId, receipt: Receipt, ) { let Some(event_id) = self.new_event_id else { @@ -508,7 +503,7 @@ impl ReadReceiptTimelineUpdate { fn apply( mut self, items: &mut ObservableItemsTransaction<'_>, - user_id: OwnedUserId, + user_id: UserId, receipt: Receipt, ) { self.remove_old_receipt(items, &user_id); @@ -806,7 +801,7 @@ impl TimelineState

{ user_id: &UserId, receipt_thread: ReceiptThread, room_data_provider: &P, - ) -> Option<(OwnedEventId, Receipt)> { + ) -> Option<(EventId, Receipt)> { let all_remote_events = self.items.all_remote_events(); let public_read_receipt = self @@ -850,7 +845,7 @@ impl TimelineState

{ pub(super) fn latest_user_read_receipt_timeline_event_id( &self, user_id: &UserId, - ) -> Option { + ) -> Option { // We only need to use the local map, since receipts for known events are // already loaded from the store. let public_read_receipt = self.meta.read_receipts.get_latest(user_id, &ReceiptType::Read); @@ -899,7 +894,7 @@ impl TimelineMetadata { receipt_thread: ReceiptThread, room_data_provider: &P, all_remote_events: &AllRemoteEvents, - ) -> Option<(OwnedEventId, Receipt)> { + ) -> Option<(EventId, Receipt)> { if let Some(receipt) = self.read_receipts.get_latest(user_id, &receipt_type) { // Since it is in the timeline, it should be the most recent. return Some(receipt.clone()); @@ -944,8 +939,8 @@ impl TimelineMetadata { /// not possible to know which one is the more recent, defaults to /// `Ordering::Less`, making the right-hand side the default. fn compare_optional_receipts( - lhs: Option<&(OwnedEventId, Receipt)>, - rhs_or_default: Option<&(OwnedEventId, Receipt)>, + lhs: Option<&(EventId, Receipt)>, + rhs_or_default: Option<&(EventId, Receipt)>, all_remote_events: &AllRemoteEvents, ) -> Ordering { // If we only have one, use it. diff --git a/crates/matrix-sdk-ui/src/timeline/controller/state.rs b/crates/matrix-sdk-ui/src/timeline/controller/state.rs index 0ac07119610..a5aeb8e1694 100644 --- a/crates/matrix-sdk-ui/src/timeline/controller/state.rs +++ b/crates/matrix-sdk-ui/src/timeline/controller/state.rs @@ -19,7 +19,7 @@ use matrix_sdk::{deserialized_responses::TimelineEvent, send_queue::SendHandle}; #[cfg(test)] use ruma::events::receipt::ReceiptEventContent; use ruma::{ - MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedTransactionId, OwnedUserId, + EventId, MilliSecondsSinceUnixEpoch, TransactionId, UserId, events::{AnyMessageLikeEventContent, AnySyncEphemeralRoomEvent}, room_version_rules::RoomVersionRules, serde::Raw, @@ -51,7 +51,7 @@ pub(in crate::timeline) struct TimelineState { impl TimelineState

{ pub(super) fn new( focus: Arc>, - own_user_id: OwnedUserId, + own_user_id: UserId, room_version_rules: RoomVersionRules, internal_id_prefix: Option, unable_to_decrypt_hook: Option>, @@ -106,7 +106,7 @@ impl TimelineState

{ /// Marks the given event as fully read, using the read marker received from /// sync. - pub(super) fn handle_fully_read_marker(&mut self, fully_read_event_id: OwnedEventId) { + pub(super) fn handle_fully_read_marker(&mut self, fully_read_event_id: EventId) { let mut txn = self.transaction(); txn.set_fully_read_event(fully_read_event_id); txn.commit(); @@ -147,10 +147,10 @@ impl TimelineState

{ #[instrument(skip_all)] pub(super) async fn handle_local_event( &mut self, - own_user_id: OwnedUserId, + own_user_id: UserId, own_profile: Option, date_divider_mode: DateDividerMode, - txn_id: OwnedTransactionId, + txn_id: TransactionId, send_handle: Option, content: AnyMessageLikeEventContent, ) { @@ -203,7 +203,7 @@ impl TimelineState

{ pub(super) fn handle_read_receipts( &mut self, receipt_event_content: ReceiptEventContent, - own_user_id: &ruma::UserId, + own_user_id: &UserId, ) { let mut txn = self.transaction(); txn.handle_explicit_read_receipts(receipt_event_content, own_user_id); diff --git a/crates/matrix-sdk-ui/src/timeline/controller/state_transaction.rs b/crates/matrix-sdk-ui/src/timeline/controller/state_transaction.rs index a59d7f9d37e..60f9b81a9bc 100644 --- a/crates/matrix-sdk-ui/src/timeline/controller/state_transaction.rs +++ b/crates/matrix-sdk-ui/src/timeline/controller/state_transaction.rs @@ -21,7 +21,7 @@ use matrix_sdk::deserialized_responses::{ UnsignedEventLocation, }; use ruma::{ - EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedTransactionId, OwnedUserId, UserId, + EventId, MilliSecondsSinceUnixEpoch, TransactionId, UserId, events::{ AnySyncTimelineEvent, receipt::{ReceiptThread, ReceiptType}, @@ -100,7 +100,7 @@ impl<'a, P: RoomDataProvider> TimelineStateTransaction<'a, P> { let mut date_divider_adjuster = DateDividerAdjuster::new(settings.date_divider_mode.clone()); - let mut cached_profiles: HashMap> = HashMap::new(); + let mut cached_profiles: HashMap> = HashMap::new(); for diff in diffs { match diff { @@ -556,12 +556,12 @@ impl<'a, P: RoomDataProvider> TimelineStateTransaction<'a, P> { deserialization_error: serde_json::Error, settings: &TimelineSettings, ) -> Option<( - OwnedEventId, - OwnedUserId, + EventId, + UserId, MilliSecondsSinceUnixEpoch, - Option, + Option, Option, - Option, + Option, bool, bool, )> { @@ -582,7 +582,7 @@ impl<'a, P: RoomDataProvider> TimelineStateTransaction<'a, P> { raw.get_field("type").ok().flatten().map(FailedToParseEvent::MsgLike) }; - let event_id: Option = raw.get_field("event_id").ok().flatten(); + let event_id: Option = raw.get_field("event_id").ok().flatten(); let Some(event_id) = event_id else { // If the event doesn't even have an event ID, we can't do anything with it. warn!( @@ -592,7 +592,7 @@ impl<'a, P: RoomDataProvider> TimelineStateTransaction<'a, P> { return None; }; - let sender: Option = raw.get_field("sender").ok().flatten(); + let sender: Option = raw.get_field("sender").ok().flatten(); let origin_server_ts: Option = raw.get_field("origin_server_ts").ok().flatten(); @@ -604,10 +604,10 @@ impl<'a, P: RoomDataProvider> TimelineStateTransaction<'a, P> { // been requested to show it, let's do it. #[derive(serde::Deserialize)] struct Unsigned { - transaction_id: Option, + transaction_id: Option, } - let transaction_id: Option = raw + let transaction_id: Option = raw .get_field::("unsigned") .ok() .flatten() @@ -640,7 +640,7 @@ impl<'a, P: RoomDataProvider> TimelineStateTransaction<'a, P> { // See [`ObservableItems::all_remote_events`]. self.add_or_update_remote_event( EventMeta::new(event_id, false, false, None), - sender.as_deref(), + sender.as_ref(), origin_server_ts, position, room_data_provider, @@ -685,7 +685,7 @@ impl<'a, P: RoomDataProvider> TimelineStateTransaction<'a, P> { summary: &SdkThreadSummary, room_data_provider: &P, settings: &TimelineSettings, - ) -> (Option, Option) { + ) -> (Option, Option) { if !settings.track_read_receipts.is_enabled() { return (None, None); } @@ -706,7 +706,7 @@ impl<'a, P: RoomDataProvider> TimelineStateTransaction<'a, P> { }) { // Parse the sender. - if let Ok(Some(sender)) = event.raw().get_field::("sender") + if let Ok(Some(sender)) = event.raw().get_field::("sender") && sender == self.meta.own_user_id { let latest = Some(latest_reply.clone()); @@ -755,7 +755,7 @@ impl<'a, P: RoomDataProvider> TimelineStateTransaction<'a, P> { room_data_provider: &P, settings: &TimelineSettings, date_divider_adjuster: &mut DateDividerAdjuster, - profiles: &mut HashMap>, + profiles: &mut HashMap>, ) -> RemovedItem { let is_highlighted = event.push_actions().is_some_and(|actions| actions.iter().any(Action::is_highlight)); @@ -818,7 +818,7 @@ impl<'a, P: RoomDataProvider> TimelineStateTransaction<'a, P> { room_data_provider, settings, &event, - thread_root.as_deref(), + thread_root.as_ref(), position, ); @@ -1005,7 +1005,7 @@ impl<'a, P: RoomDataProvider> TimelineStateTransaction<'a, P> { } #[instrument(skip_all)] - pub(super) fn set_fully_read_event(&mut self, fully_read_event_id: OwnedEventId) { + pub(super) fn set_fully_read_event(&mut self, fully_read_event_id: EventId) { // A similar event has been handled already. We can ignore it. if self.meta.fully_read_event.as_ref().is_some_and(|id| *id == fully_read_event_id) { return; @@ -1131,12 +1131,12 @@ impl<'a, P: RoomDataProvider> TimelineStateTransaction<'a, P> { /// # Returns /// /// A tuple containing: -/// - `Option`: The user ID of the forwarder, if available. +/// - `Option`: The user ID of the forwarder, if available. /// - `Option`: The profile of the forwarder, if available. async fn get_forwarder_info( event: &TimelineEvent, room_data_provider: &P, -) -> (Option, Option) { +) -> (Option, Option) { let forwarder = event .kind .encryption_info() diff --git a/crates/matrix-sdk-ui/src/timeline/event_handler.rs b/crates/matrix-sdk-ui/src/timeline/event_handler.rs index 48f93dcc7d6..d7d9fb4e2c7 100644 --- a/crates/matrix-sdk-ui/src/timeline/event_handler.rs +++ b/crates/matrix-sdk-ui/src/timeline/event_handler.rs @@ -22,8 +22,7 @@ use matrix_sdk::{ }; use matrix_sdk_base::crypto::types::events::UtdCause; use ruma::{ - EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedTransactionId, OwnedUserId, - TransactionId, + EventId, MilliSecondsSinceUnixEpoch, TransactionId, UserId, events::{ AnyMessageLikeEventContent, AnySyncMessageLikeEvent, AnySyncStateEvent, AnySyncTimelineEvent, FullStateEventContent, MessageLikeEventContent, MessageLikeEventType, @@ -67,7 +66,7 @@ pub(super) enum Flow { /// The event was locally created. Local { /// The transaction id we've used in requests associated to this event. - txn_id: OwnedTransactionId, + txn_id: TransactionId, /// A handle to manipulate this event. send_handle: Option, @@ -77,10 +76,10 @@ pub(super) enum Flow { /// etc.). This can be a "remote echo". Remote { /// The event identifier as returned by the server. - event_id: OwnedEventId, + event_id: EventId, /// The transaction id we might have used, if we're the sender of the /// event. - txn_id: Option, + txn_id: Option, /// The raw serialized JSON event. raw_event: Raw, /// Where should this be added in the timeline. @@ -106,13 +105,13 @@ impl Flow { } pub(super) struct TimelineEventContext { - pub(super) sender: OwnedUserId, + pub(super) sender: UserId, pub(super) sender_profile: Option, /// If the keys used to decrypt this event were shared-on-invite as part of /// an [MSC4268] key bundle, the user ID of the forwarder. /// /// [MSC4268]: https://github.com/matrix-org/matrix-spec-proposals/pull/4268 - pub(super) forwarder: Option, + pub(super) forwarder: Option, /// If the keys used to decrypt this event were shared-on-invite as part of /// an [MSC4268] key bundle, the forwarder's profile. /// @@ -120,7 +119,7 @@ pub(super) struct TimelineEventContext { pub(super) forwarder_profile: Option, /// The event's `origin_server_ts` field (or creation time for local echo). pub(super) timestamp: MilliSecondsSinceUnixEpoch, - pub(super) read_receipts: IndexMap, + pub(super) read_receipts: IndexMap, pub(super) is_highlighted: bool, pub(super) flow: Flow, @@ -190,7 +189,7 @@ pub(super) enum TimelineAction { /// the related event. HandleAggregation { /// To which other event does this aggregation apply to? - related_event: OwnedEventId, + related_event: EventId, /// What kind of aggregation are we handling here? kind: HandleAggregationKind, }, @@ -212,7 +211,7 @@ impl TimelineAction { room_data_provider: &P, unable_to_decrypt: Option<(UnableToDecryptInfo, Option<&Arc>)>, in_reply_to: Option, - thread_root: Option, + thread_root: Option, thread_summary: Option, ) -> Option { let redaction_rules = room_data_provider.room_version_rules().redaction; @@ -323,7 +322,7 @@ impl TimelineAction { pub(super) fn from_content( content: AnyMessageLikeEventContent, in_reply_to: Option, - thread_root: Option, + thread_root: Option, thread_summary: Option, ) -> Self { match content { @@ -585,7 +584,7 @@ impl<'a, 'o> TimelineEventHandler<'a, 'o> { } #[instrument(skip(self, edit_kind))] - fn handle_edit(&mut self, edited_event_id: OwnedEventId, edit_kind: PendingEditKind) { + fn handle_edit(&mut self, edited_event_id: EventId, edit_kind: PendingEditKind) { let target = TimelineEventItemId::EventId(edited_event_id.clone()); let encryption_info = @@ -624,7 +623,7 @@ impl<'a, 'o> TimelineEventHandler<'a, 'o> { /// Reactions to local events are applied in /// [`crate::timeline::TimelineController::handle_local_echo`]. #[instrument(skip(self))] - fn handle_reaction(&mut self, relates_to: OwnedEventId, reaction_key: String) { + fn handle_reaction(&mut self, relates_to: EventId, reaction_key: String) { let target = TimelineEventItemId::EventId(relates_to); // Add the aggregation to the manager. @@ -659,7 +658,7 @@ impl<'a, 'o> TimelineEventHandler<'a, 'o> { ); } - fn handle_poll_response(&mut self, poll_event_id: OwnedEventId, answers: Vec) { + fn handle_poll_response(&mut self, poll_event_id: EventId, answers: Vec) { let target = TimelineEventItemId::EventId(poll_event_id); let aggregation = Aggregation::new( self.ctx.flow.timeline_item_id(), @@ -679,7 +678,7 @@ impl<'a, 'o> TimelineEventHandler<'a, 'o> { ); } - fn handle_poll_end(&mut self, poll_event_id: OwnedEventId) { + fn handle_poll_end(&mut self, poll_event_id: EventId) { let target = TimelineEventItemId::EventId(poll_event_id); let aggregation = Aggregation::new( self.ctx.flow.timeline_item_id(), @@ -701,7 +700,7 @@ impl<'a, 'o> TimelineEventHandler<'a, 'o> { /// This assumes the redacted event was present in the timeline in the first /// place; it will warn if the redacted event has not been found. #[instrument(skip_all, fields(redacts_event_id = ?redacted))] - fn handle_redaction(&mut self, redacted: OwnedEventId) { + fn handle_redaction(&mut self, redacted: EventId) { // TODO: Apply local redaction of PollResponse and PollEnd events. // https://github.com/matrix-org/matrix-rust-sdk/pull/2381#issuecomment-1689647825 @@ -743,7 +742,7 @@ impl<'a, 'o> TimelineEventHandler<'a, 'o> { /// /// Returns true if it's succeeded. #[instrument(skip_all, fields(redacts = ?aggregation_id))] - fn handle_aggregation_redaction(&mut self, aggregation_id: OwnedEventId) -> bool { + fn handle_aggregation_redaction(&mut self, aggregation_id: EventId) -> bool { let aggregation_id = TimelineEventItemId::EventId(aggregation_id); match self.meta.aggregations.try_remove_aggregation(&aggregation_id, self.items) { @@ -863,7 +862,7 @@ impl<'a, 'o> TimelineEventHandler<'a, 'o> { self.meta, item, event_id, - txn_id.as_deref(), + txn_id.as_ref(), ); trace!("Adding new remote timeline item at the start"); @@ -882,7 +881,7 @@ impl<'a, 'o> TimelineEventHandler<'a, 'o> { self.meta, item, event_id, - txn_id.as_deref(), + txn_id.as_ref(), ); let all_remote_events = self.items.all_remote_events(); @@ -937,7 +936,7 @@ impl<'a, 'o> TimelineEventHandler<'a, 'o> { self.meta, item, event_id, - txn_id.as_deref(), + txn_id.as_ref(), ); // Let's find the latest remote event and insert after it diff --git a/crates/matrix-sdk-ui/src/timeline/event_item/content/message.rs b/crates/matrix-sdk-ui/src/timeline/event_item/content/message.rs index e5d4bdc528c..2675f9240da 100644 --- a/crates/matrix-sdk-ui/src/timeline/event_item/content/message.rs +++ b/crates/matrix-sdk-ui/src/timeline/event_item/content/message.rs @@ -17,7 +17,7 @@ use std::fmt; use ruma::{ - OwnedEventId, + EventId, events::{ AnySyncMessageLikeEvent, AnySyncTimelineEvent, BundledMessageLikeRelations, Mentions, poll::unstable_start::{ @@ -114,7 +114,7 @@ pub(crate) fn extract_bundled_edit_event_json( /// relations , along with the event ID of the replacement event. pub(crate) fn extract_room_msg_edit_content( relations: BundledMessageLikeRelations, -) -> Option<(OwnedEventId, RoomMessageEventContentWithoutRelation)> { +) -> Option<(EventId, RoomMessageEventContentWithoutRelation)> { match *relations.replace? { AnySyncMessageLikeEvent::RoomMessage(SyncRoomMessageEvent::Original(ev)) => match ev .content @@ -143,7 +143,7 @@ pub(crate) fn extract_room_msg_edit_content( /// relations, along with the event ID of the replacement event. pub(crate) fn extract_poll_edit_content( relations: BundledMessageLikeRelations, -) -> Option<(OwnedEventId, NewUnstablePollStartEventContentWithoutRelation)> { +) -> Option<(EventId, NewUnstablePollStartEventContentWithoutRelation)> { match *relations.replace? { AnySyncMessageLikeEvent::UnstablePollStart(SyncUnstablePollStartEvent::Original(ev)) => { match ev.content { diff --git a/crates/matrix-sdk-ui/src/timeline/event_item/content/mod.rs b/crates/matrix-sdk-ui/src/timeline/event_item/content/mod.rs index 5f16e28af3b..87d6e1c7836 100644 --- a/crates/matrix-sdk-ui/src/timeline/event_item/content/mod.rs +++ b/crates/matrix-sdk-ui/src/timeline/event_item/content/mod.rs @@ -17,7 +17,7 @@ use std::sync::Arc; use as_variant::as_variant; use matrix_sdk_base::crypto::types::events::UtdCause; use ruma::{ - OwnedDeviceId, OwnedEventId, OwnedMxcUri, OwnedUserId, UserId, + DeviceId, EventId, MxcUri, UserId, events::{ AnyFullStateEventContent, FullStateEventContent, Mentions, MessageLikeEventType, StateEventType, @@ -195,7 +195,7 @@ impl TimelineItemContent { msgtype: MessageType, mentions: Option, reactions: ReactionsByKeyBySender, - thread_root: Option, + thread_root: Option, in_reply_to: Option, thread_summary: Option, ) -> Self { @@ -231,9 +231,9 @@ impl TimelineItemContent { } pub(crate) fn room_member( - user_id: OwnedUserId, + user_id: UserId, full_content: FullStateEventContent, - sender: OwnedUserId, + sender: UserId, ) -> Self { use ruma::events::room::member::MembershipChange as MChange; match &full_content { @@ -308,7 +308,7 @@ impl TimelineItemContent { } /// Event ID of the thread root, if this is a message in a thread. - pub fn thread_root(&self) -> Option { + pub fn thread_root(&self) -> Option { as_variant!(self, Self::MsgLike)?.thread_root.clone() } @@ -389,7 +389,7 @@ pub enum EncryptedMessage { /// The ID of the sending device. #[deprecated = "this field should still be sent but should not be used when received"] #[doc(hidden)] // Included for Debug formatting only - device_id: Option, + device_id: Option, /// The ID of the session used to encrypt the message. session_id: String, @@ -445,7 +445,7 @@ impl Sticker { /// An event changing a room membership. #[derive(Clone, Debug)] pub struct RoomMembershipChange { - pub(in crate::timeline) user_id: OwnedUserId, + pub(in crate::timeline) user_id: UserId, pub(in crate::timeline) content: FullStateEventContent, pub(in crate::timeline) change: Option, } @@ -479,7 +479,7 @@ impl RoomMembershipChange { /// Retrieve the avatar URL from the current event, or, if missing, from the /// one it replaced. - pub fn avatar_url(&self) -> Option { + pub fn avatar_url(&self) -> Option { if let FullStateEventContent::Original { content, prev_content } = &self.content { content .avatar_url @@ -574,9 +574,9 @@ pub enum MembershipChange { /// membership is already `join`. #[derive(Clone, Debug)] pub struct MemberProfileChange { - pub(in crate::timeline) user_id: OwnedUserId, + pub(in crate::timeline) user_id: UserId, pub(in crate::timeline) displayname_change: Option>>, - pub(in crate::timeline) avatar_url_change: Option>>, + pub(in crate::timeline) avatar_url_change: Option>>, } impl MemberProfileChange { @@ -591,7 +591,7 @@ impl MemberProfileChange { } /// The avatar URL change induced by this event. - pub fn avatar_url_change(&self) -> Option<&Change>> { + pub fn avatar_url_change(&self) -> Option<&Change>> { self.avatar_url_change.as_ref() } diff --git a/crates/matrix-sdk-ui/src/timeline/event_item/content/msg_like.rs b/crates/matrix-sdk-ui/src/timeline/event_item/content/msg_like.rs index 9e2a482459b..4cd4733bbf8 100644 --- a/crates/matrix-sdk-ui/src/timeline/event_item/content/msg_like.rs +++ b/crates/matrix-sdk-ui/src/timeline/event_item/content/msg_like.rs @@ -13,7 +13,7 @@ // limitations under the License. use as_variant::as_variant; -use ruma::OwnedEventId; +use ruma::EventId; use super::{EmbeddedEvent, EncryptedMessage, InReplyToDetails, Message, PollState, Sticker}; use crate::timeline::{ @@ -55,11 +55,11 @@ pub struct ThreadSummary { pub num_replies: u32, /// The user's own public read receipt event id, for this particular thread. - pub public_read_receipt_event_id: Option, + pub public_read_receipt_event_id: Option, /// The user's own private read receipt event id, for this particular /// thread. - pub private_read_receipt_event_id: Option, + pub private_read_receipt_event_id: Option, } /// A special kind of [`super::TimelineItemContent`] that groups together @@ -72,7 +72,7 @@ pub struct MsgLikeContent { /// The event this message is replying to, if any. pub in_reply_to: Option, /// Event ID of the thread root, if this is a message in a thread. - pub thread_root: Option, + pub thread_root: Option, /// Information about the thread this message is the root of, if any. pub thread_summary: Option, } diff --git a/crates/matrix-sdk-ui/src/timeline/event_item/content/pinned_events.rs b/crates/matrix-sdk-ui/src/timeline/event_item/content/pinned_events.rs index d41ba569fcb..4f784b2f12f 100644 --- a/crates/matrix-sdk-ui/src/timeline/event_item/content/pinned_events.rs +++ b/crates/matrix-sdk-ui/src/timeline/event_item/content/pinned_events.rs @@ -15,7 +15,7 @@ use std::collections::HashSet; use ruma::{ - OwnedEventId, + EventId, events::{FullStateEventContent, room::pinned_events::RoomPinnedEventsEventContent}, }; @@ -36,11 +36,9 @@ impl From<&FullStateEventContent> for RoomPinnedEv match value { FullStateEventContent::Original { content, prev_content } => { if let Some(prev_content) = prev_content { - let mut new_pinned: HashSet<&OwnedEventId> = - HashSet::from_iter(&content.pinned); + let mut new_pinned: HashSet<&EventId> = HashSet::from_iter(&content.pinned); if let Some(old_pinned) = &prev_content.pinned { - let mut still_pinned: HashSet<&OwnedEventId> = - HashSet::from_iter(old_pinned); + let mut still_pinned: HashSet<&EventId> = HashSet::from_iter(old_pinned); // Newly added elements will be kept in new_pinned, previous ones in // still_pinned instead diff --git a/crates/matrix-sdk-ui/src/timeline/event_item/content/polls.rs b/crates/matrix-sdk-ui/src/timeline/event_item/content/polls.rs index 587a49cf4cc..afd059d1206 100644 --- a/crates/matrix-sdk-ui/src/timeline/event_item/content/polls.rs +++ b/crates/matrix-sdk-ui/src/timeline/event_item/content/polls.rs @@ -17,7 +17,7 @@ use std::collections::HashMap; use ruma::{ - MilliSecondsSinceUnixEpoch, OwnedUserId, UserId, + MilliSecondsSinceUnixEpoch, UserId, events::poll::{ PollResponseData, compile_unstable_poll_results, start::PollKind, @@ -47,7 +47,7 @@ pub struct PollState { #[derive(Clone, Debug)] pub(in crate::timeline) struct ResponseData { - pub sender: OwnedUserId, + pub sender: UserId, pub timestamp: MilliSecondsSinceUnixEpoch, pub answers: Vec, } @@ -86,7 +86,7 @@ impl PollState { /// Add a response to a poll. pub(crate) fn add_response( &mut self, - sender: OwnedUserId, + sender: UserId, timestamp: MilliSecondsSinceUnixEpoch, answers: Vec, ) { diff --git a/crates/matrix-sdk-ui/src/timeline/event_item/content/reply.rs b/crates/matrix-sdk-ui/src/timeline/event_item/content/reply.rs index 2f299fbf42a..a388af519e1 100644 --- a/crates/matrix-sdk-ui/src/timeline/event_item/content/reply.rs +++ b/crates/matrix-sdk-ui/src/timeline/event_item/content/reply.rs @@ -16,7 +16,7 @@ use std::sync::Arc; use imbl::Vector; use matrix_sdk::deserialized_responses::TimelineEvent; -use ruma::{MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedUserId}; +use ruma::{EventId, MilliSecondsSinceUnixEpoch, UserId}; use tracing::{debug, instrument, warn}; use super::TimelineItemContent; @@ -33,7 +33,7 @@ use crate::timeline::{ #[derive(Clone, Debug)] pub struct InReplyToDetails { /// The ID of the event. - pub event_id: OwnedEventId, + pub event_id: EventId, /// The details of the event. /// @@ -45,14 +45,11 @@ pub struct InReplyToDetails { } impl InReplyToDetails { - pub fn new( - event_id: OwnedEventId, - timeline_items: &Vector>, - ) -> InReplyToDetails { + pub fn new(event_id: EventId, timeline_items: &Vector>) -> InReplyToDetails { let event = timeline_items .iter() .filter_map(|it| it.as_event()) - .find(|it| it.event_id() == Some(&*event_id)) + .find(|it| it.event_id() == Some(&event_id)) .map(|item| Box::new(EmbeddedEvent::from_timeline_item(item))); InReplyToDetails { event_id, event: TimelineDetails::from_initial_value(event) } @@ -66,7 +63,7 @@ pub struct EmbeddedEvent { /// The content of the embedded item. pub content: TimelineItemContent, /// The user ID of the sender of the related embedded event. - pub sender: OwnedUserId, + pub sender: UserId, /// The profile of the sender of the related embedded event. pub sender_profile: TimelineDetails, /// The timestamp of the event. diff --git a/crates/matrix-sdk-ui/src/timeline/event_item/local.rs b/crates/matrix-sdk-ui/src/timeline/event_item/local.rs index d6931d2b4c3..509423ad086 100644 --- a/crates/matrix-sdk-ui/src/timeline/event_item/local.rs +++ b/crates/matrix-sdk-ui/src/timeline/event_item/local.rs @@ -19,7 +19,7 @@ use matrix_sdk::{ Error, send_queue::{AbstractProgress, SendHandle}, }; -use ruma::{EventId, OwnedEventId, OwnedTransactionId}; +use ruma::{EventId, TransactionId}; use super::TimelineEventItemId; @@ -30,7 +30,7 @@ pub(in crate::timeline) struct LocalEventTimelineItem { /// The send state of this local event. pub send_state: EventSendState, /// The transaction ID. - pub transaction_id: OwnedTransactionId, + pub transaction_id: TransactionId, /// A handle to manipulate this event before it is sent, if possible. pub send_handle: Option, } @@ -88,7 +88,7 @@ pub enum EventSendState { /// The local event has been sent successfully to the server. Sent { /// The event ID assigned by the server. - event_id: OwnedEventId, + event_id: EventId, }, } diff --git a/crates/matrix-sdk-ui/src/timeline/event_item/mod.rs b/crates/matrix-sdk-ui/src/timeline/event_item/mod.rs index d042b5564dc..68b2574e9f5 100644 --- a/crates/matrix-sdk-ui/src/timeline/event_item/mod.rs +++ b/crates/matrix-sdk-ui/src/timeline/event_item/mod.rs @@ -26,8 +26,7 @@ use matrix_sdk::{ }; use matrix_sdk_base::deserialized_responses::ShieldStateCode; use ruma::{ - EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedMxcUri, OwnedTransactionId, - OwnedUserId, TransactionId, UserId, + EventId, MilliSecondsSinceUnixEpoch, MxcUri, TransactionId, UserId, events::{AnySyncTimelineEvent, receipt::Receipt, room::message::MessageType}, room_version_rules::RedactionRules, serde::Raw, @@ -63,14 +62,14 @@ pub(super) use self::{ #[derive(Clone, Debug)] pub struct EventTimelineItem { /// The sender of the event. - pub(super) sender: OwnedUserId, + pub(super) sender: UserId, /// The sender's profile of the event. pub(super) sender_profile: TimelineDetails, /// If the keys used to decrypt this event were shared-on-invite as part of /// an [MSC4268] key bundle, the user ID of the forwarder. /// /// [MSC4268]: https://github.com/matrix-org/matrix-spec-proposals/pull/4268 - pub(super) forwarder: Option, + pub(super) forwarder: Option, /// If the keys used to decrypt this event were shared-on-invite as part of /// an [MSC4268] key bundle, the forwarder's profile, if present. /// @@ -101,9 +100,9 @@ pub(super) enum EventTimelineItemKind { pub enum TimelineEventItemId { /// The item is local, identified by its transaction id (to be used in /// subsequent requests). - TransactionId(OwnedTransactionId), + TransactionId(TransactionId), /// The item is remote, identified by its event id. - EventId(OwnedEventId), + EventId(EventId), } /// An handle that usually allows to perform an action on a timeline event. @@ -119,9 +118,9 @@ pub(crate) enum TimelineItemHandle<'a> { impl EventTimelineItem { #[allow(clippy::too_many_arguments)] pub(super) fn new( - sender: OwnedUserId, + sender: UserId, sender_profile: TimelineDetails, - forwarder: Option, + forwarder: Option, forwarder_profile: Option>, timestamp: MilliSecondsSinceUnixEpoch, content: TimelineItemContent, @@ -242,7 +241,7 @@ impl EventTimelineItem { /// /// [MSC4268]: https://github.com/matrix-org/matrix-spec-proposals/pull/4268 pub fn forwarder(&self) -> Option<&UserId> { - self.forwarder.as_deref() + self.forwarder.as_ref() } /// If the keys used to decrypt this event were shared-on-invite as part of @@ -269,8 +268,8 @@ impl EventTimelineItem { /// read receipt. /// /// Note that currently this ignores threads. - pub fn read_receipts(&self) -> &IndexMap { - static EMPTY_RECEIPTS: LazyLock> = + pub fn read_receipts(&self) -> &IndexMap { + static EMPTY_RECEIPTS: LazyLock> = LazyLock::new(Default::default); match &self.kind { EventTimelineItemKind::Local(_) => &EMPTY_RECEIPTS, @@ -610,7 +609,7 @@ pub struct Profile { pub display_name_ambiguous: bool, /// The avatar URL, if set. - pub avatar_url: Option, + pub avatar_url: Option, } /// Some details of an [`EventTimelineItem`] that may require server requests @@ -677,7 +676,7 @@ pub enum ReactionStatus { /// It's a remote reaction to a remote event. /// /// The event id is that of the reaction event (not the target event). - RemoteToRemote(OwnedEventId), + RemoteToRemote(EventId), } /// Information about a single reaction stored in [`ReactionsByKeyBySender`]. @@ -693,10 +692,10 @@ pub struct ReactionInfo { /// This representation makes sure that a given sender has sent at most one /// reaction for an event. #[derive(Debug, Clone, Default)] -pub struct ReactionsByKeyBySender(IndexMap>); +pub struct ReactionsByKeyBySender(IndexMap>); impl Deref for ReactionsByKeyBySender { - type Target = IndexMap>; + type Target = IndexMap>; fn deref(&self) -> &Self::Target { &self.0 diff --git a/crates/matrix-sdk-ui/src/timeline/event_item/remote.rs b/crates/matrix-sdk-ui/src/timeline/event_item/remote.rs index 7cee29748db..b0075ea247f 100644 --- a/crates/matrix-sdk-ui/src/timeline/event_item/remote.rs +++ b/crates/matrix-sdk-ui/src/timeline/event_item/remote.rs @@ -17,7 +17,7 @@ use std::{fmt, sync::Arc}; use indexmap::IndexMap; use matrix_sdk::deserialized_responses::EncryptionInfo; use ruma::{ - OwnedEventId, OwnedTransactionId, OwnedUserId, + EventId, TransactionId, UserId, events::{AnySyncTimelineEvent, receipt::Receipt}, serde::Raw, }; @@ -26,10 +26,10 @@ use ruma::{ #[derive(Clone)] pub(in crate::timeline) struct RemoteEventTimelineItem { /// The event ID. - pub event_id: OwnedEventId, + pub event_id: EventId, /// If available, the transaction id we've used to send this event. - pub transaction_id: Option, + pub transaction_id: Option, /// All read receipts for the event. /// @@ -37,7 +37,7 @@ pub(in crate::timeline) struct RemoteEventTimelineItem { /// read receipt. /// /// Note that currently this ignores threads. - pub read_receipts: IndexMap, + pub read_receipts: IndexMap, /// Whether the event has been sent by the logged-in user themselves. pub is_own: bool, diff --git a/crates/matrix-sdk-ui/src/timeline/latest_event.rs b/crates/matrix-sdk-ui/src/timeline/latest_event.rs index ef91e6e2a48..ad1e12b792f 100644 --- a/crates/matrix-sdk-ui/src/timeline/latest_event.rs +++ b/crates/matrix-sdk-ui/src/timeline/latest_event.rs @@ -15,7 +15,7 @@ use matrix_sdk::{Client, Room, latest_events::LocalLatestEventValue}; use matrix_sdk_base::latest_event::LatestEventValue as BaseLatestEventValue; use ruma::{ - MilliSecondsSinceUnixEpoch, OwnedUserId, + MilliSecondsSinceUnixEpoch, UserId, events::{ AnyMessageLikeEventContent, relation::Replacement, room::message::RoomMessageEventContent, }, @@ -41,7 +41,7 @@ pub enum LatestEventValue { timestamp: MilliSecondsSinceUnixEpoch, /// The sender of the remote event. - sender: OwnedUserId, + sender: UserId, /// Has this event been sent by the current logged user? is_own: bool, @@ -59,7 +59,7 @@ pub enum LatestEventValue { timestamp: MilliSecondsSinceUnixEpoch, /// The inviter (can be unknown). - inviter: Option, + inviter: Option, /// The inviter's profile (can be unknown). inviter_profile: TimelineDetails, @@ -73,7 +73,7 @@ pub enum LatestEventValue { timestamp: MilliSecondsSinceUnixEpoch, /// The sender of the remote event. - sender: OwnedUserId, + sender: UserId, /// The sender's profile. profile: TimelineDetails, @@ -322,7 +322,7 @@ mod tests { assert_matches!(value, LatestEventValue::RemoteInvite { timestamp, inviter, inviter_profile} => { assert_eq!(u64::from(timestamp.get()), 42u64); - assert_eq!(inviter.as_deref(), Some(user_id)); + assert_eq!(inviter.as_ref(), Some(user_id)); assert_matches!(inviter_profile, TimelineDetails::Unavailable); }) } diff --git a/crates/matrix-sdk-ui/src/timeline/mod.rs b/crates/matrix-sdk-ui/src/timeline/mod.rs index 4933c92b35a..f7082d7c658 100644 --- a/crates/matrix-sdk-ui/src/timeline/mod.rs +++ b/crates/matrix-sdk-ui/src/timeline/mod.rs @@ -40,7 +40,7 @@ use matrix_sdk::{ }; use mime::Mime; use ruma::{ - EventId, OwnedEventId, OwnedTransactionId, UserId, + EventId, TransactionId, UserId, api::client::receipt::create_receipt::v3::ReceiptType, events::{ AnyMessageLikeEventContent, AnySyncTimelineEvent, Mentions, @@ -135,14 +135,14 @@ pub enum TimelineFocus { /// Focus on a specific event, e.g. after clicking a permalink. Event { - target: OwnedEventId, + target: EventId, num_context_events: u16, /// How to handle threaded events. thread_mode: TimelineEventFocusThreadMode, }, /// Focus on a specific thread - Thread { root_event_id: OwnedEventId }, + Thread { root_event_id: EventId }, /// Only show pinned events. PinnedEvents, @@ -199,12 +199,12 @@ pub enum DateDividerMode { /// deciding to fill the rest of the reply parameters. #[derive(Debug, Default)] pub struct AttachmentConfig { - pub txn_id: Option, + pub txn_id: Option, pub info: Option, pub thumbnail: Option, pub caption: Option, pub mentions: Option, - pub in_reply_to: Option, + pub in_reply_to: Option, } impl Timeline { @@ -271,7 +271,7 @@ impl Timeline { } /// Get the latest of the timeline's remote event ids. - pub async fn latest_event_id(&self) -> Option { + pub async fn latest_event_id(&self) -> Option { self.controller.latest_event_id().await } @@ -383,7 +383,7 @@ impl Timeline { pub async fn send_reply( &self, content: RoomMessageEventContentWithoutRelation, - in_reply_to: OwnedEventId, + in_reply_to: EventId, ) -> Result<(), Error> { let reply = self .infer_reply(Some(in_reply_to)) @@ -397,7 +397,7 @@ impl Timeline { /// Given a message or media to send, and an optional `in_reply_to` event, /// automatically fills the [`Reply`] information based on the current /// timeline focus. - pub(crate) async fn infer_reply(&self, in_reply_to: Option) -> Option { + pub(crate) async fn infer_reply(&self, in_reply_to: Option) -> Option { // If there's a replied-to event id, the reply is pretty straightforward, and we // should only infer the `EnforceThread` based on the current focus. if let Some(in_reply_to) = in_reply_to { @@ -669,10 +669,7 @@ impl Timeline { /// receipts received from the homeserver, this keeps also track of implicit /// read receipts in this timeline, i.e. when a room member sends an event. #[instrument(skip(self))] - pub async fn latest_user_read_receipt( - &self, - user_id: &UserId, - ) -> Option<(OwnedEventId, Receipt)> { + pub async fn latest_user_read_receipt(&self, user_id: &UserId) -> Option<(EventId, Receipt)> { self.controller.latest_user_read_receipt(user_id).await } @@ -687,7 +684,7 @@ impl Timeline { pub async fn latest_user_read_receipt_timeline_event_id( &self, user_id: &UserId, - ) -> Option { + ) -> Option { self.controller.latest_user_read_receipt_timeline_event_id(user_id).await } @@ -713,7 +710,7 @@ impl Timeline { pub async fn send_single_receipt( &self, receipt_type: ReceiptType, - event_id: OwnedEventId, + event_id: EventId, ) -> Result { let thread = self.controller.infer_thread_for_read_receipt(&receipt_type); @@ -938,11 +935,11 @@ where #[cfg(feature = "unstable-msc4274")] #[derive(Debug, Default)] pub struct GalleryConfig { - pub(crate) txn_id: Option, + pub(crate) txn_id: Option, pub(crate) items: Vec, pub(crate) caption: Option, pub(crate) mentions: Option, - pub(crate) in_reply_to: Option, + pub(crate) in_reply_to: Option, } #[cfg(feature = "unstable-msc4274")] @@ -960,7 +957,7 @@ impl GalleryConfig { /// in its unsigned field as `transaction_id`. If not given, one is /// created for the message. #[must_use] - pub fn txn_id(mut self, txn_id: OwnedTransactionId) -> Self { + pub fn txn_id(mut self, txn_id: TransactionId) -> Self { self.txn_id = Some(txn_id); self } @@ -1001,7 +998,7 @@ impl GalleryConfig { /// # Arguments /// /// * `event_id` - The event ID to reply to. - pub fn in_reply_to(mut self, event_id: Option) -> Self { + pub fn in_reply_to(mut self, event_id: Option) -> Self { self.in_reply_to = event_id; self } diff --git a/crates/matrix-sdk-ui/src/timeline/tasks.rs b/crates/matrix-sdk-ui/src/timeline/tasks.rs index 6777d8057ff..415633d3c99 100644 --- a/crates/matrix-sdk-ui/src/timeline/tasks.rs +++ b/crates/matrix-sdk-ui/src/timeline/tasks.rs @@ -23,7 +23,7 @@ use matrix_sdk::{ }, send_queue::RoomSendQueueUpdate, }; -use ruma::OwnedEventId; +use ruma::EventId; use tokio::sync::broadcast::{Receiver, error::RecvError}; use tracing::{error, instrument, trace, warn}; @@ -90,7 +90,7 @@ pub(in crate::timeline) async fn thread_updates_task( mut receiver: Receiver, room_event_cache: RoomEventCache, timeline_controller: TimelineController, - root: OwnedEventId, + root: EventId, ) { trace!("Spawned the thread event subscriber task."); diff --git a/crates/matrix-sdk-ui/src/timeline/tests/mod.rs b/crates/matrix-sdk-ui/src/timeline/tests/mod.rs index 4932bfc0d3d..353e3e3b8f0 100644 --- a/crates/matrix-sdk-ui/src/timeline/tests/mod.rs +++ b/crates/matrix-sdk-ui/src/timeline/tests/mod.rs @@ -37,8 +37,7 @@ use matrix_sdk::{ use matrix_sdk_base::{RoomInfo, RoomState, crypto::types::events::CryptoContextInfo}; use matrix_sdk_test::{ALICE, DEFAULT_TEST_ROOM_ID, event_factory::EventFactory}; use ruma::{ - EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedTransactionId, OwnedUserId, - TransactionId, UInt, UserId, + EventId, MilliSecondsSinceUnixEpoch, TransactionId, UInt, UserId, events::{ AnyMessageLikeEventContent, AnyTimelineEvent, reaction::ReactionEventContent, @@ -168,7 +167,7 @@ impl TestTimeline { .await; } - async fn handle_local_event(&self, content: AnyMessageLikeEventContent) -> OwnedTransactionId { + async fn handle_local_event(&self, content: AnyMessageLikeEventContent) -> TransactionId { let txn_id = TransactionId::new(); self.controller.handle_local_event(txn_id.clone(), content, None).await; txn_id @@ -186,7 +185,7 @@ impl TestTimeline { async fn handle_read_receipts( &self, - receipts: impl IntoIterator, + receipts: impl IntoIterator, ) { let mut read_receipt = self.factory.read_receipts(); for (event_id, tyype, user_id, thread) in receipts { @@ -231,12 +230,12 @@ impl TestTimeline { } type ReadReceiptMap = - HashMap>>; + HashMap>>; #[derive(Clone, Debug, Default)] struct TestRoomDataProvider { /// The ID of our own user. - own_user_id: Option, + own_user_id: Option, /// The initial list of user receipts for that room. /// @@ -246,13 +245,13 @@ struct TestRoomDataProvider { /// Event id of the event pointed to by the fully read marker. /// /// Configurable at construction, static for the lifetime of the provider. - fully_read_marker: Option, + fully_read_marker: Option, /// Events sent with that room data provider. pub sent_events: Arc>>, /// Events redacted with that room data providier. - pub redacted: Arc>>, + pub redacted: Arc>>, } impl TestRoomDataProvider { @@ -261,7 +260,7 @@ impl TestRoomDataProvider { self } - fn with_fully_read_marker(mut self, event_id: OwnedEventId) -> Self { + fn with_fully_read_marker(mut self, event_id: EventId) -> Self { self.fully_read_marker = Some(event_id); self } @@ -285,23 +284,20 @@ impl PaginableRoom for TestRoomDataProvider { impl PaginableThread for TestRoomDataProvider { async fn relations( &self, - _thread_root: OwnedEventId, + _thread_root: EventId, _opts: matrix_sdk::room::RelationsOptions, ) -> Result { unimplemented!(); } - async fn load_event( - &self, - _event_id: &OwnedEventId, - ) -> Result { + async fn load_event(&self, _event_id: &EventId) -> Result { unimplemented!(); } } impl RoomDataProvider for TestRoomDataProvider { fn own_user_id(&self) -> &UserId { - self.own_user_id.as_deref().unwrap_or(&ALICE) + self.own_user_id.as_ref().unwrap_or(&ALICE) } fn room_version_rules(&self) -> RoomVersionRules { @@ -329,7 +325,7 @@ impl RoomDataProvider for TestRoomDataProvider { receipt_type: ReceiptType, thread: ReceiptThread, user_id: &'a UserId, - ) -> Option<(OwnedEventId, Receipt)> { + ) -> Option<(EventId, Receipt)> { self.initial_user_receipts .get(&receipt_type) .and_then(|thread_map| thread_map.get(&thread)) @@ -341,7 +337,7 @@ impl RoomDataProvider for TestRoomDataProvider { &'a self, event_id: &'a EventId, _receipt_thread: ReceiptThread, - ) -> IndexMap { + ) -> IndexMap { let mut map = IndexMap::new(); for (user_id, (receipt_event_id, receipt)) in @@ -355,7 +351,7 @@ impl RoomDataProvider for TestRoomDataProvider { map } - async fn load_fully_read_marker(&self) -> Option { + async fn load_fully_read_marker(&self) -> Option { self.fully_read_marker.clone() } @@ -368,7 +364,7 @@ impl RoomDataProvider for TestRoomDataProvider { &'a self, event_id: &'a EventId, _reason: Option<&'a str>, - _transaction_id: Option, + _transaction_id: Option, ) -> Result<(), super::Error> { self.redacted.write().await.push(event_id.to_owned()); Ok(()) diff --git a/crates/matrix-sdk-ui/src/timeline/tests/polls.rs b/crates/matrix-sdk-ui/src/timeline/tests/polls.rs index 465e4638aee..8b1f368bda5 100644 --- a/crates/matrix-sdk-ui/src/timeline/tests/polls.rs +++ b/crates/matrix-sdk-ui/src/timeline/tests/polls.rs @@ -2,7 +2,7 @@ use assert_matches2::assert_let; use fakes::poll_a2; use matrix_sdk_test::{ALICE, BOB, async_test}; use ruma::{ - EventId, OwnedEventId, UserId, event_id, + EventId, UserId, event_id, events::poll::unstable_start::{ NewUnstablePollStartEventContent, ReplacementUnstablePollStartEventContent, UnstablePollStartContentBlock, UnstablePollStartEventContent, @@ -156,7 +156,7 @@ async fn test_a_somewhat_complex_voting_session_yields_the_expected_outcome() { #[async_test] async fn test_events_received_before_start_are_not_lost() { let timeline = TestTimeline::new(); - let poll_id: OwnedEventId = EventId::new(server_name!("dummy.server")); + let poll_id: EventId = EventId::new(server_name!("dummy.server")); // Alice votes timeline.send_poll_response(&ALICE, vec!["0"], &poll_id).await; diff --git a/crates/matrix-sdk-ui/src/timeline/tests/reactions.rs b/crates/matrix-sdk-ui/src/timeline/tests/reactions.rs index bf6671d8dfd..11c2ff4e4c3 100644 --- a/crates/matrix-sdk-ui/src/timeline/tests/reactions.rs +++ b/crates/matrix-sdk-ui/src/timeline/tests/reactions.rs @@ -22,8 +22,8 @@ use imbl::vector; use matrix_sdk::assert_next_matches_with_timeout; use matrix_sdk_test::{ALICE, BOB, async_test}; use ruma::{ - EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, event_id, - events::AnyMessageLikeEventContent, server_name, uint, + EventId, MilliSecondsSinceUnixEpoch, event_id, events::AnyMessageLikeEventContent, server_name, + uint, }; use stream_assert::{assert_next_matches, assert_pending}; use tokio::time::timeout; @@ -235,7 +235,7 @@ async fn test_initial_reaction_timestamp_is_stored() { async fn send_first_message( timeline: &TestTimeline, stream: &mut (impl Stream>> + Unpin), -) -> (TimelineEventItemId, OwnedEventId, usize) { +) -> (TimelineEventItemId, EventId, usize) { timeline.handle_live_event(timeline.factory.text_msg("I want you to react").sender(&BOB)).await; let item = assert_next_matches!(*stream, VectorDiff::PushBack { value } => value); diff --git a/crates/matrix-sdk-ui/src/timeline/traits.rs b/crates/matrix-sdk-ui/src/timeline/traits.rs index 9130b7640dd..cfd46df74d7 100644 --- a/crates/matrix-sdk-ui/src/timeline/traits.rs +++ b/crates/matrix-sdk-ui/src/timeline/traits.rs @@ -24,7 +24,7 @@ use matrix_sdk::{ }; use matrix_sdk_base::{RoomInfo, crypto::types::events::CryptoContextInfo}; use ruma::{ - EventId, OwnedEventId, OwnedTransactionId, OwnedUserId, UserId, + EventId, TransactionId, UserId, events::{ AnyMessageLikeEventContent, fully_read::FullyReadEventContent, @@ -105,17 +105,17 @@ pub(super) trait RoomDataProvider: receipt_type: ReceiptType, thread: ReceiptThread, user_id: &'a UserId, - ) -> impl Future> + SendOutsideWasm + 'a; + ) -> impl Future> + SendOutsideWasm + 'a; /// Loads read receipts for an event from the storage backend. fn load_event_receipts<'a>( &'a self, event_id: &'a EventId, receipt_thread: ReceiptThread, - ) -> impl Future> + SendOutsideWasm + 'a; + ) -> impl Future> + SendOutsideWasm + 'a; /// Load the current fully-read event id, from storage. - fn load_fully_read_marker(&self) -> impl Future> + '_; + fn load_fully_read_marker(&self) -> impl Future> + '_; /// Send an event to that room. fn send( @@ -128,7 +128,7 @@ pub(super) trait RoomDataProvider: &'a self, event_id: &'a EventId, reason: Option<&'a str>, - transaction_id: Option, + transaction_id: Option, ) -> impl Future> + SendOutsideWasm + 'a; fn room_info(&self) -> Subscriber; @@ -187,7 +187,7 @@ impl RoomDataProvider for Room { receipt_type: ReceiptType, thread: ReceiptThread, user_id: &'a UserId, - ) -> Option<(OwnedEventId, Receipt)> { + ) -> Option<(EventId, Receipt)> { match self.load_user_receipt(receipt_type.clone(), thread.clone(), user_id).await { Ok(receipt) => receipt, Err(e) => { @@ -206,7 +206,7 @@ impl RoomDataProvider for Room { &'a self, event_id: &'a EventId, receipt_thread: ReceiptThread, - ) -> IndexMap { + ) -> IndexMap { match self.load_event_receipts(ReceiptType::Read, receipt_thread.clone(), event_id).await { Ok(receipts) => receipts.into_iter().collect(), Err(e) => { @@ -216,7 +216,7 @@ impl RoomDataProvider for Room { } } - async fn load_fully_read_marker(&self) -> Option { + async fn load_fully_read_marker(&self) -> Option { match self.account_data_static::().await { Ok(Some(fully_read)) => match fully_read.deserialize() { Ok(fully_read) => Some(fully_read.content.event_id), @@ -242,7 +242,7 @@ impl RoomDataProvider for Room { &'a self, event_id: &'a EventId, reason: Option<&'a str>, - transaction_id: Option, + transaction_id: Option, ) -> Result<(), super::Error> { let _ = self .redact(event_id, reason, transaction_id) diff --git a/crates/matrix-sdk-ui/src/unable_to_decrypt_hook.rs b/crates/matrix-sdk-ui/src/unable_to_decrypt_hook.rs index 1268263b283..3e9e2622b8c 100644 --- a/crates/matrix-sdk-ui/src/unable_to_decrypt_hook.rs +++ b/crates/matrix-sdk-ui/src/unable_to_decrypt_hook.rs @@ -30,7 +30,7 @@ use matrix_sdk_base::{ crypto::types::events::UtdCause, }; use ruma::{ - EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedServerName, UserId, + EventId, MilliSecondsSinceUnixEpoch, ServerName, UserId, time::{Duration, Instant}, }; use tokio::sync::{Mutex as AsyncMutex, MutexGuard}; @@ -52,7 +52,7 @@ pub trait UnableToDecryptHook: std::fmt::Debug + SendOutsideWasm + SyncOutsideWa #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct UnableToDecryptInfo { /// The identifier of the event that couldn't get decrypted. - pub event_id: OwnedEventId, + pub event_id: EventId, /// If the event could be decrypted late (that is, the event was encrypted /// at first, but could be decrypted later on), then this indicates the @@ -74,11 +74,11 @@ pub struct UnableToDecryptInfo { pub user_trusts_own_identity: bool, /// The homeserver of the user that sent the undecryptable event. - pub sender_homeserver: OwnedServerName, + pub sender_homeserver: ServerName, /// Our local user's own homeserver, or `None` if the client is not logged /// in. - pub own_homeserver: Option, + pub own_homeserver: Option, } /// Data about a UTD event which we are waiting to report to the parent hook. @@ -121,7 +121,7 @@ pub struct UtdHookManager { /// /// Note: this is theoretically unbounded in size, although this set of /// tasks will degrow over time, as tasks expire after the max delay. - pending_delayed: Arc>>, + pending_delayed: Arc>>, /// Bloom filter containing the event IDs of events which have been reported /// as UTDs @@ -264,8 +264,8 @@ impl UtdHookManager { false }; - let own_homeserver = own_user_id.map(|id| id.server_name().to_owned()); - let sender_homeserver = sender_user_id.server_name().to_owned(); + let own_homeserver = own_user_id.map(|id| id.server_name()); + let sender_homeserver = sender_user_id.server_name(); let info = UnableToDecryptInfo { event_id: event_id.to_owned(), diff --git a/crates/matrix-sdk-ui/tests/integration/timeline/edit.rs b/crates/matrix-sdk-ui/tests/integration/timeline/edit.rs index bf271f2dba4..d445e7e8cc8 100644 --- a/crates/matrix-sdk-ui/tests/integration/timeline/edit.rs +++ b/crates/matrix-sdk-ui/tests/integration/timeline/edit.rs @@ -33,7 +33,7 @@ use matrix_sdk_ui::{ }, }; use ruma::{ - OwnedRoomId, event_id, + RoomId, event_id, events::{ AnyMessageLikeEventContent, AnyTimelineEvent, poll::unstable_start::{ @@ -743,7 +743,7 @@ struct PendingEditHelper { client: Client, server: MatrixMockServer, timeline: Timeline, - room_id: OwnedRoomId, + room_id: RoomId, } impl PendingEditHelper { diff --git a/crates/matrix-sdk-ui/tests/integration/timeline/pinned_event.rs b/crates/matrix-sdk-ui/tests/integration/timeline/pinned_event.rs index b93eee4ed59..90acfcbc5bd 100644 --- a/crates/matrix-sdk-ui/tests/integration/timeline/pinned_event.rs +++ b/crates/matrix-sdk-ui/tests/integration/timeline/pinned_event.rs @@ -19,8 +19,7 @@ use matrix_sdk_test::{ }; use matrix_sdk_ui::timeline::{RoomExt, TimelineBuilder, TimelineFocus}; use ruma::{ - EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, RoomId, UserId, assign, - event_id, + EventId, MilliSecondsSinceUnixEpoch, RoomId, UserId, assign, event_id, events::{ AnySyncTimelineEvent, AnyTimelineEvent, room::{ @@ -863,7 +862,7 @@ async fn test_ensure_max_concurrency_is_observed() { let (client, server) = logged_in_client_with_server().await; let room_id = owned_room_id!("!a_room:example.org"); - let pinned_event_ids: Vec = + let pinned_event_ids: Vec = (0..100).map(|idx| EventId::parse(format!("${idx}")).unwrap()).collect(); let max_concurrent_requests = 10; @@ -943,9 +942,9 @@ async fn mock_events_endpoint( /// event ids #[derive(Debug, Clone)] struct PinnedEventsSync { - room_id: OwnedRoomId, + room_id: RoomId, timeline_events: Vec>, - pinned_event_ids: Option>, + pinned_event_ids: Option>, } impl PinnedEventsSync { @@ -959,7 +958,7 @@ impl PinnedEventsSync { } fn with_pinned_event_ids(mut self, pinned_event_ids: Vec<&str>) -> Self { - let pinned_event_ids: Vec = pinned_event_ids + let pinned_event_ids: Vec = pinned_event_ids .into_iter() .map(|id| match EventId::parse(id) { Ok(id) => id, diff --git a/crates/matrix-sdk-ui/tests/integration/timeline/thread.rs b/crates/matrix-sdk-ui/tests/integration/timeline/thread.rs index a51b0032dd3..a0cec2f3400 100644 --- a/crates/matrix-sdk-ui/tests/integration/timeline/thread.rs +++ b/crates/matrix-sdk-ui/tests/integration/timeline/thread.rs @@ -365,7 +365,7 @@ async fn test_new_thread_reply_causes_thread_summary_update() { let event_item = value.as_event().unwrap(); assert_eq!(event_item.event_id().unwrap(), reply_event_id); assert!(event_item.content().thread_summary().is_none()); - assert_eq!(event_item.content().thread_root().as_deref(), Some(thread_event_id)); + assert_eq!(event_item.content().thread_root().as_ref(), Some(thread_event_id)); // First, the replied-to event (thread root) doesn't have any thread summary // info. let replied_to_details = value.as_event().unwrap().content().in_reply_to().unwrap().event; @@ -431,7 +431,7 @@ async fn test_new_thread_reply_causes_thread_summary_update() { let event_item = value.as_event().unwrap(); assert_eq!(event_item.event_id().unwrap(), another_reply_event_id); assert!(event_item.content().thread_summary().is_none()); - assert_eq!(event_item.content().thread_root().as_deref(), Some(thread_event_id)); + assert_eq!(event_item.content().thread_root().as_ref(), Some(thread_event_id)); // Then the first thread reply is updated with the up-to-date thread summary in // the replied-to event. @@ -2171,7 +2171,7 @@ async fn test_main_timeline_has_receipts_in_thread_summaries() { assert!(summary.latest_event.is_ready()); // The public read receipt event id is filled (but the private isn't). - assert_eq!(summary.public_read_receipt_event_id.as_deref(), Some(latest_event_id)); + assert_eq!(summary.public_read_receipt_event_id.as_ref(), Some(latest_event_id)); assert_eq!(summary.private_read_receipt_event_id, None); // Now, a new read receipt is received for the same thread (we haven't received @@ -2204,6 +2204,6 @@ async fn test_main_timeline_has_receipts_in_thread_summaries() { assert_let!(Some(summary) = event_item.content().thread_summary()); // Now, the private read receipt is *also* filled. - assert_eq!(summary.public_read_receipt_event_id.as_deref(), Some(latest_event_id)); - assert_eq!(summary.private_read_receipt_event_id.as_deref(), Some(new_latest_event_id)); + assert_eq!(summary.public_read_receipt_event_id.as_ref(), Some(latest_event_id)); + assert_eq!(summary.private_read_receipt_event_id.as_ref(), Some(new_latest_event_id)); } diff --git a/crates/matrix-sdk/README.md b/crates/matrix-sdk/README.md index dfeb942f4a8..a3ee49c7a48 100644 --- a/crates/matrix-sdk/README.md +++ b/crates/matrix-sdk/README.md @@ -32,7 +32,7 @@ use matrix_sdk::{ #[tokio::main] async fn main() -> anyhow::Result<()> { let alice = user_id!("@alice:example.org"); - let client = Client::builder().server_name(alice.server_name()).build().await?; + let client = Client::builder().server_name(&alice.server_name()).build().await?; // First we need to log in. client.matrix_auth().login_username(alice, "password").send().await?; @@ -92,4 +92,4 @@ more information on this, check out the [tracing_subscriber documentation]. [examples]: https://github.com/matrix-org/matrix-rust-sdk/tree/main/examples/ [tracing_subscriber documentation]: https://tracing.rs/tracing_subscriber/filter/struct.envfilter [`matrix_sdk_crypto`]: https://docs.rs/matrix-sdk-crypto/ -[`matrix_sdk_base`]: https://docs.rs/matrix-sdk-base/ \ No newline at end of file +[`matrix_sdk_base`]: https://docs.rs/matrix-sdk-base/ diff --git a/crates/matrix-sdk/src/account.rs b/crates/matrix-sdk/src/account.rs index 89f1ff89e29..530e8e88ed0 100644 --- a/crates/matrix-sdk/src/account.rs +++ b/crates/matrix-sdk/src/account.rs @@ -31,7 +31,7 @@ use mime::Mime; #[cfg(feature = "experimental-element-recent-emojis")] use ruma::api::client::config::set_global_account_data::v3::Request as UpdateGlobalAccountDataRequest; use ruma::{ - ClientSecret, MxcUri, OwnedMxcUri, OwnedRoomId, OwnedUserId, RoomId, SessionId, UInt, UserId, + ClientSecret, MxcUri, RoomId, SessionId, UInt, UserId, api::{ Metadata, client::{ @@ -176,7 +176,7 @@ impl Account { /// } /// # anyhow::Ok(()) }; /// ``` - pub async fn get_avatar_url(&self) -> Result> { + pub async fn get_avatar_url(&self) -> Result> { let user_id = self.client.user_id().ok_or(Error::AuthenticationRequired)?; #[allow(deprecated)] // get_profile_field fails when the response is {"avatar_url":null} 🤷‍♂️ @@ -210,7 +210,7 @@ impl Account { } /// Get the URL of the account's avatar, if is stored in cache. - pub async fn get_cached_avatar_url(&self) -> Result> { + pub async fn get_cached_avatar_url(&self) -> Result> { let user_id = self.client.user_id().ok_or(Error::AuthenticationRequired)?; let data = self .client @@ -312,7 +312,7 @@ impl Account { /// ``` /// /// [`Media::upload()`]: crate::Media::upload - pub async fn upload_avatar(&self, content_type: &Mime, data: Vec) -> Result { + pub async fn upload_avatar(&self, content_type: &Mime, data: Vec) -> Result { let upload_response = self.client.media().upload(content_type, data, None).await?; self.set_avatar_url(Some(&upload_response.content_uri)).await?; Ok(upload_response.content_uri) @@ -382,7 +382,7 @@ impl Account { /// [`ErrorCode::NotFound`]: ruma::api::client::error::ErrorCode::NotFound pub async fn fetch_profile_field_of( &self, - user_id: OwnedUserId, + user_id: UserId, field: ProfileFieldName, ) -> Result> { let request = get_profile_field::v3::Request::new(user_id, field); @@ -414,7 +414,7 @@ impl Account { /// [`ErrorCode::NotFound`]: ruma::api::client::error::ErrorCode::NotFound pub async fn fetch_profile_field_of_static( &self, - user_id: OwnedUserId, + user_id: UserId, ) -> Result> where F: StaticProfileField @@ -1014,7 +1014,7 @@ impl Account { /// * `room_id` - The room ID of the direct message room. /// * `user_ids` - The user IDs to be associated with this direct message /// room. - pub async fn mark_as_dm(&self, room_id: &RoomId, user_ids: &[OwnedUserId]) -> Result<()> { + pub async fn mark_as_dm(&self, room_id: &RoomId, user_ids: &[UserId]) -> Result<()> { use ruma::events::direct::DirectEventContent; // This function does a read/update/store of an account data event stored on the @@ -1127,7 +1127,7 @@ impl Account { } /// Retrieves the user's recently visited room list - pub async fn get_recently_visited_rooms(&self) -> Result> { + pub async fn get_recently_visited_rooms(&self) -> Result> { let user_id = self.client.user_id().ok_or(Error::AuthenticationRequired)?; let data = self .client @@ -1144,14 +1144,14 @@ impl Account { } /// Moves/inserts the given room to the front of the recently visited list - pub async fn track_recently_visited_room(&self, room_id: OwnedRoomId) -> Result<(), Error> { + pub async fn track_recently_visited_room(&self, room_id: RoomId) -> Result<(), Error> { let user_id = self.client.user_id().ok_or(Error::AuthenticationRequired)?; // Get the previously stored recently visited rooms let mut recently_visited_rooms = self.get_recently_visited_rooms().await?; // Remove all other occurrences of the new room_id - recently_visited_rooms.retain(|r| r != &room_id); + recently_visited_rooms.retain(|r| r != room_id); // And insert it as the most recent recently_visited_rooms.insert(0, room_id); diff --git a/crates/matrix-sdk/src/attachment.rs b/crates/matrix-sdk/src/attachment.rs index 67c2e0fe817..5db256f6d42 100644 --- a/crates/matrix-sdk/src/attachment.rs +++ b/crates/matrix-sdk/src/attachment.rs @@ -17,7 +17,7 @@ use std::time::Duration; use ruma::{ - OwnedTransactionId, UInt, assign, + TransactionId, UInt, assign, events::{ Mentions, room::{ @@ -183,7 +183,7 @@ pub struct AttachmentConfig { /// A fixed transaction id to be used for sending this attachment. /// /// Otherwise, a random one will be generated. - pub txn_id: Option, + pub txn_id: Option, /// Type-specific metadata about the attachment. pub info: Option, @@ -228,7 +228,7 @@ impl AttachmentConfig { /// in its unsigned field as `transaction_id`. If not given, one is /// created for the message. #[must_use] - pub fn txn_id(mut self, txn_id: OwnedTransactionId) -> Self { + pub fn txn_id(mut self, txn_id: TransactionId) -> Self { self.txn_id = Some(txn_id); self } @@ -280,7 +280,7 @@ impl AttachmentConfig { #[cfg(feature = "unstable-msc4274")] #[derive(Debug, Default)] pub struct GalleryConfig { - pub(crate) txn_id: Option, + pub(crate) txn_id: Option, pub(crate) items: Vec, pub(crate) caption: Option, pub(crate) mentions: Option, @@ -302,7 +302,7 @@ impl GalleryConfig { /// in its unsigned field as `transaction_id`. If not given, one is /// created for the message. #[must_use] - pub fn txn_id(mut self, txn_id: OwnedTransactionId) -> Self { + pub fn txn_id(mut self, txn_id: TransactionId) -> Self { self.txn_id = Some(txn_id); self } diff --git a/crates/matrix-sdk/src/authentication/oauth/account_management_url.rs b/crates/matrix-sdk/src/authentication/oauth/account_management_url.rs index 077c5aa7556..1bed8380a66 100644 --- a/crates/matrix-sdk/src/authentication/oauth/account_management_url.rs +++ b/crates/matrix-sdk/src/authentication/oauth/account_management_url.rs @@ -17,7 +17,7 @@ //! This is a Matrix extension introduced in [MSC4191](https://github.com/matrix-org/matrix-spec-proposals/pull/4191). use ruma::{ - OwnedDeviceId, + DeviceId, api::client::discovery::get_authorization_server_metadata::v1::AccountManagementAction, }; use url::Url; @@ -46,7 +46,7 @@ pub enum AccountManagementActionFull { /// The user wishes to view the details of a specific session. SessionView { /// The ID of the session to view the details of. - device_id: OwnedDeviceId, + device_id: DeviceId, }, /// `org.matrix.session_end` @@ -54,7 +54,7 @@ pub enum AccountManagementActionFull { /// The user wishes to end/log out of a specific session. SessionEnd { /// The ID of the session to end. - device_id: OwnedDeviceId, + device_id: DeviceId, }, /// `org.matrix.account_deactivate` diff --git a/crates/matrix-sdk/src/authentication/oauth/auth_code_builder.rs b/crates/matrix-sdk/src/authentication/oauth/auth_code_builder.rs index 27dd28a0ce6..e34d65730f7 100644 --- a/crates/matrix-sdk/src/authentication/oauth/auth_code_builder.rs +++ b/crates/matrix-sdk/src/authentication/oauth/auth_code_builder.rs @@ -18,7 +18,7 @@ use oauth2::{ AuthUrl, CsrfToken, PkceCodeChallenge, RedirectUrl, Scope, basic::BasicClient as OAuthClient, }; use ruma::{ - OwnedDeviceId, UserId, api::client::discovery::get_authorization_server_metadata::v1::Prompt, + DeviceId, UserId, api::client::discovery::get_authorization_server_metadata::v1::Prompt, }; use tracing::{info, instrument}; use url::Url; @@ -35,7 +35,7 @@ pub struct OAuthAuthCodeUrlBuilder { oauth: OAuth, registration_data: Option, scopes: Vec, - device_id: OwnedDeviceId, + device_id: DeviceId, redirect_uri: Url, prompt: Option>, login_hint: Option, @@ -45,7 +45,7 @@ impl OAuthAuthCodeUrlBuilder { pub(super) fn new( oauth: OAuth, scopes: Vec, - device_id: OwnedDeviceId, + device_id: DeviceId, redirect_uri: Url, registration_data: Option, ) -> Self { diff --git a/crates/matrix-sdk/src/authentication/oauth/mod.rs b/crates/matrix-sdk/src/authentication/oauth/mod.rs index efed6e6c41b..aaf20093d39 100644 --- a/crates/matrix-sdk/src/authentication/oauth/mod.rs +++ b/crates/matrix-sdk/src/authentication/oauth/mod.rs @@ -190,7 +190,7 @@ use oauth2::{ }; pub use oauth2::{ClientId, CsrfToken}; use ruma::{ - DeviceId, OwnedDeviceId, + DeviceId, api::client::discovery::get_authorization_server_metadata::{ self, v1::{AccountManagementAction, AuthorizationServerMetadata}, @@ -792,9 +792,9 @@ impl OAuth { /// The scopes to request for logging in and the corresponding device ID. fn login_scopes( - device_id: Option, + device_id: Option, additional_scopes: Option>, - ) -> (Vec, OwnedDeviceId) { + ) -> (Vec, DeviceId) { /// Scope to grand full access to the client-server API. const SCOPE_MATRIX_CLIENT_SERVER_API_FULL_ACCESS: &str = "urn:matrix:org.matrix.msc2967.client:api:*"; @@ -889,7 +889,7 @@ impl OAuth { pub fn login( &self, redirect_uri: Url, - device_id: Option, + device_id: Option, registration_data: Option, additional_scopes: Option>, ) -> OAuthAuthCodeUrlBuilder { @@ -941,7 +941,7 @@ impl OAuth { /// /// Returns an error if the request to get the user ID fails, or if the /// client was already logged in with a different session. - pub(crate) async fn load_session(&self, device_id: OwnedDeviceId) -> Result<()> { + pub(crate) async fn load_session(&self, device_id: DeviceId) -> Result<()> { // Get the user ID. let whoami_res = self.client.whoami().await.map_err(crate::Error::from)?; @@ -1016,7 +1016,7 @@ impl OAuth { async fn finish_authorization( &self, auth_code: AuthorizationCode, - ) -> Result { + ) -> Result { let data = self.data().ok_or(OAuthError::NotAuthenticated)?; let client_id = data.client_id.clone(); @@ -1070,7 +1070,7 @@ impl OAuth { async fn request_device_authorization( &self, server_metadata: &AuthorizationServerMetadata, - device_id: Option, + device_id: Option, ) -> Result { let (scopes, _) = Self::login_scopes(device_id, None); @@ -1739,7 +1739,7 @@ struct AuthorizationValidationData { server_metadata: AuthorizationServerMetadata, /// The device ID used in the scope. - device_id: OwnedDeviceId, + device_id: DeviceId, /// The URI where the end-user will be redirected after authorization. redirect_uri: RedirectUrl, diff --git a/crates/matrix-sdk/src/authentication/oauth/qrcode/login.rs b/crates/matrix-sdk/src/authentication/oauth/qrcode/login.rs index 507b12fc9f3..63acb7332ab 100644 --- a/crates/matrix-sdk/src/authentication/oauth/qrcode/login.rs +++ b/crates/matrix-sdk/src/authentication/oauth/qrcode/login.rs @@ -23,7 +23,7 @@ use matrix_sdk_base::{ }; use oauth2::{DeviceCodeErrorResponseType, StandardDeviceAuthorizationResponse}; use ruma::{ - OwnedDeviceId, + DeviceId, api::client::discovery::get_authorization_server_metadata::v1::AuthorizationServerMetadata, }; use tracing::trace; @@ -146,7 +146,7 @@ async fn finish_login( .activate( SessionMeta { user_id: whoami_response.user_id, - device_id: OwnedDeviceId::from(device_id.to_base64()), + device_id: DeviceId::from(device_id.to_base64()), }, RoomLoadSettings::default(), Some(account), diff --git a/crates/matrix-sdk/src/client/builder/homeserver_config.rs b/crates/matrix-sdk/src/client/builder/homeserver_config.rs index 2c1c3b8e2b5..13ebded0915 100644 --- a/crates/matrix-sdk/src/client/builder/homeserver_config.rs +++ b/crates/matrix-sdk/src/client/builder/homeserver_config.rs @@ -13,7 +13,7 @@ // limitations under the License. use ruma::{ - OwnedServerName, ServerName, + ServerName, api::client::discovery::{discover_homeserver, get_supported_versions}, }; use tracing::debug; @@ -31,7 +31,7 @@ pub(super) enum HomeserverConfig { HomeserverUrl(String), /// A server name, with the protocol put apart. - ServerName { server: OwnedServerName, protocol: UrlScheme }, + ServerName { server: ServerName, protocol: UrlScheme }, /// A server name with or without the protocol (it will fallback to `https` /// if absent), or a homeserver URL. @@ -215,7 +215,7 @@ pub(super) async fn get_supported_versions( #[cfg(all(test, not(target_family = "wasm")))] mod tests { use matrix_sdk_test::async_test; - use ruma::OwnedServerName; + use ruma::ServerName; use serde_json::json; use wiremock::{ Mock, MockServer, ResponseTemplate, @@ -259,7 +259,7 @@ mod tests { .await; let result = HomeserverConfig::ServerName { - server: OwnedServerName::try_from(server.address().to_string()).unwrap(), + server: ServerName::try_from(server.address().to_string()).unwrap(), protocol: UrlScheme::Http, } .discover(&http_client) diff --git a/crates/matrix-sdk/src/client/builder/mod.rs b/crates/matrix-sdk/src/client/builder/mod.rs index 04c5fdee2b7..5c6f4ca0d88 100644 --- a/crates/matrix-sdk/src/client/builder/mod.rs +++ b/crates/matrix-sdk/src/client/builder/mod.rs @@ -33,7 +33,7 @@ use matrix_sdk_common::cross_process_lock::CrossProcessLockConfig; #[cfg(feature = "sqlite")] use matrix_sdk_sqlite::SqliteStoreConfig; use ruma::{ - OwnedServerName, ServerName, + ServerName, api::{MatrixVersion, SupportedVersions, error::FromHttpResponseError}, }; use thiserror::Error; @@ -643,7 +643,7 @@ impl ClientBuilder { /// Creates a server name from a user supplied string. The string is first /// sanitized by removing whitespace, the http(s) scheme and any trailing /// slashes before being parsed. -pub fn sanitize_server_name(s: &str) -> crate::Result { +pub fn sanitize_server_name(s: &str) -> crate::Result { ServerName::parse( s.trim().trim_start_matches("http://").trim_start_matches("https://").trim_end_matches('/'), ) diff --git a/crates/matrix-sdk/src/client/mod.rs b/crates/matrix-sdk/src/client/mod.rs index c18f8eabc8a..2d6f7ec7929 100644 --- a/crates/matrix-sdk/src/client/mod.rs +++ b/crates/matrix-sdk/src/client/mod.rs @@ -45,8 +45,7 @@ use matrix_sdk_common::{cross_process_lock::CrossProcessLockConfig, ttl_cache::T #[cfg(feature = "e2e-encryption")] use ruma::events::{InitialStateEvent, room::encryption::RoomEncryptionEventContent}; use ruma::{ - DeviceId, OwnedDeviceId, OwnedEventId, OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, - RoomAliasId, RoomId, RoomOrAliasId, ServerName, UInt, UserId, + DeviceId, EventId, RoomAliasId, RoomId, RoomOrAliasId, ServerName, UInt, UserId, api::{ FeatureFlag, MatrixVersion, Metadata, OutgoingRequest, SupportedVersions, auth_scheme::{AuthScheme, SendAccessToken}, @@ -225,7 +224,7 @@ pub(crate) struct ClientLocks { /// Handler making sure we only have one group session sharing request in /// flight per room. #[cfg(feature = "e2e-encryption")] - pub(crate) group_session_deduplicated_handler: DeduplicatingHandler, + pub(crate) group_session_deduplicated_handler: DeduplicatingHandler, /// Lock making sure we're only doing one key claim request at a time. #[cfg(feature = "e2e-encryption")] @@ -233,15 +232,15 @@ pub(crate) struct ClientLocks { /// Handler to ensure that only one members request is running at a time, /// given a room. - pub(crate) members_request_deduplicated_handler: DeduplicatingHandler, + pub(crate) members_request_deduplicated_handler: DeduplicatingHandler, /// Handler to ensure that only one encryption state request is running at a /// time, given a room. - pub(crate) encryption_state_deduplicated_handler: DeduplicatingHandler, + pub(crate) encryption_state_deduplicated_handler: DeduplicatingHandler, /// Deduplicating handler for sending read receipts. The string is an /// internal implementation detail, see [`Self::send_single_receipt`]. - pub(crate) read_receipt_deduplicated_handler: DeduplicatingHandler<(String, OwnedEventId)>, + pub(crate) read_receipt_deduplicated_handler: DeduplicatingHandler<(String, EventId)>, #[cfg(feature = "e2e-encryption")] pub(crate) cross_process_crypto_store_lock: OnceCell>, @@ -319,7 +318,7 @@ pub(crate) struct ClientInner { /// A mapping of the times at which the current user sent typing notices, /// keyed by room. - pub(crate) typing_notice_times: StdRwLock>, + pub(crate) typing_notice_times: StdRwLock>, /// Event handlers. See `add_event_handler`. pub(crate) event_handlers: EventHandlerStore, @@ -328,7 +327,7 @@ pub(crate) struct ClientInner { notification_handlers: RwLock>, /// The sender-side of channels used to receive room updates. - pub(crate) room_update_channels: StdMutex>>, + pub(crate) room_update_channels: StdMutex>>, /// The sender-side of a channel used to observe all the room updates of a /// sync response. @@ -724,12 +723,12 @@ impl Client { /// Get the user id of the current owner of the client. pub fn user_id(&self) -> Option<&UserId> { - self.session_meta().map(|s| s.user_id.as_ref()) + self.session_meta().map(|s| &s.user_id) } /// Get the device ID that identifies the current session. pub fn device_id(&self) -> Option<&DeviceId> { - self.session_meta().map(|s| s.device_id.as_ref()) + self.session_meta().map(|s| &s.device_id) } /// Get the current access token for this session. @@ -1086,7 +1085,7 @@ impl Client { /// `Client::observe_room_events`. fn observe_room_events_impl( &self, - room_id: Option, + room_id: Option, ) -> ObservableEventHandler<(Ev, Ctx)> where Ev: SyncEvent + DeserializeOwned + SendOutsideWasm + SyncOutsideWasm + 'static, @@ -1335,11 +1334,11 @@ impl Client { pub async fn get_room_preview( &self, room_or_alias_id: &RoomOrAliasId, - via: Vec, + via: Vec, ) -> Result { - let room_id = match <&RoomId>::try_from(room_or_alias_id) { - Ok(room_id) => room_id.to_owned(), - Err(alias) => self.resolve_room_alias(alias).await?.room_id, + let room_id = match RoomId::try_from(room_or_alias_id) { + Ok(room_id) => room_id, + Err(alias) => self.resolve_room_alias(&alias).await?.room_id, }; if let Some(room) = self.get_room(&room_id) { @@ -1676,11 +1675,11 @@ impl Client { pub async fn join_room_by_id_or_alias( &self, alias: &RoomOrAliasId, - server_names: &[OwnedServerName], + server_names: &[ServerName], ) -> Result { let pre_join_info = { match alias.try_into() { - Ok(room_id) => self.prepare_join_room_by_id(room_id).await, + Ok(room_id) => self.prepare_join_room_by_id(&room_id).await, Err(_) => { // The id is a room alias. We assume (possibly incorrectly?) that we are not // responding to an invitation to the room, and therefore don't need to handle @@ -1717,7 +1716,8 @@ impl Client { /// # let homeserver = Url::parse("http://example.com").unwrap(); /// # let limit = Some(10); /// # let since = Some("since token"); - /// # let server = Some("servername.com".try_into().unwrap()); + /// # let server_name = "servername.com".try_into().unwrap(); + /// # let server = Some(&server_name); /// # async { /// let mut client = Client::new(homeserver).await.unwrap(); /// @@ -1832,7 +1832,7 @@ impl Client { // Find the room we share with the `user_id` and only with `user_id` let room = rooms.into_iter().find(|r| { let targets = r.direct_targets(); - targets.len() == 1 && targets.contains(<&DirectUserIdentifier>::from(user_id)) + targets.len() == 1 && targets.contains(&DirectUserIdentifier::from(user_id)) }); trace!(?user_id, ?room, "Found DM room with user"); @@ -2544,7 +2544,7 @@ impl Client { /// # anyhow::Ok(()) }; pub async fn delete_devices( &self, - devices: &[OwnedDeviceId], + devices: &[DeviceId], auth_data: Option, ) -> HttpResult { let mut request = delete_devices::v3::Request::new(devices.to_owned()); @@ -2581,7 +2581,7 @@ impl Client { /// # Arguments /// /// * `device_id` - The ID of the device to query. - pub async fn device_exists(&self, device_id: OwnedDeviceId) -> Result { + pub async fn device_exists(&self, device_id: DeviceId) -> Result { let request = device::get_device::v3::Request::new(device_id); match self.send(request).await { Ok(_) => Ok(true), @@ -3173,9 +3173,9 @@ impl Client { /// join it. pub async fn knock( &self, - room_id_or_alias: OwnedRoomOrAliasId, + room_id_or_alias: RoomOrAliasId, reason: Option, - server_names: Vec, + server_names: Vec, ) -> Result { let request = assign!(knock_room::v3::Request::new(room_id_or_alias), { reason, via: server_names }); @@ -3518,7 +3518,7 @@ pub(crate) mod tests { homeserver.mock_versions().ok().mock_once().named("versions").mount().await; let client = Client::builder() - .insecure_server_name_no_tls(alice.server_name()) + .insecure_server_name_no_tls(&alice.server_name()) .build() .await .unwrap(); @@ -3539,7 +3539,7 @@ pub(crate) mod tests { assert!( Client::builder() - .insecure_server_name_no_tls(alice.server_name()) + .insecure_server_name_no_tls(&alice.server_name()) .build() .await .is_err(), @@ -3865,7 +3865,7 @@ pub(crate) mod tests { let server = MatrixMockServer::new().await; let server_url = server.uri(); let domain = server_url.strip_prefix("http://").unwrap(); - let server_name = <&ServerName>::try_from(domain).unwrap(); + let server_name = ServerName::try_from(domain).unwrap(); let rtc_foci = vec![RtcFocusInfo::livekit("https://livekit.example.com".to_owned())]; let well_known_mock = server @@ -3878,7 +3878,7 @@ pub(crate) mod tests { let memory_store = Arc::new(MemoryStore::new()); let client = Client::builder() - .insecure_server_name_no_tls(server_name) + .insecure_server_name_no_tls(&server_name) .store_config( StoreConfig::new(CrossProcessLockConfig::SingleProcess) .state_store(memory_store.clone()), @@ -4155,7 +4155,7 @@ pub(crate) mod tests { // And we get a preview, the server endpoint was reached let preview = client - .get_room_preview(room_id.into(), Vec::new()) + .get_room_preview(&room_id.into(), Vec::new()) .await .expect("Room preview should be retrieved"); @@ -4177,7 +4177,7 @@ pub(crate) mod tests { // And we get a preview, the server endpoint was reached let preview = client - .get_room_preview(room_id.into(), Vec::new()) + .get_room_preview(&room_id.into(), Vec::new()) .await .expect("Room preview should be retrieved"); @@ -4199,7 +4199,7 @@ pub(crate) mod tests { // And we get a preview, the server endpoint was reached let preview = client - .get_room_preview(room_id.into(), Vec::new()) + .get_room_preview(&room_id.into(), Vec::new()) .await .expect("Room preview should be retrieved"); @@ -4221,7 +4221,7 @@ pub(crate) mod tests { // And we get a preview, no server endpoint was reached let preview = client - .get_room_preview(room_id.into(), Vec::new()) + .get_room_preview(&room_id.into(), Vec::new()) .await .expect("Room preview should be retrieved"); diff --git a/crates/matrix-sdk/src/client/thread_subscriptions.rs b/crates/matrix-sdk/src/client/thread_subscriptions.rs index 4e785881de1..e1a72d59e26 100644 --- a/crates/matrix-sdk/src/client/thread_subscriptions.rs +++ b/crates/matrix-sdk/src/client/thread_subscriptions.rs @@ -27,7 +27,7 @@ use matrix_sdk_base::{ }; use matrix_sdk_common::executor::spawn; use ruma::{ - EventId, OwnedEventId, OwnedRoomId, RoomId, + EventId, RoomId, api::client::threads::get_thread_subscriptions_changes::unstable::{ ThreadSubscription, ThreadUnsubscription, }, @@ -174,8 +174,8 @@ impl ThreadSubscriptionCatchup { #[instrument(skip_all)] pub(crate) async fn sync_subscriptions( &self, - subscribed: BTreeMap>, - unsubscribed: BTreeMap>, + subscribed: BTreeMap>, + unsubscribed: BTreeMap>, token: Option, ) -> Result<()> { // Precompute the updates so we don't hold the guard for too long. @@ -361,8 +361,8 @@ impl ThreadSubscriptionCatchup { /// Internal helper for building the thread subscription updates Vec. fn build_subscription_updates<'a>( - subscribed: &'a BTreeMap>, - unsubscribed: &'a BTreeMap>, + subscribed: &'a BTreeMap>, + unsubscribed: &'a BTreeMap>, ) -> Vec<(&'a RoomId, &'a EventId, StoredThreadSubscription)> { let mut updates: Vec<(&RoomId, &EventId, StoredThreadSubscription)> = Vec::with_capacity(unsubscribed.len() + subscribed.len()); diff --git a/crates/matrix-sdk/src/encryption/backups/mod.rs b/crates/matrix-sdk/src/encryption/backups/mod.rs index 621e9829ae7..e2455eca036 100644 --- a/crates/matrix-sdk/src/encryption/backups/mod.rs +++ b/crates/matrix-sdk/src/encryption/backups/mod.rs @@ -35,7 +35,7 @@ use matrix_sdk_base::crypto::{ #[cfg(feature = "experimental-encrypted-state-events")] use ruma::serde::JsonCastable; use ruma::{ - OwnedRoomId, RoomId, TransactionId, + RoomId, TransactionId, api::client::{ backup::{ RoomKeyBackup, add_backup_keys, create_backup_version, get_backup_keys, @@ -1000,7 +1000,7 @@ impl Backups { #[cfg(not(feature = "experimental-encrypted-state-events"))] pub(crate) fn maybe_download_room_key( &self, - room_id: OwnedRoomId, + room_id: RoomId, event: Raw, ) { let tasks = self.client.inner.e2ee.tasks.lock(); @@ -1014,7 +1014,7 @@ impl Backups { #[cfg(feature = "experimental-encrypted-state-events")] pub(crate) fn maybe_download_room_key>( &self, - room_id: OwnedRoomId, + room_id: RoomId, event: Raw, ) { let tasks = self.client.inner.e2ee.tasks.lock(); diff --git a/crates/matrix-sdk/src/encryption/identities/devices.rs b/crates/matrix-sdk/src/encryption/identities/devices.rs index 16024008b08..fcc867f8c65 100644 --- a/crates/matrix-sdk/src/encryption/identities/devices.rs +++ b/crates/matrix-sdk/src/encryption/identities/devices.rs @@ -18,7 +18,7 @@ use matrix_sdk_base::crypto::{ Device as BaseDevice, DeviceData, LocalTrust, UserDevices as BaseUserDevices, store::CryptoStoreError, }; -use ruma::{DeviceId, OwnedDeviceId, OwnedUserId, events::key::verification::VerificationMethod}; +use ruma::{DeviceId, UserId, events::key::verification::VerificationMethod}; use super::ManualVerifyError; use crate::{ @@ -36,9 +36,9 @@ pub struct DeviceUpdates { /// A device being in this list does not necessarily mean that the device /// was just created, it just means that it's the first time we're /// seeing this device. - pub new: BTreeMap>, + pub new: BTreeMap>, /// The list of changed devices. - pub changed: BTreeMap>, + pub changed: BTreeMap>, } impl DeviceUpdates { diff --git a/crates/matrix-sdk/src/encryption/identities/mod.rs b/crates/matrix-sdk/src/encryption/identities/mod.rs index 065e5a60ad6..21d1f1d15bf 100644 --- a/crates/matrix-sdk/src/encryption/identities/mod.rs +++ b/crates/matrix-sdk/src/encryption/identities/mod.rs @@ -113,5 +113,5 @@ pub enum RequestVerificationError { /// Verifying other users requires having a DM open with them, this error /// signals that we didn't have a DM and that we failed to create one. #[error("Couldn't create a DM with user {0} where the verification should take place")] - RoomCreation(ruma::OwnedUserId), + RoomCreation(ruma::UserId), } diff --git a/crates/matrix-sdk/src/encryption/identities/users.rs b/crates/matrix-sdk/src/encryption/identities/users.rs index 8e4a9d8f4fa..9c040c9c26d 100644 --- a/crates/matrix-sdk/src/encryption/identities/users.rs +++ b/crates/matrix-sdk/src/encryption/identities/users.rs @@ -19,7 +19,7 @@ use matrix_sdk_base::{ crypto::{CryptoStoreError, UserIdentity as CryptoUserIdentity, types::MasterPubkey}, }; use ruma::{ - OwnedUserId, UserId, + UserId, events::{key::verification::VerificationMethod, room::message::RoomMessageEventContent}, }; @@ -35,9 +35,9 @@ pub struct IdentityUpdates { /// A identity being in this list does not necessarily mean that the /// identity was just created, it just means that it's the first time /// we're seeing this identity. - pub new: BTreeMap, + pub new: BTreeMap, /// The list of changed identities. - pub changed: BTreeMap, + pub changed: BTreeMap, } impl IdentityUpdates { diff --git a/crates/matrix-sdk/src/encryption/mod.rs b/crates/matrix-sdk/src/encryption/mod.rs index f8600c902f8..aa69c1dc314 100644 --- a/crates/matrix-sdk/src/encryption/mod.rs +++ b/crates/matrix-sdk/src/encryption/mod.rs @@ -51,7 +51,7 @@ use matrix_sdk_base::{ }; use matrix_sdk_common::{executor::spawn, locks::Mutex as StdMutex}; use ruma::{ - DeviceId, MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedUserId, TransactionId, UserId, + DeviceId, MilliSecondsSinceUnixEpoch, TransactionId, UserId, api::client::{ error::{ErrorBody, StandardErrorBody}, keys::{ @@ -457,7 +457,7 @@ impl Client { pub(crate) async fn keys_query( &self, request_id: &TransactionId, - device_keys: BTreeMap>, + device_keys: BTreeMap>, ) -> Result { let request = assign!(get_keys::v3::Request::new(), { device_keys }); @@ -481,7 +481,7 @@ impl Client { /// ```no_run /// # use matrix_sdk::Client; /// # use url::Url; - /// # use matrix_sdk::ruma::{room_id, OwnedRoomId}; + /// # use matrix_sdk::ruma::{room_id, RoomId}; /// use serde::{Deserialize, Serialize}; /// use matrix_sdk::ruma::events::{macros::EventContent, room::EncryptedFile}; /// @@ -874,7 +874,7 @@ impl Encryption { /// /// Tracked users are users for which we keep the device list of E2EE /// capable devices up to date. - pub async fn tracked_users(&self) -> Result, CryptoStoreError> { + pub async fn tracked_users(&self) -> Result, CryptoStoreError> { if let Some(machine) = self.client.olm_machine().await.as_ref() { machine.tracked_users().await } else { @@ -1955,7 +1955,7 @@ impl Encryption { event_type: &str, content: Raw, share_strategy: CollectStrategy, - ) -> Result> { + ) -> Result> { let users = recipient_devices.iter().map(|device| device.user_id()); // Will claim one-time-key for users that needs it @@ -1977,7 +1977,7 @@ impl Encryption { ) .await?; - let mut failures: Vec<(OwnedUserId, OwnedDeviceId)> = Default::default(); + let mut failures: Vec<(UserId, DeviceId)> = Default::default(); // Push the withhelds in the failures withhelds.iter().for_each(|(d, _)| { diff --git a/crates/matrix-sdk/src/encryption/tasks.rs b/crates/matrix-sdk/src/encryption/tasks.rs index 60df6f7760c..b11b6499465 100644 --- a/crates/matrix-sdk/src/encryption/tasks.rs +++ b/crates/matrix-sdk/src/encryption/tasks.rs @@ -28,7 +28,7 @@ use matrix_sdk_common::failures_cache::FailuresCache; use ruma::events::room::encrypted::{EncryptedEventScheme, OriginalSyncRoomEncryptedEvent}; #[cfg(feature = "experimental-encrypted-state-events")] use ruma::serde::JsonCastable; -use ruma::{OwnedEventId, OwnedRoomId, serde::Raw}; +use ruma::{EventId, RoomId, serde::Raw}; use tokio::sync::{Mutex, mpsc}; use tracing::{debug, info, instrument, trace, warn}; @@ -107,10 +107,10 @@ impl BackupUploadingTask { #[derive(Debug)] struct RoomKeyDownloadRequest { /// The room in which the event was sent. - room_id: OwnedRoomId, + room_id: RoomId, /// The ID of the event we could not decrypt. - event_id: OwnedEventId, + event_id: EventId, /// The event we could not decrypt. #[cfg(not(feature = "experimental-encrypted-state-events"))] @@ -130,7 +130,7 @@ impl RoomKeyDownloadRequest { } } -pub type RoomKeyInfo = (OwnedRoomId, String); +pub type RoomKeyInfo = (RoomId, String); pub(crate) struct BackupDownloadTask { sender: mpsc::UnboundedSender, @@ -167,7 +167,7 @@ impl BackupDownloadTask { #[cfg(not(feature = "experimental-encrypted-state-events"))] pub(crate) fn trigger_download_for_utd_event( &self, - room_id: OwnedRoomId, + room_id: RoomId, event: Raw, ) { if let Ok(deserialized_event) = event.deserialize() @@ -190,7 +190,7 @@ impl BackupDownloadTask { #[cfg(feature = "experimental-encrypted-state-events")] pub(crate) fn trigger_download_for_utd_event>( &self, - room_id: OwnedRoomId, + room_id: RoomId, event: Raw, ) { if let Ok(deserialized_event) = event.deserialize_as::() { @@ -325,7 +325,7 @@ struct BackupDownloadTaskListenerState { failures_cache: FailuresCache, /// Map from event ID to download task - active_tasks: BTreeMap>, + active_tasks: BTreeMap>, /// A list of room keys that we have already downloaded, or are about to /// download. @@ -502,7 +502,7 @@ impl BundleReceiverTask { match (state, elapsed_since_join) { (RoomState::Joined, Some(elapsed_since_join)) => { - elapsed_since_join < DAY && bundle_sender == &inviter + elapsed_since_join < DAY && bundle_sender == inviter } (RoomState::Joined, None) => false, (RoomState::Left | RoomState::Invited | RoomState::Knocked | RoomState::Banned, _) => { diff --git a/crates/matrix-sdk/src/event_cache/caches/thread/pagination.rs b/crates/matrix-sdk/src/event_cache/caches/thread/pagination.rs index 37c06337ac5..d5cf0f1c159 100644 --- a/crates/matrix-sdk/src/event_cache/caches/thread/pagination.rs +++ b/crates/matrix-sdk/src/event_cache/caches/thread/pagination.rs @@ -17,7 +17,7 @@ use std::sync::Arc; use eyeball::SharedObservable; use eyeball_im::VectorDiff; use matrix_sdk_base::event_cache::Event; -use ruma::{OwnedEventId, api::Direction}; +use ruma::{EventId, api::Direction}; use super::super::super::{ EventCacheError, Result, @@ -33,7 +33,7 @@ use crate::room::{IncludeRelations, RelationsOptions}; /// `RoomEventCache`. struct ThreadEventCacheWrapper { cache: Arc, - thread_id: OwnedEventId, + thread_id: EventId, // Threads do not support pagination status for the moment but we need one, so let's use a // dummy one for now. dummy_pagination_status: SharedObservable, @@ -47,7 +47,7 @@ impl ThreadPagination { /// Construct a new [`ThreadPagination`]. pub(in super::super::super) fn new( cache: Arc, - thread_id: OwnedEventId, + thread_id: EventId, ) -> Self { Self(Pagination::new(ThreadEventCacheWrapper { cache, diff --git a/crates/matrix-sdk/src/event_cache/deduplicator.rs b/crates/matrix-sdk/src/event_cache/deduplicator.rs index b210953c7b6..ff462b56ba1 100644 --- a/crates/matrix-sdk/src/event_cache/deduplicator.rs +++ b/crates/matrix-sdk/src/event_cache/deduplicator.rs @@ -21,7 +21,7 @@ use matrix_sdk_base::{ event_cache::store::EventCacheStoreLockGuard, linked_chunk::{LinkedChunkId, Position}, }; -use ruma::{OwnedEventId, OwnedUserId, UserId}; +use ruma::{EventId, UserId}; use super::{ EventCacheError, @@ -84,7 +84,7 @@ pub async fn filter_duplicate_events( // rationale behind the following booleans. let at_least_one_event_not_sent_by_me = new_events.iter().any(|ev| { ev.raw() - .get_field::("sender") + .get_field::("sender") .ok() .flatten() .is_some_and(|sender| sender != own_user_id) @@ -117,7 +117,7 @@ pub(super) struct DeduplicationOutcome { /// /// Events are sorted by their position, from the newest to the oldest /// (position is descending). - pub in_memory_duplicated_event_ids: Vec<(OwnedEventId, Position)>, + pub in_memory_duplicated_event_ids: Vec<(EventId, Position)>, /// Events in [`Self::all_events`] that are duplicated and present in /// the store. It means they have **NOT** been loaded from the store into @@ -125,7 +125,7 @@ pub(super) struct DeduplicationOutcome { /// /// Events are sorted by their position, from the newest to the oldest /// (position is descending). - pub in_store_duplicated_event_ids: Vec<(OwnedEventId, Position)>, + pub in_store_duplicated_event_ids: Vec<(EventId, Position)>, /// Whether there's at least one new event sent by some other user, and all /// new events are duplicate. @@ -403,9 +403,9 @@ mod tests { assert!(non_empty_all_duplicates.not()); assert_eq!(events.len(), 3); - assert_eq!(events[0].event_id().as_deref(), Some(eid1)); - assert_eq!(events[1].event_id().as_deref(), Some(eid2)); - assert_eq!(events[2].event_id().as_deref(), Some(eid3)); + assert_eq!(events[0].event_id().as_ref(), Some(eid1)); + assert_eq!(events[1].event_id().as_ref(), Some(eid2)); + assert_eq!(events[2].event_id().as_ref(), Some(eid3)); assert!(in_memory_duplicated_event_ids.is_empty()); diff --git a/crates/matrix-sdk/src/event_cache/mod.rs b/crates/matrix-sdk/src/event_cache/mod.rs index be740a80558..2876dfab3ef 100644 --- a/crates/matrix-sdk/src/event_cache/mod.rs +++ b/crates/matrix-sdk/src/event_cache/mod.rs @@ -50,10 +50,7 @@ use matrix_sdk_base::{ task_monitor::BackgroundTaskHandle, timer, }; -use ruma::{ - OwnedEventId, OwnedRoomId, OwnedTransactionId, RoomId, events::AnySyncEphemeralRoomEvent, - serde::Raw, -}; +use ruma::{EventId, RoomId, TransactionId, events::AnySyncEphemeralRoomEvent, serde::Raw}; use tokio::{ select, sync::{ @@ -101,7 +98,7 @@ pub enum EventCacheError { #[error("Room `{room_id}` is not found.")] RoomNotFound { /// The ID of the room not being found. - room_id: OwnedRoomId, + room_id: RoomId, }, /// An error has been observed while back-paginating. @@ -622,7 +619,7 @@ impl EventCache { async fn handle_thread_subscriber_send_queue_update( client: &WeakClient, thread_subscriber_sender: &Sender<()>, - events_being_sent: &mut HashMap, + events_being_sent: &mut HashMap, up: SendQueueUpdate, ) -> bool { let Some(client) = client.get() else { @@ -890,7 +887,7 @@ struct EventCacheInner { multiple_room_updates_lock: Mutex<()>, /// Lazily-filled cache of live [`RoomEventCache`], once per room. - by_room: RwLock>, + by_room: RwLock>, /// Handles to keep alive the task listening to updates. drop_handles: OnceLock>, @@ -946,7 +943,7 @@ struct EventCacheInner { redecryption_channels: redecryptor::RedecryptorChannels, } -type AutoShrinkChannelPayload = OwnedRoomId; +type AutoShrinkChannelPayload = RoomId; impl EventCacheInner { fn client(&self) -> Result { @@ -1180,7 +1177,7 @@ impl EventCacheInner { #[derive(Clone, Debug)] pub struct RoomEventCacheGenericUpdate { /// The room ID owning the timeline. - pub room_id: OwnedRoomId, + pub room_id: RoomId, } /// An update being triggered when events change in the persisted event cache @@ -1228,7 +1225,7 @@ pub enum RoomEventCacheUpdate { /// The fully read marker has moved to a different event. MoveReadMarkerTo { /// Event at which the read marker is now pointing. - event_id: OwnedEventId, + event_id: EventId, }, /// The members have changed. @@ -1237,7 +1234,7 @@ pub enum RoomEventCacheUpdate { /// /// This is a map of event ID of the `m.room.member` event to the /// details of the ambiguity change. - ambiguity_changes: BTreeMap, + ambiguity_changes: BTreeMap, }, /// The room has received updates for the timeline as _diffs_. diff --git a/crates/matrix-sdk/src/event_cache/redecryptor.rs b/crates/matrix-sdk/src/event_cache/redecryptor.rs index ebb227c1abb..a68cb698a5b 100644 --- a/crates/matrix-sdk/src/event_cache/redecryptor.rs +++ b/crates/matrix-sdk/src/event_cache/redecryptor.rs @@ -138,7 +138,7 @@ use matrix_sdk_base::{ #[cfg(doc)] use matrix_sdk_common::deserialized_responses::EncryptionInfo; use ruma::{ - OwnedEventId, OwnedRoomId, RoomId, + EventId, RoomId, events::{AnySyncTimelineEvent, room::encrypted::OriginalSyncRoomEncryptedEvent}, push::Action, serde::Raw, @@ -168,17 +168,16 @@ use crate::{ type SessionId<'a> = &'a str; type OwnedSessionId = String; -type EventIdAndUtd = (OwnedEventId, Raw); -type EventIdAndEvent = (OwnedEventId, DecryptedRoomEvent); -pub(in crate::event_cache) type ResolvedUtd = - (OwnedEventId, DecryptedRoomEvent, Option>); +type EventIdAndUtd = (EventId, Raw); +type EventIdAndEvent = (EventId, DecryptedRoomEvent); +pub(in crate::event_cache) type ResolvedUtd = (EventId, DecryptedRoomEvent, Option>); /// The information sent across the channel to the long-running task requesting /// that the supplied set of sessions be retried. #[derive(Debug, Clone)] pub struct DecryptionRetryRequest { /// The room ID of the room the events belong to. - pub room_id: OwnedRoomId, + pub room_id: RoomId, /// Events that are not decrypted. pub utd_session_ids: BTreeSet, /// Events that are decrypted but might need to have their @@ -192,9 +191,9 @@ pub enum RedecryptorReport { /// Events which we were able to decrypt. ResolvedUtds { /// The room ID of the room the events belong to. - room_id: OwnedRoomId, + room_id: RoomId, /// The list of event IDs of the decrypted events. - events: BTreeSet, + events: BTreeSet, }, /// The redecryptor might have missed some room keys so it might not have /// re-decrypted events that are now decryptable. @@ -232,7 +231,7 @@ impl RedecryptorChannels { /// The tuple can be used to attempt to redecrypt events. fn filter_timeline_event_to_utd( event: TimelineEvent, -) -> Option<(OwnedEventId, Raw)> { +) -> Option<(EventId, Raw)> { let event_id = event.event_id(); // Only pick out events that are UTDs, get just the Raw event as this is what @@ -250,7 +249,7 @@ fn filter_timeline_event_to_utd( /// decrypted event. fn filter_timeline_event_to_decrypted( event: TimelineEvent, -) -> Option<(OwnedEventId, DecryptedRoomEvent)> { +) -> Option<(EventId, DecryptedRoomEvent)> { let event_id = event.event_id(); let event = as_variant!(event.kind, TimelineEventKind::Decrypted(event) => event); @@ -287,7 +286,7 @@ impl EventCache { /// Retrieve a set of events that we weren't able to decrypt from the memory /// of the event cache. - async fn get_utds_from_memory(&self) -> BTreeMap> { + async fn get_utds_from_memory(&self) -> BTreeMap> { let mut utds = BTreeMap::new(); for (room_id, room_cache) in self.inner.by_room.read().await.iter() { @@ -323,9 +322,7 @@ impl EventCache { Ok(events.into_iter().filter_map(filter_timeline_event_to_decrypted).collect()) } - async fn get_decrypted_events_from_memory( - &self, - ) -> BTreeMap> { + async fn get_decrypted_events_from_memory(&self) -> BTreeMap> { let mut decrypted_events = BTreeMap::new(); for (room_id, room_cache) in self.inner.by_room.read().await.iter() { @@ -1099,7 +1096,7 @@ mod tests { use matrix_sdk_common::cross_process_lock::CrossProcessLockConfig; use matrix_sdk_test::{JoinedRoomBuilder, async_test, event_factory::EventFactory}; use ruma::{ - EventId, OwnedEventId, RoomId, RoomVersionId, device_id, event_id, + EventId, RoomId, RoomVersionId, device_id, event_id, events::{AnySyncTimelineEvent, relation::RelationType}, room_id, serde::Raw, @@ -1226,8 +1223,8 @@ mod tests { async fn filter_duplicated_events( &self, linked_chunk_id: LinkedChunkId<'_>, - events: Vec, - ) -> Result, Self::Error> { + events: Vec, + ) -> Result, Self::Error> { self.memory_store.filter_duplicated_events(linked_chunk_id, events).await } diff --git a/crates/matrix-sdk/src/event_cache/room/events.rs b/crates/matrix-sdk/src/event_cache/room/events.rs index a3b45e9f938..4e529882d56 100644 --- a/crates/matrix-sdk/src/event_cache/room/events.rs +++ b/crates/matrix-sdk/src/event_cache/room/events.rs @@ -507,7 +507,7 @@ mod tests { use assert_matches::assert_matches; use assert_matches2::assert_let; use matrix_sdk_test::{ALICE, DEFAULT_TEST_ROOM_ID, event_factory::EventFactory}; - use ruma::{EventId, OwnedEventId, event_id, user_id}; + use ruma::{EventId, event_id, user_id}; use super::*; @@ -528,7 +528,7 @@ mod tests { }; } - fn new_event(event_id: &str) -> (OwnedEventId, Event) { + fn new_event(event_id: &str) -> (EventId, Event) { let event_id = EventId::parse(event_id).unwrap(); let event = EventFactory::new() .text_msg("") diff --git a/crates/matrix-sdk/src/event_cache/room/mod.rs b/crates/matrix-sdk/src/event_cache/room/mod.rs index eb2dce6533e..14b43df7c5c 100644 --- a/crates/matrix-sdk/src/event_cache/room/mod.rs +++ b/crates/matrix-sdk/src/event_cache/room/mod.rs @@ -33,7 +33,7 @@ use matrix_sdk_base::{ sync::{JoinedRoomUpdate, LeftRoomUpdate, Timeline}, }; use ruma::{ - EventId, OwnedEventId, OwnedRoomId, RoomId, + EventId, RoomId, events::{AnyRoomAccountDataEvent, AnySyncEphemeralRoomEvent, relation::RelationType}, serde::Raw, }; @@ -87,7 +87,7 @@ pub struct RoomEventCacheSubscriber { recv: Receiver, /// To which room are we listening? - room_id: OwnedRoomId, + room_id: RoomId, /// Sender to the auto-shrink channel. auto_shrink_sender: mpsc::Sender, @@ -163,7 +163,7 @@ impl RoomEventCache { client: WeakClient, state: RoomEventCacheStateLock, pagination_status: SharedObservable, - room_id: OwnedRoomId, + room_id: RoomId, auto_shrink_sender: mpsc::Sender, update_sender: Sender, generic_update_sender: Sender, @@ -226,7 +226,7 @@ impl RoomEventCache { /// initially known list of events for that thread. pub async fn subscribe_to_thread( &self, - thread_root: OwnedEventId, + thread_root: EventId, ) -> Result<(Vec, Receiver)> { let mut state = self.inner.state.write().await?; Ok(state.subscribe_to_thread(thread_root)) @@ -258,7 +258,7 @@ impl RoomEventCache { /// Return a `ThreadPagination` API object useful for running /// back-pagination queries in the `thread_id` thread. - pub fn thread_pagination(&self, thread_id: OwnedEventId) -> ThreadPagination { + pub fn thread_pagination(&self, thread_id: EventId) -> ThreadPagination { ThreadPagination::new(self.inner.clone(), thread_id) } @@ -407,7 +407,7 @@ impl RoomEventCache { /// The (non-cloneable) details of the `RoomEventCache`. pub(super) struct RoomEventCacheInner { /// The room id for this room. - pub(super) room_id: OwnedRoomId, + pub(super) room_id: RoomId, pub weak_room: WeakRoom, @@ -443,7 +443,7 @@ impl RoomEventCacheInner { client: WeakClient, state: RoomEventCacheStateLock, pagination_status: SharedObservable, - room_id: OwnedRoomId, + room_id: RoomId, auto_shrink_sender: mpsc::Sender, update_sender: Sender, generic_update_sender: Sender, @@ -527,7 +527,7 @@ impl RoomEventCacheInner { &self, timeline: Timeline, ephemeral_events: Vec>, - ambiguity_changes: BTreeMap, + ambiguity_changes: BTreeMap, ) -> Result<()> { if timeline.events.is_empty() && timeline.prev_batch.is_none() @@ -604,7 +604,7 @@ mod private { }; use matrix_sdk_common::executor::spawn; use ruma::{ - EventId, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId, + EventId, RoomId, UserId, events::{ AnySyncMessageLikeEvent, AnySyncTimelineEvent, MessageLikeEventType, relation::RelationType, room::redaction::SyncRoomRedactionEvent, @@ -638,10 +638,10 @@ mod private { enabled_thread_support: bool, /// The room this state relates to. - room_id: OwnedRoomId, + room_id: RoomId, /// The user's own user id. - own_user_id: OwnedUserId, + own_user_id: UserId, /// Reference to the underlying backing store. store: EventCacheStoreLock, @@ -653,7 +653,7 @@ mod private { /// Threads present in this room. /// /// Keyed by the thread root event ID. - threads: HashMap, + threads: HashMap, /// Cache for pinned events in this room, initialized on-demand. pinned_event_cache: OnceLock, @@ -715,8 +715,8 @@ mod private { /// [`RoomPagination`]: super::RoomPagination #[allow(clippy::too_many_arguments)] pub async fn new( - own_user_id: OwnedUserId, - room_id: OwnedRoomId, + own_user_id: UserId, + room_id: RoomId, room_version_rules: RoomVersionRules, enabled_thread_support: bool, update_sender: Sender, @@ -1221,8 +1221,8 @@ mod private { #[instrument(skip_all)] pub async fn remove_events( &mut self, - in_memory_events: Vec<(OwnedEventId, Position)>, - in_store_events: Vec<(OwnedEventId, Position)>, + in_memory_events: Vec<(EventId, Position)>, + in_store_events: Vec<(EventId, Position)>, ) -> Result<(), EventCacheError> { // In-store events. if !in_store_events.is_empty() { @@ -1554,7 +1554,7 @@ mod private { /// initially known list of events for that thread. pub fn subscribe_to_thread( &mut self, - root: OwnedEventId, + root: EventId, ) -> (Vec, Receiver) { self.get_or_reload_thread(root).subscribe() } @@ -1651,7 +1651,7 @@ mod private { pub(in super::super) fn get_or_reload_thread( &mut self, - root_event_id: OwnedEventId, + root_event_id: EventId, ) -> &mut ThreadEventCache { // TODO: when there's persistent storage, try to lazily reload from disk, if // missing from memory. @@ -1666,7 +1666,7 @@ mod private { #[instrument(skip_all)] async fn update_threads( &mut self, - new_events_by_thread: BTreeMap>, + new_events_by_thread: BTreeMap>, post_processing_origin: PostProcessingOrigin, ) -> Result<(), EventCacheError> { for (thread_root, new_events) in new_events_by_thread { @@ -1701,8 +1701,8 @@ mod private { /// Update a thread summary on the given thread root, if needs be. async fn maybe_update_thread_summary( &mut self, - thread_root: OwnedEventId, - latest_event_id: Option, + thread_root: EventId, + latest_event_id: Option, _post_processing_origin: PostProcessingOrigin, ) -> Result<(), EventCacheError> { // Add a thread summary to the (room) event which has the thread root, if we @@ -2058,7 +2058,7 @@ mod private { // There are supposedly fewer events loaded in memory than in the store. Let's // start by looking up in the `EventLinkedChunk`. for (position, event) in room_linked_chunk.revents() { - if event.event_id().as_deref() == Some(event_id) { + if event.event_id().as_ref() == Some(event_id) { return Ok(Some((EventLocation::Memory(position), event.clone()))); } } @@ -2478,7 +2478,7 @@ mod timed_tests { use matrix_sdk_common::cross_process_lock::CrossProcessLockConfig; use matrix_sdk_test::{ALICE, BOB, async_test, event_factory::EventFactory}; use ruma::{ - EventId, OwnedUserId, event_id, + EventId, UserId, event_id, events::{AnySyncMessageLikeEvent, AnySyncTimelineEvent}, room_id, user_id, }; @@ -3225,7 +3225,7 @@ mod timed_tests { // Sanity check: lazily loaded, so only includes one item at start. let (events, mut stream) = room_event_cache.subscribe().await.unwrap(); assert_eq!(events.len(), 1); - assert_eq!(events[0].event_id().as_deref(), Some(evid2)); + assert_eq!(events[0].event_id().as_ref(), Some(evid2)); assert!(stream.is_empty()); let mut generic_stream = event_cache.subscribe_to_room_generic_updates(); @@ -3233,7 +3233,7 @@ mod timed_tests { // Force loading the full linked chunk by back-paginating. let outcome = room_event_cache.pagination().run_backwards_once(20).await.unwrap(); assert_eq!(outcome.events.len(), 1); - assert_eq!(outcome.events[0].event_id().as_deref(), Some(evid1)); + assert_eq!(outcome.events[0].event_id().as_ref(), Some(evid1)); assert!(outcome.reached_start); // We also get an update about the loading from the store. @@ -3243,7 +3243,7 @@ mod timed_tests { ); assert_eq!(diffs.len(), 1); assert_matches!(&diffs[0], VectorDiff::Insert { index: 0, value } => { - assert_eq!(value.event_id().as_deref(), Some(evid1)); + assert_eq!(value.event_id().as_ref(), Some(evid1)); }); assert!(stream.is_empty()); @@ -3275,7 +3275,7 @@ mod timed_tests { assert_matches!(&diffs[0], VectorDiff::Clear); assert_matches!(&diffs[1], VectorDiff::Append { values} => { assert_eq!(values.len(), 1); - assert_eq!(values[0].event_id().as_deref(), Some(evid2)); + assert_eq!(values[0].event_id().as_ref(), Some(evid2)); }); assert!(stream.is_empty()); @@ -3287,13 +3287,13 @@ mod timed_tests { // When reading the events, we do get only the last one. let events = room_event_cache.events().await.unwrap(); assert_eq!(events.len(), 1); - assert_eq!(events[0].event_id().as_deref(), Some(evid2)); + assert_eq!(events[0].event_id().as_ref(), Some(evid2)); // But if we back-paginate, we don't need access to network to find out about // the previous event. let outcome = room_event_cache.pagination().run_backwards_once(20).await.unwrap(); assert_eq!(outcome.events.len(), 1); - assert_eq!(outcome.events[0].event_id().as_deref(), Some(evid1)); + assert_eq!(outcome.events[0].event_id().as_ref(), Some(evid1)); assert!(outcome.reached_start); } @@ -3378,7 +3378,7 @@ mod timed_tests { let mut events = room_linked_chunk.events(); let (pos, ev) = events.next().unwrap(); assert_eq!(pos, Position::new(ChunkIdentifier::new(1), 0)); - assert_eq!(ev.event_id().as_deref(), Some(evid3)); + assert_eq!(ev.event_id().as_ref(), Some(evid3)); assert_eq!(room_linked_chunk.event_order(pos), Some(2)); // No other loaded events. @@ -3426,11 +3426,11 @@ mod timed_tests { let mut events = room_linked_chunk.events(); let (pos, ev) = events.next().unwrap(); - assert_eq!(ev.event_id().as_deref(), Some(evid3)); + assert_eq!(ev.event_id().as_ref(), Some(evid3)); assert_eq!(room_linked_chunk.event_order(pos), Some(2)); let (pos, ev) = events.next().unwrap(); - assert_eq!(ev.event_id().as_deref(), Some(evid4)); + assert_eq!(ev.event_id().as_ref(), Some(evid4)); assert_eq!(room_linked_chunk.event_order(pos), Some(3)); // No other loaded events. @@ -3515,7 +3515,7 @@ mod timed_tests { // Sanity check: lazily loaded, so only includes one item at start. let (events1, mut stream1) = room_event_cache.subscribe().await.unwrap(); assert_eq!(events1.len(), 1); - assert_eq!(events1[0].event_id().as_deref(), Some(evid2)); + assert_eq!(events1[0].event_id().as_ref(), Some(evid2)); assert!(stream1.is_empty()); let mut generic_stream = event_cache.subscribe_to_room_generic_updates(); @@ -3523,7 +3523,7 @@ mod timed_tests { // Force loading the full linked chunk by back-paginating. let outcome = room_event_cache.pagination().run_backwards_once(20).await.unwrap(); assert_eq!(outcome.events.len(), 1); - assert_eq!(outcome.events[0].event_id().as_deref(), Some(evid1)); + assert_eq!(outcome.events[0].event_id().as_ref(), Some(evid1)); assert!(outcome.reached_start); // We also get an update about the loading from the store. Ignore it, for this @@ -3534,7 +3534,7 @@ mod timed_tests { ); assert_eq!(diffs.len(), 1); assert_matches!(&diffs[0], VectorDiff::Insert { index: 0, value } => { - assert_eq!(value.event_id().as_deref(), Some(evid1)); + assert_eq!(value.event_id().as_ref(), Some(evid1)); }); assert!(stream1.is_empty()); @@ -3550,8 +3550,8 @@ mod timed_tests { // the second subscribers sees them all. let (events2, stream2) = room_event_cache.subscribe().await.unwrap(); assert_eq!(events2.len(), 2); - assert_eq!(events2[0].event_id().as_deref(), Some(evid1)); - assert_eq!(events2[1].event_id().as_deref(), Some(evid2)); + assert_eq!(events2[0].event_id().as_ref(), Some(evid1)); + assert_eq!(events2[1].event_id().as_ref(), Some(evid2)); assert!(stream2.is_empty()); // Drop the first stream, and wait a bit. @@ -3576,7 +3576,7 @@ mod timed_tests { // Getting the events will only give us the latest chunk. let events3 = room_event_cache.events().await.unwrap(); assert_eq!(events3.len(), 1); - assert_eq!(events3[0].event_id().as_deref(), Some(evid2)); + assert_eq!(events3[0].event_id().as_ref(), Some(evid2)); } #[async_test] @@ -3648,11 +3648,11 @@ mod timed_tests { assert_matches!( room_event_cache .rfind_map_event_in_memory_by(|event| { - (event.raw().get_field::("sender").unwrap().as_deref() == Some(*BOB)).then(|| event.event_id()) + (event.raw().get_field::("sender").unwrap().as_ref() == Some(*BOB)).then(|| event.event_id()) }) .await, Ok(Some(event_id)) => { - assert_eq!(event_id.as_deref(), Some(event_id_0)); + assert_eq!(event_id.as_ref(), Some(event_id_0)); } ); @@ -3661,11 +3661,11 @@ mod timed_tests { assert_matches!( room_event_cache .rfind_map_event_in_memory_by(|event| { - (event.raw().get_field::("sender").unwrap().as_deref() == Some(*ALICE)).then(|| event.event_id()) + (event.raw().get_field::("sender").unwrap().as_ref() == Some(*ALICE)).then(|| event.event_id()) }) .await, Ok(Some(event_id)) => { - assert_eq!(event_id.as_deref(), Some(event_id_2)); + assert_eq!(event_id.as_ref(), Some(event_id_2)); } ); @@ -3673,9 +3673,8 @@ mod timed_tests { assert!( room_event_cache .rfind_map_event_in_memory_by(|event| { - (event.raw().get_field::("sender").unwrap().as_deref() - == Some(user_id)) - .then(|| event.event_id()) + (event.raw().get_field::("sender").unwrap().as_ref() == Some(user_id)) + .then(|| event.event_id()) }) .await .unwrap() @@ -3791,7 +3790,7 @@ mod timed_tests { // Initial updates contain `ev_id_1` only. assert_eq!(initial_updates.len(), 1); - assert_eq!(initial_updates[0].event_id().as_deref(), Some(ev_id_1)); + assert_eq!(initial_updates[0].event_id().as_ref(), Some(ev_id_1)); assert!(updates_stream.is_empty()); // `ev_id_1` must be loaded in memory. @@ -3811,7 +3810,7 @@ mod timed_tests { assert_matches!( &diffs[0], VectorDiff::Insert { index: 0, value: event } => { - assert_eq!(event.event_id().as_deref(), Some(ev_id_0)); + assert_eq!(event.event_id().as_ref(), Some(ev_id_0)); } ); } @@ -3831,7 +3830,7 @@ mod timed_tests { // Initial updates contain `ev_id_1` only. assert_eq!(initial_updates.len(), 1); - assert_eq!(initial_updates[0].event_id().as_deref(), Some(ev_id_1)); + assert_eq!(initial_updates[0].event_id().as_ref(), Some(ev_id_1)); assert!(updates_stream.is_empty()); // `ev_id_1` must be loaded in memory. @@ -3851,7 +3850,7 @@ mod timed_tests { assert_matches!( &diffs[0], VectorDiff::Insert { index: 0, value: event } => { - assert_eq!(event.event_id().as_deref(), Some(ev_id_0)); + assert_eq!(event.event_id().as_ref(), Some(ev_id_0)); } ); } @@ -3889,7 +3888,7 @@ mod timed_tests { &diffs[1], VectorDiff::Append { values: events } => { assert_eq!(events.len(), 1); - assert_eq!(events[0].event_id().as_deref(), Some(ev_id_1)); + assert_eq!(events[0].event_id().as_ref(), Some(ev_id_1)); } ); } @@ -3909,7 +3908,7 @@ mod timed_tests { assert_matches!( &diffs[0], VectorDiff::Insert { index: 0, value: event } => { - assert_eq!(event.event_id().as_deref(), Some(ev_id_0)); + assert_eq!(event.event_id().as_ref(), Some(ev_id_0)); } ); } @@ -3940,7 +3939,7 @@ mod timed_tests { &diffs[1], VectorDiff::Append { values: events } => { assert_eq!(events.len(), 1); - assert_eq!(events[0].event_id().as_deref(), Some(ev_id_1)); + assert_eq!(events[0].event_id().as_ref(), Some(ev_id_1)); } ); } @@ -3960,7 +3959,7 @@ mod timed_tests { assert_matches!( &diffs[0], VectorDiff::Insert { index: 0, value: event } => { - assert_eq!(event.event_id().as_deref(), Some(ev_id_0)); + assert_eq!(event.event_id().as_ref(), Some(ev_id_0)); } ); } @@ -3994,7 +3993,7 @@ mod timed_tests { &diffs[1], VectorDiff::Append { values: events } => { assert_eq!(events.len(), 1); - assert_eq!(events[0].event_id().as_deref(), Some(ev_id_1)); + assert_eq!(events[0].event_id().as_ref(), Some(ev_id_1)); } ); } @@ -4021,7 +4020,7 @@ mod timed_tests { assert_matches!( &diffs[0], VectorDiff::Insert { index: 0, value: event } => { - assert_eq!(event.event_id().as_deref(), Some(ev_id_0)); + assert_eq!(event.event_id().as_ref(), Some(ev_id_0)); } ); } @@ -4050,7 +4049,7 @@ mod timed_tests { &diffs[1], VectorDiff::Append { values: events } => { assert_eq!(events.len(), 1); - assert_eq!(events[0].event_id().as_deref(), Some(ev_id_1)); + assert_eq!(events[0].event_id().as_ref(), Some(ev_id_1)); } ); } @@ -4077,7 +4076,7 @@ mod timed_tests { assert_matches!( &diffs[0], VectorDiff::Insert { index: 0, value: event } => { - assert_eq!(event.event_id().as_deref(), Some(ev_id_0)); + assert_eq!(event.event_id().as_ref(), Some(ev_id_0)); } ); } @@ -4106,7 +4105,7 @@ mod timed_tests { &diffs[1], VectorDiff::Append { values: events } => { assert_eq!(events.len(), 1); - assert_eq!(events[0].event_id().as_deref(), Some(ev_id_1)); + assert_eq!(events[0].event_id().as_ref(), Some(ev_id_1)); } ); } @@ -4130,7 +4129,7 @@ mod timed_tests { assert_matches!( &diffs[0], VectorDiff::Insert { index: 0, value: event } => { - assert_eq!(event.event_id().as_deref(), Some(ev_id_0)); + assert_eq!(event.event_id().as_ref(), Some(ev_id_0)); } ); } @@ -4156,7 +4155,7 @@ mod timed_tests { &diffs[1], VectorDiff::Append { values: events } => { assert_eq!(events.len(), 1); - assert_eq!(events[0].event_id().as_deref(), Some(ev_id_1)); + assert_eq!(events[0].event_id().as_ref(), Some(ev_id_1)); } ); } @@ -4180,7 +4179,7 @@ mod timed_tests { assert_matches!( &diffs[0], VectorDiff::Insert { index: 0, value: event } => { - assert_eq!(event.event_id().as_deref(), Some(ev_id_0)); + assert_eq!(event.event_id().as_ref(), Some(ev_id_0)); } ); } @@ -4274,7 +4273,7 @@ mod timed_tests { async fn event_loaded(room_event_cache: &RoomEventCache, event_id: &EventId) -> bool { room_event_cache .rfind_map_event_in_memory_by(|event| { - (event.event_id().as_deref() == Some(event_id)).then_some(()) + (event.event_id().as_ref() == Some(event_id)).then_some(()) }) .await .unwrap() diff --git a/crates/matrix-sdk/src/event_cache/room/pinned_events.rs b/crates/matrix-sdk/src/event_cache/room/pinned_events.rs index f2dbf3c9da1..95d752f5d83 100644 --- a/crates/matrix-sdk/src/event_cache/room/pinned_events.rs +++ b/crates/matrix-sdk/src/event_cache/room/pinned_events.rs @@ -23,10 +23,8 @@ use matrix_sdk_base::{ serde_helpers::extract_relation, task_monitor::BackgroundTaskHandle, }; -#[cfg(feature = "e2e-encryption")] -use ruma::EventId; use ruma::{ - MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, + EventId, MilliSecondsSinceUnixEpoch, RoomId, events::{ AnySyncMessageLikeEvent, AnySyncTimelineEvent, MessageLikeEventType, relation::RelationType, }, @@ -49,7 +47,7 @@ use crate::{ pub(in super::super) struct PinnedEventCacheState { /// The ID of the room owning this list of pinned events. - room_id: OwnedRoomId, + room_id: RoomId, /// A sender for live events updates in this room's pinned events list. sender: Sender, @@ -204,7 +202,7 @@ impl<'a> PinnedEventCacheStateLockWriteGuard<'a> { impl PinnedEventCacheState { /// Return a list of the current event IDs in this linked chunk. - fn current_event_ids(&self) -> Vec { + fn current_event_ids(&self) -> Vec { self.chunk.events().filter_map(|(_position, event)| event.event_id()).collect() } @@ -218,7 +216,7 @@ impl PinnedEventCacheState { #[cfg(feature = "e2e-encryption")] fn find_event(&self, event_id: &EventId) -> Option<(Position, Event)> { for (position, event) in self.chunk.revents() { - if event.event_id().as_deref() == Some(event_id) { + if event.event_id().as_ref() == Some(event_id) { return Some((position, event.clone())); } } @@ -329,7 +327,7 @@ impl PinnedEventCache { /// Given a raw event, try to extract the target event ID of a relation as /// defined with `m.relates_to`. - fn extract_relation_target(raw: &Raw) -> Option { + fn extract_relation_target(raw: &Raw) -> Option { let (rel_type, event_id) = extract_relation(raw)?; // Don't include thread responses in the pinned event chunk. @@ -344,7 +342,7 @@ impl PinnedEventCache { fn extract_redaction_target( raw: &Raw, room_redaction_rules: &RedactionRules, - ) -> Option { + ) -> Option { // Try to find a redaction, but do not deserialize the entire event if we aren't // certain it's a `m.room.redaction`. if raw.get_field::("type").ok()?? @@ -375,7 +373,7 @@ impl PinnedEventCache { trace!("checking live events for relations to pinned events"); let mut guard = self.state.write().await?; - let pinned_event_ids: BTreeSet = + let pinned_event_ids: BTreeSet = guard.state.current_event_ids().into_iter().collect(); if pinned_event_ids.is_empty() { @@ -539,7 +537,7 @@ impl PinnedEventCache { (config.max_pinned_events_to_load, config.max_pinned_events_concurrent_requests) }; - let pinned_event_ids: Vec = room + let pinned_event_ids: Vec = room .pinned_event_ids() .unwrap_or_default() .into_iter() diff --git a/crates/matrix-sdk/src/event_cache/room/threads.rs b/crates/matrix-sdk/src/event_cache/room/threads.rs index 56157887c11..a5f9223374a 100644 --- a/crates/matrix-sdk/src/event_cache/room/threads.rs +++ b/crates/matrix-sdk/src/event_cache/room/threads.rs @@ -20,7 +20,7 @@ use matrix_sdk_base::{ event_cache::{Event, Gap}, linked_chunk::{ChunkContent, OwnedLinkedChunkId, Position}, }; -use ruma::{EventId, OwnedEventId, OwnedRoomId}; +use ruma::{EventId, RoomId}; use tokio::sync::broadcast::{Receiver, Sender}; use tracing::{error, trace}; @@ -34,11 +34,11 @@ use super::super::{ /// All the information related to a single thread. pub(crate) struct ThreadEventCache { /// The room owning this thread. - room_id: OwnedRoomId, + room_id: RoomId, /// The ID of the thread root event, which is the first event in the thread /// (and eventually the first in the linked chunk). - thread_root: OwnedEventId, + thread_root: EventId, /// The linked chunk for this thread. chunk: EventLinkedChunk, @@ -56,8 +56,8 @@ pub(crate) struct ThreadEventCache { impl ThreadEventCache { /// Create a new empty thread event cache. pub fn new( - room_id: OwnedRoomId, - thread_root: OwnedEventId, + room_id: RoomId, + thread_root: EventId, linked_chunk_update_sender: Sender, ) -> Self { Self { @@ -143,9 +143,11 @@ impl ThreadEventCache { /// If the event has been found and removed, then an update will be /// propagated to observers. pub(crate) fn remove_if_present(&mut self, event_id: &EventId) { - let Some(pos) = self.chunk.events().find_map(|(pos, event)| { - (event.event_id().as_deref() == Some(event_id)).then_some(pos) - }) else { + let Some(pos) = self + .chunk + .events() + .find_map(|(pos, event)| (event.event_id().as_ref() == Some(event_id)).then_some(pos)) + else { // Event not found in the linked chunk, nothing to do. return; }; @@ -249,7 +251,7 @@ impl ThreadEventCache { /// result of the above function, otherwise this can panic. fn remove_in_memory_duplicated_events( &mut self, - in_memory_duplicated_event_ids: Vec<(OwnedEventId, Position)>, + in_memory_duplicated_event_ids: Vec<(EventId, Position)>, ) { // Remove the duplicated events from the thread chunk. self.chunk @@ -327,7 +329,7 @@ impl ThreadEventCache { } /// Returns the latest event ID in this thread, if any. - pub fn latest_event_id(&self) -> Option { + pub fn latest_event_id(&self) -> Option { self.chunk.revents().next().and_then(|(_position, event)| event.event_id()) } } diff --git a/crates/matrix-sdk/src/event_handler/maps.rs b/crates/matrix-sdk/src/event_handler/maps.rs index dc02fb12fa4..1dbbdb9256b 100644 --- a/crates/matrix-sdk/src/event_handler/maps.rs +++ b/crates/matrix-sdk/src/event_handler/maps.rs @@ -17,7 +17,7 @@ use std::{ collections::{BTreeMap, btree_map}, }; -use ruma::{OwnedRoomId, RoomId}; +use ruma::RoomId; use super::{ EventHandlerFn, EventHandlerHandle, EventHandlerWrapper, HandlerKind, StaticEventTypePart, @@ -265,7 +265,7 @@ struct KindType<'a> { #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] struct KindRoomId { ev_kind: HandlerKind, - room_id: OwnedRoomId, + room_id: RoomId, } #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] @@ -275,7 +275,7 @@ struct KindTypeRoomIdWrap(KindTypeRoomId<'static>); struct KindTypeRoomId<'a> { ev_kind: HandlerKind, ev_type: &'a str, - room_id: OwnedRoomId, + room_id: RoomId, } // These lifetime-generic impls are what makes it possible to obtain a diff --git a/crates/matrix-sdk/src/event_handler/mod.rs b/crates/matrix-sdk/src/event_handler/mod.rs index 74debf5b0dd..bdef1032fd3 100644 --- a/crates/matrix-sdk/src/event_handler/mod.rs +++ b/crates/matrix-sdk/src/event_handler/mod.rs @@ -59,7 +59,7 @@ use matrix_sdk_base::{ }; use matrix_sdk_common::deserialized_responses::ProcessedToDeviceEvent; use pin_project_lite::pin_project; -use ruma::{OwnedRoomId, events::BooleanType, push::Action, serde::Raw}; +use ruma::{RoomId, events::BooleanType, push::Action, serde::Raw}; use serde::{Deserialize, de::DeserializeOwned}; use serde_json::value::RawValue as RawJsonValue; use tracing::{debug, error, field::debug, instrument, warn}; @@ -166,7 +166,7 @@ pub(crate) struct EventHandlerWrapper { pub struct EventHandlerHandle { pub(crate) ev_kind: HandlerKind, pub(crate) ev_type: Option, - pub(crate) room_id: Option, + pub(crate) room_id: Option, pub(crate) handler_id: u64, } @@ -299,7 +299,7 @@ impl Client { pub(crate) fn add_event_handler_impl( &self, handler: H, - room_id: Option, + room_id: Option, ) -> EventHandlerHandle where Ev: SyncEvent + DeserializeOwned + SendOutsideWasm + 'static, diff --git a/crates/matrix-sdk/src/latest_events/latest_event/builder.rs b/crates/matrix-sdk/src/latest_events/latest_event/builder.rs index 073887de331..f5404b10322 100644 --- a/crates/matrix-sdk/src/latest_events/latest_event/builder.rs +++ b/crates/matrix-sdk/src/latest_events/latest_event/builder.rs @@ -12,16 +12,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::{ - collections::HashMap, - iter::once, - ops::{ControlFlow, Deref}, -}; +use std::{collections::HashMap, iter::once, ops::ControlFlow}; pub use matrix_sdk_base::latest_event::{LatestEventValue, LocalLatestEventValue}; use matrix_sdk_base::{deserialized_responses::TimelineEvent, store::SerializableEventContent}; use ruma::{ - MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedTransactionId, TransactionId, UserId, + EventId, MilliSecondsSinceUnixEpoch, TransactionId, UserId, events::{ AnyMessageLikeEventContent, AnySyncStateEvent, AnySyncTimelineEvent, SyncStateEvent, relation::Replacement, @@ -44,7 +40,7 @@ impl Builder { /// Create a new [`LatestEventValue::Remote`]. pub async fn new_remote( room_event_cache: &RoomEventCache, - current_value_event_id: Option, + current_value_event_id: Option, own_user_id: &UserId, power_levels: Option<&RoomPowerLevels>, ) -> Option { @@ -59,7 +55,7 @@ impl Builder { let mut current_value_must_be_erased = false; // Track the most recent edit for each event. - let mut latest_edit_for_event: HashMap = HashMap::new(); + let mut latest_edit_for_event: HashMap = HashMap::new(); if let Ok(Some(event)) = room_event_cache .rfind_map_event_in_memory_by(|event| { @@ -149,7 +145,7 @@ impl Builder { send_queue_update: &RoomSendQueueUpdate, buffer_of_values_for_local_events: &mut BufferOfValuesForLocalEvents, room_event_cache: &RoomEventCache, - current_value_event_id: Option, + current_value_event_id: Option, own_user_id: &UserId, power_levels: Option<&RoomPowerLevels>, ) -> Option { @@ -387,7 +383,7 @@ impl Builder { async fn new_local_or_remote( buffer_of_values_for_local_events: &mut BufferOfValuesForLocalEvents, room_event_cache: &RoomEventCache, - current_value_event_id: Option, + current_value_event_id: Option, own_user_id: &UserId, power_levels: Option<&RoomPowerLevels>, ) -> Option { @@ -441,7 +437,7 @@ impl Builder { /// behaviours. #[derive(Debug)] pub(super) struct BufferOfValuesForLocalEvents { - buffer: Vec<(OwnedTransactionId, LatestEventValue)>, + buffer: Vec<(TransactionId, LatestEventValue)>, } impl BufferOfValuesForLocalEvents { @@ -456,7 +452,7 @@ impl BufferOfValuesForLocalEvents { } /// Get the last [`LatestEventValue`]. - fn last(&self) -> Option<&(OwnedTransactionId, LatestEventValue)> { + fn last(&self) -> Option<&(TransactionId, LatestEventValue)> { self.buffer.last() } @@ -473,7 +469,7 @@ impl BufferOfValuesForLocalEvents { /// /// Panics if `value` is not of kind [`LatestEventValue::LocalIsSending`] or /// [`LatestEventValue::LocalCannotBeSent`]. - fn push(&mut self, transaction_id: OwnedTransactionId, value: LatestEventValue) { + fn push(&mut self, transaction_id: TransactionId, value: LatestEventValue) { assert!(value.is_local(), "`value` must be a local `LatestEventValue`"); self.buffer.push((transaction_id, value)); @@ -506,7 +502,7 @@ impl BufferOfValuesForLocalEvents { /// # Panics /// /// Panics if `position` is strictly greater than buffer's length. - fn remove(&mut self, position: usize) -> (OwnedTransactionId, LatestEventValue) { + fn remove(&mut self, position: usize) -> (TransactionId, LatestEventValue) { self.buffer.remove(position) } @@ -579,7 +575,7 @@ struct FilterContinue { /// Whether the current [`LatestEventValue`] must be erased or not. current_value_must_be_erased: bool, /// When the event is a replacement, this is the targeted event ID. - edited_event_id: Option, + edited_event_id: Option, } /// Build the [`ControlFlow::Break`] for the filters. @@ -605,7 +601,7 @@ fn filter_continue_with_erasing() -> ControlFlow<(), FilterContinue> { /// Build the [`ControlFlow::Continue`] with an edited event ID, for the /// filters. -fn filter_continue_with_edit(edited_event_id: OwnedEventId) -> ControlFlow<(), FilterContinue> { +fn filter_continue_with_edit(edited_event_id: EventId) -> ControlFlow<(), FilterContinue> { ControlFlow::Continue(FilterContinue { current_value_must_be_erased: false, edited_event_id: Some(edited_event_id), @@ -621,7 +617,7 @@ fn filter_continue_with_edit(edited_event_id: OwnedEventId) -> ControlFlow<(), F /// [`LatestEventValue`]. fn filter_timeline_event( event: &TimelineEvent, - current_value_event_id: Option<&OwnedEventId>, + current_value_event_id: Option<&EventId>, own_user_id: &UserId, power_levels: Option<&RoomPowerLevels>, ) -> ControlFlow<(), FilterContinue> { @@ -660,7 +656,7 @@ fn filter_timeline_event( fn filter_any_message_like_event_content( event: AnyMessageLikeEventContent, - current_value_event_id: Option<&OwnedEventId>, + current_value_event_id: Option<&EventId>, ) -> ControlFlow<(), FilterContinue> { match event { // `m.room.message` @@ -761,11 +757,7 @@ fn filter_any_sync_state_event( // `LatestEventValue` to get a first value! // - the user is being invited: we want a `LatestEventValue` to represent the // invitation! - if member.state_key.deref() == own_user_id { - filter_break() - } else { - filter_continue() - } + if member.state_key == own_user_id { filter_break() } else { filter_continue() } } _ => filter_continue(), @@ -928,7 +920,7 @@ mod filter_tests { event | event_factory | { event_factory .call_invite( - ruma::OwnedVoipId::from("vvooiipp".to_owned()), + ruma::VoipId::from("vvooiipp".to_owned()), ruma::UInt::from(1234u32), ruma::events::call::SessionDescription::new( "type".to_owned(), @@ -951,7 +943,7 @@ mod filter_tests { NotificationType::Ring, ) .mentions(vec![owned_user_id!("@alice:server.name")]) - .relates_to_membership_state_event(ruma::OwnedEventId::try_from("$abc:server.name").unwrap()) + .relates_to_membership_state_event(ruma::EventId::try_from("$abc:server.name").unwrap()) .lifetime(60) .into_event() } @@ -967,7 +959,7 @@ mod filter_tests { .sticker( "wink wink", ruma::events::room::ImageInfo::new(), - ruma::OwnedMxcUri::from("mxc://foo/bar"), + ruma::MxcUri::from("mxc://foo/bar"), ) .into_event() } @@ -1269,7 +1261,7 @@ mod filter_tests { #[test] fn test_room_message_verification_request() { - use ruma::{OwnedDeviceId, events::room::message}; + use ruma::{DeviceId, events::room::message}; assert_latest_event_content!( event | event_factory | { @@ -1278,7 +1270,7 @@ mod filter_tests { message::KeyVerificationRequestEventContent::new( "body".to_owned(), vec![], - OwnedDeviceId::from("device_id"), + DeviceId::from("device_id"), owned_user_id!("@user:server.name"), ), ))) @@ -1293,7 +1285,7 @@ mod filter_tests { mod buffer_of_values_for_local_event_tests { use assert_matches::assert_matches; use ruma::{ - OwnedTransactionId, + TransactionId, events::{AnyMessageLikeEventContent, room::message::RoomMessageEventContent}, owned_event_id, serde::Raw, @@ -1327,7 +1319,7 @@ mod buffer_of_values_for_local_event_tests { assert!(buffer.last().is_none()); - let transaction_id = OwnedTransactionId::from("txnid"); + let transaction_id = TransactionId::from("txnid"); buffer.push( transaction_id.clone(), LatestEventValue::LocalIsSending(local_room_message("tome")), @@ -1344,7 +1336,7 @@ mod buffer_of_values_for_local_event_tests { #[test] fn test_position() { let mut buffer = BufferOfValuesForLocalEvents::new(); - let transaction_id = OwnedTransactionId::from("txnid"); + let transaction_id = TransactionId::from("txnid"); assert!(buffer.position(&transaction_id).is_none()); @@ -1353,7 +1345,7 @@ mod buffer_of_values_for_local_event_tests { LatestEventValue::LocalIsSending(local_room_message("raclette")), ); buffer.push( - OwnedTransactionId::from("othertxnid"), + TransactionId::from("othertxnid"), LatestEventValue::LocalIsSending(local_room_message("tome")), ); @@ -1365,7 +1357,7 @@ mod buffer_of_values_for_local_event_tests { fn test_push_none() { let mut buffer = BufferOfValuesForLocalEvents::new(); - buffer.push(OwnedTransactionId::from("txnid"), LatestEventValue::None); + buffer.push(TransactionId::from("txnid"), LatestEventValue::None); } #[test] @@ -1374,7 +1366,7 @@ mod buffer_of_values_for_local_event_tests { let mut buffer = BufferOfValuesForLocalEvents::new(); buffer.push( - OwnedTransactionId::from("txnid"), + TransactionId::from("txnid"), LatestEventValue::Remote(remote_room_message("tome")), ); } @@ -1384,15 +1376,15 @@ mod buffer_of_values_for_local_event_tests { let mut buffer = BufferOfValuesForLocalEvents::new(); buffer.push( - OwnedTransactionId::from("txnid0"), + TransactionId::from("txnid0"), LatestEventValue::LocalIsSending(local_room_message("tome")), ); buffer.push( - OwnedTransactionId::from("txnid1"), + TransactionId::from("txnid1"), LatestEventValue::LocalCannotBeSent(local_room_message("raclette")), ); buffer.push( - OwnedTransactionId::from("txnid1"), + TransactionId::from("txnid1"), LatestEventValue::LocalHasBeenSent { event_id: owned_event_id!("$ev0"), value: local_room_message("raclette"), @@ -1408,7 +1400,7 @@ mod buffer_of_values_for_local_event_tests { let mut buffer = BufferOfValuesForLocalEvents::new(); buffer.push( - OwnedTransactionId::from("txnid"), + TransactionId::from("txnid"), LatestEventValue::Remote(remote_room_message("gruyère")), ); @@ -1423,7 +1415,7 @@ mod buffer_of_values_for_local_event_tests { let mut buffer = BufferOfValuesForLocalEvents::new(); buffer.push( - OwnedTransactionId::from("txnid"), + TransactionId::from("txnid"), LatestEventValue::LocalHasBeenSent { event_id: owned_event_id!("$ev0"), value: local_room_message("gruyère"), @@ -1439,7 +1431,7 @@ mod buffer_of_values_for_local_event_tests { fn test_replace_content_on_local_is_sending() { let mut buffer = BufferOfValuesForLocalEvents::new(); - let transaction_id = OwnedTransactionId::from("txnid0"); + let transaction_id = TransactionId::from("txnid0"); buffer.push( transaction_id.clone(), LatestEventValue::LocalIsSending(local_room_message("gruyère")), @@ -1467,7 +1459,7 @@ mod buffer_of_values_for_local_event_tests { fn test_replace_content_on_local_cannot_be_sent() { let mut buffer = BufferOfValuesForLocalEvents::new(); - let transaction_id = OwnedTransactionId::from("txnid0"); + let transaction_id = TransactionId::from("txnid0"); buffer.push( transaction_id.clone(), LatestEventValue::LocalCannotBeSent(local_room_message("gruyère")), @@ -1496,7 +1488,7 @@ mod buffer_of_values_for_local_event_tests { let mut buffer = BufferOfValuesForLocalEvents::new(); buffer.push( - OwnedTransactionId::from("txnid"), + TransactionId::from("txnid"), LatestEventValue::LocalIsSending(local_room_message("gryuère")), ); @@ -1510,9 +1502,9 @@ mod buffer_of_values_for_local_event_tests { #[test] fn test_mark_cannot_be_sent_from() { let mut buffer = BufferOfValuesForLocalEvents::new(); - let transaction_id_0 = OwnedTransactionId::from("txnid0"); - let transaction_id_1 = OwnedTransactionId::from("txnid1"); - let transaction_id_2 = OwnedTransactionId::from("txnid2"); + let transaction_id_0 = TransactionId::from("txnid0"); + let transaction_id_1 = TransactionId::from("txnid1"); + let transaction_id_2 = TransactionId::from("txnid2"); buffer.push( transaction_id_0, @@ -1538,9 +1530,9 @@ mod buffer_of_values_for_local_event_tests { #[test] fn test_mark_is_sending_from() { let mut buffer = BufferOfValuesForLocalEvents::new(); - let transaction_id_0 = OwnedTransactionId::from("txnid0"); - let transaction_id_1 = OwnedTransactionId::from("txnid1"); - let transaction_id_2 = OwnedTransactionId::from("txnid2"); + let transaction_id_0 = TransactionId::from("txnid0"); + let transaction_id_1 = TransactionId::from("txnid1"); + let transaction_id_2 = TransactionId::from("txnid2"); buffer.push( transaction_id_0, @@ -1566,9 +1558,9 @@ mod buffer_of_values_for_local_event_tests { #[test] fn test_mark_is_sending_after() { let mut buffer = BufferOfValuesForLocalEvents::new(); - let transaction_id_0 = OwnedTransactionId::from("txnid0"); - let transaction_id_1 = OwnedTransactionId::from("txnid1"); - let transaction_id_2 = OwnedTransactionId::from("txnid2"); + let transaction_id_0 = TransactionId::from("txnid0"); + let transaction_id_1 = TransactionId::from("txnid1"); + let transaction_id_2 = TransactionId::from("txnid2"); buffer.push( transaction_id_0, @@ -1605,7 +1597,7 @@ mod builder_tests { }; use matrix_sdk_test::{async_test, event_factory::EventFactory}; use ruma::{ - EventId, MilliSecondsSinceUnixEpoch, OwnedRoomId, OwnedTransactionId, event_id, + EventId, MilliSecondsSinceUnixEpoch, RoomId, TransactionId, event_id, events::{ AnyMessageLikeEventContent, AnySyncMessageLikeEvent, AnySyncTimelineEvent, SyncMessageLikeEvent, reaction::ReactionEventContent, relation::Annotation, @@ -2491,7 +2483,7 @@ mod builder_tests { assert!(Builder::new_remote(&room_event_cache, None, user_id, None).await.is_none()); } - async fn local_prelude() -> (Client, OwnedRoomId, RoomSendQueue, RoomEventCache) { + async fn local_prelude() -> (Client, RoomId, RoomSendQueue, RoomEventCache) { let room_id = owned_room_id!("!r0"); let server = MatrixMockServer::new().await; @@ -2539,7 +2531,7 @@ mod builder_tests { fn new_local_echo_content( room_send_queue: &RoomSendQueue, - transaction_id: &OwnedTransactionId, + transaction_id: &TransactionId, body: &str, ) -> LocalEchoContent { LocalEchoContent::Event { @@ -2565,7 +2557,7 @@ mod builder_tests { // Receiving one `NewLocalEvent`. let previous_value = { - let transaction_id = OwnedTransactionId::from("txnid0"); + let transaction_id = TransactionId::from("txnid0"); let content = new_local_echo_content(&room_send_queue, &transaction_id, "A"); let update = RoomSendQueueUpdate::NewLocalEvent(LocalEcho { transaction_id, content }); @@ -2579,7 +2571,7 @@ mod builder_tests { // Receiving another `NewLocalEvent`, ensuring it's pushed back in the buffer. { - let transaction_id = OwnedTransactionId::from("txnid1"); + let transaction_id = TransactionId::from("txnid1"); let content = new_local_echo_content(&room_send_queue, &transaction_id, "B"); let update = RoomSendQueueUpdate::NewLocalEvent(LocalEcho { transaction_id, content }); @@ -2604,7 +2596,7 @@ mod builder_tests { // Receiving one `NewLocalEvent`. let (transaction_id_0, previous_value) = { - let transaction_id = OwnedTransactionId::from("txnid0"); + let transaction_id = TransactionId::from("txnid0"); let content = new_local_echo_content(&room_send_queue, &transaction_id, "A"); let update = RoomSendQueueUpdate::NewLocalEvent(LocalEcho { @@ -2648,7 +2640,7 @@ mod builder_tests { // and as a `LocalCannotBeSent` because the previous value is itself // `LocalCannotBeSent`. { - let transaction_id = OwnedTransactionId::from("txnid1"); + let transaction_id = TransactionId::from("txnid1"); let content = new_local_echo_content(&room_send_queue, &transaction_id, "B"); let update = RoomSendQueueUpdate::NewLocalEvent(LocalEcho { transaction_id, content }); @@ -2674,7 +2666,7 @@ mod builder_tests { // Receiving one `NewLocalEvent` with content of kind event. let (transaction_id_0, previous_value) = { - let transaction_id = OwnedTransactionId::from("txnid0"); + let transaction_id = TransactionId::from("txnid0"); let content = new_local_echo_content(&room_send_queue, &transaction_id, "A"); let update = RoomSendQueueUpdate::NewLocalEvent(LocalEcho { @@ -2694,7 +2686,7 @@ mod builder_tests { // Receiving one `NewLocalEvent` with content of kind react! This time, it is // ignored. { - let transaction_id = OwnedTransactionId::from("txnid1"); + let transaction_id = TransactionId::from("txnid1"); let content = LocalEchoContent::React { key: "<< 1".to_owned(), send_handle: SendReactionHandle::new( @@ -2730,9 +2722,9 @@ mod builder_tests { let user_id = client.user_id().unwrap(); let mut buffer = BufferOfValuesForLocalEvents::new(); - let transaction_id_0 = OwnedTransactionId::from("txnid0"); - let transaction_id_1 = OwnedTransactionId::from("txnid1"); - let transaction_id_2 = OwnedTransactionId::from("txnid2"); + let transaction_id_0 = TransactionId::from("txnid0"); + let transaction_id_1 = TransactionId::from("txnid1"); + let transaction_id_2 = TransactionId::from("txnid2"); // Receiving three `NewLocalEvent`s. let previous_value = { @@ -2830,8 +2822,8 @@ mod builder_tests { let user_id = client.user_id().unwrap(); let mut buffer = BufferOfValuesForLocalEvents::new(); - let transaction_id_0 = OwnedTransactionId::from("txnid0"); - let transaction_id_1 = OwnedTransactionId::from("txnid1"); + let transaction_id_0 = TransactionId::from("txnid0"); + let transaction_id_1 = TransactionId::from("txnid1"); // Receiving two `NewLocalEvent`s. let previous_value = { @@ -2908,8 +2900,8 @@ mod builder_tests { let user_id = client.user_id().unwrap(); let mut buffer = BufferOfValuesForLocalEvents::new(); - let transaction_id_0 = OwnedTransactionId::from("txnid0"); - let transaction_id_1 = OwnedTransactionId::from("txnid1"); + let transaction_id_0 = TransactionId::from("txnid0"); + let transaction_id_1 = TransactionId::from("txnid1"); // Receiving two `NewLocalEvent`s. let previous_value = { @@ -2994,7 +2986,7 @@ mod builder_tests { let user_id = client.user_id().unwrap(); let mut buffer = BufferOfValuesForLocalEvents::new(); - let transaction_id = OwnedTransactionId::from("txnid0"); + let transaction_id = TransactionId::from("txnid0"); // Receiving one `NewLocalEvent`. let previous_value = { @@ -3058,7 +3050,7 @@ mod builder_tests { let user_id = client.user_id().unwrap(); let mut buffer = BufferOfValuesForLocalEvents::new(); - let transaction_id = OwnedTransactionId::from("txnid0"); + let transaction_id = TransactionId::from("txnid0"); // Receiving one `NewLocalEvent`. let previous_value = { @@ -3135,8 +3127,8 @@ mod builder_tests { let user_id = client.user_id().unwrap(); let mut buffer = BufferOfValuesForLocalEvents::new(); - let transaction_id_0 = OwnedTransactionId::from("txnid0"); - let transaction_id_1 = OwnedTransactionId::from("txnid1"); + let transaction_id_0 = TransactionId::from("txnid0"); + let transaction_id_1 = TransactionId::from("txnid1"); // Receiving two `NewLocalEvent`s. let previous_value = { @@ -3213,8 +3205,8 @@ mod builder_tests { let user_id = client.user_id().unwrap(); let mut buffer = BufferOfValuesForLocalEvents::new(); - let transaction_id_0 = OwnedTransactionId::from("txnid0"); - let transaction_id_1 = OwnedTransactionId::from("txnid1"); + let transaction_id_0 = TransactionId::from("txnid0"); + let transaction_id_1 = TransactionId::from("txnid1"); // Receiving two `NewLocalEvent`s. let previous_value = { @@ -3291,8 +3283,8 @@ mod builder_tests { let user_id = client.user_id().unwrap(); let mut buffer = BufferOfValuesForLocalEvents::new(); - let transaction_id_0 = OwnedTransactionId::from("txnid0"); - let transaction_id_1 = OwnedTransactionId::from("txnid1"); + let transaction_id_0 = TransactionId::from("txnid0"); + let transaction_id_1 = TransactionId::from("txnid1"); // Receiving two `NewLocalEvent`s. let previous_value = { @@ -3367,7 +3359,7 @@ mod builder_tests { let user_id = client.user_id().unwrap(); let mut buffer = BufferOfValuesForLocalEvents::new(); - let transaction_id = OwnedTransactionId::from("txnid"); + let transaction_id = TransactionId::from("txnid"); // Receiving a `NewLocalEvent`. let previous_value = { @@ -3475,7 +3467,7 @@ mod builder_tests { // An update that won't create a new `LatestEventValue`: it maps // to zero existing local value. &RoomSendQueueUpdate::SentEvent { - transaction_id: OwnedTransactionId::from("txnid"), + transaction_id: TransactionId::from("txnid"), event_id: event_id_1.to_owned(), }, &mut buffer, diff --git a/crates/matrix-sdk/src/latest_events/latest_event/mod.rs b/crates/matrix-sdk/src/latest_events/latest_event/mod.rs index 1a9aab59346..8b77b0e38b0 100644 --- a/crates/matrix-sdk/src/latest_events/latest_event/mod.rs +++ b/crates/matrix-sdk/src/latest_events/latest_event/mod.rs @@ -22,7 +22,7 @@ pub use matrix_sdk_base::latest_event::{ LatestEventValue, LocalLatestEventValue, RemoteLatestEventValue, }; use matrix_sdk_base::{RoomInfoNotableUpdateReasons, RoomState, StateChanges}; -use ruma::{EventId, OwnedEventId, UserId, events::room::power_levels::RoomPowerLevels}; +use ruma::{EventId, UserId, events::room::power_levels::RoomPowerLevels}; use tracing::{error, info, instrument, trace, warn}; use crate::{Room, event_cache::RoomEventCache, room::WeakRoom, send_queue::RoomSendQueueUpdate}; @@ -36,7 +36,7 @@ pub(super) struct LatestEvent { weak_room: WeakRoom, /// The thread (if any) owning this latest event. - _thread_id: Option, + _thread_id: Option, /// A buffer of the current [`LatestEventValue`]s computed for local events /// seen by the send queue. See [`BufferOfValuesForLocalEvents`] to learn @@ -314,7 +314,7 @@ mod tests_latest_event { use matrix_sdk_common::cross_process_lock::CrossProcessLockConfig; use matrix_sdk_test::{async_test, event_factory::EventFactory}; use ruma::{ - MilliSecondsSinceUnixEpoch, OwnedTransactionId, event_id, + MilliSecondsSinceUnixEpoch, TransactionId, event_id, events::{AnyMessageLikeEventContent, room::message::RoomMessageEventContent}, owned_event_id, owned_room_id, room_id, user_id, }; @@ -331,7 +331,7 @@ mod tests_latest_event { fn new_local_echo_content( room_send_queue: &RoomSendQueue, - transaction_id: &OwnedTransactionId, + transaction_id: &TransactionId, body: &str, ) -> LocalEchoContent { LocalEchoContent::Event { @@ -526,7 +526,7 @@ mod tests_latest_event { // Second, let's create a `LatestEventValue` from the send queue. It // must overwrite the current `LatestEventValue`. - let transaction_id = OwnedTransactionId::from("txnid0"); + let transaction_id = TransactionId::from("txnid0"); { let content = new_local_echo_content(&room_send_queue, &transaction_id, "B"); diff --git a/crates/matrix-sdk/src/latest_events/mod.rs b/crates/matrix-sdk/src/latest_events/mod.rs index 8831df91368..798237d0349 100644 --- a/crates/matrix-sdk/src/latest_events/mod.rs +++ b/crates/matrix-sdk/src/latest_events/mod.rs @@ -63,7 +63,7 @@ pub use latest_event::{LatestEventValue, LocalLatestEventValue, RemoteLatestEven use matrix_sdk_base::{RoomInfoNotableUpdate, RoomInfoNotableUpdateReasons, timer}; use matrix_sdk_common::executor::{AbortOnDrop, JoinHandleExt as _, spawn}; use room_latest_events::{RoomLatestEvents, RoomLatestEventsWriteGuard}; -use ruma::{EventId, OwnedRoomId, RoomId}; +use ruma::{EventId, RoomId}; use tokio::{ select, sync::{RwLock, RwLockReadGuard, RwLockWriteGuard, broadcast, mpsc}, @@ -231,7 +231,7 @@ impl LatestEvents { #[derive(Debug)] struct RegisteredRooms { /// All the registered [`RoomLatestEvents`]. - rooms: RwLock>, + rooms: RwLock>, /// The (weak) client. weak_client: WeakClient, @@ -273,7 +273,7 @@ impl RegisteredRooms { ) -> Result>, LatestEventsError> { fn create_and_insert_room_latest_events( room_id: &RoomId, - rooms: &mut HashMap, + rooms: &mut HashMap, weak_client: &WeakClient, event_cache: &EventCache, latest_event_queue_sender: &mpsc::UnboundedSender, @@ -428,13 +428,13 @@ enum LatestEventQueueUpdate { /// An update from the [`EventCache`] happened. EventCache { /// The ID of the room that has triggered the update. - room_id: OwnedRoomId, + room_id: RoomId, }, /// An update from the [`SendQueue`] happened. SendQueue { /// The ID of the room that has triggered the update. - room_id: OwnedRoomId, + room_id: RoomId, /// The update itself. update: RoomSendQueueUpdate, @@ -445,7 +445,7 @@ enum LatestEventQueueUpdate { /// [`RoomInfo`]: crate::RoomInfo RoomInfo { /// The ID of the room that has triggered the update. - room_id: OwnedRoomId, + room_id: RoomId, /// The notable update reasons. reasons: RoomInfoNotableUpdateReasons, @@ -495,7 +495,7 @@ async fn listen_to_updates_task( /// Having this function detached from its task is helpful for testing and for /// state isolation. async fn listen_to_updates( - registered_rooms: &RwLock>, + registered_rooms: &RwLock>, event_cache_generic_updates_subscriber: &mut broadcast::Receiver, send_queue_generic_updates_subscriber: &mut broadcast::Receiver, room_info_updates_subscriber: &mut broadcast::Receiver, @@ -590,7 +590,7 @@ async fn compute_latest_events( ) { async fn room_latest_events_write_guard( registered_rooms: &RegisteredRooms, - room_id: &OwnedRoomId, + room_id: &RoomId, ) -> ControlFlow { let rooms = registered_rooms.rooms.read().await; @@ -675,7 +675,7 @@ mod tests { InvitedRoomBuilder, JoinedRoomBuilder, async_test, event_factory::EventFactory, }; use ruma::{ - MilliSecondsSinceUnixEpoch, OwnedTransactionId, event_id, + MilliSecondsSinceUnixEpoch, TransactionId, event_id, events::{ AnySyncMessageLikeEvent, AnySyncStateEvent, AnySyncTimelineEvent, SyncMessageLikeEvent, room::member::{MembershipState, SyncRoomMemberEvent}, @@ -945,7 +945,7 @@ mod tests { .send(SendQueueUpdate { room_id: room_id.clone(), update: RoomSendQueueUpdate::SentEvent { - transaction_id: OwnedTransactionId::from("txnid0"), + transaction_id: TransactionId::from("txnid0"), event_id: owned_event_id!("$ev0"), }, }) @@ -978,7 +978,7 @@ mod tests { .send(SendQueueUpdate { room_id: room_id.clone(), update: RoomSendQueueUpdate::SentEvent { - transaction_id: OwnedTransactionId::from("txnid1"), + transaction_id: TransactionId::from("txnid1"), event_id: owned_event_id!("$ev1"), }, }) @@ -1481,7 +1481,7 @@ mod tests { assert!(event_id.is_none()); // It's a stripped state event: they don't have a timestamp (`origin_server_ts`), but `now` is normally used as a fallback. assert!(timestamp.get() >= now); - assert_eq!(inviter.as_deref(), Some(other_user_id)); + assert_eq!(inviter.as_ref(), Some(other_user_id)); } ); diff --git a/crates/matrix-sdk/src/latest_events/room_latest_events.rs b/crates/matrix-sdk/src/latest_events/room_latest_events.rs index 1c1125cc8fd..3e055172b88 100644 --- a/crates/matrix-sdk/src/latest_events/room_latest_events.rs +++ b/crates/matrix-sdk/src/latest_events/room_latest_events.rs @@ -16,7 +16,7 @@ use std::{collections::HashMap, sync::Arc}; use async_once_cell::OnceCell; use matrix_sdk_base::RoomInfoNotableUpdateReasons; -use ruma::{EventId, OwnedEventId}; +use ruma::EventId; use tokio::sync::{OwnedRwLockReadGuard, OwnedRwLockWriteGuard, RwLock}; use tracing::error; @@ -82,7 +82,7 @@ struct RoomLatestEventsState { for_the_room: LatestEvent, /// The latest events for each thread. - per_thread: HashMap, + per_thread: HashMap, /// The event cache. event_cache: EventCache, @@ -114,7 +114,7 @@ impl RoomLatestEventsReadGuard { } #[cfg(test)] - pub fn per_thread(&self) -> &HashMap { + pub fn per_thread(&self) -> &HashMap { &self.inner.per_thread } } diff --git a/crates/matrix-sdk/src/lib.rs b/crates/matrix-sdk/src/lib.rs index f7ccf826ebd..ad5de8e55ef 100644 --- a/crates/matrix-sdk/src/lib.rs +++ b/crates/matrix-sdk/src/lib.rs @@ -86,7 +86,7 @@ pub use matrix_sdk_sqlite::{ pub use media::Media; pub use pusher::Pusher; pub use room::Room; -pub use ruma::{IdParseError, OwnedServerName, ServerName}; +pub use ruma::{IdParseError, ServerName}; pub use sliding_sync::{ SlidingSync, SlidingSyncBuilder, SlidingSyncList, SlidingSyncListBuilder, SlidingSyncListLoadingState, SlidingSyncMode, UpdateSummary, diff --git a/crates/matrix-sdk/src/live_location_share.rs b/crates/matrix-sdk/src/live_location_share.rs index 45613fd267c..5c20b460ecc 100644 --- a/crates/matrix-sdk/src/live_location_share.rs +++ b/crates/matrix-sdk/src/live_location_share.rs @@ -19,7 +19,7 @@ use async_stream::stream; use futures_util::Stream; use ruma::{ - MilliSecondsSinceUnixEpoch, OwnedUserId, RoomId, + MilliSecondsSinceUnixEpoch, RoomId, UserId, events::{ beacon::OriginalSyncBeaconEvent, beacon_info::BeaconInfoEventContent, location::LocationContent, @@ -82,5 +82,5 @@ pub struct LiveLocationShare { /// Information about the associated beacon event. pub beacon_info: Option, /// The user ID of the person sharing their live location. - pub user_id: OwnedUserId, + pub user_id: UserId, } diff --git a/crates/matrix-sdk/src/media.rs b/crates/matrix-sdk/src/media.rs index 0947ba51235..1c9673dc648 100644 --- a/crates/matrix-sdk/src/media.rs +++ b/crates/matrix-sdk/src/media.rs @@ -27,7 +27,7 @@ use matrix_sdk_base::media::store::IgnoreMediaRetentionPolicy; pub use matrix_sdk_base::media::{store::MediaRetentionPolicy, *}; use mime::Mime; use ruma::{ - MilliSecondsSinceUnixEpoch, MxcUri, OwnedMxcUri, TransactionId, UInt, + MilliSecondsSinceUnixEpoch, MxcUri, TransactionId, UInt, api::{ Metadata, client::{authenticated_media, error::ErrorKind, media}, @@ -123,7 +123,7 @@ impl fmt::Display for PersistError { #[derive(Debug)] pub struct PreallocatedMxcUri { /// The URI for the media URI. - pub uri: OwnedMxcUri, + pub uri: MxcUri, /// The expiration date for the media URI. expire_date: Option, } @@ -755,12 +755,12 @@ impl Media { Ok(Some((MediaSource::Plain(url), thumbnail_info))) } - /// Create an [`OwnedMxcUri`] for a file or thumbnail we want to store + /// Create an [`MxcUri`] for a file or thumbnail we want to store /// locally before sending it. /// /// This uses a MXC ID that is only locally valid. - pub(crate) fn make_local_uri(txn_id: &TransactionId) -> OwnedMxcUri { - OwnedMxcUri::from(format!("mxc://{LOCAL_MXC_SERVER_NAME}/{txn_id}")) + pub(crate) fn make_local_uri(txn_id: &TransactionId) -> MxcUri { + MxcUri::from(format!("mxc://{LOCAL_MXC_SERVER_NAME}/{txn_id}")) } /// Create a [`MediaRequest`] for a file we want to store locally before @@ -828,17 +828,17 @@ mod tests { let txn_id = "abcdef"; // Request generated with `make_local_file_media_request`. - let request = Media::make_local_file_media_request(txn_id.into()); + let request = Media::make_local_file_media_request(&txn_id.into()); assert_matches!(Media::as_local_uri(&request.source), Some(uri)); assert_eq!(uri.media_id(), Ok(txn_id)); // Local plain source. - let source = MediaSource::Plain(Media::make_local_uri(txn_id.into())); + let source = MediaSource::Plain(Media::make_local_uri(&txn_id.into())); assert_matches!(Media::as_local_uri(&source), Some(uri)); assert_eq!(uri.media_id(), Ok(txn_id)); // Local encrypted source. - let source = MediaSource::Encrypted(encrypted_file(&Media::make_local_uri(txn_id.into()))); + let source = MediaSource::Encrypted(encrypted_file(&Media::make_local_uri(&txn_id.into()))); assert_matches!(Media::as_local_uri(&source), Some(uri)); assert_eq!(uri.media_id(), Ok(txn_id)); diff --git a/crates/matrix-sdk/src/notification_settings/command.rs b/crates/matrix-sdk/src/notification_settings/command.rs index 4fe5c2e301c..ced17b0d623 100644 --- a/crates/matrix-sdk/src/notification_settings/command.rs +++ b/crates/matrix-sdk/src/notification_settings/command.rs @@ -1,7 +1,7 @@ use std::fmt::Debug; use ruma::{ - OwnedRoomId, + RoomId, push::{ Action, NewConditionalPushRule, NewPatternedPushRule, NewPushRule, NewSimplePushRule, PushCondition, RuleKind, Tweak, @@ -14,9 +14,9 @@ use crate::NotificationSettingsError; #[derive(Clone, Debug)] pub(crate) enum Command { /// Set a new `Room` push rule - SetRoomPushRule { room_id: OwnedRoomId, notify: bool }, + SetRoomPushRule { room_id: RoomId, notify: bool }, /// Set a new `Override` push rule matching a `RoomId` - SetOverridePushRule { rule_id: String, room_id: OwnedRoomId, notify: bool }, + SetOverridePushRule { rule_id: String, room_id: RoomId, notify: bool }, /// Set a new push rule for a keyword. SetKeywordPushRule { keyword: String }, /// Set whether a push rule is enabled diff --git a/crates/matrix-sdk/src/notification_settings/mod.rs b/crates/matrix-sdk/src/notification_settings/mod.rs index cb64b1cda4d..f22a0e03771 100644 --- a/crates/matrix-sdk/src/notification_settings/mod.rs +++ b/crates/matrix-sdk/src/notification_settings/mod.rs @@ -591,7 +591,7 @@ mod tests { notification_settings::{build_ruleset, get_server_default_ruleset}, }; use ruma::{ - OwnedRoomId, RoomId, owned_room_id, + RoomId, owned_room_id, push::{ Action, AnyPushRuleRef, NewPatternedPushRule, NewPushRule, PredefinedContentRuleId, PredefinedOverrideRuleId, PredefinedUnderrideRuleId, RuleKind, Ruleset, @@ -613,7 +613,7 @@ mod tests { test_utils::{logged_in_client, mocks::MatrixMockServer}, }; - fn get_test_room_id() -> OwnedRoomId { + fn get_test_room_id() -> RoomId { owned_room_id!("!AAAaAAAAAaaAAaaaaa:matrix.org") } diff --git a/crates/matrix-sdk/src/notification_settings/rule_commands.rs b/crates/matrix-sdk/src/notification_settings/rule_commands.rs index 7f510079580..466e68caa2d 100644 --- a/crates/matrix-sdk/src/notification_settings/rule_commands.rs +++ b/crates/matrix-sdk/src/notification_settings/rule_commands.rs @@ -224,7 +224,7 @@ mod tests { }, }; use ruma::{ - OwnedRoomId, RoomId, + RoomId, push::{ Action, NewPushRule, NewSimplePushRule, PredefinedContentRuleId, PredefinedOverrideRuleId, PredefinedUnderrideRuleId, RemovePushRuleError, RuleKind, @@ -235,7 +235,7 @@ mod tests { use super::RuleCommands; use crate::{error::NotificationSettingsError, notification_settings::command::Command}; - fn get_test_room_id() -> OwnedRoomId { + fn get_test_room_id() -> RoomId { RoomId::parse("!AAAaAAAAAaaAAaaaaa:matrix.org").unwrap() } diff --git a/crates/matrix-sdk/src/notification_settings/rules.rs b/crates/matrix-sdk/src/notification_settings/rules.rs index 4df2566c689..8e9f401c163 100644 --- a/crates/matrix-sdk/src/notification_settings/rules.rs +++ b/crates/matrix-sdk/src/notification_settings/rules.rs @@ -321,7 +321,7 @@ pub(crate) mod tests { }, }; use ruma::{ - OwnedRoomId, RoomId, + RoomId, push::{ Action, NewConditionalPushRule, NewPushRule, PredefinedContentRuleId, PredefinedOverrideRuleId, PredefinedUnderrideRuleId, PushCondition, RuleKind, @@ -337,7 +337,7 @@ pub(crate) mod tests { }, }; - fn get_test_room_id() -> OwnedRoomId { + fn get_test_room_id() -> RoomId { RoomId::parse("!AAAaAAAAAaaAAaaaaa:matrix.org").unwrap() } diff --git a/crates/matrix-sdk/src/paginators/mod.rs b/crates/matrix-sdk/src/paginators/mod.rs index 78b4859b826..55e00c060ad 100644 --- a/crates/matrix-sdk/src/paginators/mod.rs +++ b/crates/matrix-sdk/src/paginators/mod.rs @@ -19,7 +19,7 @@ pub mod thread; use matrix_sdk_base::deserialized_responses::TimelineEvent; pub use room::*; -use ruma::OwnedEventId; +use ruma::EventId; /// Pagination token data, indicating in which state is the current pagination. #[derive(Clone, Debug, PartialEq)] @@ -71,7 +71,7 @@ pub struct PaginationResult { pub enum PaginatorError { /// The target event could not be found. #[error("target event with id {0} could not be found")] - EventNotFound(OwnedEventId), + EventNotFound(EventId), /// We're trying to manipulate the paginator in the wrong state. #[error("expected paginator state {expected:?}, observed {actual:?}")] diff --git a/crates/matrix-sdk/src/paginators/thread.rs b/crates/matrix-sdk/src/paginators/thread.rs index def9b867bd9..271377df4f3 100644 --- a/crates/matrix-sdk/src/paginators/thread.rs +++ b/crates/matrix-sdk/src/paginators/thread.rs @@ -19,7 +19,7 @@ use std::{fmt::Formatter, future::Future, sync::Mutex}; use matrix_sdk_base::{SendOutsideWasm, SyncOutsideWasm, deserialized_responses::TimelineEvent}; -use ruma::{EventId, OwnedEventId, UInt, api::Direction}; +use ruma::{EventId, UInt, api::Direction}; use crate::{ Error, Room, @@ -32,27 +32,27 @@ pub trait PaginableThread: SendOutsideWasm + SyncOutsideWasm { /// Runs a /relations query for the given thread, with the given options. fn relations( &self, - thread_root: OwnedEventId, + thread_root: EventId, opts: RelationsOptions, ) -> impl Future> + SendOutsideWasm; /// Load an event, given its event ID. fn load_event( &self, - event_id: &OwnedEventId, + event_id: &EventId, ) -> impl Future> + SendOutsideWasm; } impl PaginableThread for Room { async fn relations( &self, - thread_root: OwnedEventId, + thread_root: EventId, opts: RelationsOptions, ) -> Result { self.relations(thread_root, opts).await } - async fn load_event(&self, event_id: &OwnedEventId) -> Result { + async fn load_event(&self, event_id: &EventId) -> Result { self.event(event_id, None).await } } @@ -63,7 +63,7 @@ pub struct ThreadedEventsLoader { room: P, /// The thread root event ID (the event that started the thread). - root_event_id: OwnedEventId, + root_event_id: EventId, /// The current pagination tokens, which are used to keep track of the /// pagination state. @@ -72,7 +72,7 @@ pub struct ThreadedEventsLoader { impl ThreadedEventsLoader

{ /// Create a new [`ThreadedEventsLoader`], given a room implementation. - pub fn new(room: P, root_event_id: OwnedEventId, tokens: PaginationTokens) -> Self { + pub fn new(room: P, root_event_id: EventId, tokens: PaginationTokens) -> Self { Self { room, root_event_id, tokens: Mutex::new(tokens) } } diff --git a/crates/matrix-sdk/src/room/calls.rs b/crates/matrix-sdk/src/room/calls.rs index 083f618abee..d48560663df 100644 --- a/crates/matrix-sdk/src/room/calls.rs +++ b/crates/matrix-sdk/src/room/calls.rs @@ -15,7 +15,7 @@ //! Facilities to handle incoming calls. use ruma::{ - EventId, OwnedUserId, UserId, + EventId, UserId, events::{ AnySyncMessageLikeEvent, AnySyncTimelineEvent, rtc::decline::{RtcDeclineEventContent, SyncRtcDeclineEvent}, @@ -115,7 +115,7 @@ impl Room { pub fn subscribe_to_call_decline_events( &self, notification_event_id: &EventId, - ) -> (EventHandlerDropGuard, broadcast::Receiver) { + ) -> (EventHandlerDropGuard, broadcast::Receiver) { let (sender, receiver) = broadcast::channel(16); let decline_call_event_handler_handle = diff --git a/crates/matrix-sdk/src/room/edit.rs b/crates/matrix-sdk/src/room/edit.rs index 246590e826f..39b1d5785f5 100644 --- a/crates/matrix-sdk/src/room/edit.rs +++ b/crates/matrix-sdk/src/room/edit.rs @@ -290,7 +290,7 @@ mod tests { use matrix_sdk_base::deserialized_responses::TimelineEvent; use matrix_sdk_test::{async_test, event_factory::EventFactory}; use ruma::{ - EventId, OwnedEventId, event_id, + EventId, event_id, events::{ AnyMessageLikeEventContent, AnySyncTimelineEvent, Mentions, room::message::{MessageType, Relation, RoomMessageEventContentWithoutRelation}, @@ -303,7 +303,7 @@ mod tests { #[derive(Default)] struct TestEventCache { - events: BTreeMap, + events: BTreeMap, } impl EventSource for TestEventCache { diff --git a/crates/matrix-sdk/src/room/futures.rs b/crates/matrix-sdk/src/room/futures.rs index 368c3199f8e..eb265e0f415 100644 --- a/crates/matrix-sdk/src/room/futures.rs +++ b/crates/matrix-sdk/src/room/futures.rs @@ -27,7 +27,7 @@ use mime::Mime; #[cfg(doc)] use ruma::events::{MessageLikeUnsigned, SyncMessageLikeEvent}; use ruma::{ - OwnedTransactionId, TransactionId, + TransactionId, api::client::message::send_message_event, assign, events::{AnyMessageLikeEventContent, MessageLikeEventContent}, @@ -63,7 +63,7 @@ pub struct SendMessageLikeEvent<'a> { room: &'a Room, event_type: String, content: serde_json::Result, - transaction_id: Option, + transaction_id: Option, request_config: Option, } @@ -91,7 +91,7 @@ impl<'a> SendMessageLikeEvent<'a> { /// corresponding [`SyncMessageLikeEvent`], but only for the *sending* /// device. Other devices will not see it. This is then used to ignore /// events sent by our own device and/or to implement local echo. - pub fn with_transaction_id(mut self, txn_id: OwnedTransactionId) -> Self { + pub fn with_transaction_id(mut self, txn_id: TransactionId) -> Self { self.transaction_id = Some(txn_id); self } @@ -124,7 +124,7 @@ pub struct SendRawMessageLikeEvent<'a> { event_type: &'a str, content: Raw, tracing_span: Span, - transaction_id: Option, + transaction_id: Option, request_config: Option, } diff --git a/crates/matrix-sdk/src/room/identity_status_changes.rs b/crates/matrix-sdk/src/room/identity_status_changes.rs index 38b2a4adc0f..7f5cf35bf14 100644 --- a/crates/matrix-sdk/src/room/identity_status_changes.rs +++ b/crates/matrix-sdk/src/room/identity_status_changes.rs @@ -23,7 +23,7 @@ use futures_util::{StreamExt, stream_select}; use matrix_sdk_base::crypto::{ IdentityState, IdentityStatusChange, RoomIdentityChange, RoomIdentityState, }; -use ruma::{OwnedUserId, UserId, events::room::member::SyncRoomMemberEvent}; +use ruma::{UserId, events::room::member::SyncRoomMemberEvent}; use tokio::sync::mpsc; use tokio_stream::wrappers::ReceiverStream; @@ -178,8 +178,8 @@ fn to_base_updates( } fn to_base_identities( - input: BTreeMap, -) -> BTreeMap { + input: BTreeMap, +) -> BTreeMap { input.into_iter().map(|(k, v)| (k, v.underlying_identity())).collect() } @@ -607,7 +607,7 @@ mod tests { test_json::keys_query_sets::IdentityChangeDataSet, }; use ruma::{ - OwnedUserId, TransactionId, UserId, + TransactionId, UserId, api::client::keys::{get_keys, get_keys::v3::Response as KeyQueryResponse}, events::room::member::MembershipState, owned_user_id, user_id, @@ -633,7 +633,7 @@ mod tests { /// The other user is called `@bob:localhost`. pub(super) struct TestSetup { client: Client, - bob_user_id: OwnedUserId, + bob_user_id: UserId, sync_response_builder: SyncResponseBuilder, room: Room, } @@ -800,7 +800,7 @@ mod tests { .expect("Should be able to subscribe") } - async fn init() -> (Client, OwnedUserId, SyncResponseBuilder) { + async fn init() -> (Client, UserId, SyncResponseBuilder) { let (client, _server) = create_client_and_server().await; // Ensure our user has cross-signing keys etc. diff --git a/crates/matrix-sdk/src/room/knock_requests.rs b/crates/matrix-sdk/src/room/knock_requests.rs index f204a95bff7..769ed6e4589 100644 --- a/crates/matrix-sdk/src/room/knock_requests.rs +++ b/crates/matrix-sdk/src/room/knock_requests.rs @@ -13,7 +13,7 @@ // limitations under the License. use js_int::UInt; -use ruma::{EventId, OwnedEventId, OwnedMxcUri, OwnedUserId, RoomId}; +use ruma::{EventId, MxcUri, RoomId, UserId}; use crate::{Error, Room, room::RoomMember}; @@ -22,7 +22,7 @@ use crate::{Error, Room, room::RoomMember}; pub struct KnockRequest { room: Room, /// The event id of the event containing knock membership change. - pub event_id: OwnedEventId, + pub event_id: EventId, /// The timestamp when this request was created. pub timestamp: Option, /// Some general room member info to display. @@ -82,11 +82,11 @@ impl KnockRequest { #[derive(Debug, Clone)] pub struct KnockRequestMemberInfo { /// The user id for the room member requesting access. - pub user_id: OwnedUserId, + pub user_id: UserId, /// The optional display name of the room member requesting access. pub display_name: Option, /// The optional avatar url of the room member requesting access. - pub avatar_url: Option, + pub avatar_url: Option, /// An optional reason why the user wants access to the room. pub reason: Option, } diff --git a/crates/matrix-sdk/src/room/messages.rs b/crates/matrix-sdk/src/room/messages.rs index 4d63d8d3d9a..301fc342334 100644 --- a/crates/matrix-sdk/src/room/messages.rs +++ b/crates/matrix-sdk/src/room/messages.rs @@ -17,7 +17,7 @@ use std::fmt; use futures_util::future::join_all; use matrix_sdk_common::{debug::DebugStructExt as _, deserialized_responses::TimelineEvent}; use ruma::{ - OwnedEventId, RoomId, UInt, + EventId, RoomId, UInt, api::{ Direction, client::{ @@ -282,7 +282,7 @@ pub struct RelationsOptions { impl RelationsOptions { /// Converts this options object into a request, according to the filled /// parameters, and returns a canonicalized response. - pub(super) async fn send(self, room: &Room, event: OwnedEventId) -> Result { + pub(super) async fn send(self, room: &Room, event: EventId) -> Result { macro_rules! fill_params { ($request:expr) => { assign! { $request, { diff --git a/crates/matrix-sdk/src/room/mod.rs b/crates/matrix-sdk/src/room/mod.rs index 88fa702d62b..3e01e03509d 100644 --- a/crates/matrix-sdk/src/room/mod.rs +++ b/crates/matrix-sdk/src/room/mod.rs @@ -76,8 +76,7 @@ use ruma::events::{ AnySyncTimelineEvent, SyncMessageLikeEvent, room::encrypted::OriginalSyncRoomEncryptedEvent, }; use ruma::{ - EventId, Int, MatrixToUri, MatrixUri, MxcUri, OwnedEventId, OwnedRoomId, OwnedServerName, - OwnedTransactionId, OwnedUserId, RoomId, TransactionId, UInt, UserId, + EventId, Int, MatrixToUri, MatrixUri, MxcUri, RoomId, ServerName, TransactionId, UInt, UserId, api::client::{ config::{set_global_account_data, set_room_account_data}, context, @@ -655,7 +654,7 @@ impl Room { /// be filtered out. pub fn subscribe_to_typing_notifications( &self, - ) -> (EventHandlerDropGuard, broadcast::Receiver>) { + ) -> (EventHandlerDropGuard, broadcast::Receiver>) { let (sender, receiver) = broadcast::channel(16); let typing_event_handler_handle = self.client.add_room_event_handler(self.room_id(), { let own_user_id = self.own_user_id().to_owned(); @@ -1324,7 +1323,7 @@ impl Room { /// ```no_run /// # async { /// # let room: matrix_sdk::Room = todo!(); - /// # let user_ids: &[matrix_sdk::ruma::OwnedUserId] = &[]; + /// # let user_ids: &[matrix_sdk::ruma::UserId] = &[]; /// use matrix_sdk::ruma::events::room::member::RoomMemberEventContent; /// /// let room_members = room @@ -1460,7 +1459,7 @@ impl Room { } }) // Check whether the parent recognizes this room as its child - .map(|(state_key, sender): (OwnedRoomId, OwnedUserId)| async move { + .map(|(state_key, sender): (RoomId, UserId)| async move { let Some(parent_room) = self.client.get_room(&state_key) else { // We are not in the room, cannot check if the relationship is reciprocal // TODO: try peeking into the room @@ -1577,7 +1576,7 @@ impl Room { /// ``` /// # async { /// # let room: matrix_sdk::Room = todo!(); - /// # let event_id: ruma::OwnedEventId = todo!(); + /// # let event_id: ruma::EventId = todo!(); /// use matrix_sdk::ruma::events::fully_read::FullyReadEventContent; /// let content = FullyReadEventContent::new(event_id); /// @@ -2143,7 +2142,7 @@ impl Room { &self, receipt_type: create_receipt::v3::ReceiptType, thread: ReceiptThread, - event_id: OwnedEventId, + event_id: EventId, ) -> Result<()> { // Since the receipt type and the thread aren't Hash/Ord, flatten then as a // string key. @@ -2387,7 +2386,7 @@ impl Room { .state_store() .get_user_ids(self.room_id(), RoomMemberships::ACTIVE) .await?; - self.client.claim_one_time_keys(members.iter().map(Deref::deref)).await?; + self.client.claim_one_time_keys(members.iter()).await?; }; let response = self.share_room_key().await; @@ -2542,8 +2541,7 @@ impl Room { let members_with_unknown_devices = members.iter().filter(|member| tracked.get(*member).is_none_or(|dirty| *dirty)); - let (req_id, request) = - olm.query_keys_for_users(members_with_unknown_devices.map(|owned| owned.borrow())); + let (req_id, request) = olm.query_keys_for_users(members_with_unknown_devices); if !request.device_keys.is_empty() { self.client.keys_query(&req_id, request.device_keys).await?; @@ -2921,9 +2919,9 @@ impl Room { /// Gets a map with the `UserId` of users with power levels other than `0` /// and this power level. - pub async fn users_with_power_levels(&self) -> HashMap { + pub async fn users_with_power_levels(&self) -> HashMap { let power_levels = self.power_levels().await.ok(); - let mut user_power_levels = HashMap::::new(); + let mut user_power_levels = HashMap::::new(); if let Some(power_levels) = power_levels { for (id, level) in power_levels.users.into_iter() { user_power_levels.insert(id, level.into()); @@ -3365,7 +3363,7 @@ impl Room { &self, event_id: &EventId, reason: Option<&str>, - txn_id: Option, + txn_id: Option, ) -> HttpResult { let txn_id = txn_id.unwrap_or_else(TransactionId::new); let request = assign!( @@ -3384,7 +3382,7 @@ impl Room { /// Returns at most three servers. /// /// [routing algorithm]: https://spec.matrix.org/v1.3/appendices/#routing - pub async fn route(&self) -> Result> { + pub async fn route(&self) -> Result> { let acl_ev = self .get_state_event_static::() .await? @@ -3403,7 +3401,7 @@ impl Room { .into_iter() .filter(|member| { let server = member.user_id().server_name(); - acl.filter(|acl| !acl.is_allowed(server)).is_none() && !server.is_ip_literal() + acl.filter(|acl| !acl.is_allowed(&server)).is_none() && !server.is_ip_literal() }) .collect(); @@ -3419,7 +3417,7 @@ impl Room { let servers = members .iter() .map(|member| member.user_id().server_name()) - .filter(|server| max.filter(|max| max == server).is_none()) + .filter(|server| max.as_ref().filter(|max| max == server).is_none()) .fold(BTreeMap::<_, u32>::new(), |mut servers, server| { *servers.entry(server).or_default() += 1; servers @@ -3427,12 +3425,7 @@ impl Room { let mut servers: Vec<_> = servers.into_iter().collect(); servers.sort_unstable_by(|(_, count_a), (_, count_b)| count_b.cmp(count_a)); - Ok(max - .into_iter() - .chain(servers.into_iter().map(|(name, _)| name)) - .take(3) - .map(ToOwned::to_owned) - .collect()) + Ok(max.into_iter().chain(servers.into_iter().map(|(name, _)| name)).take(3).collect()) } /// Get a `matrix.to` permalink to this room. @@ -3484,7 +3477,7 @@ impl Room { /// [routing]: https://spec.matrix.org/v1.3/appendices/#routing pub async fn matrix_to_event_permalink( &self, - event_id: impl Into, + event_id: impl Into, ) -> Result { // Don't use the alias because an event is tied to a room ID, but an // alias might point to another room, e.g. after a room upgrade. @@ -3505,10 +3498,7 @@ impl Room { /// * `event_id` - The ID of the event. /// /// [routing]: https://spec.matrix.org/v1.3/appendices/#routing - pub async fn matrix_event_permalink( - &self, - event_id: impl Into, - ) -> Result { + pub async fn matrix_event_permalink(&self, event_id: impl Into) -> Result { // Don't use the alias because an event is tied to a room ID, but an // alias might point to another room, e.g. after a room upgrade. let via = self.route().await?; @@ -3532,7 +3522,7 @@ impl Room { receipt_type: ReceiptType, thread: ReceiptThread, user_id: &UserId, - ) -> Result> { + ) -> Result> { self.inner.load_user_receipt(receipt_type, thread, user_id).await.map_err(Into::into) } @@ -3553,7 +3543,7 @@ impl Room { receipt_type: ReceiptType, thread: ReceiptThread, event_id: &EventId, - ) -> Result> { + ) -> Result> { self.inner.load_event_receipts(receipt_type, thread, event_id).await.map_err(Into::into) } @@ -3830,7 +3820,7 @@ impl Room { /// the request. pub async fn report_content( &self, - event_id: OwnedEventId, + event_id: EventId, score: Option, reason: Option, ) -> Result { @@ -4036,7 +4026,7 @@ impl Room { /// Load pinned state events for a room from the `/state` endpoint in the /// home server. - pub async fn load_pinned_events(&self) -> Result>> { + pub async fn load_pinned_events(&self) -> Result>> { let response = self .client .send(get_state_event_for_key::v3::Request::new( @@ -4195,7 +4185,7 @@ impl Room { async fn get_current_join_requests( &self, - seen_request_ids: &BTreeMap, + seen_request_ids: &BTreeMap, ) -> Result> { Ok(self .members(RoomMemberships::KNOCK) @@ -4253,11 +4243,7 @@ impl Room { /// then it must be used with the same /// [`RelationsOptions::include_relations`] value as the request that /// returns the `from` token, otherwise the server behavior is undefined. - pub async fn relations( - &self, - event_id: OwnedEventId, - opts: RelationsOptions, - ) -> Result { + pub async fn relations(&self, event_id: EventId, opts: RelationsOptions) -> Result { let relations = opts.send(self, event_id).await; // Save any new related events to the cache. @@ -4278,7 +4264,7 @@ impl Room { query: &str, max_number_of_results: usize, pagination_offset: Option, - ) -> Result, IndexError> { + ) -> Result, IndexError> { let mut search_index_guard = self.client.search_index().lock().await; search_index_guard.search(query, max_number_of_results, pagination_offset, self.room_id()) } @@ -4307,8 +4293,8 @@ impl Room { #[instrument(skip(self), fields(room_id = %self.room_id()))] pub async fn subscribe_thread( &self, - thread_root: OwnedEventId, - automatic: Option, + thread_root: EventId, + automatic: Option, ) -> Result<()> { let is_automatic = automatic.is_some(); @@ -4366,7 +4352,7 @@ impl Room { pub async fn subscribe_thread_if_needed( &self, thread_root: &EventId, - automatic: Option, + automatic: Option, ) -> Result<()> { if let Some(prev_sub) = self.load_or_fetch_thread_subscription(thread_root).await? { // If we have a previous subscription, we should only send the new one if it's @@ -4392,7 +4378,7 @@ impl Room { /// already unsubscribed. /// - A 404 error if the event isn't known, or isn't a thread root. #[instrument(skip(self), fields(room_id = %self.room_id()))] - pub async fn unsubscribe_thread(&self, thread_root: OwnedEventId) -> Result<()> { + pub async fn unsubscribe_thread(&self, thread_root: EventId) -> Result<()> { self.client .send(unsubscribe_thread::unstable::Request::new( self.room_id().to_owned(), @@ -4437,7 +4423,7 @@ impl Room { #[instrument(skip(self), fields(room_id = %self.room_id()))] pub async fn fetch_thread_subscription( &self, - thread_root: OwnedEventId, + thread_root: EventId, ) -> Result> { let result = self .client @@ -4552,7 +4538,7 @@ impl Room { self.load_pinned_events().await?.unwrap_or_default() }; let event_id = event_id.to_owned(); - if let Some(idx) = pinned_event_ids.iter().position(|e| *e == *event_id) { + if let Some(idx) = pinned_event_ids.iter().position(|e| *e == event_id) { pinned_event_ids.remove(idx); let content = RoomPinnedEventsEventContent::new(pinned_event_ids); self.send_state_event(content).await?; @@ -4603,12 +4589,12 @@ impl RoomIdentityProvider for Room { #[derive(Clone, Debug)] pub(crate) struct WeakRoom { client: WeakClient, - room_id: OwnedRoomId, + room_id: RoomId, } impl WeakRoom { /// Create a new `WeakRoom` given its weak components. - pub fn new(client: WeakClient, room_id: OwnedRoomId) -> Self { + pub fn new(client: WeakClient, room_id: RoomId) -> Self { Self { client, room_id } } @@ -4632,7 +4618,7 @@ pub struct Invite { /// The user ID of who sent the invite. /// /// This is useful if `Self::inviter` is `None`. - pub inviter_id: OwnedUserId, + pub inviter_id: UserId, /// Who sent the invite. /// @@ -4651,11 +4637,11 @@ enum InvitationError { #[non_exhaustive] pub struct Receipts { /// Fully-read marker (room account data). - pub fully_read: Option, + pub fully_read: Option, /// Read receipt (public ephemeral room event). - pub public_read_receipt: Option, + pub public_read_receipt: Option, /// Read receipt (private ephemeral room event). - pub private_read_receipt: Option, + pub private_read_receipt: Option, } impl Receipts { @@ -4672,7 +4658,7 @@ impl Receipts { /// /// Note that this is technically not a receipt as it is persisted in the /// room account data. - pub fn fully_read_marker(mut self, event_id: impl Into>) -> Self { + pub fn fully_read_marker(mut self, event_id: impl Into>) -> Self { self.fully_read = event_id.into(); self } @@ -4682,7 +4668,7 @@ impl Receipts { /// /// This is used to reset the unread messages/notification count and /// advertise to other users the last event that the user has likely seen. - pub fn public_read_receipt(mut self, event_id: impl Into>) -> Self { + pub fn public_read_receipt(mut self, event_id: impl Into>) -> Self { self.public_read_receipt = event_id.into(); self } @@ -4690,7 +4676,7 @@ impl Receipts { /// Set the last event presented to the user and don't forward it. /// /// This is used to reset the unread messages/notification count. - pub fn private_read_receipt(mut self, event_id: impl Into>) -> Self { + pub fn private_read_receipt(mut self, event_id: impl Into>) -> Self { self.private_read_receipt = event_id.into(); self } @@ -4720,7 +4706,7 @@ pub enum ParentSpace { Illegitimate(Room), /// The room recognizes the given id as its parent room, but we cannot check /// whether the parent recognizes it as its child. - Unverifiable(OwnedRoomId), + Unverifiable(RoomId), } /// The score to rate an inappropriate content. diff --git a/crates/matrix-sdk/src/room/power_levels.rs b/crates/matrix-sdk/src/room/power_levels.rs index cb33c1ab20a..85194ba0841 100644 --- a/crates/matrix-sdk/src/room/power_levels.rs +++ b/crates/matrix-sdk/src/room/power_levels.rs @@ -3,7 +3,7 @@ use std::collections::HashMap; use ruma::{ - OwnedUserId, + UserId, events::{ StateEventType, room::power_levels::{ @@ -178,7 +178,7 @@ impl From for crate::error::Error { pub fn power_level_user_changes( content: &RoomPowerLevelsEventContent, prev_content: &Option, -) -> HashMap { +) -> HashMap { let Some(prev_content) = prev_content.as_ref() else { return Default::default(); }; @@ -357,14 +357,14 @@ mod tests { // moderator. let prev_content = default_power_levels_event_content(); let mut content = prev_content.clone(); - content.users.insert(OwnedUserId::try_from("@charlie:example.com").unwrap(), int!(50)); + content.users.insert(UserId::try_from("@charlie:example.com").unwrap(), int!(50)); // When calculating the changes. let changes = power_level_user_changes(&content, &Some(prev_content)); // Then the changes should reflect the new moderator. assert_eq!(changes.len(), 1); - assert_eq!(changes.get(&OwnedUserId::try_from("@charlie:example.com").unwrap()), Some(&50)); + assert_eq!(changes.get(&UserId::try_from("@charlie:example.com").unwrap()), Some(&50)); } #[test] @@ -373,14 +373,14 @@ mod tests { // moderator. let prev_content = default_power_levels_event_content(); let mut content = prev_content.clone(); - content.users.remove(&OwnedUserId::try_from("@bob:example.com").unwrap()); + content.users.remove(&UserId::try_from("@bob:example.com").unwrap()); // When calculating the changes. let changes = power_level_user_changes(&content, &Some(prev_content)); // Then the changes should reflect the removed moderator. assert_eq!(changes.len(), 1); - assert_eq!(changes.get(&OwnedUserId::try_from("@bob:example.com").unwrap()), Some(&0)); + assert_eq!(changes.get(&UserId::try_from("@bob:example.com").unwrap()), Some(&0)); } #[test] @@ -389,14 +389,14 @@ mod tests { // moderator to an admin. let prev_content = default_power_levels_event_content(); let mut content = prev_content.clone(); - content.users.insert(OwnedUserId::try_from("@bob:example.com").unwrap(), int!(100)); + content.users.insert(UserId::try_from("@bob:example.com").unwrap(), int!(100)); // When calculating the changes. let changes = power_level_user_changes(&content, &Some(prev_content)); // Then the changes should reflect the new admin. assert_eq!(changes.len(), 1); - assert_eq!(changes.get(&OwnedUserId::try_from("@bob:example.com").unwrap()), Some(&100)); + assert_eq!(changes.get(&UserId::try_from("@bob:example.com").unwrap()), Some(&100)); } #[test] @@ -406,7 +406,7 @@ mod tests { let prev_content = default_power_levels_event_content(); let mut content = prev_content.clone(); content.users_default = int!(50); - content.users.remove(&OwnedUserId::try_from("@bob:example.com").unwrap()); + content.users.remove(&UserId::try_from("@bob:example.com").unwrap()); // When calculating the changes. let changes = power_level_user_changes(&content, &Some(prev_content)); @@ -461,8 +461,8 @@ mod tests { content.state_default = int!(50); content.users_default = int!(0); content.users = BTreeMap::from_iter(vec![ - (OwnedUserId::try_from("@alice:example.com").unwrap(), int!(100)), - (OwnedUserId::try_from("@bob:example.com").unwrap(), int!(50)), + (UserId::try_from("@alice:example.com").unwrap(), int!(100)), + (UserId::try_from("@bob:example.com").unwrap(), int!(50)), ]); content.notifications = NotificationPowerLevels::default(); content diff --git a/crates/matrix-sdk/src/room/privacy_settings.rs b/crates/matrix-sdk/src/room/privacy_settings.rs index b69c693cd18..984bab48471 100644 --- a/crates/matrix-sdk/src/room/privacy_settings.rs +++ b/crates/matrix-sdk/src/room/privacy_settings.rs @@ -1,6 +1,6 @@ use matrix_sdk_base::Room as BaseRoom; use ruma::{ - OwnedRoomAliasId, RoomAliasId, + RoomAliasId, api::client::{ directory::{get_room_visibility, set_room_visibility}, room::Visibility, @@ -82,8 +82,8 @@ impl<'a> RoomPrivacySettings<'a> { /// as the canonical alias. pub async fn update_canonical_alias( &'a self, - alias: Option, - alt_aliases: Vec, + alias: Option, + alt_aliases: Vec, ) -> Result<()> { // Create a new alias event combining both the new and previous values let content = assign!( diff --git a/crates/matrix-sdk/src/room/reply.rs b/crates/matrix-sdk/src/room/reply.rs index efa2d01cdeb..755bbe1e2fe 100644 --- a/crates/matrix-sdk/src/room/reply.rs +++ b/crates/matrix-sdk/src/room/reply.rs @@ -16,7 +16,7 @@ use as_variant::as_variant; use ruma::{ - OwnedEventId, UserId, + EventId, UserId, events::{ AnySyncTimelineEvent, room::{ @@ -37,7 +37,7 @@ use super::{EventSource, Room}; #[derive(Debug)] pub struct Reply { /// The event ID of the event to reply to. - pub event_id: OwnedEventId, + pub event_id: EventId, /// Whether to enforce a thread relation. pub enforce_thread: EnforceThread, } @@ -150,7 +150,7 @@ mod tests { use matrix_sdk_base::deserialized_responses::TimelineEvent; use matrix_sdk_test::{async_test, event_factory::EventFactory}; use ruma::{ - EventId, OwnedEventId, event_id, + EventId, event_id, events::{ AnySyncTimelineEvent, room::message::{Relation, ReplyWithinThread, RoomMessageEventContentWithoutRelation}, @@ -165,7 +165,7 @@ mod tests { #[derive(Default)] struct TestEventCache { - events: BTreeMap, + events: BTreeMap, } impl EventSource for TestEventCache { diff --git a/crates/matrix-sdk/src/room/shared_room_history.rs b/crates/matrix-sdk/src/room/shared_room_history.rs index 509998aa478..22762bc6d0b 100644 --- a/crates/matrix-sdk/src/room/shared_room_history.rs +++ b/crates/matrix-sdk/src/room/shared_room_history.rs @@ -18,7 +18,7 @@ use matrix_sdk_base::{ crypto::{store::types::Changes, types::events::room_key_bundle::RoomKeyBundleContent}, media::{MediaFormat, MediaRequestParameters}, }; -use ruma::{OwnedUserId, UserId, events::room::MediaSource}; +use ruma::{UserId, events::room::MediaSource}; use tracing::{debug, info, instrument, warn}; use crate::{Error, Result, Room}; @@ -28,7 +28,7 @@ use crate::{Error, Result, Room}; /// /// [MSC4268]: https://github.com/matrix-org/matrix-spec-proposals/pull/4268 #[instrument(skip(room), fields(room_id = ?room.room_id()))] -pub(super) async fn share_room_history(room: &Room, user_id: OwnedUserId) -> Result<()> { +pub(super) async fn share_room_history(room: &Room, user_id: UserId) -> Result<()> { let client = &room.client; // 0. We can only share room history if our user has set up cross signing @@ -80,14 +80,14 @@ pub(super) async fn share_room_history(room: &Room, user_id: OwnedUserId) -> Res ); // 4. Ensure that we get a fresh list of devices for the invited user. - let (req_id, request) = olm_machine.query_keys_for_users(iter::once(user_id.as_ref())); + let (req_id, request) = olm_machine.query_keys_for_users(iter::once(&user_id)); if !request.device_keys.is_empty() { room.client.keys_query(&req_id, request.device_keys).await?; } // 5. Establish Olm sessions with all of the recipient's devices. - client.claim_one_time_keys(iter::once(user_id.as_ref())).await?; + client.claim_one_time_keys(iter::once(&user_id)).await?; // 6. Send to-device messages to the recipient to share the keys. let content = RoomKeyBundleContent { room_id: room.room_id().to_owned(), file: upload }; @@ -152,8 +152,7 @@ pub(crate) async fn maybe_accept_key_bundle(room: &Room, inviter: &UserId) -> Re // XXX: is this necessary, given (with exclude-insecure-devices), we should have // checked that the inviter device was cross-signed when we received the // to-device message? - let (req_id, request) = - olm_machine.query_keys_for_users(iter::once(bundle_info.sender_user.as_ref())); + let (req_id, request) = olm_machine.query_keys_for_users(iter::once(&bundle_info.sender_user)); if !request.device_keys.is_empty() { room.client.keys_query(&req_id, request.device_keys).await?; diff --git a/crates/matrix-sdk/src/room_directory_search.rs b/crates/matrix-sdk/src/room_directory_search.rs index af22418af25..287906504ce 100644 --- a/crates/matrix-sdk/src/room_directory_search.rs +++ b/crates/matrix-sdk/src/room_directory_search.rs @@ -19,12 +19,12 @@ use eyeball_im::{ObservableVector, VectorDiff}; use futures_core::Stream; use imbl::Vector; use ruma::{ - OwnedMxcUri, OwnedRoomAliasId, OwnedRoomId, + MxcUri, RoomAliasId, RoomId, api::client::directory::get_public_rooms_filtered::v3::Request as PublicRoomsFilterRequest, directory::Filter, room::JoinRuleKind, }; -use crate::{Client, OwnedServerName, Result}; +use crate::{Client, Result, ServerName}; /// This struct represents a single result of a room directory search. /// @@ -32,15 +32,15 @@ use crate::{Client, OwnedServerName, Result}; #[derive(Clone, Debug, Eq, PartialEq)] pub struct RoomDescription { /// The room's ID. - pub room_id: OwnedRoomId, + pub room_id: RoomId, /// The name of the room, if any. pub name: Option, /// The topic of the room, if any. pub topic: Option, /// The canonical alias of the room, if any. - pub alias: Option, + pub alias: Option, /// The room's avatar URL, if any. - pub avatar_url: Option, + pub avatar_url: Option, /// The room's join rule. pub join_rule: JoinRuleKind, /// Whether can be previewed @@ -114,7 +114,7 @@ impl SearchState { pub struct RoomDirectorySearch { batch_size: u32, filter: Option, - server: Option, + server: Option, search_state: SearchState, client: Client, results: ObservableVector, @@ -149,7 +149,7 @@ impl RoomDirectorySearch { &mut self, filter: Option, batch_size: u32, - via_server: Option, + via_server: Option, ) -> Result<()> { self.filter = filter; self.batch_size = batch_size; diff --git a/crates/matrix-sdk/src/room_preview.rs b/crates/matrix-sdk/src/room_preview.rs index 401fb7c05f8..d9016fb8b0f 100644 --- a/crates/matrix-sdk/src/room_preview.rs +++ b/crates/matrix-sdk/src/room_preview.rs @@ -21,7 +21,7 @@ use futures_util::future::join_all; use matrix_sdk_base::{RawSyncStateEventWithKeys, RoomHero, RoomInfo, RoomState}; use ruma::{ - OwnedMxcUri, OwnedRoomAliasId, OwnedRoomId, OwnedServerName, RoomId, RoomOrAliasId, ServerName, + MxcUri, RoomAliasId, RoomId, RoomOrAliasId, ServerName, api::client::{membership::joined_members, state::get_state_events}, events::room::history_visibility::HistoryVisibility, room::{JoinRuleSummary, RoomType}, @@ -38,10 +38,10 @@ pub struct RoomPreview { /// /// Remember the room preview can be fetched from a room alias id, so we /// might not know ahead of time what the room id is. - pub room_id: OwnedRoomId, + pub room_id: RoomId, /// The canonical alias for the room. - pub canonical_alias: Option, + pub canonical_alias: Option, /// The room's name, if set. pub name: Option, @@ -50,7 +50,7 @@ pub struct RoomPreview { pub topic: Option, /// The MXC URI to the room's avatar, if set. - pub avatar_url: Option, + pub avatar_url: Option, /// The number of joined members. pub num_joined_members: u64, @@ -135,9 +135,9 @@ impl RoomPreview { #[instrument(skip(client))] pub(crate) async fn from_remote_room( client: &Client, - room_id: OwnedRoomId, + room_id: RoomId, room_or_alias_id: &RoomOrAliasId, - via: Vec, + via: Vec, ) -> crate::Result { // Use the room summary endpoint, if available, as described in // https://github.com/deepbluev7/matrix-doc/blob/room-summaries/proposals/3266-room-summary.md @@ -182,7 +182,7 @@ impl RoomPreview { client: &Client, room_id: &RoomId, room_or_alias_id: &RoomOrAliasId, - via: Vec, + via: Vec, ) -> crate::Result> { // Get either the room alias or the room id without the leading identifier char let search_term = if room_or_alias_id.is_room_alias_id() { @@ -232,12 +232,12 @@ impl RoomPreview { /// `Client::get_room_preview` in general over this. pub async fn from_room_summary( client: &Client, - room_id: OwnedRoomId, + room_id: RoomId, room_or_alias_id: &RoomOrAliasId, - via: Vec, + via: Vec, ) -> crate::Result { let own_server_name = client.session_meta().map(|s| s.user_id.server_name()); - let via = ensure_server_names_is_not_empty(own_server_name, via, room_or_alias_id); + let via = ensure_server_names_is_not_empty(own_server_name.as_ref(), via, room_or_alias_id); let request = ruma::api::client::room::get_summary::v1::Request::new( room_or_alias_id.to_owned(), @@ -337,7 +337,7 @@ async fn search_for_room_preview_in_room_directory( client: Client, filter: Option, batch_size: u32, - server: Option, + server: Option, expected_room_id: &RoomId, ) -> crate::Result> { let mut directory_search = RoomDirectorySearch::new(client); @@ -375,16 +375,16 @@ async fn search_for_room_preview_in_room_directory( // included in the list of server names to send if no server names are provided fn ensure_server_names_is_not_empty( own_server_name: Option<&ServerName>, - server_names: Vec, + server_names: Vec, room_or_alias_id: &RoomOrAliasId, -) -> Vec { +) -> Vec { let mut server_names = server_names; if let Some((own_server, alias_server)) = own_server_name.zip(room_or_alias_id.server_name()) && server_names.is_empty() && own_server != alias_server { - server_names.push(alias_server.to_owned()); + server_names.push(alias_server); } server_names @@ -399,10 +399,10 @@ mod tests { #[test] fn test_ensure_server_names_is_not_empty_when_no_own_server_name_is_provided() { let own_server_name: Option<&ServerName> = None; - let room_or_alias_id: &RoomOrAliasId = room_id!("!test:localhost").into(); + let room_or_alias_id: RoomOrAliasId = room_id!("!test:localhost").into(); let server_names = - ensure_server_names_is_not_empty(own_server_name, Vec::new(), room_or_alias_id); + ensure_server_names_is_not_empty(own_server_name, Vec::new(), &room_or_alias_id); // There was no own server name to check against, so no additional server name // was added @@ -412,10 +412,10 @@ mod tests { #[test] fn test_ensure_server_names_is_not_empty_when_room_alias_or_id_has_no_server_name() { let own_server_name: Option<&ServerName> = Some(server_name!("localhost")); - let room_or_alias_id: &RoomOrAliasId = room_id!("!test").into(); + let room_or_alias_id: RoomOrAliasId = room_id!("!test").into(); let server_names = - ensure_server_names_is_not_empty(own_server_name, Vec::new(), room_or_alias_id); + ensure_server_names_is_not_empty(own_server_name, Vec::new(), &room_or_alias_id); // The room id has no server name, so nothing could be added assert!(server_names.is_empty()); @@ -424,10 +424,10 @@ mod tests { #[test] fn test_ensure_server_names_is_not_empty_with_same_server_name() { let own_server_name: Option<&ServerName> = Some(server_name!("localhost")); - let room_or_alias_id: &RoomOrAliasId = room_id!("!test:localhost").into(); + let room_or_alias_id: RoomOrAliasId = room_id!("!test:localhost").into(); let server_names = - ensure_server_names_is_not_empty(own_server_name, Vec::new(), room_or_alias_id); + ensure_server_names_is_not_empty(own_server_name, Vec::new(), &room_or_alias_id); // The room id's server name was the same as our own server name, so there's no // need to add it @@ -437,10 +437,10 @@ mod tests { #[test] fn test_ensure_server_names_is_not_empty_with_different_room_id_server_name() { let own_server_name: Option<&ServerName> = Some(server_name!("localhost")); - let room_or_alias_id: &RoomOrAliasId = room_id!("!test:matrix.org").into(); + let room_or_alias_id: RoomOrAliasId = room_id!("!test:matrix.org").into(); let server_names = - ensure_server_names_is_not_empty(own_server_name, Vec::new(), room_or_alias_id); + ensure_server_names_is_not_empty(own_server_name, Vec::new(), &room_or_alias_id); // The server name in the room id was added assert!(!server_names.is_empty()); @@ -450,10 +450,10 @@ mod tests { #[test] fn test_ensure_server_names_is_not_empty_with_different_room_alias_server_name() { let own_server_name: Option<&ServerName> = Some(server_name!("localhost")); - let room_or_alias_id: &RoomOrAliasId = room_alias_id!("#test:matrix.org").into(); + let room_or_alias_id: RoomOrAliasId = room_alias_id!("#test:matrix.org").into(); let server_names = - ensure_server_names_is_not_empty(own_server_name, Vec::new(), room_or_alias_id); + ensure_server_names_is_not_empty(own_server_name, Vec::new(), &room_or_alias_id); // The server name in the room alias was added assert!(!server_names.is_empty()); diff --git a/crates/matrix-sdk/src/search_index/mod.rs b/crates/matrix-sdk/src/search_index/mod.rs index 6f696e42671..edc8e720bcd 100644 --- a/crates/matrix-sdk/src/search_index/mod.rs +++ b/crates/matrix-sdk/src/search_index/mod.rs @@ -25,7 +25,7 @@ use matrix_sdk_search::{ index::{RoomIndex, RoomIndexOperation, builder::RoomIndexBuilder}, }; use ruma::{ - EventId, OwnedEventId, OwnedRoomId, RoomId, + EventId, RoomId, events::{ AnySyncMessageLikeEvent, AnySyncTimelineEvent, room::{ @@ -57,7 +57,7 @@ pub enum SearchIndexStoreKind { #[derive(Clone, Debug)] pub struct SearchIndex { /// HashMap that links each joined room to its RoomIndex - room_indexes: Arc>>, + room_indexes: Arc>>, /// Base directory that stores the directories for each RoomIndex search_index_store_kind: SearchIndexStoreKind, @@ -66,7 +66,7 @@ pub struct SearchIndex { impl SearchIndex { /// Create a new [`SearchIndex`] pub fn new( - room_indexes: Arc>>, + room_indexes: Arc>>, search_index_store_kind: SearchIndexStoreKind, ) -> Self { Self { room_indexes, search_index_store_kind } @@ -85,7 +85,7 @@ impl SearchIndex { #[derive(Debug)] pub struct SearchIndexGuard<'a> { /// Guard around the [`RoomIndex`] map - index_map: MutexGuard<'a, HashMap>, + index_map: MutexGuard<'a, HashMap>, /// Base directory that stores the directories for each RoomIndex search_index_store_kind: &'a SearchIndexStoreKind, @@ -157,7 +157,7 @@ impl SearchIndexGuard<'_> { max_number_of_results: usize, pagination_offset: Option, room_id: &RoomId, - ) -> Result, IndexError> { + ) -> Result, IndexError> { if !self.index_map.contains_key(room_id) { let index = self.create_index(room_id)?; self.index_map.insert(room_id.to_owned(), index); diff --git a/crates/matrix-sdk/src/send_queue/mod.rs b/crates/matrix-sdk/src/send_queue/mod.rs index 4cd956474c0..044986facdf 100644 --- a/crates/matrix-sdk/src/send_queue/mod.rs +++ b/crates/matrix-sdk/src/send_queue/mod.rs @@ -158,8 +158,7 @@ use matrix_sdk_base::{ use matrix_sdk_common::locks::Mutex as SyncMutex; use mime::Mime; use ruma::{ - MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, OwnedTransactionId, RoomId, - TransactionId, + EventId, MilliSecondsSinceUnixEpoch, RoomId, TransactionId, events::{ AnyMessageLikeEventContent, Mentions, MessageLikeEventContent as _, reaction::ReactionEventContent, @@ -307,7 +306,7 @@ impl SendQueue { /// Get local echoes from all room send queues. pub async fn local_echoes( &self, - ) -> Result>, RoomSendQueueError> { + ) -> Result>, RoomSendQueueError> { let room_ids = self.client.state_store().load_rooms_with_unsent_requests().await.unwrap_or_else( |err| { @@ -316,7 +315,7 @@ impl SendQueue { }, ); - let mut local_echoes: BTreeMap> = BTreeMap::new(); + let mut local_echoes: BTreeMap> = BTreeMap::new(); for room_id in room_ids { if let Some(room) = self.client.get_room(&room_id) { @@ -357,7 +356,7 @@ struct QueueThumbnailInfo { #[derive(Clone, Debug)] pub struct SendQueueRoomError { /// For which room is the send queue failing? - pub room_id: OwnedRoomId, + pub room_id: RoomId, /// The error the room has ran into, when trying to send a request. pub error: Arc, @@ -380,7 +379,7 @@ impl Client { pub(super) struct SendQueueData { /// Mapping of room to their unique send queue. - rooms: RwLock>, + rooms: RwLock>, /// Is the whole mechanism enabled or disabled? /// @@ -463,7 +462,7 @@ impl RoomSendQueue { global_error_sender: broadcast::Sender, is_dropping: Arc, client: &Client, - room_id: OwnedRoomId, + room_id: RoomId, report_media_upload_progress: Arc, ) -> Self { let (update_sender, _) = broadcast::channel(32); @@ -1171,7 +1170,7 @@ struct RoomSendQueueInner { /// Information about a request being sent right this moment. struct BeingSentInfo { /// Transaction id of the thing being sent. - transaction_id: OwnedTransactionId, + transaction_id: TransactionId, /// For an upload request, a trigger to cancel the upload before it /// completes. @@ -1242,7 +1241,7 @@ struct QueueStorage { store: StoreLock, /// To which room is this storage related. - room_id: OwnedRoomId, + room_id: RoomId, /// In-memory mapping of media transaction IDs to thumbnail sizes for the /// purpose of progress reporting. @@ -1256,7 +1255,7 @@ struct QueueStorage { /// For galleries, some gallery items might not have a thumbnail while /// others do. Since we access the thumbnails by their index within the /// gallery, the vector needs to hold optional usize's. - thumbnail_file_sizes: Arc>>>>, + thumbnail_file_sizes: Arc>>>>, } impl QueueStorage { @@ -1267,7 +1266,7 @@ impl QueueStorage { const HIGH_PRIORITY: usize = 10; /// Create a new queue for queuing requests to be sent later. - fn new(client: WeakClient, room: OwnedRoomId) -> Self { + fn new(client: WeakClient, room: RoomId) -> Self { Self { room_id: room, store: StoreLock { client, being_sent: Default::default() }, @@ -1282,7 +1281,7 @@ impl QueueStorage { &self, request: QueuedRequestKind, created_at: MilliSecondsSinceUnixEpoch, - ) -> Result { + ) -> Result { let transaction_id = TransactionId::new(); self.store @@ -1347,7 +1346,7 @@ impl QueueStorage { async fn mark_as_not_being_sent(&self, transaction_id: &TransactionId) { let was_being_sent = self.store.lock().await.being_sent.take(); - let prev_txn = was_being_sent.as_ref().map(|info| info.transaction_id.as_ref()); + let prev_txn = was_being_sent.as_ref().map(|info| &info.transaction_id); if prev_txn != Some(transaction_id) { error!(prev_txn = ?prev_txn, "previous active request didn't match that we expect (after transient error)"); } @@ -1365,7 +1364,7 @@ impl QueueStorage { let mut guard = self.store.lock().await; let was_being_sent = guard.being_sent.take(); - let prev_txn = was_being_sent.as_ref().map(|info| info.transaction_id.as_ref()); + let prev_txn = was_being_sent.as_ref().map(|info| &info.transaction_id); if prev_txn != Some(transaction_id) { error!( ?prev_txn, @@ -1407,7 +1406,7 @@ impl QueueStorage { let mut guard = self.store.lock().await; let was_being_sent = guard.being_sent.take(); - let prev_txn = was_being_sent.as_ref().map(|info| info.transaction_id.as_ref()); + let prev_txn = was_being_sent.as_ref().map(|info| &info.transaction_id); if prev_txn != Some(transaction_id) { error!( ?prev_txn, @@ -1446,9 +1445,7 @@ impl QueueStorage { ) -> Result { let guard = self.store.lock().await; - if guard.being_sent.as_ref().map(|info| info.transaction_id.as_ref()) - == Some(transaction_id) - { + if guard.being_sent.as_ref().map(|info| &info.transaction_id) == Some(transaction_id) { // Save the intent to redact the event. guard .client()? @@ -1489,9 +1486,7 @@ impl QueueStorage { ) -> Result { let guard = self.store.lock().await; - if guard.being_sent.as_ref().map(|info| info.transaction_id.as_ref()) - == Some(transaction_id) - { + if guard.being_sent.as_ref().map(|info| &info.transaction_id) == Some(transaction_id) { // Save the intent to edit the associated event. guard .client()? @@ -1525,9 +1520,9 @@ impl QueueStorage { &self, event: RoomMessageEventContent, content_type: Mime, - send_event_txn: OwnedTransactionId, + send_event_txn: TransactionId, created_at: MilliSecondsSinceUnixEpoch, - upload_file_txn: OwnedTransactionId, + upload_file_txn: TransactionId, file_media_request: MediaRequestParameters, thumbnail: Option, ) -> Result<(), RoomSendQueueStorageError> { @@ -1578,7 +1573,7 @@ impl QueueStorage { async fn push_gallery( &self, event: RoomMessageEventContent, - send_event_txn: OwnedTransactionId, + send_event_txn: TransactionId, created_at: MilliSecondsSinceUnixEpoch, item_queue_infos: Vec, ) -> Result<(), RoomSendQueueStorageError> { @@ -1710,9 +1705,9 @@ impl QueueStorage { &self, store: &DynStateStore, content_type: &Mime, - send_event_txn: OwnedTransactionId, + send_event_txn: TransactionId, created_at: MilliSecondsSinceUnixEpoch, - upload_file_txn: OwnedTransactionId, + upload_file_txn: TransactionId, file_media_request: MediaRequestParameters, thumbnail: Option, ) -> Result, RoomSendQueueStorageError> { @@ -2298,7 +2293,7 @@ impl QueueStorage { /// Metadata needed for pushing gallery item uploads onto the send queue. struct GalleryItemQueueInfo { content_type: Mime, - upload_file_txn: OwnedTransactionId, + upload_file_txn: TransactionId, file_media_request: MediaRequestParameters, thumbnail: Option, } @@ -2325,7 +2320,7 @@ pub enum LocalEchoContent { /// A handle to manipulate the sending of the reaction. send_handle: SendReactionHandle, /// The local echo which has been reacted to. - applies_to: OwnedTransactionId, + applies_to: TransactionId, }, } @@ -2334,7 +2329,7 @@ pub enum LocalEchoContent { #[derive(Clone, Debug)] pub struct LocalEcho { /// Transaction id used to identify the associated request. - pub transaction_id: OwnedTransactionId, + pub transaction_id: TransactionId, /// The content for the local echo. pub content: LocalEchoContent, } @@ -2353,13 +2348,13 @@ pub enum RoomSendQueueUpdate { /// before sending. CancelledLocalEvent { /// Transaction id used to identify this event. - transaction_id: OwnedTransactionId, + transaction_id: TransactionId, }, /// A local event's content has been replaced with something else. ReplacedLocalEvent { /// Transaction id used to identify this event. - transaction_id: OwnedTransactionId, + transaction_id: TransactionId, /// The new content replacing the previous one. new_content: SerializableEventContent, @@ -2371,7 +2366,7 @@ pub enum RoomSendQueueUpdate { /// will be disabled after this happens, and must be manually re-enabled. SendError { /// Transaction id used to identify this event. - transaction_id: OwnedTransactionId, + transaction_id: TransactionId, /// Error received while sending the event. error: Arc, /// Whether the error is considered recoverable or not. @@ -2385,23 +2380,23 @@ pub enum RoomSendQueueUpdate { /// The event has been unwedged and sending is now being retried. RetryEvent { /// Transaction id used to identify this event. - transaction_id: OwnedTransactionId, + transaction_id: TransactionId, }, /// The event has been sent to the server, and the query returned /// successfully. SentEvent { /// Transaction id used to identify this event. - transaction_id: OwnedTransactionId, + transaction_id: TransactionId, /// Received event id from the send response. - event_id: OwnedEventId, + event_id: EventId, }, /// A media upload (consisting of a file and possibly a thumbnail) has made /// progress. MediaUpload { /// The media event this uploaded media relates to. - related_to: OwnedTransactionId, + related_to: TransactionId, /// The final media source for the file if it has finished uploading. file: Option, @@ -2418,14 +2413,14 @@ pub enum RoomSendQueueUpdate { }, } -/// A [`RoomSendQueueUpdate`] with an associated [`OwnedRoomId`]. +/// A [`RoomSendQueueUpdate`] with an associated [`RoomId`]. /// /// This is used by [`SendQueue::subscribe`] to get a single channel to receive /// updates for all [`RoomSendQueue`]s. #[derive(Clone, Debug)] pub struct SendQueueUpdate { /// The room where the update happened. - pub room_id: OwnedRoomId, + pub room_id: RoomId, /// The update for this room. pub update: RoomSendQueueUpdate, @@ -2510,10 +2505,10 @@ struct MediaHandles { /// Transaction id used when uploading the thumbnail. /// /// Optional because a media can be uploaded without a thumbnail. - upload_thumbnail_txn: Option, + upload_thumbnail_txn: Option, /// Transaction id used when uploading the media itself. - upload_file_txn: OwnedTransactionId, + upload_file_txn: TransactionId, } /// A handle to manipulate an event that was scheduled to be sent to a room. @@ -2526,7 +2521,7 @@ pub struct SendHandle { /// /// If this is a media upload, this is the "main" transaction id, i.e. the /// one used to send the event, and that will be seen by observers. - transaction_id: OwnedTransactionId, + transaction_id: TransactionId, /// Additional handles for a media upload. media_handles: Vec, @@ -2540,7 +2535,7 @@ impl SendHandle { #[cfg(test)] pub(crate) fn new( room: RoomSendQueue, - transaction_id: OwnedTransactionId, + transaction_id: TransactionId, created_at: MilliSecondsSinceUnixEpoch, ) -> Self { Self { room, transaction_id, media_handles: vec![], created_at } @@ -2819,7 +2814,7 @@ impl SendReactionHandle { fn canonicalize_dependent_requests( dependent: &[DependentQueuedRequest], ) -> Vec { - let mut by_txn = HashMap::>::new(); + let mut by_txn = HashMap::>::new(); for d in dependent { let prevs = by_txn.entry(d.parent_transaction_id.clone()).or_default(); diff --git a/crates/matrix-sdk/src/send_queue/upload.rs b/crates/matrix-sdk/src/send_queue/upload.rs index e45bacc1e3c..d310f209f5f 100644 --- a/crates/matrix-sdk/src/send_queue/upload.rs +++ b/crates/matrix-sdk/src/send_queue/upload.rs @@ -37,7 +37,7 @@ use mime::Mime; #[cfg(feature = "unstable-msc4274")] use ruma::events::room::message::{GalleryItemType, GalleryMessageEventContent}; use ruma::{ - MilliSecondsSinceUnixEpoch, OwnedTransactionId, TransactionId, + MilliSecondsSinceUnixEpoch, TransactionId, events::{ AnyMessageLikeEventContent, Mentions, room::{ @@ -170,7 +170,7 @@ fn update_gallery_event_after_upload( #[derive(Default)] struct MediaCacheResult { - upload_thumbnail_txn: Option, + upload_thumbnail_txn: Option, event_thumbnail_info: Option<(MediaSource, Box)>, queue_thumbnail_info: Option, } @@ -486,10 +486,10 @@ impl QueueStorage { pub(super) async fn handle_dependent_finish_upload( &self, client: &Client, - event_txn: OwnedTransactionId, + event_txn: TransactionId, parent_key: SentRequestKey, mut local_echo: RoomMessageEventContent, - file_upload_txn: OwnedTransactionId, + file_upload_txn: TransactionId, thumbnail_info: Option, new_updates: &mut Vec, ) -> Result<(), RoomSendQueueError> { @@ -536,7 +536,7 @@ impl QueueStorage { pub(super) async fn handle_dependent_finish_gallery_upload( &self, client: &Client, - event_txn: OwnedTransactionId, + event_txn: TransactionId, parent_key: SentRequestKey, mut local_echo: RoomMessageEventContent, item_infos: Vec, @@ -607,11 +607,11 @@ impl QueueStorage { pub(super) async fn handle_dependent_file_or_thumbnail_upload( &self, client: &Client, - next_upload_txn: OwnedTransactionId, + next_upload_txn: TransactionId, parent_key: SentRequestKey, content_type: String, cache_key: MediaRequestParameters, - event_txn: OwnedTransactionId, + event_txn: TransactionId, parent_is_thumbnail_upload: bool, ) -> Result<(), RoomSendQueueError> { // The previous file or thumbnail has been sent, now transform the dependent @@ -927,7 +927,7 @@ impl QueueStorage { /// thumbnail. async fn update_media_cache_keys_after_upload( client: &Client, - file_upload_txn: &OwnedTransactionId, + file_upload_txn: &TransactionId, thumbnail_info: Option, sent_media: &SentMediaInfo, ) -> Result<(), RoomSendQueueError> { diff --git a/crates/matrix-sdk/src/sliding_sync/README.md b/crates/matrix-sdk/src/sliding_sync/README.md index 50d105726b7..94adfd2eaf4 100644 --- a/crates/matrix-sdk/src/sliding_sync/README.md +++ b/crates/matrix-sdk/src/sliding_sync/README.md @@ -121,7 +121,7 @@ in two additional full-sync-modes, which require additional configuration: ## Rooms Next to the room list, the details for rooms are the next important aspect. -Each [list](#lists) only references the [`OwnedRoomId`] of the room at the given +Each [list](#lists) only references the [`RoomId`] of the room at the given position. The details (`required_state`s and timeline items) requested by all lists are bundled, together with the common details (e.g. whether it is a `dm` or its calculated name). Use the `Room` API to get these updated data. diff --git a/crates/matrix-sdk/src/sliding_sync/builder.rs b/crates/matrix-sdk/src/sliding_sync/builder.rs index 00f237605d3..14b7d468ba4 100644 --- a/crates/matrix-sdk/src/sliding_sync/builder.rs +++ b/crates/matrix-sdk/src/sliding_sync/builder.rs @@ -7,7 +7,7 @@ use std::{ use cfg_if::cfg_if; use matrix_sdk_common::timer; -use ruma::{OwnedRoomId, api::client::sync::sync_events::v5 as http}; +use ruma::{RoomId, api::client::sync::sync_events::v5 as http}; use tokio::sync::{Mutex as AsyncMutex, RwLock as AsyncRwLock, broadcast::channel}; use super::{ @@ -28,7 +28,7 @@ pub struct SlidingSyncBuilder { client: Client, lists: Vec, extensions: Option, - room_subscriptions: BTreeMap, + room_subscriptions: BTreeMap, poll_timeout: Duration, network_timeout: Duration, #[cfg(feature = "e2e-encryption")] diff --git a/crates/matrix-sdk/src/sliding_sync/client.rs b/crates/matrix-sdk/src/sliding_sync/client.rs index ab689b76899..2dd7e956e4f 100644 --- a/crates/matrix-sdk/src/sliding_sync/client.rs +++ b/crates/matrix-sdk/src/sliding_sync/client.rs @@ -6,7 +6,7 @@ use matrix_sdk_base::{ }; use matrix_sdk_common::deserialized_responses::ProcessedToDeviceEvent; use ruma::{ - OwnedRoomId, + RoomId, api::{ FeatureFlag, SupportedVersions, client::sync::sync_events::v5::{self as http, response}, @@ -256,7 +256,7 @@ impl SlidingSyncResponseProcessor { /// This will only fill the in-memory caches, not save the info on disk. async fn update_in_memory_caches( client: &Client, - previously_joined_rooms: &BTreeSet, + previously_joined_rooms: &BTreeSet, response: &SyncResponse, ) { let _timer = timer!(tracing::Level::TRACE, "update_in_memory_caches"); diff --git a/crates/matrix-sdk/src/sliding_sync/mod.rs b/crates/matrix-sdk/src/sliding_sync/mod.rs index 2f42ae20560..df9dc3f3c8e 100644 --- a/crates/matrix-sdk/src/sliding_sync/mod.rs +++ b/crates/matrix-sdk/src/sliding_sync/mod.rs @@ -37,7 +37,7 @@ use matrix_sdk_base::RequestedRequiredStates; use matrix_sdk_common::executor::JoinHandleExt as _; use matrix_sdk_common::{executor::spawn, timer}; use ruma::{ - OwnedRoomId, RoomId, + RoomId, api::client::{error::ErrorKind, sync::sync_events::v5 as http}, assign, }; @@ -107,7 +107,7 @@ pub(super) struct SlidingSyncInner { /// Room subscriptions, i.e. rooms that may be out-of-scope of all lists /// but one wants to receive updates. - room_subscriptions: StdRwLock>, + room_subscriptions: StdRwLock>, /// The intended state of the extensions being supplied to sliding /sync /// calls. @@ -814,7 +814,7 @@ impl SlidingSync { fn subscribe_to_rooms( mut room_subscriptions: StdRwLockWriteGuard< '_, - BTreeMap, + BTreeMap, >, client: &Client, room_ids: &[&RoomId], @@ -888,7 +888,7 @@ pub struct UpdateSummary { /// The names of the lists that have seen an update. pub lists: Vec, /// The rooms that have seen updates - pub rooms: Vec, + pub rooms: Vec, } /// Define what kind of poll timeout [`SlidingSync`] must use. @@ -957,7 +957,7 @@ mod tests { use matrix_sdk_common::executor::spawn; use matrix_sdk_test::{ALICE, async_test, event_factory::EventFactory}; use ruma::{ - OwnedRoomId, assign, + RoomId, assign, events::{direct::DirectEvent, room::member::MembershipState}, owned_room_id, room_id, serde::Raw, @@ -1054,7 +1054,7 @@ mod tests { assert!(room0.are_members_synced().not()); { - struct MemberMatcher(OwnedRoomId); + struct MemberMatcher(RoomId); impl Match for MemberMatcher { fn matches(&self, request: &Request) -> bool { @@ -1094,7 +1094,7 @@ mod tests { // Subscribing to the same room doesn't reset the member sync state. { - struct MemberMatcher(OwnedRoomId); + struct MemberMatcher(RoomId); impl Match for MemberMatcher { fn matches(&self, request: &Request) -> bool { @@ -1891,7 +1891,7 @@ mod tests { fn make_mark_unread_response( response_number: &str, - room_id: OwnedRoomId, + room_id: RoomId, unread: bool, add_rooms_section: bool, ) -> http::Response { diff --git a/crates/matrix-sdk/src/sync.rs b/crates/matrix-sdk/src/sync.rs index e21fff47e43..9dd276e556c 100644 --- a/crates/matrix-sdk/src/sync.rs +++ b/crates/matrix-sdk/src/sync.rs @@ -32,7 +32,7 @@ use matrix_sdk_base::{ }; use matrix_sdk_common::deserialized_responses::ProcessedToDeviceEvent; use ruma::{ - OwnedRoomId, RoomId, + RoomId, api::client::sync::sync_events::{ self, v3::{InvitedRoom, KnockedRoom}, @@ -60,7 +60,7 @@ pub struct SyncResponse { /// Messages sent directly between devices. pub to_device: Vec, /// New notifications per room. - pub notifications: BTreeMap>, + pub notifications: BTreeMap>, } impl SyncResponse { @@ -357,7 +357,7 @@ impl Client { #[instrument(skip_all)] pub(crate) async fn subscribe_to_room_latest_events<'a, R>(client: &'a Client, room_ids: R) where - R: Iterator, + R: Iterator, { if !client.event_cache().has_subscribed() { return; diff --git a/crates/matrix-sdk/src/test_utils/client.rs b/crates/matrix-sdk/src/test_utils/client.rs index 2edc1def032..3ccd6f9c721 100644 --- a/crates/matrix-sdk/src/test_utils/client.rs +++ b/crates/matrix-sdk/src/test_utils/client.rs @@ -15,7 +15,7 @@ //! Augmented [`ClientBuilder`] that can set up an already logged-in user. use matrix_sdk_base::{SessionMeta, store::RoomLoadSettings}; -use ruma::{OwnedDeviceId, OwnedUserId, api::MatrixVersion, owned_device_id, owned_user_id}; +use ruma::{DeviceId, UserId, api::MatrixVersion, owned_device_id, owned_user_id}; use crate::{ Client, ClientBuilder, SessionTokens, authentication::matrix::MatrixSession, @@ -90,8 +90,8 @@ impl MockClientBuilder { pub fn logged_in_with_token( mut self, token: String, - user_id: OwnedUserId, - device_id: OwnedDeviceId, + user_id: UserId, + device_id: DeviceId, ) -> Self { self.auth_state = AuthState::LoggedInWithMatrixAuth { token: Some(token), @@ -148,8 +148,8 @@ enum AuthState { /// The client is logged in with the native Matrix API. LoggedInWithMatrixAuth { token: Option, - user_id: Option, - device_id: Option, + user_id: Option, + device_id: Option, }, /// The client is registered with the OAuth 2.0 API. RegisteredWithOAuth, diff --git a/crates/matrix-sdk/src/test_utils/mocks/encryption.rs b/crates/matrix-sdk/src/test_utils/mocks/encryption.rs index 9da68aedf91..5eaef763ace 100644 --- a/crates/matrix-sdk/src/test_utils/mocks/encryption.rs +++ b/crates/matrix-sdk/src/test_utils/mocks/encryption.rs @@ -25,8 +25,8 @@ use assert_matches2::assert_let; use matrix_sdk_base::crypto::types::events::room::encrypted::EncryptedToDeviceEvent; use matrix_sdk_test::test_json; use ruma::{ - CrossSigningKeyId, DeviceId, MilliSecondsSinceUnixEpoch, OneTimeKeyAlgorithm, OwnedDeviceId, - OwnedOneTimeKeyId, OwnedUserId, UserId, + CrossSigningKeyId, DeviceId, MilliSecondsSinceUnixEpoch, OneTimeKeyAlgorithm, OneTimeKeyId, + UserId, api::client::{ keys::upload_signatures::v3::SignedKeys, to_device::send_event_to_device::v3::Messages, }, @@ -53,8 +53,7 @@ use crate::{ /// Stores pending to-device messages for each user and device. /// To be used with [`MatrixMockServer::capture_put_to_device_traffic`]. -pub type PendingToDeviceMessages = - BTreeMap>>>; +pub type PendingToDeviceMessages = BTreeMap>>>; /// Extends the `MatrixMockServer` with useful methods to help mocking /// matrix crypto API and perform integration test with encryption. @@ -105,7 +104,7 @@ impl MatrixMockServer { } /// Makes the server forget about all the one-time-keys for that device. - pub fn exhaust_one_time_keys(&self, user_id: OwnedUserId, device_id: OwnedDeviceId) { + pub fn exhaust_one_time_keys(&self, user_id: UserId, device_id: DeviceId) { let mut keys = self.keys.lock().unwrap(); let known_otks = &mut keys.one_time_keys; known_otks.entry(user_id).or_default().entry(device_id).or_default().clear(); @@ -518,7 +517,7 @@ fn mock_keys_query(keys: Arc>) -> impl Fn(&Request) -> ResponseTempl move |req| { #[derive(Debug, serde::Deserialize)] struct Parameters { - device_keys: BTreeMap>, + device_keys: BTreeMap>, } let params: Parameters = req.body_json().unwrap(); @@ -560,13 +559,13 @@ fn mock_keys_query(keys: Arc>) -> impl Fn(&Request) -> ResponseTempl /// in this mapping, only merge the signatures. fn mock_keys_upload( keys: Arc>, - token_to_user_id_map: Arc>>, + token_to_user_id_map: Arc>>, ) -> impl Fn(&Request) -> ResponseTemplate { move |req: &Request| { #[derive(Debug, serde::Deserialize)] struct Parameters { device_keys: Option>, - one_time_keys: Option>>, + one_time_keys: Option>>, } let bearer_token = req .headers @@ -712,7 +711,7 @@ fn mock_keys_signature_upload(keys: Arc>) -> impl Fn(&Request) -> Re move |req: &Request| { #[derive(Debug, serde::Deserialize)] #[serde(transparent)] - struct Parameters(BTreeMap); + struct Parameters(BTreeMap); let params: Parameters = req.body_json().unwrap(); @@ -726,7 +725,7 @@ fn mock_keys_signature_upload(keys: Arc>) -> impl Fn(&Request) -> Re let target = CrossSigningKeyId::from_parts( ruma::SigningKeyAlgorithm::Ed25519, - key_id.try_into().unwrap(), + &key_id.try_into().unwrap(), ); if existing.keys.contains_key(&target) { @@ -787,7 +786,7 @@ fn mock_keys_claimed_request(keys: Arc>) -> impl Fn(&Request) -> Res // Accept all cross-signing setups by default. #[derive(Debug, serde::Deserialize)] struct Parameters { - one_time_keys: BTreeMap>, + one_time_keys: BTreeMap>, } let params: Parameters = req.body_json().unwrap(); @@ -796,8 +795,8 @@ fn mock_keys_claimed_request(keys: Arc>) -> impl Fn(&Request) -> Res let known_otks = &mut keys.one_time_keys; let mut found_one_time_keys: BTreeMap< - OwnedUserId, - BTreeMap>>, + UserId, + BTreeMap>>, > = BTreeMap::new(); for (user, requested_one_time_keys) in params.one_time_keys { diff --git a/crates/matrix-sdk/src/test_utils/mocks/mod.rs b/crates/matrix-sdk/src/test_utils/mocks/mod.rs index 47199cf4b2c..53d9087d900 100644 --- a/crates/matrix-sdk/src/test_utils/mocks/mod.rs +++ b/crates/matrix-sdk/src/test_utils/mocks/mod.rs @@ -32,8 +32,8 @@ use matrix_sdk_test::{ }; use percent_encoding::{AsciiSet, CONTROLS}; use ruma::{ - DeviceId, EventId, MilliSecondsSinceUnixEpoch, MxcUri, OwnedDeviceId, OwnedEventId, - OwnedOneTimeKeyId, OwnedRoomId, OwnedUserId, RoomId, ServerName, UserId, + DeviceId, EventId, MilliSecondsSinceUnixEpoch, MxcUri, OneTimeKeyId, RoomId, ServerName, + UserId, api::client::{ profile::{ProfileFieldName, ProfileFieldValue}, receipt::create_receipt::v3::ReceiptType, @@ -72,20 +72,17 @@ pub mod encryption; pub mod oauth; use super::client::MockClientBuilder; -use crate::{Client, OwnedServerName, Room, SlidingSyncBuilder, room::IncludeRelations}; +use crate::{Client, Room, SlidingSyncBuilder, room::IncludeRelations}; /// Structure used to store the crypto keys uploaded to the server. /// They will be served back to clients when requested. #[derive(Debug, Default)] struct Keys { - device: BTreeMap>>, - master: BTreeMap>, - self_signing: BTreeMap>, - user_signing: BTreeMap>, - one_time_keys: BTreeMap< - OwnedUserId, - BTreeMap>>, - >, + device: BTreeMap>>, + master: BTreeMap>, + self_signing: BTreeMap>, + user_signing: BTreeMap>, + one_time_keys: BTreeMap>>>, } /// A [`wiremock`] [`MockServer`] along with useful methods to help mocking @@ -164,7 +161,7 @@ pub struct MatrixMockServer { /// For crypto API end-points to work we need to be able to recognise /// what client is doing the request by mapping the token to the user_id - token_to_user_id_map: Arc>>, + token_to_user_id_map: Arc>>, token_counter: AtomicU32, } @@ -2014,7 +2011,7 @@ impl<'a, T> MockEndpoint<'a, T> { /// Internal helper to return an `{ event_id }` JSON struct along with a 200 /// ok response. - fn ok_with_event_id(self, event_id: OwnedEventId) -> MatrixMock<'a> { + fn ok_with_event_id(self, event_id: EventId) -> MatrixMock<'a> { self.respond_with(ResponseTemplate::new(200).set_body_json(json!({ "event_id": event_id }))) } @@ -2311,7 +2308,7 @@ impl<'a> MockEndpoint<'a, RoomSendEndpoint> { /// ); /// # anyhow::Ok(()) }); /// ``` - pub fn ok(self, returned_event_id: impl Into) -> MatrixMock<'a> { + pub fn ok(self, returned_event_id: impl Into) -> MatrixMock<'a> { self.ok_with_event_id(returned_event_id.into()) } @@ -2370,8 +2367,8 @@ impl<'a> MockEndpoint<'a, RoomSendEndpoint> { /// ``` pub fn ok_with_capture( self, - returned_event_id: impl Into, - event_sender: impl Into, + returned_event_id: impl Into, + event_sender: impl Into, ) -> (Receiver>, MatrixMock<'a>) { let event_id = returned_event_id.into(); let event_sender = event_sender.into(); @@ -2703,7 +2700,7 @@ impl<'a> MockEndpoint<'a, RoomSendStateEndpoint> { /// ); /// # anyhow::Ok(()) }); /// ``` - pub fn ok(self, returned_event_id: impl Into) -> MatrixMock<'a> { + pub fn ok(self, returned_event_id: impl Into) -> MatrixMock<'a> { self.ok_with_event_id(returned_event_id.into()) } } @@ -2871,7 +2868,7 @@ pub struct SetEncryptionStateEndpoint; impl<'a> MockEndpoint<'a, SetEncryptionStateEndpoint> { /// Returns a mock for a successful setting of the encryption state event. - pub fn ok(self, returned_event_id: impl Into) -> MatrixMock<'a> { + pub fn ok(self, returned_event_id: impl Into) -> MatrixMock<'a> { self.ok_with_event_id(returned_event_id.into()) } } @@ -2882,20 +2879,20 @@ pub struct RoomRedactEndpoint; impl<'a> MockEndpoint<'a, RoomRedactEndpoint> { /// Returns a redact endpoint that emulates success, i.e. the redaction /// event has been sent with the given event id. - pub fn ok(self, returned_event_id: impl Into) -> MatrixMock<'a> { + pub fn ok(self, returned_event_id: impl Into) -> MatrixMock<'a> { self.ok_with_event_id(returned_event_id.into()) } } /// A prebuilt mock for getting a single event in a room. pub struct RoomEventEndpoint { - room: Option, + room: Option, match_event_id: bool, } impl<'a> MockEndpoint<'a, RoomEventEndpoint> { /// Limits the scope of this mock to a specific room. - pub fn room(mut self, room: impl Into) -> Self { + pub fn room(mut self, room: impl Into) -> Self { self.endpoint.room = Some(room.into()); self } @@ -2986,13 +2983,13 @@ impl RoomContextResponseTemplate { /// A prebuilt mock for getting a single event with its context in a room. pub struct RoomEventContextEndpoint { - room: Option, + room: Option, match_event_id: bool, } impl<'a> MockEndpoint<'a, RoomEventContextEndpoint> { /// Limits the scope of this mock to a specific room. - pub fn room(mut self, room: impl Into) -> Self { + pub fn room(mut self, room: impl Into) -> Self { self.endpoint.room = Some(room.into()); self } @@ -3264,12 +3261,12 @@ impl<'a> MockEndpoint<'a, PublicRoomsEndpoint> { /// fail. pub fn ok_with_via_params( self, - server_map: BTreeMap>, + server_map: BTreeMap>, ) -> MatrixMock<'a> { self.respond_with(move |req: &Request| { #[derive(Deserialize)] struct PartialRequest { - server: Option, + server: Option, } let (_, server) = req @@ -3505,7 +3502,7 @@ pub struct SetRoomPinnedEventsEndpoint; impl<'a> MockEndpoint<'a, SetRoomPinnedEventsEndpoint> { /// Returns a successful response with a given event id. /// id. - pub fn ok(self, event_id: OwnedEventId) -> MatrixMock<'a> { + pub fn ok(self, event_id: EventId) -> MatrixMock<'a> { self.ok_with_event_id(event_id) } @@ -3747,7 +3744,7 @@ impl<'a> MockEndpoint<'a, RoomThreadsEndpoint> { /// requests. #[derive(Default)] pub struct RoomRelationsEndpoint { - event_id: Option, + event_id: Option, spec: Option, } @@ -3769,7 +3766,7 @@ impl<'a> MockEndpoint<'a, RoomRelationsEndpoint> { } /// Expects the request to match a specific event id. - pub fn match_target_event(mut self, event_id: OwnedEventId) -> Self { + pub fn match_target_event(mut self, event_id: EventId) -> Self { self.endpoint.event_id = Some(event_id); self } @@ -4209,7 +4206,7 @@ pub struct LoginResponseTemplate200 { /// Required: ID of the logged-in device. Will be the same as the /// corresponding parameter in the request, if one was specified. - device_id: Option, + device_id: Option, /// The lifetime of the access token, in milliseconds. Once the access token /// has expired a new access token can be obtained by using the provided @@ -4223,7 +4220,7 @@ pub struct LoginResponseTemplate200 { refresh_token: Option, /// Required: The fully-qualified Matrix ID for the account. - user_id: Option, + user_id: Option, /// Optional client configuration provided by the server. well_known: Option, @@ -4231,7 +4228,7 @@ pub struct LoginResponseTemplate200 { impl LoginResponseTemplate200 { /// Constructor for empty response - pub fn new, T2: Into>( + pub fn new, T2: Into>( access_token: &str, device_id: T1, user_id: T2, @@ -4412,7 +4409,7 @@ impl<'a> MockEndpoint<'a, AuthedMediaThumbnailEndpoint> { /// A prebuilt mock for `GET /client/v3/rooms/{room_id}/join` requests. pub struct JoinRoomEndpoint { - room_id: OwnedRoomId, + room_id: RoomId, } impl<'a> MockEndpoint<'a, JoinRoomEndpoint> { @@ -4429,20 +4426,20 @@ impl<'a> MockEndpoint<'a, JoinRoomEndpoint> { #[derive(Default)] struct ThreadSubscriptionMatchers { /// Optional room id to match in the query. - room_id: Option, + room_id: Option, /// Optional thread root event id to match in the query. - thread_root: Option, + thread_root: Option, } impl ThreadSubscriptionMatchers { /// Match the request parameter against a specific room id. - fn match_room_id(mut self, room_id: OwnedRoomId) -> Self { + fn match_room_id(mut self, room_id: RoomId) -> Self { self.room_id = Some(room_id); self } /// Match the request parameter against a specific thread root event id. - fn match_thread_id(mut self, thread_root: OwnedEventId) -> Self { + fn match_thread_id(mut self, thread_root: EventId) -> Self { self.thread_root = Some(thread_root); self } @@ -4452,8 +4449,8 @@ impl ThreadSubscriptionMatchers { if self.room_id.is_some() || self.thread_root.is_some() { format!( "^/_matrix/client/unstable/io.element.msc4306/rooms/{}/thread/{}/subscription$", - self.room_id.as_deref().map(|s| s.as_str()).unwrap_or(".*"), - self.thread_root.as_deref().map(|s| s.as_str()).unwrap_or(".*").replace("$", "\\$") + self.room_id.as_ref().map(|s| s.as_str()).unwrap_or(".*"), + self.thread_root.as_ref().map(|s| s.as_str()).unwrap_or(".*").replace("$", "\\$") ) } else { "^/_matrix/client/unstable/io.element.msc4306/rooms/.*/thread/.*/subscription$" @@ -4479,12 +4476,12 @@ impl<'a> MockEndpoint<'a, RoomGetThreadSubscriptionEndpoint> { } /// Match the request parameter against a specific room id. - pub fn match_room_id(mut self, room_id: OwnedRoomId) -> Self { + pub fn match_room_id(mut self, room_id: RoomId) -> Self { self.endpoint.matchers = self.endpoint.matchers.match_room_id(room_id); self } /// Match the request parameter against a specific thread root event id. - pub fn match_thread_id(mut self, thread_root: OwnedEventId) -> Self { + pub fn match_thread_id(mut self, thread_root: EventId) -> Self { self.endpoint.matchers = self.endpoint.matchers.match_thread_id(thread_root); self } @@ -4517,12 +4514,12 @@ impl<'a> MockEndpoint<'a, RoomPutThreadSubscriptionEndpoint> { } /// Match the request parameter against a specific room id. - pub fn match_room_id(mut self, room_id: OwnedRoomId) -> Self { + pub fn match_room_id(mut self, room_id: RoomId) -> Self { self.endpoint.matchers = self.endpoint.matchers.match_room_id(room_id); self } /// Match the request parameter against a specific thread root event id. - pub fn match_thread_id(mut self, thread_root: OwnedEventId) -> Self { + pub fn match_thread_id(mut self, thread_root: EventId) -> Self { self.endpoint.matchers = self.endpoint.matchers.match_thread_id(thread_root); self } @@ -4551,12 +4548,12 @@ impl<'a> MockEndpoint<'a, RoomDeleteThreadSubscriptionEndpoint> { } /// Match the request parameter against a specific room id. - pub fn match_room_id(mut self, room_id: OwnedRoomId) -> Self { + pub fn match_room_id(mut self, room_id: RoomId) -> Self { self.endpoint.matchers = self.endpoint.matchers.match_room_id(room_id); self } /// Match the request parameter against a specific thread root event id. - pub fn match_thread_id(mut self, thread_root: OwnedEventId) -> Self { + pub fn match_thread_id(mut self, thread_root: EventId) -> Self { self.endpoint.matchers = self.endpoint.matchers.match_thread_id(thread_root); self } @@ -4632,9 +4629,9 @@ impl<'a> MockEndpoint<'a, FederationVersionEndpoint> { #[derive(Default)] pub struct GetThreadSubscriptionsEndpoint { /// New thread subscriptions per (room id, thread root event id). - subscribed: BTreeMap>, + subscribed: BTreeMap>, /// New thread unsubscriptions per (room id, thread root event id). - unsubscribed: BTreeMap>, + unsubscribed: BTreeMap>, /// Optional delay to respond to the query. delay: Option, } @@ -4643,8 +4640,8 @@ impl<'a> MockEndpoint<'a, GetThreadSubscriptionsEndpoint> { /// Add a single thread subscription to the response. pub fn add_subscription( mut self, - room_id: OwnedRoomId, - thread_root: OwnedEventId, + room_id: RoomId, + thread_root: EventId, subscription: ThreadSubscription, ) -> Self { self.endpoint.subscribed.entry(room_id).or_default().insert(thread_root, subscription); @@ -4654,8 +4651,8 @@ impl<'a> MockEndpoint<'a, GetThreadSubscriptionsEndpoint> { /// Add a single thread unsubscription to the response. pub fn add_unsubscription( mut self, - room_id: OwnedRoomId, - thread_root: OwnedEventId, + room_id: RoomId, + thread_root: EventId, unsubscription: ThreadUnsubscription, ) -> Self { self.endpoint.unsubscribed.entry(room_id).or_default().insert(thread_root, unsubscription); @@ -4774,7 +4771,7 @@ pub struct SetSpaceChildEndpoint; impl<'a> MockEndpoint<'a, SetSpaceChildEndpoint> { /// Returns a successful response with a given event id. - pub fn ok(self, event_id: OwnedEventId) -> MatrixMock<'a> { + pub fn ok(self, event_id: EventId) -> MatrixMock<'a> { self.ok_with_event_id(event_id) } @@ -4791,7 +4788,7 @@ pub struct SetSpaceParentEndpoint; impl<'a> MockEndpoint<'a, SetSpaceParentEndpoint> { /// Returns a successful response with a given event id. - pub fn ok(self, event_id: OwnedEventId) -> MatrixMock<'a> { + pub fn ok(self, event_id: EventId) -> MatrixMock<'a> { self.ok_with_event_id(event_id) } diff --git a/crates/matrix-sdk/src/test_utils/mod.rs b/crates/matrix-sdk/src/test_utils/mod.rs index 9eae44e22fd..def21f277f6 100644 --- a/crates/matrix-sdk/src/test_utils/mod.rs +++ b/crates/matrix-sdk/src/test_utils/mod.rs @@ -268,8 +268,8 @@ macro_rules! assert_next_eq_with_timeout { /// ```no_run /// # async { /// # let client: matrix_sdk::Client = unreachable!(); -/// # let room_id: ruma::OwnedRoomId = unreachable!(); -/// # let event_id: ruma::OwnedEventId = unreachable!(); +/// # let room_id: ruma::RoomId = unreachable!(); +/// # let event_id: ruma::EventId = unreachable!(); /// use matrix_sdk::assert_decrypted_message_eq; /// /// let room = @@ -319,8 +319,8 @@ macro_rules! assert_decrypted_message_eq { /// ```no_run /// # async { /// # let client: matrix_sdk::Client = unreachable!(); -/// # let room_id: ruma::OwnedRoomId = unreachable!(); -/// # let event_id: ruma::OwnedEventId = unreachable!(); +/// # let room_id: ruma::RoomId = unreachable!(); +/// # let event_id: ruma::EventId = unreachable!(); /// use matrix_sdk::assert_let_decrypted_state_event_content; /// /// let room = diff --git a/crates/matrix-sdk/src/widget/machine/driver_req.rs b/crates/matrix-sdk/src/widget/machine/driver_req.rs index 1a419e467f8..f5fadeaabfc 100644 --- a/crates/matrix-sdk/src/widget/machine/driver_req.rs +++ b/crates/matrix-sdk/src/widget/machine/driver_req.rs @@ -17,7 +17,7 @@ use std::{collections::BTreeMap, marker::PhantomData}; use ruma::{ - OwnedUserId, + UserId, api::client::{account::request_openid_token, delayed_events::update_delayed_event}, events::{AnyStateEvent, AnyTimelineEvent, AnyToDeviceEventContent}, serde::Raw, @@ -297,7 +297,7 @@ pub(crate) struct SendToDeviceRequest { /// They are organized in a map of user ID -> device ID -> content like the /// cs api request. pub(crate) messages: - BTreeMap>>, + BTreeMap>>, } impl From for MatrixDriverRequestData { diff --git a/crates/matrix-sdk/src/widget/machine/from_widget.rs b/crates/matrix-sdk/src/widget/machine/from_widget.rs index 86b1d061307..4da2948c646 100644 --- a/crates/matrix-sdk/src/widget/machine/from_widget.rs +++ b/crates/matrix-sdk/src/widget/machine/from_widget.rs @@ -16,7 +16,7 @@ use std::collections::BTreeMap; use as_variant::as_variant; use ruma::{ - OwnedEventId, OwnedRoomId, + EventId, RoomId, api::client::{ delayed_events::{delayed_message_event, delayed_state_event, update_delayed_event}, error::{ErrorBody, StandardErrorBody}, @@ -210,20 +210,20 @@ pub(super) struct ReadEventsResponse { #[derive(Serialize, Debug)] pub(crate) struct SendEventResponse { /// The room id for the send event. - pub(crate) room_id: Option, + pub(crate) room_id: Option, /// The event id of the send event. It's optional because if it's a delayed /// event, it does not get the event_id at this point. - pub(crate) event_id: Option, + pub(crate) event_id: Option, /// The `delay_id` generated for this delayed event. Used to interact with /// the delayed event. pub(crate) delay_id: Option, } impl SendEventResponse { - pub(crate) fn from_event_id(event_id: OwnedEventId) -> Self { + pub(crate) fn from_event_id(event_id: EventId) -> Self { SendEventResponse { room_id: None, event_id: Some(event_id), delay_id: None } } - pub(crate) fn set_room_id(&mut self, room_id: OwnedRoomId) { + pub(crate) fn set_room_id(&mut self, room_id: RoomId) { self.room_id = Some(room_id); } } diff --git a/crates/matrix-sdk/src/widget/machine/mod.rs b/crates/matrix-sdk/src/widget/machine/mod.rs index 694d291b328..9c31fd7a906 100644 --- a/crates/matrix-sdk/src/widget/machine/mod.rs +++ b/crates/matrix-sdk/src/widget/machine/mod.rs @@ -20,7 +20,7 @@ use driver_req::{ReadStateRequest, UpdateDelayedEventRequest}; use from_widget::UpdateDelayedEventResponse; use indexmap::IndexMap; use ruma::{ - OwnedRoomId, + RoomId, events::{AnyStateEvent, AnyTimelineEvent}, serde::{JsonObject, Raw}, }; @@ -131,7 +131,7 @@ pub(crate) struct WidgetMachine { widget_id: String, /// The room to which this widget machine is attached. - room_id: OwnedRoomId, + room_id: RoomId, /// Outstanding requests sent to the widget (mapped by uuid). pending_to_widget_requests: PendingRequests, @@ -161,7 +161,7 @@ impl WidgetMachine { /// actions (commands) from the client. pub(crate) fn new( widget_id: String, - room_id: OwnedRoomId, + room_id: RoomId, init_on_content_load: bool, ) -> (Self, Vec) { let limits = diff --git a/crates/matrix-sdk/src/widget/machine/openid.rs b/crates/matrix-sdk/src/widget/machine/openid.rs index b17cd39e7b9..3d5e8d2ed1d 100644 --- a/crates/matrix-sdk/src/widget/machine/openid.rs +++ b/crates/matrix-sdk/src/widget/machine/openid.rs @@ -14,9 +14,7 @@ use std::time::Duration; -use ruma::{ - OwnedServerName, api::client::account::request_openid_token, authentication::TokenType, -}; +use ruma::{ServerName, api::client::account::request_openid_token, authentication::TokenType}; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Deserialize, Serialize)] @@ -25,7 +23,7 @@ pub(crate) struct OpenIdState { pub(crate) access_token: String, #[serde(with = "ruma::serde::duration::secs")] pub(crate) expires_in: Duration, - pub(crate) matrix_server_name: OwnedServerName, + pub(crate) matrix_server_name: ServerName, pub(crate) token_type: TokenType, } diff --git a/crates/matrix-sdk/src/widget/matrix.rs b/crates/matrix-sdk/src/widget/matrix.rs index c96db388ba2..14e6982610d 100644 --- a/crates/matrix-sdk/src/widget/matrix.rs +++ b/crates/matrix-sdk/src/widget/matrix.rs @@ -24,7 +24,7 @@ use matrix_sdk_base::{ sync::State, }; use ruma::{ - EventId, OwnedDeviceId, OwnedUserId, RoomId, TransactionId, + DeviceId, EventId, RoomId, TransactionId, UserId, api::client::{ account::request_openid_token::v3::{Request as OpenIdRequest, Response as OpenIdResponse}, delayed_events::{self, update_delayed_event::unstable::UpdateAction}, @@ -353,10 +353,7 @@ impl MatrixDriver { pub(crate) async fn send_to_device( &self, event_type: ToDeviceEventType, - messages: BTreeMap< - OwnedUserId, - BTreeMap>, - >, + messages: BTreeMap>>, ) -> Result { // TODO: block this at the negotiation stage, no reason to let widget believe // they can do that @@ -368,7 +365,7 @@ impl MatrixDriver { let client = self.room.client(); - let mut failures: BTreeMap> = BTreeMap::new(); + let mut failures: BTreeMap> = BTreeMap::new(); let room_encrypted = self .room @@ -387,7 +384,7 @@ impl MatrixDriver { // map]. let mut content_to_recipients_map: BTreeMap< &str, - BTreeMap>, + BTreeMap>, > = BTreeMap::new(); for (user_id, device_map) in messages.iter() { @@ -434,8 +431,8 @@ impl MatrixDriver { &self, event_type: &ToDeviceEventType, content: &str, - user_to_list_of_device_id_or_all: BTreeMap>, - failures: &mut BTreeMap>, + user_to_list_of_device_id_or_all: BTreeMap>, + failures: &mut BTreeMap>, ) -> Result<()> { let client = self.room.client(); let mut recipient_devices = Vec::<_>::new(); diff --git a/crates/matrix-sdk/src/widget/settings/element_call.rs b/crates/matrix-sdk/src/widget/settings/element_call.rs index 6afa9fc7ba8..bf6dd0add70 100644 --- a/crates/matrix-sdk/src/widget/settings/element_call.rs +++ b/crates/matrix-sdk/src/widget/settings/element_call.rs @@ -528,9 +528,9 @@ mod tests { settings ._generate_webview_url( profile, - "@test:user.org".try_into().unwrap(), - "!room_id:room.org".try_into().unwrap(), - "ABCDEFG".into(), + &"@test:user.org".try_into().unwrap(), + &"!room_id:room.org".try_into().unwrap(), + &"ABCDEFG".into(), "https://client-matrix.server.org".try_into().unwrap(), ClientProperties::new( "io.my_matrix.client", diff --git a/crates/matrix-sdk/src/widget/settings/mod.rs b/crates/matrix-sdk/src/widget/settings/mod.rs index 709820a671d..9a4f82befe8 100644 --- a/crates/matrix-sdk/src/widget/settings/mod.rs +++ b/crates/matrix-sdk/src/widget/settings/mod.rs @@ -95,12 +95,16 @@ impl WidgetSettings { room: &Room, props: ClientProperties, ) -> Result { + let client = room.client(); + let device_id = + if let Some(device_id) = client.device_id() { device_id } else { &"UNKNOWN".into() }; + self._generate_webview_url( - room.client().account().fetch_user_profile().await.unwrap_or_default(), + client.account().fetch_user_profile().await.unwrap_or_default(), room.own_user_id(), room.room_id(), - room.client().device_id().unwrap_or("UNKNOWN".into()), - room.client().homeserver(), + device_id, + client.homeserver(), props, ) } diff --git a/crates/matrix-sdk/tests/integration/account.rs b/crates/matrix-sdk/tests/integration/account.rs index 9a11510bb8c..c65c83a5a68 100644 --- a/crates/matrix-sdk/tests/integration/account.rs +++ b/crates/matrix-sdk/tests/integration/account.rs @@ -296,12 +296,12 @@ async fn test_get_cached_avatar_url() { .await; let res_avatar_url = account.get_avatar_url().await.unwrap(); - assert_eq!(res_avatar_url.as_deref(), Some(avatar_url)); + assert_eq!(res_avatar_url.as_ref(), Some(avatar_url)); } // The cache was filled. let res_avatar_url = account.get_cached_avatar_url().await.unwrap(); - assert_eq!(res_avatar_url.as_deref(), Some(avatar_url)); + assert_eq!(res_avatar_url.as_ref(), Some(avatar_url)); // Fetch it again from the homeserver, a missing value should empty the cache. { diff --git a/crates/matrix-sdk/tests/integration/client.rs b/crates/matrix-sdk/tests/integration/client.rs index fa88783e392..4cc8a2830cc 100644 --- a/crates/matrix-sdk/tests/integration/client.rs +++ b/crates/matrix-sdk/tests/integration/client.rs @@ -29,7 +29,7 @@ use matrix_sdk_test::{ }, }; use ruma::{ - EventId, Int, OwnedUserId, RoomId, RoomVersionId, + EventId, Int, RoomId, RoomVersionId, UserId, api::client::{ directory::{ get_public_rooms, @@ -46,7 +46,7 @@ use ruma::{ event_id, events::{ AnyInitialStateEvent, AnyRoomAccountDataEvent, - direct::{DirectEventContent, OwnedDirectUserIdentifier}, + direct::{DirectEventContent, DirectUserIdentifier}, room::{ encrypted::OriginalSyncRoomEncryptedEvent, history_visibility::HistoryVisibility, member::MembershipState, @@ -234,7 +234,7 @@ async fn test_join_room_by_id_or_alias() { // field client .join_room_by_id_or_alias( - (&**DEFAULT_TEST_ROOM_ID).into(), + &(*DEFAULT_TEST_ROOM_ID).into(), &["server.com".try_into().unwrap()] ) .await @@ -544,7 +544,7 @@ async fn test_marking_room_as_dm() { ); let bob_entry = content - .get(&OwnedDirectUserIdentifier::from(bob.to_owned())) + .get(&DirectUserIdentifier::from(bob.to_owned())) .expect("We should have bob in the direct event content"); assert_eq!(content.len(), 2, "We should have entries for bob and foo"); @@ -789,7 +789,7 @@ async fn test_encrypt_room_event() { .await; room.send_raw("m.room.message", json!({"body": "Hello", "msgtype": "m.text"})) - .with_transaction_id("foobar".into()) + .with_transaction_id(&"foobar".into()) .await .expect("We should be able to send a message to the encrypted room"); @@ -866,7 +866,7 @@ async fn test_create_dm_non_encrypted() { // The body's `invite` field is set to an array with the user ID. if !body - .get_field::>("invite") + .get_field::>("invite") .is_ok_and(|v| v.as_deref() == Some(&[user_id.to_owned()])) { return false; @@ -915,7 +915,7 @@ async fn test_create_dm_encrypted() { // The body's `invite` field is set to an array with the user ID. if !body - .get_field::>("invite") + .get_field::>("invite") .is_ok_and(|v| v.as_deref() == Some(&[user_id.to_owned()])) { return false; @@ -1058,7 +1058,7 @@ async fn test_test_ambiguity_changes() { let example_2_change = changes.get(example_2_rename_1_event_id).unwrap(); assert_eq!(example_2_change.member_id, example_2_id); assert!(example_2_change.member_ambiguous); - assert_eq!(example_2_change.ambiguated_member.as_deref(), Some(example_id)); + assert_eq!(example_2_change.ambiguated_member.as_ref(), Some(example_id)); assert_eq!(example_2_change.disambiguated_member, None); // Second joined member only adds itself as ambiguous. @@ -1080,7 +1080,7 @@ async fn test_test_ambiguity_changes() { let example_2_change = changes.get(example_2_rename_1_event_id).unwrap(); assert_eq!(example_2_change.member_id, example_2_id); assert!(example_2_change.member_ambiguous); - assert_eq!(example_2_change.ambiguated_member.as_deref(), Some(example_id)); + assert_eq!(example_2_change.ambiguated_member.as_ref(), Some(example_id)); assert_eq!(example_2_change.disambiguated_member, None); let example_3_change = changes.get(example_3_join_event_id).unwrap(); @@ -1165,8 +1165,8 @@ async fn test_test_ambiguity_changes() { let example_3_change = changes.get(example_3_rename_event_id).unwrap(); assert_eq!(example_3_change.member_id, example_3_id); assert!(example_3_change.member_ambiguous); - assert_eq!(example_3_change.ambiguated_member.as_deref(), Some(example_2_id)); - assert_eq!(example_3_change.disambiguated_member.as_deref(), Some(example_id)); + assert_eq!(example_3_change.ambiguated_member.as_ref(), Some(example_2_id)); + assert_eq!(example_3_change.disambiguated_member.as_ref(), Some(example_id)); let example = room.get_member_no_sync(example_id).await.unwrap().unwrap(); assert!(!example.name_ambiguous()); @@ -1180,8 +1180,8 @@ async fn test_test_ambiguity_changes() { let example_3_change = changes.get(example_3_rename_event_id).unwrap(); assert_eq!(example_3_change.member_id, example_3_id); assert!(example_3_change.member_ambiguous); - assert_eq!(example_3_change.ambiguated_member.as_deref(), Some(example_2_id)); - assert_eq!(example_3_change.disambiguated_member.as_deref(), Some(example_id)); + assert_eq!(example_3_change.ambiguated_member.as_ref(), Some(example_2_id)); + assert_eq!(example_3_change.disambiguated_member.as_ref(), Some(example_id)); // Rename example, still using a unique name. let example_rename_event_id = event_id!("$example_rename"); diff --git a/crates/matrix-sdk/tests/integration/encryption/verification.rs b/crates/matrix-sdk/tests/integration/encryption/verification.rs index 145ae8e882a..ee19f6c6c1b 100644 --- a/crates/matrix-sdk/tests/integration/encryption/verification.rs +++ b/crates/matrix-sdk/tests/integration/encryption/verification.rs @@ -181,7 +181,7 @@ async fn test_unchecked_mutual_verification() { { let alice_olm = alice.olm_machine_for_testing().await; let alice_olm = alice_olm.as_ref().unwrap(); - alice_olm.update_tracked_users([bob_user_id.as_ref()]).await.unwrap(); + alice_olm.update_tracked_users([&bob_user_id]).await.unwrap(); } // Run a sync so we do send outgoing requests, including the /keys/query for diff --git a/crates/matrix-sdk/tests/integration/event_cache/threads.rs b/crates/matrix-sdk/tests/integration/event_cache/threads.rs index e0d5bd09844..a0729abc2f1 100644 --- a/crates/matrix-sdk/tests/integration/event_cache/threads.rs +++ b/crates/matrix-sdk/tests/integration/event_cache/threads.rs @@ -15,7 +15,7 @@ use matrix_sdk::{ }; use matrix_sdk_test::{ALICE, JoinedRoomBuilder, async_test, event_factory::EventFactory}; use ruma::{ - OwnedEventId, OwnedRoomId, event_id, + EventId, RoomId, event_id, events::{AnySyncTimelineEvent, Mentions}, push::{ConditionalPushRule, Ruleset}, room_id, @@ -91,7 +91,7 @@ async fn test_thread_can_paginate_even_if_seen_sync_event() { // Sanity check: the sync event is added to the thread. let mut thread_events = wait_for_initial_events(thread_events, &mut thread_stream).await; assert_eq!(thread_events.len(), 1); - assert_eq!(thread_events.remove(0).event_id().as_deref(), Some(thread_resp_id)); + assert_eq!(thread_events.remove(0).event_id().as_ref(), Some(thread_resp_id)); // It's possible to paginate the thread, and this will push the thread root // because there's no prev-batch token. @@ -121,7 +121,7 @@ async fn test_thread_can_paginate_even_if_seen_sync_event() { assert_let_timeout!(Ok(TimelineVectorDiffs { diffs, .. }) = thread_stream.recv()); assert_eq!(diffs.len(), 1); assert_let!(VectorDiff::Insert { index: 0, value } = &diffs[0]); - assert_eq!(value.event_id().as_deref(), Some(thread_root_id)); + assert_eq!(value.event_id().as_ref(), Some(thread_root_id)); } #[async_test] @@ -458,12 +458,12 @@ struct ThreadSubscriptionTestSetup { server: MatrixMockServer, client: Client, factory: EventFactory, - room_id: OwnedRoomId, + room_id: RoomId, subscriber: RoomEventCacheSubscriber, /// 3 events: 1 non-mention, 1 mention, and another non-mention. events: Vec>, - mention_event_id: OwnedEventId, - thread_root: OwnedEventId, + mention_event_id: EventId, + thread_root: EventId, } /// Create a new setup for a thread subscription test, with enough data so that @@ -663,7 +663,7 @@ async fn test_auto_subscribe_on_thread_paginate() { // Sanity check: the sync event is added to the thread. let mut thread_events = wait_for_initial_events(thread_events, &mut thread_stream).await; assert_eq!(thread_events.len(), 1); - assert_eq!(thread_events.remove(0).event_id().as_deref(), Some(thread_resp_id)); + assert_eq!(thread_events.remove(0).event_id().as_ref(), Some(thread_resp_id)); assert!(thread_subscriber_updates.is_empty()); @@ -748,7 +748,7 @@ async fn test_auto_subscribe_on_thread_paginate_root_event() { // Sanity check: the sync event is added to the thread. let mut thread_events = wait_for_initial_events(thread_events, &mut thread_stream).await; assert_eq!(thread_events.len(), 1); - assert_eq!(thread_events.remove(0).event_id().as_deref(), Some(thread_resp_id)); + assert_eq!(thread_events.remove(0).event_id().as_ref(), Some(thread_resp_id)); assert!(thread_subscriber_updates.is_empty()); @@ -811,8 +811,8 @@ async fn test_redact_touches_threads() { event_cache.subscribe().unwrap(); let thread_root_id = s.thread_root; - let thread_resp1 = s.events[0].get_field::("event_id").unwrap().unwrap(); - let thread_resp2 = s.events[1].get_field::("event_id").unwrap().unwrap(); + let thread_resp1 = s.events[0].get_field::("event_id").unwrap().unwrap(); + let thread_resp2 = s.events[1].get_field::("event_id").unwrap().unwrap(); let room = s.server.sync_joined_room(&s.client, &s.room_id).await; @@ -889,7 +889,7 @@ async fn test_redact_touches_threads() { // The redaction event is appended to the room cache. assert_let!(VectorDiff::Append { values: new_events } = &diffs[0]); assert_eq!(new_events.len(), 1); - assert_eq!(new_events[0].event_id().as_deref(), Some(thread_resp1_redaction)); + assert_eq!(new_events[0].event_id().as_ref(), Some(thread_resp1_redaction)); // The room event is redacted. { @@ -946,7 +946,7 @@ async fn test_redact_touches_threads() { // The redaction event is appended to the room cache. assert_let!(VectorDiff::Append { values: new_events } = &diffs[0]); assert_eq!(new_events.len(), 1); - assert_eq!(new_events[0].event_id().as_deref(), Some(thread_resp2_redaction)); + assert_eq!(new_events[0].event_id().as_ref(), Some(thread_resp2_redaction)); // The room event is redacted. { diff --git a/crates/matrix-sdk/tests/integration/latest_event.rs b/crates/matrix-sdk/tests/integration/latest_event.rs index 57336793eec..548841fd8e0 100644 --- a/crates/matrix-sdk/tests/integration/latest_event.rs +++ b/crates/matrix-sdk/tests/integration/latest_event.rs @@ -61,7 +61,7 @@ async fn test_latest_event_is_recomputed_when_a_user_is_ignored() { assert_matches!( latest_event_stream.next_now().await, LatestEventValue::Remote(event) => { - assert_eq!(event.event_id().as_deref(), Some(event_bob)); + assert_eq!(event.event_id().as_ref(), Some(event_bob)); } ); diff --git a/crates/matrix-sdk/tests/integration/matrix_auth.rs b/crates/matrix-sdk/tests/integration/matrix_auth.rs index dd93264712d..4420da6bc0b 100644 --- a/crates/matrix-sdk/tests/integration/matrix_auth.rs +++ b/crates/matrix-sdk/tests/integration/matrix_auth.rs @@ -10,7 +10,7 @@ use matrix_sdk::{ use matrix_sdk_base::SessionMeta; use matrix_sdk_test::{async_test, test_json}; use ruma::{ - OwnedUserId, + UserId, api::{ MatrixVersion, client::{ @@ -434,7 +434,7 @@ async fn test_login_with_cross_signing_bootstrapping() { .respond_with(|req: &Request| { #[derive(Debug, serde::Deserialize)] #[serde(transparent)] - struct Parameters(BTreeMap); + struct Parameters(BTreeMap); let params: Parameters = req.body_json().unwrap(); assert!(params.0.contains_key(user_id!("@alice:example.org"))); diff --git a/crates/matrix-sdk/tests/integration/notification.rs b/crates/matrix-sdk/tests/integration/notification.rs index b90576e7f1f..499b32e397c 100644 --- a/crates/matrix-sdk/tests/integration/notification.rs +++ b/crates/matrix-sdk/tests/integration/notification.rs @@ -11,7 +11,7 @@ use matrix_sdk_test::{ event_factory::EventFactory, stripped_state_event, sync_state_event, }; use ruma::{ - Int, OwnedRoomId, event_id, + Int, RoomId, event_id, events::{AnyStrippedStateEvent, StateEventType}, owned_user_id, room_id, serde::Raw, @@ -29,7 +29,7 @@ async fn test_notifications_joined() { let room_id = room_id!("!joined_room:localhost"); let user_id = client.user_id().unwrap(); - let (sender, receiver) = mpsc::channel::<(OwnedRoomId, Notification)>(10); + let (sender, receiver) = mpsc::channel::<(RoomId, Notification)>(10); let mut receiver_stream = ReceiverStream::new(receiver); client @@ -110,7 +110,7 @@ async fn test_notifications_invite() { let room_id = room_id!("!invited_room:localhost"); let user_id = client.user_id().unwrap(); - let (sender, receiver) = mpsc::channel::<(OwnedRoomId, Notification)>(10); + let (sender, receiver) = mpsc::channel::<(RoomId, Notification)>(10); let mut receiver_stream = ReceiverStream::new(receiver); client diff --git a/crates/matrix-sdk/tests/integration/room/beacon/mod.rs b/crates/matrix-sdk/tests/integration/room/beacon/mod.rs index 1aec44a55ce..ad084bb0688 100644 --- a/crates/matrix-sdk/tests/integration/room/beacon/mod.rs +++ b/crates/matrix-sdk/tests/integration/room/beacon/mod.rs @@ -245,7 +245,7 @@ async fn test_most_recent_event_in_stream() { nth, Some(MilliSecondsSinceUnixEpoch(1_636_829_458u32.into())), ) - .event_id(<&EventId>::try_from(event_id.as_str()).unwrap()) + .event_id(&EventId::try_from(event_id).unwrap()) .server_ts(1_636_829_458) .sender(user_id!("@example2:localhost")) .age(598971) diff --git a/crates/matrix-sdk/tests/integration/room/calls.rs b/crates/matrix-sdk/tests/integration/room/calls.rs index af2c4512c65..a2d277791ac 100644 --- a/crates/matrix-sdk/tests/integration/room/calls.rs +++ b/crates/matrix-sdk/tests/integration/room/calls.rs @@ -3,9 +3,7 @@ use std::sync::{Arc, Mutex}; use assert_matches2::assert_matches; use matrix_sdk::{room::calls::CallError, test_utils::mocks::MatrixMockServer}; use matrix_sdk_test::{JoinedRoomBuilder, async_test, event_factory::EventFactory}; -use ruma::{ - OwnedUserId, events::rtc::notification::NotificationType, owned_event_id, room_id, user_id, -}; +use ruma::{UserId, events::rtc::notification::NotificationType, owned_event_id, room_id, user_id}; use tokio::spawn; #[async_test] @@ -13,7 +11,7 @@ async fn test_subscribe_to_decline_call_events() { let server = MatrixMockServer::new().await; let client = server.client_builder().build().await; - let decliners_sequences: Arc>> = Arc::new(Mutex::new(Vec::new())); + let decliners_sequences: Arc>> = Arc::new(Mutex::new(Vec::new())); let asserted_decliners = vec![user_id!("@bob:matrix.org"), user_id!("@carl:example.com")]; let room_id = room_id!("!test:example.org"); diff --git a/crates/matrix-sdk/tests/integration/room/common.rs b/crates/matrix-sdk/tests/integration/room/common.rs index aa56376a44b..cd01583ed25 100644 --- a/crates/matrix-sdk/tests/integration/room/common.rs +++ b/crates/matrix-sdk/tests/integration/room/common.rs @@ -807,7 +807,7 @@ async fn test_is_direct() { // The room is direct now. let direct_targets = room.direct_targets(); assert_eq!(direct_targets.len(), 1); - assert!(direct_targets.contains(<&DirectUserIdentifier>::from(*BOB))); + assert!(direct_targets.contains(&DirectUserIdentifier::from(*BOB))); assert!(room.is_direct().await.unwrap()); // Unset the room as direct. @@ -866,7 +866,7 @@ async fn test_room_avatar() { client.sync_once(SyncSettings::default().token(SyncToken::NoToken)).await.unwrap(); server.reset().await; - assert_eq!(room.avatar_url().as_deref(), Some(avatar_url_1)); + assert_eq!(room.avatar_url().as_ref(), Some(avatar_url_1)); assert_matches!(room.avatar_info(), None); // Set the avatar and the info. @@ -885,7 +885,7 @@ async fn test_room_avatar() { client.sync_once(SyncSettings::default().token(SyncToken::NoToken)).await.unwrap(); server.reset().await; - assert_eq!(room.avatar_url().as_deref(), Some(avatar_url_2)); + assert_eq!(room.avatar_url().as_ref(), Some(avatar_url_2)); let avatar_info = room.avatar_info().unwrap(); assert_eq!(avatar_info.height, Some(uint!(200))); assert_eq!(avatar_info.width, Some(uint!(200))); diff --git a/crates/matrix-sdk/tests/integration/room/joined.rs b/crates/matrix-sdk/tests/integration/room/joined.rs index 50d8b84b0ad..6737c3477ec 100644 --- a/crates/matrix-sdk/tests/integration/room/joined.rs +++ b/crates/matrix-sdk/tests/integration/room/joined.rs @@ -22,7 +22,7 @@ use matrix_sdk_test::{ test_json::{self, sync::CUSTOM_ROOM_POWER_LEVELS}, }; use ruma::{ - OwnedUserId, RoomVersionId, TransactionId, + RoomVersionId, TransactionId, UserId, api::client::{ membership::Invite3pidInit, receipt::create_receipt::v3::ReceiptType, room::upgrade_room::v3::Request as UpgradeRoomRequest, @@ -840,7 +840,7 @@ async fn test_subscribe_to_typing_notifications() { let server = MatrixMockServer::new().await; let client = server.client_builder().build().await; - let typing_sequences: Arc>>> = Arc::new(Mutex::new(Vec::new())); + let typing_sequences: Arc>>> = Arc::new(Mutex::new(Vec::new())); // The expected typing sequences that we will receive, note that the current // user_id is filtered out. let asserted_typing_sequences = @@ -1012,7 +1012,7 @@ async fn test_is_direct_invite_by_3pid() { let room = client.get_room(&DEFAULT_TEST_ROOM_ID).unwrap(); assert!(room.is_direct().await.unwrap()); - assert!(room.direct_targets().contains(<&DirectUserIdentifier>::from("invited@localhost.com"))); + assert!(room.direct_targets().contains(&DirectUserIdentifier::from("invited@localhost.com"))); } #[async_test] diff --git a/crates/matrix-sdk/tests/integration/room/left.rs b/crates/matrix-sdk/tests/integration/room/left.rs index 02faa287d8c..cf5875f6c40 100644 --- a/crates/matrix-sdk/tests/integration/room/left.rs +++ b/crates/matrix-sdk/tests/integration/room/left.rs @@ -8,7 +8,7 @@ use matrix_sdk_test::{ event_factory::EventFactory, test_json, }; use ruma::{ - OwnedRoomOrAliasId, + RoomOrAliasId, events::direct::{DirectEventContent, DirectUserIdentifier}, user_id, }; @@ -193,7 +193,7 @@ async fn test_forget_direct_room() { let room = client.get_room(&DEFAULT_TEST_ROOM_ID).unwrap(); assert_eq!(room.state(), RoomState::Left); assert!(room.is_direct().await.unwrap()); - assert!(room.direct_targets().contains(<&DirectUserIdentifier>::from(invited_user_id))); + assert!(room.direct_targets().contains(&DirectUserIdentifier::from(invited_user_id))); let direct_account_data = client .account() @@ -204,7 +204,7 @@ async fn test_forget_direct_room() { .deserialize() .expect("failed to deserialize m.direct account data"); assert_matches!( - direct_account_data.get(<&DirectUserIdentifier>::from(invited_user_id)), + direct_account_data.get(&DirectUserIdentifier::from(invited_user_id)), Some(invited_user_dms) ); assert_eq!(invited_user_dms, &[DEFAULT_TEST_ROOM_ID.to_owned()]); @@ -276,7 +276,7 @@ async fn test_knocking() { let room = client.get_room(&DEFAULT_TEST_ROOM_ID).unwrap(); assert_eq!(room.state(), RoomState::Left); - let room_id = OwnedRoomOrAliasId::from((*DEFAULT_TEST_ROOM_ID).to_owned()); + let room_id = RoomOrAliasId::from((*DEFAULT_TEST_ROOM_ID).to_owned()); let room = client.knock(room_id, None, Vec::new()).await.unwrap(); assert_eq!(room.state(), RoomState::Knocked); } diff --git a/crates/matrix-sdk/tests/integration/room_preview.rs b/crates/matrix-sdk/tests/integration/room_preview.rs index 8081d806048..713fcd700ed 100644 --- a/crates/matrix-sdk/tests/integration/room_preview.rs +++ b/crates/matrix-sdk/tests/integration/room_preview.rs @@ -47,7 +47,7 @@ async fn test_room_preview_leave_invited() { .await; mock_leave(room_id, &server).await; - let room_preview = client.get_room_preview(room_id.into(), Vec::new()).await.unwrap(); + let room_preview = client.get_room_preview(&room_id.into(), Vec::new()).await.unwrap(); assert_eq!(room_preview.state.unwrap(), RoomState::Invited); client.get_room(room_id).unwrap().leave().await.unwrap(); @@ -65,7 +65,7 @@ async fn test_room_preview_invite_leave_room_summary_msc3266_disabled() { // A preview should be built from the sync data above let preview = client - .get_room_preview(room_id.into(), Vec::new()) + .get_room_preview(&room_id.into(), Vec::new()) .await .expect("Room preview should be retrieved"); @@ -78,7 +78,7 @@ async fn test_room_preview_invite_leave_room_summary_msc3266_disabled() { assert_matches!(client.get_room(room_id).unwrap().state(), RoomState::Left); assert_matches!( - client.get_room_preview(room_id.into(), Vec::new()).await.unwrap().state.unwrap(), + client.get_room_preview(&room_id.into(), Vec::new()).await.unwrap().state.unwrap(), RoomState::Left ); } @@ -99,7 +99,7 @@ async fn test_room_preview_leave_knocked() { .await; mock_leave(room_id, &server).await; - let room_preview = client.get_room_preview(room_id.into(), Vec::new()).await.unwrap(); + let room_preview = client.get_room_preview(&room_id.into(), Vec::new()).await.unwrap(); assert_eq!(room_preview.state.unwrap(), RoomState::Knocked); let room = client.get_room(room_id).unwrap(); @@ -122,7 +122,7 @@ async fn test_room_preview_leave_joined() { mock_leave(room_id, &server).await; - let room_preview = client.get_room_preview(room_id.into(), Vec::new()).await.unwrap(); + let room_preview = client.get_room_preview(&room_id.into(), Vec::new()).await.unwrap(); assert_eq!(room_preview.state.unwrap(), RoomState::Joined); let room = client.get_room(room_id).unwrap(); @@ -138,7 +138,7 @@ async fn test_room_preview_leave_unknown_room_fails() { mock_unknown_summary(room_id, None, JoinRuleKind::Knock, None, &server).await; - let room_preview = client.get_room_preview(room_id.into(), Vec::new()).await.unwrap(); + let room_preview = client.get_room_preview(&room_id.into(), Vec::new()).await.unwrap(); assert!(room_preview.state.is_none()); assert!(client.get_room(room_id).is_none()); @@ -168,7 +168,7 @@ async fn test_room_preview_computes_name_if_room_is_known() { .expect("Failed to process sync"); // When we get its preview - let room_preview = client.get_room_preview(room_id.into(), Vec::new()).await.unwrap(); + let room_preview = client.get_room_preview(&room_id.into(), Vec::new()).await.unwrap(); // Its name is computed from its heroes assert_eq!(room_preview.name.unwrap(), "Alice"); diff --git a/crates/matrix-sdk/tests/integration/send_queue.rs b/crates/matrix-sdk/tests/integration/send_queue.rs index 36314981de6..20a530b3772 100644 --- a/crates/matrix-sdk/tests/integration/send_queue.rs +++ b/crates/matrix-sdk/tests/integration/send_queue.rs @@ -26,7 +26,7 @@ use matrix_sdk_test::{ #[cfg(feature = "unstable-msc4274")] use ruma::events::room::message::GalleryItemType; use ruma::{ - MxcUri, OwnedEventId, OwnedTransactionId, TransactionId, event_id, + EventId, MxcUri, TransactionId, event_id, events::{ AnyMessageLikeEventContent, Mentions, MessageLikeEventContent as _, poll::unstable_start::{ @@ -755,7 +755,7 @@ async fn test_reenabling_queue() { // They're sent, in the same order. for i in 1..=3 { - let event_id = OwnedEventId::try_from(format!("${i}").as_str()).unwrap(); + let event_id = EventId::try_from(format!("${i}").as_str()).unwrap(); assert_update!((global_watch, watch) => sent { event_id = event_id }); } @@ -2836,7 +2836,7 @@ async fn abort_and_verify( watch: &mut Receiver, img_content: ImageMessageEventContent, upload_handle: SendHandle, - upload_txn: OwnedTransactionId, + upload_txn: TransactionId, ) { let file_source = img_content.source; let info = img_content.info.unwrap(); @@ -3894,7 +3894,7 @@ async fn test_sending_event_still_saves_sync_gap() { assert_eq!(up.diffs.len(), 1); assert_let!(VectorDiff::Append { values } = &up.diffs[0]); assert_eq!(values.len(), 1); - assert_eq!(values[0].event_id().as_deref().unwrap(), event_id!("$msg_now")); + assert_eq!(values[0].event_id().as_ref().unwrap(), event_id!("$msg_now")); // Now, assume that a /sync response comes with only this message as part of the // response, and with a previous gap. This can happen under real-world @@ -3919,7 +3919,7 @@ async fn test_sending_event_still_saves_sync_gap() { assert_eq!(update.diffs.len(), 2); assert_let!(VectorDiff::Clear = &update.diffs[0]); assert_let!(VectorDiff::Append { values } = &update.diffs[1]); - assert_eq!(values[0].event_id().as_deref().unwrap(), event_id!("$msg_now")); + assert_eq!(values[0].event_id().as_ref().unwrap(), event_id!("$msg_now")); // When paginating with this previous batch token, we should get new events from // this room. @@ -3940,5 +3940,5 @@ async fn test_sending_event_still_saves_sync_gap() { assert_let_timeout!(Ok(RoomEventCacheUpdate::UpdateTimelineEvents(update)) = stream.recv()); assert_eq!(update.diffs.len(), 1); assert_let!(VectorDiff::Insert { index: 0, value: event } = &update.diffs[0]); - assert_eq!(event.event_id().as_deref().unwrap(), event_id!("$past_msg")); + assert_eq!(event.event_id().as_ref().unwrap(), event_id!("$past_msg")); } diff --git a/crates/matrix-sdk/tests/integration/sync.rs b/crates/matrix-sdk/tests/integration/sync.rs index 4361d4743b8..5d44df0fde4 100644 --- a/crates/matrix-sdk/tests/integration/sync.rs +++ b/crates/matrix-sdk/tests/integration/sync.rs @@ -217,7 +217,7 @@ async fn test_receive_room_avatar_event_via_sync() { .await; // The room info is set and the valid state event is in the store. - assert_eq!(room.avatar_url().as_deref(), Some(avatar_url)); + assert_eq!(room.avatar_url().as_ref(), Some(avatar_url)); assert_matches!( room.get_state_event_static::().await, Ok(Some(RawSyncOrStrippedState::Sync(raw_event))) @@ -229,7 +229,7 @@ async fn test_receive_room_avatar_event_via_sync() { let (raw_event, _) = assert_ready!(raw_event_subscriber); assert_eq!(raw_event.json().get(), valid_raw_event.json().get()); let (event, _) = assert_ready!(event_subscriber); - assert_eq!(event.as_original().unwrap().content.url.as_deref(), Some(avatar_url)); + assert_eq!(event.as_original().unwrap().content.url.as_ref(), Some(avatar_url)); // Now we receive an event with an invalid content but a valid type // and state key. @@ -1062,7 +1062,7 @@ async fn test_receive_room_canonical_alias_event_via_sync() { .await; // The room info is set and the valid state event is in the store. - assert_eq!(room.canonical_alias().as_deref(), Some(room_alias)); + assert_eq!(room.canonical_alias().as_ref(), Some(room_alias)); assert_matches!( room.get_state_event_static::().await, Ok(Some(RawSyncOrStrippedState::Sync(raw_event))) @@ -1074,7 +1074,7 @@ async fn test_receive_room_canonical_alias_event_via_sync() { let (raw_event, _) = assert_ready!(raw_event_subscriber); assert_eq!(raw_event.json().get(), valid_raw_event.json().get()); let (event, _) = assert_ready!(event_subscriber); - assert_eq!(event.as_original().unwrap().content.alias.as_deref(), Some(room_alias)); + assert_eq!(event.as_original().unwrap().content.alias.as_ref(), Some(room_alias)); // Now we receive an event with an invalid content but a valid type // and state key. @@ -1332,7 +1332,7 @@ async fn test_receive_room_tombstone_event_via_sync() { // The room info is set and the valid state event is in the store. assert_eq!( - room.tombstone_content().unwrap().replacement_room.as_deref(), + room.tombstone_content().unwrap().replacement_room.as_ref(), Some(tombstone_replacement) ); assert_matches!( diff --git a/crates/matrix-sdk/tests/integration/widget.rs b/crates/matrix-sdk/tests/integration/widget.rs index 938ab224895..3ee857736f2 100644 --- a/crates/matrix-sdk/tests/integration/widget.rs +++ b/crates/matrix-sdk/tests/integration/widget.rs @@ -37,7 +37,7 @@ use matrix_sdk_common::{ }; use matrix_sdk_test::{ALICE, BOB, JoinedRoomBuilder, async_test, event_factory::EventFactory}; use ruma::{ - OwnedRoomId, + RoomId, api::client::to_device::send_event_to_device::v3::Messages, device_id, event_id, events::{ @@ -68,7 +68,7 @@ macro_rules! json_string { type HandledDeviceEventMutex = Arc>, Option)>>; const WIDGET_ID: &str = "test-widget"; -static ROOM_ID: LazyLock = LazyLock::new(|| owned_room_id!("!a98sd12bjh:example.org")); +static ROOM_ID: LazyLock = LazyLock::new(|| owned_room_id!("!a98sd12bjh:example.org")); struct DummyCapabilitiesProvider; diff --git a/examples/cross_signing_bootstrap/src/main.rs b/examples/cross_signing_bootstrap/src/main.rs index 2b152ed4038..7440b7fede2 100644 --- a/examples/cross_signing_bootstrap/src/main.rs +++ b/examples/cross_signing_bootstrap/src/main.rs @@ -9,11 +9,11 @@ use matrix_sdk::{ Client, LoopCtrl, config::SyncSettings, encryption::CrossSigningResetAuthType, - ruma::{OwnedUserId, api::client::uiaa}, + ruma::{UserId, api::client::uiaa}, }; use url::Url; -async fn bootstrap(client: Client, user_id: OwnedUserId, password: String) -> Result<()> { +async fn bootstrap(client: Client, user_id: UserId, password: String) -> Result<()> { println!("Bootstrapping a new cross signing identity, press enter to continue."); let mut input = String::new(); diff --git a/examples/custom_events/src/main.rs b/examples/custom_events/src/main.rs index 562dc57e3af..5a3c8b4f9ab 100644 --- a/examples/custom_events/src/main.rs +++ b/examples/custom_events/src/main.rs @@ -23,7 +23,7 @@ use matrix_sdk::{ config::SyncSettings, event_handler::Ctx, ruma::{ - OwnedEventId, + EventId, events::{ macros::EventContent, room::{ @@ -47,7 +47,7 @@ pub struct PingEventContent {} #[ruma_event(type = "rs.matrix-sdk.example.ack", kind = MessageLike)] pub struct AckEventContent { // the event ID of the ping. - ping_id: OwnedEventId, + ping_id: EventId, } // We're going to create a small struct which will count how many times we have diff --git a/examples/get_profiles/src/main.rs b/examples/get_profiles/src/main.rs index 20cb866137a..61cd38abae5 100644 --- a/examples/get_profiles/src/main.rs +++ b/examples/get_profiles/src/main.rs @@ -3,7 +3,7 @@ use std::{env, process::exit}; use matrix_sdk::{ Client, Result as MatrixResult, ruma::{ - OwnedMxcUri, UserId, + MxcUri, UserId, api::client::profile::{self, AvatarUrl, DisplayName}, }, }; @@ -12,7 +12,7 @@ use url::Url; #[derive(Debug)] #[allow(dead_code)] struct UserProfile { - avatar_url: Option, + avatar_url: Option, displayname: Option, } diff --git a/examples/secret_storage/src/main.rs b/examples/secret_storage/src/main.rs index 3d933b07b7e..599b0966615 100644 --- a/examples/secret_storage/src/main.rs +++ b/examples/secret_storage/src/main.rs @@ -4,7 +4,7 @@ use matrix_sdk::{ AuthSession, Client, SessionMeta, SessionTokens, authentication::matrix::MatrixSession, encryption::secret_storage::SecretStore, - ruma::{OwnedDeviceId, OwnedUserId, events::secret::request::SecretName}, + ruma::{DeviceId, UserId, events::secret::request::SecretName}, }; use url::Url; @@ -21,11 +21,11 @@ struct Cli { /// The user ID that should be used to restore the session. #[clap(value_parser)] - user_id: OwnedUserId, + user_id: UserId, /// The user name that should be used for the login. #[clap(value_parser)] - device_id: OwnedDeviceId, + device_id: DeviceId, /// The password that should be used for the login. #[clap(value_parser)] diff --git a/examples/timeline/src/main.rs b/examples/timeline/src/main.rs index aa2b662fede..006d2fdec80 100644 --- a/examples/timeline/src/main.rs +++ b/examples/timeline/src/main.rs @@ -1,7 +1,7 @@ use anyhow::Result; use clap::Parser; use futures_util::StreamExt; -use matrix_sdk::{Client, config::SyncSettings, ruma::OwnedRoomId}; +use matrix_sdk::{Client, config::SyncSettings, ruma::RoomId}; use matrix_sdk_ui::timeline::RoomExt; use url::Url; @@ -29,7 +29,7 @@ struct Cli { /// The room id that we should listen for the, #[clap(value_parser)] - room_id: OwnedRoomId, + room_id: RoomId, } async fn login(cli: Cli) -> Result { diff --git a/labs/multiverse/src/main.rs b/labs/multiverse/src/main.rs index f5e315696ce..63c262ffe33 100644 --- a/labs/multiverse/src/main.rs +++ b/labs/multiverse/src/main.rs @@ -27,9 +27,7 @@ use matrix_sdk::{ deserialized_responses::TimelineEvent, encryption::{BackupDownloadStrategy, EncryptionSettings}, reqwest::Url, - ruma::{ - OwnedEventId, OwnedRoomId, api::client::room::create_room::v3::Request as CreateRoomRequest, - }, + ruma::{EventId, RoomId, api::client::room::create_room::v3::Request as CreateRoomRequest}, search_index::{SearchIndexGuard, SearchIndexStoreKind}, }; use matrix_sdk_base::{RoomStateFilter, event_cache::store::EventCacheStoreLockGuard}; @@ -73,7 +71,7 @@ const ALT_ROW_COLOR: Color = tailwind::SLATE.c900; const SELECTED_STYLE_FG: Color = tailwind::BLUE.c300; const TEXT_COLOR: Color = tailwind::SLATE.c200; -type Timelines = Arc>>; +type Timelines = Arc>>; #[derive(Debug, Parser)] struct Cli { @@ -961,7 +959,7 @@ async fn login_with_password(client: &Client) -> Result<()> { async fn get_events_from_event_ids( client: &Client, room: &Room, - event_ids: Vec, + event_ids: Vec, ) -> Vec { if let Ok(cache_lock) = client.event_cache_store().lock().await { let cache_lock = diff --git a/labs/multiverse/src/widgets/room_list.rs b/labs/multiverse/src/widgets/room_list.rs index add66f8c5fe..670a13d348d 100644 --- a/labs/multiverse/src/widgets/room_list.rs +++ b/labs/multiverse/src/widgets/room_list.rs @@ -1,7 +1,7 @@ use std::{collections::HashMap, sync::Arc}; use imbl::Vector; -use matrix_sdk::{Client, Room, locks::Mutex, ruma::OwnedRoomId}; +use matrix_sdk::{Client, Room, locks::Mutex, ruma::RoomId}; use matrix_sdk_ui::sync_service::SyncService; use ratatui::{prelude::*, widgets::*}; @@ -24,7 +24,7 @@ pub struct ExtraRoomInfo { } pub type Rooms = Arc>>; -pub type RoomInfos = Arc>>; +pub type RoomInfos = Arc>>; pub struct RoomList { pub state: ListState, @@ -109,13 +109,13 @@ impl RoomList { } } - /// Returns the [`OwnedRoomId`] of the `nth` room within the [`RoomList`]. - pub fn get_room_id_of_entry(&self, nth: usize) -> Option { + /// Returns the [`RoomId`] of the `nth` room within the [`RoomList`]. + pub fn get_room_id_of_entry(&self, nth: usize) -> Option { self.rooms.lock().get(nth).cloned().map(|room| room.room_id().to_owned()) } - /// Returns the [`OwnedRoomId`] of the currently selected room, if any. - pub fn get_selected_room_id(&self) -> Option { + /// Returns the [`RoomId`] of the currently selected room, if any. + pub fn get_selected_room_id(&self) -> Option { let selected = self.state.selected()?; self.get_room_id_of_entry(selected) } diff --git a/labs/multiverse/src/widgets/room_view/mod.rs b/labs/multiverse/src/widgets/room_view/mod.rs index d2c9d37290a..c76f445aed3 100644 --- a/labs/multiverse/src/widgets/room_view/mod.rs +++ b/labs/multiverse/src/widgets/room_view/mod.rs @@ -9,8 +9,7 @@ use matrix_sdk::{ Client, Room, RoomState, locks::Mutex, ruma::{ - OwnedEventId, OwnedRoomId, RoomId, UserId, - api::client::receipt::create_receipt::v3::ReceiptType, + EventId, RoomId, UserId, api::client::receipt::create_receipt::v3::ReceiptType, events::room::message::RoomMessageEventContent, }, }; @@ -48,12 +47,12 @@ enum Mode { enum TimelineKind { Room { - room: Option, + room: Option, }, Thread { - room: OwnedRoomId, - thread_root: OwnedEventId, + room: RoomId, + thread_root: EventId, /// The threaded-focused timeline for this thread. timeline: Arc>>, /// Items in the thread timeline (to avoid recomputing them every single @@ -97,7 +96,7 @@ impl RoomView { } } - fn switch_to_room_timeline(&mut self, room: Option) { + fn switch_to_room_timeline(&mut self, room: Option) { match &mut self.kind { TimelineKind::Room { room: prev_room } => { self.kind = TimelineKind::Room { room: room.or(prev_room.take()) }; @@ -184,7 +183,7 @@ impl RoomView { fn room_id(&self) -> Option<&RoomId> { match &self.kind { - TimelineKind::Room { room } => room.as_deref(), + TimelineKind::Room { room } => room.as_ref(), TimelineKind::Thread { room, .. } => Some(room), } } @@ -342,8 +341,8 @@ impl RoomView { } } - pub fn set_selected_room(&mut self, room_id: Option) { - if let Some(room_id) = room_id.as_deref() { + pub fn set_selected_room(&mut self, room_id: Option) { + if let Some(room_id) = room_id.as_ref() { let maybe_room = self.client.get_room(room_id); if let Some(room) = maybe_room { @@ -369,7 +368,7 @@ impl RoomView { fn get_selected_timeline(&self) -> Option> { match &self.kind { TimelineKind::Room { room } => room - .as_deref() + .as_ref() .and_then(|room_id| Some(self.timelines.lock().get(room_id)?.timeline.clone())), TimelineKind::Thread { timeline, .. } => timeline.get().cloned(), } @@ -378,7 +377,7 @@ impl RoomView { fn get_selected_timeline_items(&self) -> Option>> { match &self.kind { TimelineKind::Room { room } => room - .as_deref() + .as_ref() .and_then(|room_id| Some(self.timelines.lock().get(room_id)?.items.lock().clone())), TimelineKind::Thread { items, .. } => Some(items.lock().clone()), } @@ -451,7 +450,7 @@ impl RoomView { self.call_with_room(async move |room, status_handle| { let user_id = match UserId::parse_with_server_name( user_id, - room.client().user_id().unwrap().server_name(), + &room.client().user_id().unwrap().server_name(), ) { Ok(user_id) => user_id, Err(e) => { diff --git a/labs/multiverse/src/widgets/room_view/timeline.rs b/labs/multiverse/src/widgets/room_view/timeline.rs index 21637155f6a..9a57ed009c5 100644 --- a/labs/multiverse/src/widgets/room_view/timeline.rs +++ b/labs/multiverse/src/widgets/room_view/timeline.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use imbl::Vector; use indexmap::IndexMap; use matrix_sdk::ruma::{ - OwnedUserId, + UserId, events::{receipt::Receipt, room::message::MessageType}, }; use matrix_sdk_ui::timeline::{ @@ -159,7 +159,7 @@ fn format_text_message( sender: &str, message: &Message, thread_summary: Option, - read_receipts: &IndexMap, + read_receipts: &IndexMap, ) -> Option> { if let MessageType::Text(text) = message.msgtype() { let mut lines = Vec::new(); diff --git a/labs/multiverse/src/widgets/search/searching.rs b/labs/multiverse/src/widgets/search/searching.rs index 98d87485702..a2c20bccb86 100644 --- a/labs/multiverse/src/widgets/search/searching.rs +++ b/labs/multiverse/src/widgets/search/searching.rs @@ -2,7 +2,7 @@ use crossterm::event::KeyEvent; use matrix_sdk::{ deserialized_responses::TimelineEvent, ruma::{ - OwnedUserId, + UserId, events::{ AnySyncMessageLikeEvent, AnySyncTimelineEvent, room::message::{MessageType, SyncRoomMessageEvent}, @@ -30,7 +30,7 @@ const MESSAGE_PADDING_BOTTOM: u16 = 0; #[derive(Default)] pub struct SearchingView { input: PopupInput, - results: Option>, + results: Option>, pub(crate) list_state: ListState, } @@ -52,7 +52,7 @@ impl SearchingView { } pub fn results(&mut self, values: Vec) { - let values: Vec<(OwnedUserId, String, String)> = + let values: Vec<(UserId, String, String)> = values.iter().filter_map(get_message_from_timeline_event).collect(); self.results = Some(values); @@ -135,7 +135,7 @@ impl Widget for &mut SearchingView { } } -fn get_message_from_timeline_event(ev: &TimelineEvent) -> Option<(OwnedUserId, String, String)> { +fn get_message_from_timeline_event(ev: &TimelineEvent) -> Option<(UserId, String, String)> { if let Ok(AnySyncTimelineEvent::MessageLike(AnySyncMessageLikeEvent::RoomMessage( SyncRoomMessageEvent::Original(ev), ))) = ev.raw().deserialize() diff --git a/testing/matrix-sdk-integration-testing/src/tests/e2ee/mod.rs b/testing/matrix-sdk-integration-testing/src/tests/e2ee/mod.rs index fcb4d32a9f2..844321527af 100644 --- a/testing/matrix-sdk-integration-testing/src/tests/e2ee/mod.rs +++ b/testing/matrix-sdk-integration-testing/src/tests/e2ee/mod.rs @@ -18,7 +18,7 @@ use matrix_sdk::{ }, }, ruma::{ - OwnedEventId, OwnedRoomId, + EventId, RoomId, api::client::room::create_room::v3::{Request as CreateRoomRequest, RoomPreset}, events::{ GlobalAccountDataEventType, OriginalSyncMessageLikeEvent, @@ -138,7 +138,7 @@ async fn test_mutual_sas_verification_with_notification_client_ignores_verificat .await .expect("couldn't create notification client"); - let event_id = OwnedEventId::try_from(alice_verification_request.flow_id()) + let event_id = EventId::try_from(alice_verification_request.flow_id()) .expect("We should be able to get the event id from the verification flow id"); // Simulate getting the event for a notification @@ -914,7 +914,7 @@ pub(super) async fn assert_can_perform_interactive_verification( username: impl AsRef, backup_download_strategy: BackupDownloadStrategy, enable_history_share_on_invite: bool, -) -> Result<(SyncTokenAwareClient, SyncTokenAwareClient, OwnedRoomId, OwnedEventId)> { +) -> Result<(SyncTokenAwareClient, SyncTokenAwareClient, RoomId, EventId)> { let encryption_settings = EncryptionSettings { auto_enable_cross_signing: true, auto_enable_backups: true, diff --git a/testing/matrix-sdk-integration-testing/src/tests/e2ee/shared_history.rs b/testing/matrix-sdk-integration-testing/src/tests/e2ee/shared_history.rs index 7826079a7ba..631895495dc 100644 --- a/testing/matrix-sdk-integration-testing/src/tests/e2ee/shared_history.rs +++ b/testing/matrix-sdk-integration-testing/src/tests/e2ee/shared_history.rs @@ -11,7 +11,7 @@ use matrix_sdk::{ encryption::{BackupDownloadStrategy, EncryptionSettings}, room::power_levels::RoomPowerLevelChanges, ruma::{ - EventId, OwnedEventId, OwnedRoomId, + EventId, RoomId, api::client::{ room::create_room::v3::{Request as CreateRoomRequest, RoomPreset}, uiaa::Password, @@ -135,7 +135,7 @@ async fn test_history_share_on_invite_helper(exclude_insecure_devices: bool) -> .flatten() .expect("We should be notified about the received bundle"); - assert_eq!(Some(info.sender.deref()), alice.user_id()); + assert_eq!(Some(&info.sender), alice.user_id()); assert_eq!(info.room_id, alice_room.room_id()); let bob_room = bob @@ -780,7 +780,7 @@ async fn test_history_share_on_invite_no_forwarder_info_for_normal_events() -> R .flatten() .expect("We should be notified about the received bundle"); - assert_eq!(Some(info.sender.deref()), alice.user_id()); + assert_eq!(Some(&info.sender), alice.user_id()); assert_eq!(info.room_id, alice_room.room_id()); let bob_room = bob @@ -861,8 +861,8 @@ async fn test_history_share_on_invite_downloads_backup_keys() -> Result<()> { let (alice_a, alice_b, room_id, event_id): ( SyncTokenAwareClient, SyncTokenAwareClient, - OwnedRoomId, - OwnedEventId, + RoomId, + EventId, ) = assert_can_perform_interactive_verification("alice", BackupDownloadStrategy::Manual, true) .instrument(alice_span) .await?; @@ -966,7 +966,7 @@ async fn test_history_share_on_invite_downloads_backup_keys() -> Result<()> { .flatten() .expect("We should be notified about the received bundle"); - assert_eq!(Some(info.sender.deref()), alice_b.user_id()); + assert_eq!(Some(&info.sender), alice_b.user_id()); assert_eq!(info.room_id, room_id); // We now check that Bob can access the event. diff --git a/testing/matrix-sdk-integration-testing/src/tests/e2ee/state_events.rs b/testing/matrix-sdk-integration-testing/src/tests/e2ee/state_events.rs index aeaae6c0caf..d184349f5df 100644 --- a/testing/matrix-sdk-integration-testing/src/tests/e2ee/state_events.rs +++ b/testing/matrix-sdk-integration-testing/src/tests/e2ee/state_events.rs @@ -1,4 +1,4 @@ -use std::{ops::Deref, time::Duration}; +use std::time::Duration; use anyhow::Result; use assert_matches2::assert_let; @@ -114,7 +114,7 @@ async fn test_e2ee_state_events() -> Result<()> { .flatten() .expect("We should be notified about the received bundle"); - assert_eq!(Some(info.sender.deref()), alice.user_id()); + assert_eq!(Some(&info.sender), alice.user_id()); assert_eq!(info.room_id, alice_room.room_id()); let bob_room = bob diff --git a/testing/matrix-sdk-integration-testing/src/tests/nse.rs b/testing/matrix-sdk-integration-testing/src/tests/nse.rs index a2c35c42a07..1fc299291f7 100644 --- a/testing/matrix-sdk-integration-testing/src/tests/nse.rs +++ b/testing/matrix-sdk-integration-testing/src/tests/nse.rs @@ -11,7 +11,7 @@ use matrix_sdk::{ Client, Room, encryption::EncryptionSettings, ruma::{ - EventEncryptionAlgorithm, OwnedEventId, OwnedRoomId, RoomId, + EventEncryptionAlgorithm, EventId, RoomId, api::client::room::create_room::v3::Request as CreateRoomRequest, events::{ AnyMessageLikeEventContent, AnySyncTimelineEvent, OriginalSyncMessageLikeEvent, @@ -116,10 +116,10 @@ struct ClientWrapper { sync_service: SyncService, /// The received events and their plain text content. - events: Arc>>, + events: Arc>>, } -type EncryptedEventInfo = (Raw, OwnedRoomId); +type EncryptedEventInfo = (Raw, RoomId); impl ClientWrapper { /// Create a new ClientWrapper. @@ -203,7 +203,7 @@ impl ClientWrapper { } /// Create an encrypted room and invite the supplied people. - async fn create_room(&self, invite: &[&ClientWrapper]) -> OwnedRoomId { + async fn create_room(&self, invite: &[&ClientWrapper]) -> RoomId { let invite = invite.iter().map(|cw| cw.client.user_id().unwrap().to_owned()).collect(); let request = assign!(CreateRoomRequest::new(), { @@ -244,7 +244,7 @@ impl ClientWrapper { /// Send a text message in the supplied room and return the event ID and /// contents. - async fn send(&self, room_id: &RoomId, message: &str) -> (OwnedEventId, String) { + async fn send(&self, room_id: &RoomId, message: &str) -> (EventId, String) { let room = self.wait_until_room_exists(room_id).await; ( @@ -291,7 +291,7 @@ impl ClientWrapper { /// Wait (syncing if needed) until the event with this ID appears, or time /// out. #[instrument(skip(self))] - async fn wait_until_received(&self, event_info: &(OwnedEventId, String)) { + async fn wait_until_received(&self, event_info: &(EventId, String)) { self.sync_until(|| async { self.events.lock().unwrap().contains(event_info).then_some(()) }) @@ -346,7 +346,7 @@ struct NotificationClientWrapper { pub notif_client: NotificationClient, /// The received events and their plain text content. - events: Arc>>, + events: Arc>>, } impl NotificationClientWrapper { @@ -377,7 +377,7 @@ impl NotificationClientWrapper { /// Wait (using [`NotificationClient::get_notification`]) until the event /// with this ID appears, or time out. #[instrument(skip(self))] - async fn nse_wait_until_received(&self, room_id: &RoomId, event_info: &(OwnedEventId, String)) { + async fn nse_wait_until_received(&self, room_id: &RoomId, event_info: &(EventId, String)) { if self.events.lock().unwrap().contains(event_info) { // The event is already here - we are done. return; @@ -424,7 +424,7 @@ async fn decrypt_event( client: &Client, room_id: &RoomId, event: &Raw>, -) -> Option<(OwnedEventId, String)> { +) -> Option<(EventId, String)> { let room = client.get_room(room_id).unwrap(); let push_ctx = room.push_context().await.unwrap(); let Ok(decrypted) = room.decrypt_event(event, push_ctx.as_ref()).await else { @@ -458,7 +458,7 @@ fn timeout() -> Duration { } /// Create an encrypted room as `alice_main` and join `bob` to it. -async fn create_encrypted_room(alice_main: &ClientWrapper, bob: &ClientWrapper) -> OwnedRoomId { +async fn create_encrypted_room(alice_main: &ClientWrapper, bob: &ClientWrapper) -> RoomId { let room_id = alice_main.create_room(&[bob]).await; info!("alice_main has created and enabled encryption in the room"); diff --git a/testing/matrix-sdk-integration-testing/src/tests/sliding_sync/notification_client.rs b/testing/matrix-sdk-integration-testing/src/tests/sliding_sync/notification_client.rs index 0bd4020a1c1..657044244a2 100644 --- a/testing/matrix-sdk-integration-testing/src/tests/sliding_sync/notification_client.rs +++ b/testing/matrix-sdk-integration-testing/src/tests/sliding_sync/notification_client.rs @@ -10,7 +10,7 @@ use matrix_sdk::{ RoomState, config::SyncSettings, ruma::{ - OwnedEventId, + EventId, api::client::room::create_room::v3::Request as CreateRoomRequest, assign, events::{ @@ -81,7 +81,7 @@ async fn test_notification() -> Result<()> { return None; } - let Ok(Some(event_id)) = event.get_field::("event_id") else { + let Ok(Some(event_id)) = event.get_field::("event_id") else { return None; }; diff --git a/testing/matrix-sdk-integration-testing/src/tests/sliding_sync/room.rs b/testing/matrix-sdk-integration-testing/src/tests/sliding_sync/room.rs index 1879a04b3c8..44dd84a2211 100644 --- a/testing/matrix-sdk-integration-testing/src/tests/sliding_sync/room.rs +++ b/testing/matrix-sdk-integration-testing/src/tests/sliding_sync/room.rs @@ -218,7 +218,7 @@ async fn test_room_avatar_group_conversation() -> Result<()> { for _ in 0..3 { sleep(Duration::from_secs(1)).await; - assert_eq!(alice_room.avatar_url().as_deref(), Some(group_avatar_uri)); + assert_eq!(alice_room.avatar_url().as_ref(), Some(group_avatar_uri)); // Force a new server response. alice_room.send(RoomMessageEventContent::text_plain("hello world")).await?; @@ -1002,7 +1002,7 @@ async fn test_room_preview() -> Result<()> { // Dummy test for `Client::get_room_preview` which may call one or the other // methods. info!("Alice gets a preview of the public room using any method"); - let preview = alice.get_room_preview(room_id.into(), Vec::new()).await?; + let preview = alice.get_room_preview(&room_id.into(), Vec::new()).await?; assert_room_preview(&preview, &room_alias); assert_eq!(preview.state, Some(RoomState::Joined)); assert!(preview.heroes.is_some()); @@ -1041,7 +1041,7 @@ async fn test_room_preview_with_room_directory_search_and_room_alias_only() { // The room preview is found let preview = client - .get_room_preview(room_alias.into(), Vec::new()) + .get_room_preview(&room_alias.into(), Vec::new()) .await .expect("room preview couldn't be retrieved"); assert_eq!(preview.room_id, expected_room_id); @@ -1106,7 +1106,7 @@ async fn test_room_preview_with_room_directory_search_and_room_alias_only_in_sev // The room preview is found in the first response let preview = client - .get_room_preview(room_alias.into(), vec![via_1, via_2]) + .get_room_preview(&room_alias.into(), vec![via_1, via_2]) .await .expect("room preview couldn't be retrieved"); assert_eq!(preview.room_id, expected_room_id); @@ -1163,7 +1163,7 @@ async fn get_room_preview_with_room_summary( // Alice has joined the room, so they get the full details. info!("Alice gets a preview of the public room from msc3266 using the room id"); let preview = - RoomPreview::from_room_summary(alice, room_id.to_owned(), room_id.into(), Vec::new()) + RoomPreview::from_room_summary(alice, room_id.to_owned(), &room_id.into(), Vec::new()) .await .unwrap(); @@ -1177,7 +1177,7 @@ async fn get_room_preview_with_room_summary( let preview = RoomPreview::from_room_summary( alice, room_id.to_owned(), - <_>::try_from(full_alias.as_str()).unwrap(), + &<_>::try_from(full_alias).unwrap(), Vec::new(), ) .await @@ -1191,7 +1191,7 @@ async fn get_room_preview_with_room_summary( // room too. info!("Bob gets a preview of the public room from msc3266 using the room id"); let preview = - RoomPreview::from_room_summary(bob, room_id.to_owned(), room_id.into(), Vec::new()) + RoomPreview::from_room_summary(bob, room_id.to_owned(), &room_id.into(), Vec::new()) .await .unwrap(); assert_room_preview(&preview, room_alias); @@ -1204,7 +1204,7 @@ async fn get_room_preview_with_room_summary( let preview = RoomPreview::from_room_summary( bob, public_no_history_room_id.to_owned(), - public_no_history_room_id.into(), + &public_no_history_room_id.into(), Vec::new(), ) .await diff --git a/testing/matrix-sdk-integration-testing/src/tests/timeline.rs b/testing/matrix-sdk-integration-testing/src/tests/timeline.rs index 138d673f662..c5c18b89278 100644 --- a/testing/matrix-sdk-integration-testing/src/tests/timeline.rs +++ b/testing/matrix-sdk-integration-testing/src/tests/timeline.rs @@ -33,7 +33,7 @@ use matrix_sdk::{ reply::{EnforceThread, Reply}, }, ruma::{ - MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, RoomId, UserId, + EventId, MilliSecondsSinceUnixEpoch, RoomId, UserId, api::client::room::create_room::v3::{Request as CreateRoomRequest, RoomPreset}, events::{ InitialStateEvent, @@ -732,7 +732,7 @@ async fn test_new_users_first_messages_dont_warn_about_insecure_device_if_it_is_ } /// Send the supplied message in the supplied room - async fn send_message(room: &Room, message: &str) -> OwnedEventId { + async fn send_message(room: &Room, message: &str) -> EventId { room.send(RoomMessageEventContent::text_plain(message)) .await .expect("We should be able to send a message to our new room") @@ -1093,7 +1093,7 @@ async fn prepare_room_with_pinned_events( alice: &Client, recovery_passphrase: &str, number_of_normal_events: usize, -) -> Result<(OwnedRoomId, OwnedEventId), TestError> { +) -> Result<(RoomId, EventId), TestError> { let sync_service = SyncService::builder(alice.clone()).build().await?; sync_service.start().await; diff --git a/testing/matrix-sdk-test/src/event_factory.rs b/testing/matrix-sdk-test/src/event_factory.rs index f6c275af2b4..24f02b572f5 100644 --- a/testing/matrix-sdk-test/src/event_factory.rs +++ b/testing/matrix-sdk-test/src/event_factory.rs @@ -25,9 +25,8 @@ use matrix_sdk_common::deserialized_responses::{ TimelineEvent, UnableToDecryptInfo, UnableToDecryptReason, }; use ruma::{ - EventId, Int, MilliSecondsSinceUnixEpoch, MxcUri, OwnedDeviceId, OwnedEventId, OwnedMxcUri, - OwnedRoomAliasId, OwnedRoomId, OwnedTransactionId, OwnedUserId, OwnedVoipId, RoomId, - RoomVersionId, TransactionId, UInt, UserId, VoipVersionId, + DeviceId, EventId, Int, MilliSecondsSinceUnixEpoch, MxcUri, RoomAliasId, RoomId, RoomVersionId, + TransactionId, UInt, UserId, VoipId, VoipVersionId, events::{ AnyGlobalAccountDataEvent, AnyMessageLikeEvent, AnyRoomAccountDataEvent, AnyStateEvent, AnyStrippedStateEvent, AnySyncEphemeralRoomEvent, AnySyncMessageLikeEvent, @@ -39,7 +38,7 @@ use ruma::{ StaticStateEventContent, StrippedStateEvent, SyncMessageLikeEvent, SyncStateEvent, beacon::BeaconEventContent, call::{SessionDescription, invite::CallInviteEventContent}, - direct::{DirectEventContent, OwnedDirectUserIdentifier}, + direct::{DirectEventContent, DirectUserIdentifier}, fully_read::FullyReadEventContent, ignored_user_list::IgnoredUserListEventContent, macros::EventContent, @@ -94,6 +93,7 @@ use ruma::{ tag::{TagEventContent, Tags}, typing::TypingEventContent, }, + owned_server_name, presence::PresenceState, push::Ruleset, room::RoomType, @@ -127,10 +127,10 @@ struct RedactedBecause { content: RoomRedactionEventContent, /// The globally unique event identifier for the user who sent the event. - event_id: OwnedEventId, + event_id: EventId, /// The fully-qualified ID of the user who sent this event. - sender: OwnedUserId, + sender: UserId, /// Timestamp in milliseconds on originating homeserver when this event was /// sent. @@ -143,7 +143,7 @@ struct Unsigned { prev_content: Option, #[serde(skip_serializing_if = "Option::is_none")] - transaction_id: Option, + transaction_id: Option, #[serde(rename = "m.relations", skip_serializing_if = "Option::is_none")] relations: Option>>, @@ -213,12 +213,12 @@ pub struct EventBuilder> { /// /// It will decide which fields are added to the JSON. format: EventFormat, - sender: Option, - room: Option, - event_id: Option, + sender: Option, + room: Option, + event_id: Option, /// Whether the event should *not* have an event id. False by default. no_event_id: bool, - redacts: Option, + redacts: Option, content: C, server_ts: MilliSecondsSinceUnixEpoch, unsigned: Option>, @@ -347,9 +347,9 @@ where .room .as_ref() .and_then(|room_id| room_id.server_name()) - .unwrap_or(server_name!("dummy.org")); + .unwrap_or_else(|| owned_server_name!("dummy.org")); - EventId::new(server_name) + EventId::new(&server_name) }); map.insert("event_id".to_owned(), json!(event_id)); @@ -862,8 +862,8 @@ where #[derive(Debug, Default)] pub struct EventFactory { next_ts: AtomicU64, - sender: Option, - room: Option, + sender: Option, + room: Option, } impl EventFactory { @@ -927,7 +927,7 @@ impl EventFactory { &self, ciphertext: impl Into, sender_key: impl Into, - device_id: impl Into, + device_id: impl Into, session_id: impl Into, ) -> EventBuilder { self.event(RoomEncryptedEventContent::new( @@ -1072,7 +1072,7 @@ impl EventFactory { /// Create a state event for the room's pinned events. pub fn room_pinned_events( &self, - pinned: Vec, + pinned: Vec, ) -> EventBuilder { self.event(RoomPinnedEventsEventContent::new(pinned)).state_key("") } @@ -1099,7 +1099,7 @@ impl EventFactory { /// ``` pub fn member_hints( &self, - service_members: BTreeSet, + service_members: BTreeSet, ) -> EventBuilder { // The `m.member_hints` event always has an empty state key, so let's set it. self.event(MemberHintsEventContent::new(service_members)).state_key("") @@ -1255,11 +1255,7 @@ impl EventFactory { /// Creates a plain (unencrypted) image event content referencing the given /// MXC ID. - pub fn image( - &self, - filename: String, - url: OwnedMxcUri, - ) -> EventBuilder { + pub fn image(&self, filename: String, url: MxcUri) -> EventBuilder { let image_event_content = ImageMessageEventContent::plain(filename, url); self.event(RoomMessageEventContent::new(MessageType::Image(image_event_content))) } @@ -1270,7 +1266,7 @@ impl EventFactory { &self, body: String, filename: String, - url: OwnedMxcUri, + url: MxcUri, ) -> EventBuilder { let gallery_event_content = GalleryMessageEventContent::new( body, @@ -1314,7 +1310,7 @@ impl EventFactory { /// Create a new `m.room.power_levels` event. pub fn power_levels( &self, - map: &mut BTreeMap, + map: &mut BTreeMap, ) -> EventBuilder { let mut content = RoomPowerLevelsEventContent::new(&AuthorizationRules::V1); content.users.append(map); @@ -1341,8 +1337,8 @@ impl EventFactory { /// Create a new `m.room.canonical_alias` event. pub fn canonical_alias( &self, - alias: Option, - alt_aliases: Vec, + alias: Option, + alt_aliases: Vec, ) -> EventBuilder { let mut content = RoomCanonicalAliasEventContent::new(); content.alias = alias; @@ -1380,7 +1376,7 @@ impl EventFactory { /// ``` pub fn beacon( &self, - beacon_info_event_id: OwnedEventId, + beacon_info_event_id: EventId, latitude: f64, longitude: f64, uncertainty: u32, @@ -1395,7 +1391,7 @@ impl EventFactory { &self, body: impl Into, info: ImageInfo, - url: OwnedMxcUri, + url: MxcUri, ) -> EventBuilder { self.event(StickerEventContent::new(body.into(), info, url)) } @@ -1403,7 +1399,7 @@ impl EventFactory { /// Create a new `m.call.invite` event. pub fn call_invite( &self, - call_id: OwnedVoipId, + call_id: VoipId, lifetime: UInt, offer: SessionDescription, version: VoipVersionId, @@ -1439,7 +1435,7 @@ impl EventFactory { /// Create a new `m.ignored_user_list` global account data event. pub fn ignored_user_list( &self, - users: impl IntoIterator, + users: impl IntoIterator, ) -> EventBuilder { self.global_account_data(IgnoredUserListEventContent::users(users)) } @@ -1452,8 +1448,8 @@ impl EventFactory { /// Create a new `m.space.child` state event. pub fn space_child( &self, - parent: OwnedRoomId, - child: OwnedRoomId, + parent: RoomId, + child: RoomId, ) -> EventBuilder { let mut event = self.event(SpaceChildEventContent::new(vec![])); event.room = Some(parent); @@ -1464,8 +1460,8 @@ impl EventFactory { /// Create a new `m.space.parent` state event. pub fn space_parent( &self, - parent: OwnedRoomId, - child: OwnedRoomId, + parent: RoomId, + child: RoomId, ) -> EventBuilder { let mut event = self.event(SpaceParentEventContent::new(vec![])); event.state_key = Some(parent.to_string()); @@ -1535,7 +1531,7 @@ impl EventFactory { /// Builder for presence events. #[derive(Debug)] pub struct PresenceBuilder { - sender: Option, + sender: Option, content: PresenceEventContent, } @@ -1587,7 +1583,7 @@ impl From for Raw { impl EventBuilder { /// Add a user/room pair to the `m.direct` event. - pub fn add_user(mut self, user_id: OwnedDirectUserIdentifier, room_id: &RoomId) -> Self { + pub fn add_user(mut self, user_id: DirectUserIdentifier, room_id: &RoomId) -> Self { self.content.0.entry(user_id).or_default().push(room_id.to_owned()); self } @@ -1607,7 +1603,7 @@ impl EventBuilder { /// here. pub fn invited(mut self, invited_user: &UserId) -> Self { assert_ne!( - self.sender.as_deref().unwrap(), + self.sender.as_ref().unwrap(), invited_user, "invited user and sender can't be the same person" ); @@ -1629,7 +1625,7 @@ impl EventBuilder { /// here. pub fn kicked(mut self, kicked_user: &UserId) -> Self { assert_ne!( - self.sender.as_deref().unwrap(), + self.sender.as_ref().unwrap(), kicked_user, "kicked user and sender can't be the same person, otherwise it's just a Leave" ); @@ -1642,7 +1638,7 @@ impl EventBuilder { /// here. pub fn banned(mut self, banned_user: &UserId) -> Self { assert_ne!( - self.sender.as_deref().unwrap(), + self.sender.as_ref().unwrap(), banned_user, "a user can't ban itself" // hopefully ); @@ -1715,12 +1711,12 @@ impl EventBuilder { } impl EventBuilder { - pub fn mentions(mut self, users: impl IntoIterator) -> Self { + pub fn mentions(mut self, users: impl IntoIterator) -> Self { self.content.mentions = Some(Mentions::with_user_ids(users)); self } - pub fn relates_to_membership_state_event(mut self, event_id: OwnedEventId) -> Self { + pub fn relates_to_membership_state_event(mut self, event_id: EventId) -> Self { self.content.relates_to = Some(Reference::new(event_id)); self } @@ -1784,7 +1780,7 @@ impl ReadReceiptBuilder<'_> { pub struct PreviousMembership { state: MembershipState, - avatar_url: Option, + avatar_url: Option, display_name: Option, } diff --git a/testing/matrix-sdk-test/src/sync_builder/invited_room.rs b/testing/matrix-sdk-test/src/sync_builder/invited_room.rs index 842a86be39e..775dafe9082 100644 --- a/testing/matrix-sdk-test/src/sync_builder/invited_room.rs +++ b/testing/matrix-sdk-test/src/sync_builder/invited_room.rs @@ -1,12 +1,12 @@ use ruma::{ - OwnedRoomId, RoomId, api::client::sync::sync_events::v3::InvitedRoom, - events::AnyStrippedStateEvent, serde::Raw, + RoomId, api::client::sync::sync_events::v3::InvitedRoom, events::AnyStrippedStateEvent, + serde::Raw, }; use crate::DEFAULT_TEST_ROOM_ID; pub struct InvitedRoomBuilder { - pub(super) room_id: OwnedRoomId, + pub(super) room_id: RoomId, pub(super) inner: InvitedRoom, } diff --git a/testing/matrix-sdk-test/src/sync_builder/joined_room.rs b/testing/matrix-sdk-test/src/sync_builder/joined_room.rs index 65d7f04bcbb..5ad49fb7623 100644 --- a/testing/matrix-sdk-test/src/sync_builder/joined_room.rs +++ b/testing/matrix-sdk-test/src/sync_builder/joined_room.rs @@ -1,5 +1,5 @@ use ruma::{ - OwnedRoomId, RoomId, + RoomId, api::client::sync::sync_events::v3::JoinedRoom, events::{ AnyRoomAccountDataEvent, AnySyncStateEvent, AnySyncTimelineEvent, @@ -14,7 +14,7 @@ use crate::{DEFAULT_TEST_ROOM_ID, event_factory::EventBuilder}; #[derive(Debug, Clone)] pub struct JoinedRoomBuilder { - pub(super) room_id: OwnedRoomId, + pub(super) room_id: RoomId, pub(super) inner: JoinedRoom, } diff --git a/testing/matrix-sdk-test/src/sync_builder/knocked_room.rs b/testing/matrix-sdk-test/src/sync_builder/knocked_room.rs index 62bf42c0498..808fb7444f9 100644 --- a/testing/matrix-sdk-test/src/sync_builder/knocked_room.rs +++ b/testing/matrix-sdk-test/src/sync_builder/knocked_room.rs @@ -1,12 +1,12 @@ use ruma::{ - OwnedRoomId, RoomId, api::client::sync::sync_events::v3::KnockedRoom, - events::AnyStrippedStateEvent, serde::Raw, + RoomId, api::client::sync::sync_events::v3::KnockedRoom, events::AnyStrippedStateEvent, + serde::Raw, }; use crate::DEFAULT_TEST_ROOM_ID; pub struct KnockedRoomBuilder { - pub(super) room_id: OwnedRoomId, + pub(super) room_id: RoomId, pub(super) inner: KnockedRoom, } diff --git a/testing/matrix-sdk-test/src/sync_builder/left_room.rs b/testing/matrix-sdk-test/src/sync_builder/left_room.rs index c7fae215236..3e49aa31ba2 100644 --- a/testing/matrix-sdk-test/src/sync_builder/left_room.rs +++ b/testing/matrix-sdk-test/src/sync_builder/left_room.rs @@ -1,5 +1,5 @@ use ruma::{ - OwnedRoomId, RoomId, + RoomId, api::client::sync::sync_events::v3::LeftRoom, events::{AnyRoomAccountDataEvent, AnySyncStateEvent, AnySyncTimelineEvent}, serde::Raw, @@ -9,7 +9,7 @@ use super::StateMutExt; use crate::DEFAULT_TEST_ROOM_ID; pub struct LeftRoomBuilder { - pub(super) room_id: OwnedRoomId, + pub(super) room_id: RoomId, pub(super) inner: LeftRoom, } diff --git a/testing/matrix-sdk-test/src/sync_builder/mod.rs b/testing/matrix-sdk-test/src/sync_builder/mod.rs index f04bf16cc5b..7aaf54865be 100644 --- a/testing/matrix-sdk-test/src/sync_builder/mod.rs +++ b/testing/matrix-sdk-test/src/sync_builder/mod.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; use http::Response; use ruma::{ - OwnedRoomId, OwnedUserId, UserId, + RoomId, UserId, api::{ IncomingResponse, client::sync::sync_events::v3::{ @@ -37,13 +37,13 @@ pub use left_room::LeftRoomBuilder; #[derive(Default)] pub struct SyncResponseBuilder { /// Updates to joined `Room`s. - joined_rooms: HashMap, + joined_rooms: HashMap, /// Updates to invited `Room`s. - invited_rooms: HashMap, + invited_rooms: HashMap, /// Updates to left `Room`s. - left_rooms: HashMap, + left_rooms: HashMap, /// Updates to knocked `Room`s. - knocked_rooms: HashMap, + knocked_rooms: HashMap, /// Events that determine the presence state of a user. presence: Vec>, /// Global account data events. @@ -52,7 +52,7 @@ pub struct SyncResponseBuilder { /// sync response to vary. batch_counter: i64, /// The device lists of the user. - changed_device_lists: Vec, + changed_device_lists: Vec, to_device_events: Vec>, } diff --git a/testing/matrix-sdk-test/src/test_json/keys_query_sets.rs b/testing/matrix-sdk-test/src/test_json/keys_query_sets.rs index b50d8ff419d..fb50a32fae7 100644 --- a/testing/matrix-sdk-test/src/test_json/keys_query_sets.rs +++ b/testing/matrix-sdk-test/src/test_json/keys_query_sets.rs @@ -2,9 +2,9 @@ use std::{collections::BTreeMap, default::Default}; use insta::{assert_json_snapshot, with_settings}; use ruma::{ - CanonicalJsonValue, CrossSigningKeyId, CrossSigningOrDeviceSignatures, - CrossSigningOrDeviceSigningKeyId, DeviceId, OwnedBase64PublicKey, - OwnedBase64PublicKeyOrDeviceId, OwnedDeviceId, OwnedUserId, SigningKeyAlgorithm, UserId, + Base64PublicKey, Base64PublicKeyOrDeviceId, CanonicalJsonValue, CrossSigningKeyId, + CrossSigningOrDeviceSignatures, CrossSigningOrDeviceSigningKeyId, DeviceId, + SigningKeyAlgorithm, UserId, api::client::keys::get_keys::v3::Response as KeyQueryResponse, device_id, encryption::{CrossSigningKey, DeviceKeys, KeyUsage}, @@ -79,7 +79,7 @@ use crate::{ /// ``` pub struct KeyQueryResponseTemplate { /// The User ID of the user that this test data is about. - user_id: OwnedUserId, + user_id: UserId, /// The user's private master cross-signing key, once it has been set via /// [`KeyQueryResponseTemplate::with_cross_signing_keys`]. @@ -104,12 +104,12 @@ pub struct KeyQueryResponseTemplate { /// The JSON object containing the public, signed, device keys, added via /// [`KeyQueryResponseTemplate::with_device`]. - device_keys: BTreeMap>, + device_keys: BTreeMap>, } impl KeyQueryResponseTemplate { /// Create a new [`KeyQueryResponseTemplate`] for the given user. - pub fn new(user_id: OwnedUserId) -> Self { + pub fn new(user_id: UserId) -> Self { KeyQueryResponseTemplate { user_id, master_cross_signing_key: None, @@ -258,7 +258,7 @@ impl KeyQueryResponseTemplate { public_key: &Ed25519PublicKey, key_usage: KeyUsage, ) -> CrossSigningKey { - let public_key_base64 = OwnedBase64PublicKey::with_bytes(public_key.as_bytes()); + let public_key_base64 = Base64PublicKey::with_bytes(public_key.as_bytes()); let mut key = CrossSigningKey::new( self.user_id.clone(), vec![key_usage], @@ -810,7 +810,7 @@ impl VerificationViolationTestData { } /// Device ID of the device returned by [`Self::own_unsigned_device_keys`]. - pub fn own_unsigned_device_id() -> OwnedDeviceId { + pub fn own_unsigned_device_id() -> DeviceId { Self::own_unsigned_device_keys().0 } @@ -820,7 +820,7 @@ impl VerificationViolationTestData { /// /// For convenience, returns a tuple `(, )`. The /// device id is also returned by [`Self::own_unsigned_device_id`]. - pub fn own_unsigned_device_keys() -> (OwnedDeviceId, Raw) { + pub fn own_unsigned_device_keys() -> (DeviceId, Raw) { let json = json!({ "algorithms": [ "m.olm.v1.curve25519-aes-sha2", @@ -845,7 +845,7 @@ impl VerificationViolationTestData { } /// Device ID of the device returned by [`Self::own_signed_device_keys`]. - pub fn own_signed_device_id() -> OwnedDeviceId { + pub fn own_signed_device_id() -> DeviceId { Self::own_signed_device_keys().0 } @@ -855,7 +855,7 @@ impl VerificationViolationTestData { /// /// For convenience, returns a tuple `(, )`. The /// device id is also returned by [`Self::own_signed_device_id`]. - pub fn own_signed_device_keys() -> (OwnedDeviceId, Raw) { + pub fn own_signed_device_keys() -> (DeviceId, Raw) { let json = json!({ "algorithms": [ "m.olm.v1.curve25519-aes-sha2", @@ -1484,8 +1484,8 @@ fn sign_cross_signing_key( let signature = calculate_json_signature(key_json, signing_key); // Poke the signature into the struct - let signing_key_id: OwnedBase64PublicKeyOrDeviceId = - OwnedBase64PublicKey::with_bytes(signing_key.public_key().as_bytes()).into(); + let signing_key_id: Base64PublicKeyOrDeviceId = + Base64PublicKey::with_bytes(signing_key.public_key().as_bytes()).into(); value.signatures.insert_signature( user_id.to_owned(),