From ad2d3d20372fc3697051ab2661f5c603f134302f Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Sat, 15 Aug 2020 02:49:34 +0200 Subject: [PATCH 1/2] Simplify tests in matrix_sdk::client --- matrix_sdk/src/client.rs | 95 +++++++--------------------------------- 1 file changed, 17 insertions(+), 78 deletions(-) diff --git a/matrix_sdk/src/client.rs b/matrix_sdk/src/client.rs index b4fb25d0..414a0407 100644 --- a/matrix_sdk/src/client.rs +++ b/matrix_sdk/src/client.rs @@ -1559,12 +1559,10 @@ impl Client { #[cfg(test)] mod test { use super::{ - ban_user, create_receipt, create_typing_event, forget_room, get_public_rooms, + create_typing_event, get_public_rooms, get_public_rooms_filtered::{self, Filter}, - invite_user, kick_user, leave_room, register::RegistrationKind, - set_read_marker, Client, ClientConfig, Invite3pid, MessageEventContent, Session, - SyncSettings, Url, + Client, ClientConfig, Invite3pid, MessageEventContent, Session, SyncSettings, Url, }; use crate::{RegistrationBuilder, RoomListFilterBuilder}; @@ -1852,7 +1850,6 @@ mod test { } #[tokio::test] - #[allow(irrefutable_let_patterns)] async fn invite_user_by_id() { let client = logged_in_client().await; @@ -1868,11 +1865,10 @@ mod test { let user = user_id!("@example:localhost"); let room_id = room_id!("!testroom:example.org"); - if let invite_user::Response = client.invite_user_by_id(&room_id, &user).await.unwrap() {} + client.invite_user_by_id(&room_id, &user).await.unwrap(); } #[tokio::test] - #[allow(irrefutable_let_patterns)] async fn invite_user_by_3pid() { let client = logged_in_client().await; @@ -1888,7 +1884,7 @@ mod test { let room_id = room_id!("!testroom:example.org"); - if let invite_user::Response = client + client .invite_user_by_3pid( &room_id, &Invite3pid { @@ -1899,12 +1895,10 @@ mod test { }, ) .await - .unwrap() - {} + .unwrap(); } #[tokio::test] - #[allow(irrefutable_let_patterns)] async fn room_search_all() { let homeserver = Url::from_str(&mockito::server_url()).unwrap(); let client = Client::new(homeserver).unwrap(); @@ -1917,15 +1911,12 @@ mod test { .with_body(test_json::PUBLIC_ROOMS.to_string()) .create(); - if let get_public_rooms::Response { chunk, .. } = - client.public_rooms(Some(10), None, None).await.unwrap() - { - assert_eq!(chunk.len(), 1) - } + let get_public_rooms::Response { chunk, .. } = + client.public_rooms(Some(10), None, None).await.unwrap(); + assert_eq!(chunk.len(), 1); } #[tokio::test] - #[allow(irrefutable_let_patterns)] async fn room_search_filtered() { let client = logged_in_client().await; @@ -1944,15 +1935,12 @@ mod test { generic_search_term, }); - if let get_public_rooms_filtered::Response { chunk, .. } = - client.public_rooms_filtered(request).await.unwrap() - { - assert_eq!(chunk.len(), 1) - } + let get_public_rooms_filtered::Response { chunk, .. } = + client.public_rooms_filtered(request).await.unwrap(); + assert_eq!(chunk.len(), 1); } #[tokio::test] - #[allow(irrefutable_let_patterns)] async fn leave_room() { let client = logged_in_client().await; @@ -1968,18 +1956,10 @@ mod test { let room_id = room_id!("!testroom:example.org"); - let response = client.leave_room(&room_id).await.unwrap(); - if let leave_room::Response = response { - } else { - panic!( - "expected `ruma_client_api::leave_room::Response` found {:?}", - response - ) - } + client.leave_room(&room_id).await.unwrap(); } #[tokio::test] - #[allow(irrefutable_let_patterns)] async fn ban_user() { let client = logged_in_client().await; @@ -1995,19 +1975,10 @@ mod test { let user = user_id!("@example:localhost"); let room_id = room_id!("!testroom:example.org"); - let response = client.ban_user(&room_id, &user, None).await.unwrap(); - - if let ban_user::Response = response { - } else { - panic!( - "expected `ruma_client_api::ban_user::Response` found {:?}", - response - ) - } + client.ban_user(&room_id, &user, None).await.unwrap(); } #[tokio::test] - #[allow(irrefutable_let_patterns)] async fn kick_user() { let client = logged_in_client().await; @@ -2024,19 +1995,10 @@ mod test { let user = user_id!("@example:localhost"); let room_id = room_id!("!testroom:example.org"); - let response = client.kick_user(&room_id, &user, None).await.unwrap(); - - if let kick_user::Response = response { - } else { - panic!( - "expected `ruma_client_api::kick_user::Response` found {:?}", - response - ) - } + client.kick_user(&room_id, &user, None).await.unwrap(); } #[tokio::test] - #[allow(irrefutable_let_patterns)] async fn forget_room() { let client = logged_in_client().await; @@ -2052,18 +2014,10 @@ mod test { let room_id = room_id!("!testroom:example.org"); - let response = client.forget_room_by_id(&room_id).await.unwrap(); - if let forget_room::Response = response { - } else { - panic!( - "expected `ruma_client_api::forget_room::Response` found {:?}", - response - ) - } + client.forget_room_by_id(&room_id).await.unwrap(); } #[tokio::test] - #[allow(irrefutable_let_patterns)] async fn read_receipt() { let client = logged_in_client().await; @@ -2080,18 +2034,10 @@ mod test { let room_id = room_id!("!testroom:example.org"); let event_id = event_id!("$xxxxxx:example.org"); - let response = client.read_receipt(&room_id, &event_id).await.unwrap(); - if let create_receipt::Response = response { - } else { - panic!( - "expected `ruma_client_api::create_receipt::Response` found {:?}", - response - ) - } + client.read_receipt(&room_id, &event_id).await.unwrap(); } #[tokio::test] - #[allow(irrefutable_let_patterns)] async fn read_marker() { let client = logged_in_client().await; @@ -2108,14 +2054,7 @@ mod test { let room_id = room_id!("!testroom:example.org"); let event_id = event_id!("$xxxxxx:example.org"); - let response = client.read_marker(&room_id, &event_id, None).await.unwrap(); - if let set_read_marker::Response = response { - } else { - panic!( - "expected `ruma_client_api::set_read_marker::Response` found {:?}", - response - ) - } + client.read_marker(&room_id, &event_id, None).await.unwrap(); } #[tokio::test] From 5040be042f862917570d40b16339d21f1971bae2 Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Sat, 15 Aug 2020 03:09:13 +0200 Subject: [PATCH 2/2] Update ruma --- matrix_sdk/examples/autojoin.rs | 13 +- matrix_sdk/examples/command_bot.rs | 7 +- matrix_sdk/examples/emoji_verification.rs | 8 +- matrix_sdk/examples/get_profiles.rs | 10 +- matrix_sdk/examples/login.rs | 8 +- matrix_sdk/src/client.rs | 129 ++++++++------------ matrix_sdk/src/http_client.rs | 8 +- matrix_sdk/src/request_builder.rs | 76 ++++++------ matrix_sdk_base/src/models/room.rs | 19 +-- matrix_sdk_common/Cargo.toml | 3 +- matrix_sdk_common/src/lib.rs | 5 +- matrix_sdk_crypto/src/device.rs | 14 +-- matrix_sdk_crypto/src/machine.rs | 11 +- matrix_sdk_crypto/src/olm/account.rs | 20 +-- matrix_sdk_crypto/src/olm/group_sessions.rs | 10 +- matrix_sdk_crypto/src/store/sqlite.rs | 9 +- 16 files changed, 162 insertions(+), 188 deletions(-) diff --git a/matrix_sdk/examples/autojoin.rs b/matrix_sdk/examples/autojoin.rs index d8813ae4..ece720e7 100644 --- a/matrix_sdk/examples/autojoin.rs +++ b/matrix_sdk/examples/autojoin.rs @@ -43,8 +43,8 @@ impl EventEmitter for AutoJoinBot { async fn login_and_sync( homeserver_url: String, - username: String, - password: String, + username: &str, + password: &str, ) -> Result<(), matrix_sdk::Error> { let mut home = dirs::home_dir().expect("no home directory found"); home.push("autojoin_bot"); @@ -55,12 +55,7 @@ async fn login_and_sync( let mut client = Client::new_with_config(homeserver_url, client_config).unwrap(); client - .login( - username.clone(), - password, - None, - Some("autojoin bot".to_string()), - ) + .login(username, password, None, Some("autojoin bot")) .await?; println!("logged in as {}", username); @@ -92,6 +87,6 @@ async fn main() -> Result<(), matrix_sdk::Error> { } }; - login_and_sync(homeserver_url, username, password).await?; + login_and_sync(homeserver_url, &username, &password).await?; Ok(()) } diff --git a/matrix_sdk/examples/command_bot.rs b/matrix_sdk/examples/command_bot.rs index 9e186c01..45339660 100644 --- a/matrix_sdk/examples/command_bot.rs +++ b/matrix_sdk/examples/command_bot.rs @@ -81,12 +81,7 @@ async fn login_and_sync( let mut client = Client::new_with_config(homeserver_url, client_config).unwrap(); client - .login( - username.clone(), - password, - None, - Some("command bot".to_string()), - ) + .login(&username, &password, None, Some("command bot")) .await?; println!("logged in as {}", username); diff --git a/matrix_sdk/examples/emoji_verification.rs b/matrix_sdk/examples/emoji_verification.rs index fae1b16c..992e29ed 100644 --- a/matrix_sdk/examples/emoji_verification.rs +++ b/matrix_sdk/examples/emoji_verification.rs @@ -36,15 +36,15 @@ fn print_result(sas: Sas) { async fn login( homeserver_url: String, - username: String, - password: String, + username: &str, + password: &str, ) -> Result<(), matrix_sdk::Error> { let client_config = ClientConfig::new(); let homeserver_url = Url::parse(&homeserver_url).expect("Couldn't parse the homeserver URL"); let client = Client::new_with_config(homeserver_url, client_config).unwrap(); client - .login(username, password, None, Some("rust-sdk".to_string())) + .login(username, password, None, Some("rust-sdk")) .await?; let client_ref = &client; @@ -112,5 +112,5 @@ async fn main() -> Result<(), matrix_sdk::Error> { } }; - login(homeserver_url, username, password).await + login(homeserver_url, &username, &password).await } diff --git a/matrix_sdk/examples/get_profiles.rs b/matrix_sdk/examples/get_profiles.rs index 6850c404..46324875 100644 --- a/matrix_sdk/examples/get_profiles.rs +++ b/matrix_sdk/examples/get_profiles.rs @@ -37,8 +37,8 @@ async fn get_profile(client: Client, mxid: UserId) -> MatrixResult async fn login( homeserver_url: String, - username: String, - password: String, + username: &str, + password: &str, ) -> Result { let client_config = ClientConfig::new() .proxy("http://localhost:8080")? @@ -47,7 +47,7 @@ async fn login( let client = Client::new_with_config(homeserver_url, client_config).unwrap(); client - .login(username, password, None, Some("rust-sdk".to_string())) + .login(username, password, None, Some("rust-sdk")) .await?; Ok(client) @@ -69,9 +69,9 @@ async fn main() -> Result<(), matrix_sdk::Error> { } }; - let client = login(homeserver_url, username.clone(), password).await?; + let client = login(homeserver_url, &username, &password).await?; - let user_id = UserId::try_from(username.clone()).expect("Couldn't parse the MXID"); + let user_id = UserId::try_from(username).expect("Couldn't parse the MXID"); let profile = get_profile(client, user_id).await?; println!("{:#?}", profile); Ok(()) diff --git a/matrix_sdk/examples/login.rs b/matrix_sdk/examples/login.rs index ca3276f8..875a3ee9 100644 --- a/matrix_sdk/examples/login.rs +++ b/matrix_sdk/examples/login.rs @@ -38,8 +38,8 @@ impl EventEmitter for EventCallback { async fn login( homeserver_url: String, - username: String, - password: String, + username: &str, + password: &str, ) -> Result<(), matrix_sdk::Error> { let client_config = ClientConfig::new() .proxy("http://localhost:8080")? @@ -50,7 +50,7 @@ async fn login( client.add_event_emitter(Box::new(EventCallback)).await; client - .login(username, password, None, Some("rust-sdk".to_string())) + .login(username, password, None, Some("rust-sdk")) .await?; client.sync_forever(SyncSettings::new(), |_| async {}).await; @@ -73,5 +73,5 @@ async fn main() -> Result<(), matrix_sdk::Error> { } }; - login(homeserver_url, username, password).await + login(homeserver_url, &username, &password).await } diff --git a/matrix_sdk/src/client.rs b/matrix_sdk/src/client.rs index 414a0407..0d05b302 100644 --- a/matrix_sdk/src/client.rs +++ b/matrix_sdk/src/client.rs @@ -57,6 +57,7 @@ use matrix_sdk_common::{ sync::sync_events, typing::create_typing_event, }, + assign, identifiers::ServerName, instant::{Duration, Instant}, js_int::UInt, @@ -80,10 +81,10 @@ use matrix_sdk_common::{ }; use crate::{ - events::{room::message::MessageEventContent, EventType}, + events::{room::message::MessageEventContent, AnyMessageEventContent}, http_client::{DefaultHttpClient, HttpClient, HttpSend}, identifiers::{EventId, RoomId, RoomIdOrAliasId, UserId}, - Endpoint, Error, EventEmitter, Result, + Error, EventEmitter, OutgoingRequest, Result, }; #[cfg(feature = "encryption")] @@ -260,14 +261,14 @@ impl ClientConfig { #[derive(Debug, Default, Clone)] /// Settings for a sync call. -pub struct SyncSettings { - pub(crate) filter: Option, +pub struct SyncSettings<'a> { + pub(crate) filter: Option>, pub(crate) timeout: Option, pub(crate) token: Option, pub(crate) full_state: bool, } -impl SyncSettings { +impl<'a> SyncSettings<'a> { /// Create new default sync settings. pub fn new() -> Self { Default::default() @@ -300,7 +301,7 @@ impl SyncSettings { /// # Arguments /// /// * `filter` - The filter configuration that should be used for the sync call. - pub fn filter(mut self, filter: sync_events::Filter) -> Self { + pub fn filter(mut self, filter: sync_events::Filter<'a>) -> Self { self.filter = Some(filter); self } @@ -467,22 +468,20 @@ impl Client { /// device_id from a previous login call. Note that this should be done /// only if the client also holds the encryption keys for this device. #[instrument(skip(password))] - pub async fn login + Debug>( + pub async fn login( &self, - user: S, - password: S, - device_id: Option, - initial_device_display_name: Option, + user: &str, + password: &str, + device_id: Option<&str>, + initial_device_display_name: Option<&str>, ) -> Result { info!("Logging in to {} as {:?}", self.homeserver, user); let request = login::Request { - user: login::UserInfo::MatrixId(user.into()), - login_info: login::LoginInfo::Password { - password: password.into(), - }, - device_id: device_id.map(|d| d.into().into()), - initial_device_display_name: initial_device_display_name.map(|d| d.into()), + user: login::UserInfo::MatrixId(user), + login_info: login::LoginInfo::Password { password }, + device_id: device_id.map(|d| d.into()), + initial_device_display_name, }; let response = self.send(request).await?; @@ -533,7 +532,7 @@ impl Client { /// # }) /// ``` #[instrument(skip(registration))] - pub async fn register_user>( + pub async fn register_user<'a, R: Into>>( &self, registration: R, ) -> Result { @@ -552,10 +551,7 @@ impl Client { /// /// * `room_id` - The `RoomId` of the room to be joined. pub async fn join_room_by_id(&self, room_id: &RoomId) -> Result { - let request = join_room_by_id::Request { - room_id: room_id.clone(), - third_party_signed: None, - }; + let request = join_room_by_id::Request::new(room_id); self.send(request).await } @@ -575,7 +571,7 @@ impl Client { ) -> Result { let request = join_room_by_id_or_alias::Request { room_id_or_alias: alias.clone(), - server_name: server_names.to_owned(), + server_name: server_names, third_party_signed: None, }; self.send(request).await @@ -589,9 +585,7 @@ impl Client { /// /// * `room_id` - The `RoomId` of the room to be forget. pub async fn forget_room_by_id(&self, room_id: &RoomId) -> Result { - let request = forget_room::Request { - room_id: room_id.clone(), - }; + let request = forget_room::Request::new(room_id); self.send(request).await } @@ -610,13 +604,9 @@ impl Client { &self, room_id: &RoomId, user_id: &UserId, - reason: Option, + reason: Option<&str>, ) -> Result { - let request = ban_user::Request { - reason, - room_id: room_id.clone(), - user_id: user_id.clone(), - }; + let request = assign!(ban_user::Request::new(room_id, user_id), { reason }); self.send(request).await } @@ -635,13 +625,9 @@ impl Client { &self, room_id: &RoomId, user_id: &UserId, - reason: Option, + reason: Option<&str>, ) -> Result { - let request = kick_user::Request { - reason, - room_id: room_id.clone(), - user_id: user_id.clone(), - }; + let request = assign!(kick_user::Request::new(room_id, user_id), { reason }); self.send(request).await } @@ -653,9 +639,7 @@ impl Client { /// /// * `room_id` - The `RoomId` of the room to leave. pub async fn leave_room(&self, room_id: &RoomId) -> Result { - let request = leave_room::Request { - room_id: room_id.clone(), - }; + let request = leave_room::Request::new(room_id); self.send(request).await } @@ -761,7 +745,8 @@ impl Client { /// ``` /// # use std::convert::TryFrom; /// # use matrix_sdk::{Client, RoomListFilterBuilder}; - /// # use matrix_sdk::api::r0::directory::get_public_rooms_filtered::{self, RoomNetwork, Filter}; + /// # use matrix_sdk::directory::{Filter, RoomNetwork}; + /// # use matrix_sdk::api::r0::directory::get_public_rooms_filtered; /// # use url::Url; /// # use futures::executor::block_on; /// # let homeserver = Url::parse("http://example.com").unwrap(); @@ -847,12 +832,10 @@ impl Client { /// # use matrix_sdk::js_int::UInt; /// /// # let homeserver = Url::parse("http://example.com").unwrap(); - /// let mut builder = MessagesRequestBuilder::new( - /// room_id!("!roomid:example.com"), - /// "t47429-4392820_219380_26003_2265".to_string(), - /// ); + /// let room_id = room_id!("!roomid:example.com"); + /// let mut builder = MessagesRequestBuilder::new(&room_id, "t47429-4392820_219380_26003_2265"); /// - /// builder.to("t4357353_219380_26003_2265".to_string()) + /// builder.to("t4357353_219380_26003_2265") /// .direction(Direction::Backward) /// .limit(10); /// @@ -862,7 +845,7 @@ impl Client { /// assert!(client.room_messages(builder).await.is_ok()); /// # }); /// ``` - pub async fn room_messages>( + pub async fn room_messages<'a, R: Into>>( &self, request: R, ) -> Result { @@ -1047,13 +1030,11 @@ impl Client { content: MessageEventContent, txn_id: Option, ) -> Result { - #[allow(unused_mut)] - let mut event_type = EventType::RoomMessage; - #[allow(unused_mut)] - let mut raw_content = serde_json::value::to_raw_value(&content)?; + #[cfg(not(feature = "encryption"))] + let content = AnyMessageEventContent::RoomMessage(content); #[cfg(feature = "encryption")] - { + let content = { let encrypted = { let room = self.base_client.get_joined_room(room_id).await; @@ -1065,21 +1046,17 @@ impl Client { if encrypted { self.preshare_group_session(room_id).await?; - - raw_content = serde_json::value::to_raw_value( - &self.base_client.encrypt(room_id, content).await?, - )?; - event_type = EventType::RoomEncrypted; + AnyMessageEventContent::RoomEncrypted( + self.base_client.encrypt(room_id, content).await?, + ) + } else { + AnyMessageEventContent::RoomMessage(content) } - } - - let request = send_message_event::Request { - room_id: &room_id, - event_type, - txn_id: &txn_id.unwrap_or_else(Uuid::new_v4).to_string(), - data: raw_content, }; + let txn_id = txn_id.unwrap_or_else(Uuid::new_v4).to_string(); + let request = send_message_event::Request::new(&room_id, &txn_id, &content); + let response = self.send(request).await?; Ok(response) } @@ -1124,8 +1101,8 @@ impl Client { /// ``` pub async fn send(&self, request: Request) -> Result where - Request: Endpoint + Debug, - Error: From>, + Request: OutgoingRequest + Debug, + Error: From>, { self.http_client .send(request, self.base_client.session().clone()) @@ -1152,10 +1129,10 @@ impl Client { /// /// * `sync_settings` - Settings for the sync call. #[instrument] - pub async fn sync(&self, sync_settings: SyncSettings) -> Result { + pub async fn sync(&self, sync_settings: SyncSettings<'_>) -> Result { let request = sync_events::Request { filter: sync_settings.filter, - since: sync_settings.token, + since: sync_settings.token.as_deref(), full_state: sync_settings.full_state, set_presence: PresenceState::Online, timeout: sync_settings.timeout, @@ -1228,7 +1205,7 @@ impl Client { #[instrument(skip(callback))] pub async fn sync_forever( &self, - sync_settings: SyncSettings, + sync_settings: SyncSettings<'_>, callback: impl Fn(sync_events::Response) -> C, ) where C: Future, @@ -1559,16 +1536,16 @@ impl Client { #[cfg(test)] mod test { use super::{ - create_typing_event, get_public_rooms, - get_public_rooms_filtered::{self, Filter}, - register::RegistrationKind, - Client, ClientConfig, Invite3pid, MessageEventContent, Session, SyncSettings, Url, + create_typing_event, get_public_rooms, get_public_rooms_filtered, + register::RegistrationKind, Client, ClientConfig, Invite3pid, MessageEventContent, Session, + SyncSettings, Url, }; use crate::{RegistrationBuilder, RoomListFilterBuilder}; use matrix_sdk_base::JsonStore; use matrix_sdk_common::{ api::r0::uiaa::AuthData, + directory::Filter, events::room::message::TextMessageEventContent, identifiers::{event_id, room_id, user_id}, thirdparty, @@ -1778,9 +1755,7 @@ mod test { user.username("user") .password("password") - .auth(AuthData::FallbackAcknowledgement { - session: "foobar".to_string(), - }) + .auth(AuthData::FallbackAcknowledgement { session: "foobar" }) .kind(RegistrationKind::User); if let Err(err) = client.register_user(user).await { diff --git a/matrix_sdk/src/http_client.rs b/matrix_sdk/src/http_client.rs index 2c48a336..f7063256 100644 --- a/matrix_sdk/src/http_client.rs +++ b/matrix_sdk/src/http_client.rs @@ -22,7 +22,7 @@ use url::Url; use matrix_sdk_common::{locks::RwLock, FromHttpResponseError}; use matrix_sdk_common_macros::async_trait; -use crate::{ClientConfig, Endpoint, Error, Result, Session}; +use crate::{ClientConfig, Error, OutgoingRequest, Result, Session}; /// Abstraction around the http layer. The allows implementors to use different /// http libraries. @@ -71,7 +71,7 @@ pub(crate) struct HttpClient { } impl HttpClient { - async fn send_request( + async fn send_request( &self, request: Request, session: Arc>>, @@ -126,8 +126,8 @@ impl HttpClient { session: Arc>>, ) -> Result where - Request: Endpoint, - Error: From>, + Request: OutgoingRequest, + Error: From>, { let response = self.send_request(request, session).await?; diff --git a/matrix_sdk/src/request_builder.rs b/matrix_sdk/src/request_builder.rs index 5793f64c..7ec31036 100644 --- a/matrix_sdk/src/request_builder.rs +++ b/matrix_sdk/src/request_builder.rs @@ -1,7 +1,7 @@ use matrix_sdk_common::{ api::r0::{ account::register::{self, RegistrationKind}, - directory::get_public_rooms_filtered::{self, Filter, RoomNetwork}, + directory::get_public_rooms_filtered, filter::RoomEventFilter, membership::Invite3pid, message::get_message_events::{self, Direction}, @@ -11,6 +11,7 @@ use matrix_sdk_common::{ }, uiaa::AuthData, }, + directory::{Filter, RoomNetwork}, events::room::{create::PreviousRoom, power_levels::PowerLevelsEventContent}, identifiers::{DeviceId, RoomId, UserId}, js_int::UInt, @@ -178,12 +179,10 @@ impl Into for RoomBuilder { /// # let last_sync_token = "".to_string(); /// let mut client = Client::new(homeserver).unwrap(); /// -/// let mut builder = MessagesRequestBuilder::new( -/// room_id!("!roomid:example.com"), -/// "t47429-4392820_219380_26003_2265".to_string(), -/// ); +/// let room_id = room_id!("!roomid:example.com"); +/// let mut builder = MessagesRequestBuilder::new(&room_id, "t47429-4392820_219380_26003_2265"); /// -/// builder.to("t4357353_219380_26003_2265".to_string()) +/// builder.to("t4357353_219380_26003_2265") /// .direction(Direction::Backward) /// .limit(10); /// @@ -191,9 +190,9 @@ impl Into for RoomBuilder { /// # }) /// ``` #[derive(Clone, Debug)] -pub struct MessagesRequestBuilder(get_message_events::Request); +pub struct MessagesRequestBuilder<'a>(get_message_events::Request<'a>); -impl MessagesRequestBuilder { +impl<'a> MessagesRequestBuilder<'a> { /// Create a `MessagesRequestBuilder` builder to make a `get_message_events::Request`. /// /// # Arguments @@ -203,7 +202,7 @@ impl MessagesRequestBuilder { /// * `from` - The token to start returning events from. This token can be obtained from /// a `prev_batch` token from a sync response, or a start or end token from a previous request /// to this endpoint. - pub fn new(room_id: RoomId, from: String) -> Self { + pub fn new(room_id: &'a RoomId, from: &'a str) -> Self { Self(get_message_events::Request::new( room_id, from, @@ -214,8 +213,8 @@ impl MessagesRequestBuilder { /// A `next_batch` token or `start` or `end` from a previous `get_message_events` request. /// /// This token signals when to stop receiving events. - pub fn to>(&mut self, to: S) -> &mut Self { - self.0.to = Some(to.into()); + pub fn to(&mut self, to: &'a str) -> &mut Self { + self.0.to = Some(to); self } @@ -242,8 +241,8 @@ impl MessagesRequestBuilder { } } -impl Into for MessagesRequestBuilder { - fn into(self) -> get_message_events::Request { +impl<'a> Into> for MessagesRequestBuilder<'a> { + fn into(self) -> get_message_events::Request<'a> { self.0 } } @@ -269,17 +268,17 @@ impl Into for MessagesRequestBuilder { /// # }) /// ``` #[derive(Clone, Debug, Default)] -pub struct RegistrationBuilder { - password: Option, - username: Option, - device_id: Option>, - initial_device_display_name: Option, - auth: Option, +pub struct RegistrationBuilder<'a> { + password: Option<&'a str>, + username: Option<&'a str>, + device_id: Option<&'a DeviceId>, + initial_device_display_name: Option<&'a str>, + auth: Option>, kind: Option, inhibit_login: bool, } -impl RegistrationBuilder { +impl<'a> RegistrationBuilder<'a> { /// Create a `RegistrationBuilder` builder to make a `register::Request`. pub fn new() -> Self { Self::default() @@ -289,16 +288,16 @@ impl RegistrationBuilder { /// /// May be empty for accounts that should not be able to log in again /// with a password, e.g., for guest or application service accounts. - pub fn password>(&mut self, password: S) -> &mut Self { - self.password = Some(password.into()); + pub fn password(&mut self, password: &'a str) -> &mut Self { + self.password = Some(password); self } /// local part of the desired Matrix ID. /// /// If omitted, the homeserver MUST generate a Matrix ID local part. - pub fn username>(&mut self, username: S) -> &mut Self { - self.username = Some(username.into()); + pub fn username(&mut self, username: &'a str) -> &mut Self { + self.username = Some(username); self } @@ -306,19 +305,19 @@ impl RegistrationBuilder { /// /// If this does not correspond to a known client device, a new device will be created. /// The server will auto-generate a device_id if this is not specified. - pub fn device_id>>(&mut self, device_id: S) -> &mut Self { - self.device_id = Some(device_id.into()); + pub fn device_id(&mut self, device_id: &'a DeviceId) -> &mut Self { + self.device_id = Some(device_id); self } /// A display name to assign to the newly-created device. /// /// Ignored if `device_id` corresponds to a known device. - pub fn initial_device_display_name>( + pub fn initial_device_display_name( &mut self, - initial_device_display_name: S, + initial_device_display_name: &'a str, ) -> &mut Self { - self.initial_device_display_name = Some(initial_device_display_name.into()); + self.initial_device_display_name = Some(initial_device_display_name); self } @@ -328,7 +327,7 @@ impl RegistrationBuilder { /// authenticated, but is instead used to authenticate the register call itself. /// It should be left empty, or omitted, unless an earlier call returned an response /// with status code 401. - pub fn auth(&mut self, auth: AuthData) -> &mut Self { + pub fn auth(&mut self, auth: AuthData<'a>) -> &mut Self { self.auth = Some(auth); self } @@ -349,8 +348,8 @@ impl RegistrationBuilder { } } -impl Into for RegistrationBuilder { - fn into(self) -> register::Request { +impl<'a> Into> for RegistrationBuilder<'a> { + fn into(self) -> register::Request<'a> { register::Request { password: self.password, username: self.username, @@ -369,7 +368,8 @@ impl Into for RegistrationBuilder { /// ``` /// # use std::convert::TryFrom; /// # use matrix_sdk::{Client, RoomListFilterBuilder}; -/// # use matrix_sdk::api::r0::directory::get_public_rooms_filtered::{self, RoomNetwork, Filter}; +/// # use matrix_sdk::directory::{Filter, RoomNetwork}; +/// # use matrix_sdk::api::r0::directory::get_public_rooms_filtered; /// # use url::Url; /// # let homeserver = Url::parse("http://example.com").unwrap(); /// # let mut rt = tokio::runtime::Runtime::new().unwrap(); @@ -380,7 +380,7 @@ impl Into for RegistrationBuilder { /// let generic_search_term = Some("matrix-rust-sdk".to_string()); /// let mut builder = RoomListFilterBuilder::new(); /// builder -/// .filter(Filter { generic_search_term, }) +/// .filter(Filter { generic_search_term }) /// .since(&last_sync_token) /// .room_network(RoomNetwork::Matrix); /// @@ -529,12 +529,10 @@ mod test { device_id: "DEVICEID".into(), }; - let mut builder = MessagesRequestBuilder::new( - room_id!("!roomid:example.com"), - "t47429-4392820_219380_26003_2265".to_string(), - ); + let room_id = room_id!("!roomid:example.com"); + let mut builder = MessagesRequestBuilder::new(&room_id, "t47429-4392820_219380_26003_2265"); builder - .to("t4357353_219380_26003_2265".to_string()) + .to("t4357353_219380_26003_2265") .direction(Direction::Backward) .limit(10) .filter(RoomEventFilter { diff --git a/matrix_sdk_base/src/models/room.rs b/matrix_sdk_base/src/models/room.rs index d7ee36ce..3015fd8f 100644 --- a/matrix_sdk_base/src/models/room.rs +++ b/matrix_sdk_base/src/models/room.rs @@ -44,10 +44,10 @@ use matrix_sdk_common::{ power_levels::{NotificationPowerLevels, PowerLevelsEventContent}, tombstone::TombstoneEventContent, }, - Algorithm, AnyStrippedStateEvent, AnySyncRoomEvent, AnySyncStateEvent, EventType, - StrippedStateEvent, SyncStateEvent, + AnyStrippedStateEvent, AnySyncRoomEvent, AnySyncStateEvent, EventType, StrippedStateEvent, + SyncStateEvent, }, - identifiers::{RoomAliasId, RoomId, UserId}, + identifiers::{EventEncryptionAlgorithm, RoomAliasId, RoomId, UserId}, js_int::{int, uint, Int, UInt}, }; use serde::{Deserialize, Serialize}; @@ -110,7 +110,7 @@ pub struct PowerLevels { pub struct EncryptionInfo { /// The encryption algorithm that should be used to encrypt messages in the /// room. - algorithm: Algorithm, + algorithm: EventEncryptionAlgorithm, /// How long should a session be used before it is rotated. rotation_period_ms: u64, /// The maximum amount of messages that should be encrypted using the same @@ -121,7 +121,7 @@ pub struct EncryptionInfo { impl Default for EncryptionInfo { fn default() -> Self { Self { - algorithm: Algorithm::MegolmV1AesSha2, + algorithm: EventEncryptionAlgorithm::MegolmV1AesSha2, rotation_period_ms: 604_800_000, rotation_period_messages: 100, } @@ -131,7 +131,7 @@ impl Default for EncryptionInfo { impl EncryptionInfo { /// The encryption algorithm that should be used to encrypt messages in the /// room. - pub fn algorithm(&self) -> &Algorithm { + pub fn algorithm(&self) -> &EventEncryptionAlgorithm { &self.algorithm } @@ -1734,7 +1734,7 @@ mod test { client.restore_login(session).await.unwrap(); client.receive_sync_response(&mut response).await.unwrap(); - let mut content = EncryptionEventContent::new(Algorithm::MegolmV1AesSha2); + let mut content = EncryptionEventContent::new(EventEncryptionAlgorithm::MegolmV1AesSha2); content.rotation_period_ms = Some(100_000u32.into()); content.rotation_period_msgs = Some(100u32.into()); @@ -1757,7 +1757,10 @@ mod test { let room_lock = room.read().await; let encryption_info = room_lock.encryption_info().unwrap(); - assert_eq!(encryption_info.algorithm(), &Algorithm::MegolmV1AesSha2); + assert_eq!( + encryption_info.algorithm(), + &EventEncryptionAlgorithm::MegolmV1AesSha2 + ); assert_eq!(encryption_info.rotation_period(), 100_000); assert_eq!(encryption_info.rotation_period_messages(), 100); } diff --git a/matrix_sdk_common/Cargo.toml b/matrix_sdk_common/Cargo.toml index 531520b6..29060896 100644 --- a/matrix_sdk_common/Cargo.toml +++ b/matrix_sdk_common/Cargo.toml @@ -11,13 +11,14 @@ repository = "https://github.com/matrix-org/matrix-rust-sdk" version = "0.1.0" [dependencies] +assign = "1.1.0" instant = { version = "0.1.6", features = ["wasm-bindgen", "now"] } js_int = "0.1.9" [dependencies.ruma] version = "0.0.1" git = "https://github.com/ruma/ruma" -rev = "9cf552f36186eedff44ebe0c6a32d598315f5860" +rev = "e74158b2626186ce23d4d3c07782e60b3be39434" features = ["client-api", "unstable-pre-spec"] [target.'cfg(not(target_arch = "wasm32"))'.dependencies] diff --git a/matrix_sdk_common/src/lib.rs b/matrix_sdk_common/src/lib.rs index fd8fff5f..bc6430cf 100644 --- a/matrix_sdk_common/src/lib.rs +++ b/matrix_sdk_common/src/lib.rs @@ -1,12 +1,13 @@ +pub use assign::assign; pub use instant; pub use js_int; pub use ruma::{ api::{ client as api, error::{FromHttpRequestError, FromHttpResponseError, IntoHttpError, ServerError}, - Endpoint, EndpointError, Outgoing, + EndpointError, Outgoing, OutgoingRequest, }, - events, identifiers, presence, push, thirdparty, Raw, + directory, encryption, events, identifiers, presence, push, thirdparty, Raw, }; pub use uuid; diff --git a/matrix_sdk_crypto/src/device.rs b/matrix_sdk_crypto/src/device.rs index 029703d8..9e4b88eb 100644 --- a/matrix_sdk_crypto/src/device.rs +++ b/matrix_sdk_crypto/src/device.rs @@ -23,9 +23,9 @@ use std::{ use atomic::Atomic; use matrix_sdk_common::{ - api::r0::keys::{DeviceKeys, SignedKey}, - events::Algorithm, - identifiers::{DeviceId, DeviceKeyAlgorithm, DeviceKeyId, UserId}, + api::r0::keys::SignedKey, + encryption::DeviceKeys, + identifiers::{DeviceId, DeviceKeyAlgorithm, DeviceKeyId, EventEncryptionAlgorithm, UserId}, }; use serde_json::{json, Value}; @@ -39,7 +39,7 @@ use crate::{error::SignatureError, verify_json}; pub struct Device { user_id: Arc, device_id: Arc>, - algorithms: Arc>, + algorithms: Arc>, keys: Arc>, signatures: Arc>>, display_name: Arc>, @@ -79,7 +79,7 @@ impl Device { device_id: Box, display_name: Option, trust_state: TrustState, - algorithms: Vec, + algorithms: Vec, keys: BTreeMap, signatures: BTreeMap>, ) -> Self { @@ -152,7 +152,7 @@ impl Device { } /// Get the list of algorithms this device supports. - pub fn algorithms(&self) -> &[Algorithm] { + pub fn algorithms(&self) -> &[EventEncryptionAlgorithm] { &self.algorithms } @@ -274,7 +274,7 @@ pub(crate) mod test { use crate::device::{Device, TrustState}; use matrix_sdk_common::{ - api::r0::keys::DeviceKeys, + encryption::DeviceKeys, identifiers::{user_id, DeviceKeyAlgorithm}, }; diff --git a/matrix_sdk_crypto/src/machine.rs b/matrix_sdk_crypto/src/machine.rs index d17c2bed..4b0b5966 100644 --- a/matrix_sdk_crypto/src/machine.rs +++ b/matrix_sdk_crypto/src/machine.rs @@ -27,7 +27,7 @@ use serde_json::Value; use tracing::{debug, error, info, instrument, trace, warn}; use api::r0::{ - keys::{claim_keys, get_keys, upload_keys, DeviceKeys, OneTimeKey}, + keys::{claim_keys, get_keys, upload_keys, OneTimeKey}, sync::sync_events::Response as SyncResponse, to_device::{ send_event_to_device::IncomingRequest as OwnedToDeviceRequest, DeviceIdOrAllDevices, @@ -35,14 +35,17 @@ use api::r0::{ }; use matrix_sdk_common::{ api, + encryption::DeviceKeys, events::{ forwarded_room_key::ForwardedRoomKeyEventContent, room::{encrypted::EncryptedEventContent, message::MessageEventContent}, room_key::RoomKeyEventContent, room_key_request::RoomKeyRequestEventContent, - Algorithm, AnySyncRoomEvent, AnyToDeviceEvent, EventType, SyncMessageEvent, ToDeviceEvent, + AnySyncRoomEvent, AnyToDeviceEvent, EventType, SyncMessageEvent, ToDeviceEvent, + }, + identifiers::{ + DeviceId, DeviceKeyAlgorithm, DeviceKeyId, EventEncryptionAlgorithm, RoomId, UserId, }, - identifiers::{DeviceId, DeviceKeyAlgorithm, DeviceKeyId, RoomId, UserId}, uuid::Uuid, Raw, }; @@ -796,7 +799,7 @@ impl OlmMachine { event: &mut ToDeviceEvent, ) -> OlmResult>> { match event.content.algorithm { - Algorithm::MegolmV1AesSha2 => { + EventEncryptionAlgorithm::MegolmV1AesSha2 => { let session_key = GroupSessionKey(mem::take(&mut event.content.session_key)); let session = InboundGroupSession::new( diff --git a/matrix_sdk_crypto/src/olm/account.rs b/matrix_sdk_crypto/src/olm/account.rs index 68bf4690..a41bb93b 100644 --- a/matrix_sdk_crypto/src/olm/account.rs +++ b/matrix_sdk_crypto/src/olm/account.rs @@ -23,9 +23,11 @@ use std::{ }; use matrix_sdk_common::{ - api::r0::keys::{DeviceKeys, OneTimeKey, SignedKey}, - events::Algorithm, - identifiers::{DeviceId, DeviceKeyAlgorithm, DeviceKeyId, RoomId, UserId}, + api::r0::keys::{OneTimeKey, SignedKey}, + encryption::DeviceKeys, + identifiers::{ + DeviceId, DeviceKeyAlgorithm, DeviceKeyId, EventEncryptionAlgorithm, RoomId, UserId, + }, instant::Instant, locks::Mutex, }; @@ -74,9 +76,9 @@ impl fmt::Debug for Account { } impl Account { - const ALGORITHMS: &'static [&'static Algorithm] = &[ - &Algorithm::OlmV1Curve25519AesSha2, - &Algorithm::MegolmV1AesSha2, + const ALGORITHMS: &'static [&'static EventEncryptionAlgorithm] = &[ + &EventEncryptionAlgorithm::OlmV1Curve25519AesSha2, + &EventEncryptionAlgorithm::MegolmV1AesSha2, ]; /// Create a fresh new account, this will generate the identity key-pair. @@ -314,8 +316,8 @@ impl Account { user_id: (*self.user_id).clone(), device_id: (*self.device_id).clone(), algorithms: vec![ - Algorithm::OlmV1Curve25519AesSha2, - Algorithm::MegolmV1AesSha2, + EventEncryptionAlgorithm::OlmV1Curve25519AesSha2, + EventEncryptionAlgorithm::MegolmV1AesSha2, ], keys, signatures, @@ -545,7 +547,7 @@ impl Account { room_id: &RoomId, settings: EncryptionSettings, ) -> Result<(OutboundGroupSession, InboundGroupSession), ()> { - if settings.algorithm != Algorithm::MegolmV1AesSha2 { + if settings.algorithm != EventEncryptionAlgorithm::MegolmV1AesSha2 { return Err(()); } diff --git a/matrix_sdk_crypto/src/olm/group_sessions.rs b/matrix_sdk_crypto/src/olm/group_sessions.rs index 5073934f..a2710c38 100644 --- a/matrix_sdk_crypto/src/olm/group_sessions.rs +++ b/matrix_sdk_crypto/src/olm/group_sessions.rs @@ -28,9 +28,9 @@ use matrix_sdk_common::{ encrypted::EncryptedEventContent, encryption::EncryptionEventContent, message::MessageEventContent, }, - Algorithm, AnySyncRoomEvent, EventType, SyncMessageEvent, + AnySyncRoomEvent, EventType, SyncMessageEvent, }, - identifiers::{DeviceId, RoomId}, + identifiers::{DeviceId, EventEncryptionAlgorithm, RoomId}, instant::Instant, locks::Mutex, Raw, @@ -60,7 +60,7 @@ const ROTATION_MESSAGES: u64 = 100; #[derive(Debug)] pub struct EncryptionSettings { /// The encryption algorithm that should be used in the room. - pub algorithm: Algorithm, + pub algorithm: EventEncryptionAlgorithm, /// How long the session should be used before changing it. pub rotation_period: Duration, /// How many messages should be sent before changing the session. @@ -70,7 +70,7 @@ pub struct EncryptionSettings { impl Default for EncryptionSettings { fn default() -> Self { Self { - algorithm: Algorithm::MegolmV1AesSha2, + algorithm: EventEncryptionAlgorithm::MegolmV1AesSha2, rotation_period: ROTATION_PERIOD, rotation_period_msgs: ROTATION_MESSAGES, } @@ -448,7 +448,7 @@ impl OutboundGroupSession { /// m.room_key. pub async fn as_json(&self) -> Value { json!({ - "algorithm": Algorithm::MegolmV1AesSha2, + "algorithm": EventEncryptionAlgorithm::MegolmV1AesSha2, "room_id": &*self.room_id, "session_id": &*self.session_id, "session_key": self.session_key().await, diff --git a/matrix_sdk_crypto/src/store/sqlite.rs b/matrix_sdk_crypto/src/store/sqlite.rs index ede11f5c..6c5a62ea 100644 --- a/matrix_sdk_crypto/src/store/sqlite.rs +++ b/matrix_sdk_crypto/src/store/sqlite.rs @@ -23,8 +23,9 @@ use std::{ use async_trait::async_trait; use dashmap::DashSet; use matrix_sdk_common::{ - events::Algorithm, - identifiers::{DeviceId, DeviceKeyAlgorithm, DeviceKeyId, RoomId, UserId}, + identifiers::{ + DeviceId, DeviceKeyAlgorithm, DeviceKeyId, EventEncryptionAlgorithm, RoomId, UserId, + }, instant::{Duration, Instant}, locks::Mutex, }; @@ -496,9 +497,9 @@ impl SqliteStore { .iter() .map(|row| { let algorithm: &str = &row.0; - Algorithm::from(algorithm) + EventEncryptionAlgorithm::from(algorithm) }) - .collect::>(); + .collect::>(); let key_rows: Vec<(String, String)> = query_as("SELECT algorithm, key FROM device_keys WHERE device_id = ?")