Merge branch 'up-ruma' into master

This commit is contained in:
Damir Jelić 2020-08-17 11:17:02 +02:00
commit 16a115d27e
16 changed files with 176 additions and 263 deletions

View file

@ -43,8 +43,8 @@ impl EventEmitter for AutoJoinBot {
async fn login_and_sync( async fn login_and_sync(
homeserver_url: String, homeserver_url: String,
username: String, username: &str,
password: String, password: &str,
) -> Result<(), matrix_sdk::Error> { ) -> Result<(), matrix_sdk::Error> {
let mut home = dirs::home_dir().expect("no home directory found"); let mut home = dirs::home_dir().expect("no home directory found");
home.push("autojoin_bot"); 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(); let mut client = Client::new_with_config(homeserver_url, client_config).unwrap();
client client
.login( .login(username, password, None, Some("autojoin bot"))
username.clone(),
password,
None,
Some("autojoin bot".to_string()),
)
.await?; .await?;
println!("logged in as {}", username); 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(()) Ok(())
} }

View file

@ -81,12 +81,7 @@ async fn login_and_sync(
let mut client = Client::new_with_config(homeserver_url, client_config).unwrap(); let mut client = Client::new_with_config(homeserver_url, client_config).unwrap();
client client
.login( .login(&username, &password, None, Some("command bot"))
username.clone(),
password,
None,
Some("command bot".to_string()),
)
.await?; .await?;
println!("logged in as {}", username); println!("logged in as {}", username);

View file

@ -36,15 +36,15 @@ fn print_result(sas: Sas) {
async fn login( async fn login(
homeserver_url: String, homeserver_url: String,
username: String, username: &str,
password: String, password: &str,
) -> Result<(), matrix_sdk::Error> { ) -> Result<(), matrix_sdk::Error> {
let client_config = ClientConfig::new(); let client_config = ClientConfig::new();
let homeserver_url = Url::parse(&homeserver_url).expect("Couldn't parse the homeserver URL"); 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(); let client = Client::new_with_config(homeserver_url, client_config).unwrap();
client client
.login(username, password, None, Some("rust-sdk".to_string())) .login(username, password, None, Some("rust-sdk"))
.await?; .await?;
let client_ref = &client; 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
} }

View file

@ -37,8 +37,8 @@ async fn get_profile(client: Client, mxid: UserId) -> MatrixResult<UserProfile>
async fn login( async fn login(
homeserver_url: String, homeserver_url: String,
username: String, username: &str,
password: String, password: &str,
) -> Result<Client, matrix_sdk::Error> { ) -> Result<Client, matrix_sdk::Error> {
let client_config = ClientConfig::new() let client_config = ClientConfig::new()
.proxy("http://localhost:8080")? .proxy("http://localhost:8080")?
@ -47,7 +47,7 @@ async fn login(
let client = Client::new_with_config(homeserver_url, client_config).unwrap(); let client = Client::new_with_config(homeserver_url, client_config).unwrap();
client client
.login(username, password, None, Some("rust-sdk".to_string())) .login(username, password, None, Some("rust-sdk"))
.await?; .await?;
Ok(client) 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?; let profile = get_profile(client, user_id).await?;
println!("{:#?}", profile); println!("{:#?}", profile);
Ok(()) Ok(())

View file

@ -38,8 +38,8 @@ impl EventEmitter for EventCallback {
async fn login( async fn login(
homeserver_url: String, homeserver_url: String,
username: String, username: &str,
password: String, password: &str,
) -> Result<(), matrix_sdk::Error> { ) -> Result<(), matrix_sdk::Error> {
let client_config = ClientConfig::new() let client_config = ClientConfig::new()
.proxy("http://localhost:8080")? .proxy("http://localhost:8080")?
@ -50,7 +50,7 @@ async fn login(
client.add_event_emitter(Box::new(EventCallback)).await; client.add_event_emitter(Box::new(EventCallback)).await;
client client
.login(username, password, None, Some("rust-sdk".to_string())) .login(username, password, None, Some("rust-sdk"))
.await?; .await?;
client.sync_forever(SyncSettings::new(), |_| async {}).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
} }

View file

@ -57,6 +57,7 @@ use matrix_sdk_common::{
sync::sync_events, sync::sync_events,
typing::create_typing_event, typing::create_typing_event,
}, },
assign,
identifiers::ServerName, identifiers::ServerName,
instant::{Duration, Instant}, instant::{Duration, Instant},
js_int::UInt, js_int::UInt,
@ -80,10 +81,10 @@ use matrix_sdk_common::{
}; };
use crate::{ use crate::{
events::{room::message::MessageEventContent, EventType}, events::{room::message::MessageEventContent, AnyMessageEventContent},
http_client::{DefaultHttpClient, HttpClient, HttpSend}, http_client::{DefaultHttpClient, HttpClient, HttpSend},
identifiers::{EventId, RoomId, RoomIdOrAliasId, UserId}, identifiers::{EventId, RoomId, RoomIdOrAliasId, UserId},
Endpoint, Error, EventEmitter, Result, Error, EventEmitter, OutgoingRequest, Result,
}; };
#[cfg(feature = "encryption")] #[cfg(feature = "encryption")]
@ -260,14 +261,14 @@ impl ClientConfig {
#[derive(Debug, Default, Clone)] #[derive(Debug, Default, Clone)]
/// Settings for a sync call. /// Settings for a sync call.
pub struct SyncSettings { pub struct SyncSettings<'a> {
pub(crate) filter: Option<sync_events::Filter>, pub(crate) filter: Option<sync_events::Filter<'a>>,
pub(crate) timeout: Option<Duration>, pub(crate) timeout: Option<Duration>,
pub(crate) token: Option<String>, pub(crate) token: Option<String>,
pub(crate) full_state: bool, pub(crate) full_state: bool,
} }
impl SyncSettings { impl<'a> SyncSettings<'a> {
/// Create new default sync settings. /// Create new default sync settings.
pub fn new() -> Self { pub fn new() -> Self {
Default::default() Default::default()
@ -300,7 +301,7 @@ impl SyncSettings {
/// # Arguments /// # Arguments
/// ///
/// * `filter` - The filter configuration that should be used for the sync call. /// * `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.filter = Some(filter);
self self
} }
@ -467,22 +468,20 @@ impl Client {
/// device_id from a previous login call. Note that this should be done /// 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. /// only if the client also holds the encryption keys for this device.
#[instrument(skip(password))] #[instrument(skip(password))]
pub async fn login<S: Into<String> + Debug>( pub async fn login(
&self, &self,
user: S, user: &str,
password: S, password: &str,
device_id: Option<S>, device_id: Option<&str>,
initial_device_display_name: Option<S>, initial_device_display_name: Option<&str>,
) -> Result<login::Response> { ) -> Result<login::Response> {
info!("Logging in to {} as {:?}", self.homeserver, user); info!("Logging in to {} as {:?}", self.homeserver, user);
let request = login::Request { let request = login::Request {
user: login::UserInfo::MatrixId(user.into()), user: login::UserInfo::MatrixId(user),
login_info: login::LoginInfo::Password { login_info: login::LoginInfo::Password { password },
password: password.into(), device_id: device_id.map(|d| d.into()),
}, initial_device_display_name,
device_id: device_id.map(|d| d.into().into()),
initial_device_display_name: initial_device_display_name.map(|d| d.into()),
}; };
let response = self.send(request).await?; let response = self.send(request).await?;
@ -533,7 +532,7 @@ impl Client {
/// # }) /// # })
/// ``` /// ```
#[instrument(skip(registration))] #[instrument(skip(registration))]
pub async fn register_user<R: Into<register::Request>>( pub async fn register_user<'a, R: Into<register::Request<'a>>>(
&self, &self,
registration: R, registration: R,
) -> Result<register::Response> { ) -> Result<register::Response> {
@ -552,10 +551,7 @@ impl Client {
/// ///
/// * `room_id` - The `RoomId` of the room to be joined. /// * `room_id` - The `RoomId` of the room to be joined.
pub async fn join_room_by_id(&self, room_id: &RoomId) -> Result<join_room_by_id::Response> { pub async fn join_room_by_id(&self, room_id: &RoomId) -> Result<join_room_by_id::Response> {
let request = join_room_by_id::Request { let request = join_room_by_id::Request::new(room_id);
room_id: room_id.clone(),
third_party_signed: None,
};
self.send(request).await self.send(request).await
} }
@ -575,7 +571,7 @@ impl Client {
) -> Result<join_room_by_id_or_alias::Response> { ) -> Result<join_room_by_id_or_alias::Response> {
let request = join_room_by_id_or_alias::Request { let request = join_room_by_id_or_alias::Request {
room_id_or_alias: alias.clone(), room_id_or_alias: alias.clone(),
server_name: server_names.to_owned(), server_name: server_names,
third_party_signed: None, third_party_signed: None,
}; };
self.send(request).await self.send(request).await
@ -589,9 +585,7 @@ impl Client {
/// ///
/// * `room_id` - The `RoomId` of the room to be forget. /// * `room_id` - The `RoomId` of the room to be forget.
pub async fn forget_room_by_id(&self, room_id: &RoomId) -> Result<forget_room::Response> { pub async fn forget_room_by_id(&self, room_id: &RoomId) -> Result<forget_room::Response> {
let request = forget_room::Request { let request = forget_room::Request::new(room_id);
room_id: room_id.clone(),
};
self.send(request).await self.send(request).await
} }
@ -610,13 +604,9 @@ impl Client {
&self, &self,
room_id: &RoomId, room_id: &RoomId,
user_id: &UserId, user_id: &UserId,
reason: Option<String>, reason: Option<&str>,
) -> Result<ban_user::Response> { ) -> Result<ban_user::Response> {
let request = ban_user::Request { let request = assign!(ban_user::Request::new(room_id, user_id), { reason });
reason,
room_id: room_id.clone(),
user_id: user_id.clone(),
};
self.send(request).await self.send(request).await
} }
@ -635,13 +625,9 @@ impl Client {
&self, &self,
room_id: &RoomId, room_id: &RoomId,
user_id: &UserId, user_id: &UserId,
reason: Option<String>, reason: Option<&str>,
) -> Result<kick_user::Response> { ) -> Result<kick_user::Response> {
let request = kick_user::Request { let request = assign!(kick_user::Request::new(room_id, user_id), { reason });
reason,
room_id: room_id.clone(),
user_id: user_id.clone(),
};
self.send(request).await self.send(request).await
} }
@ -653,9 +639,7 @@ impl Client {
/// ///
/// * `room_id` - The `RoomId` of the room to leave. /// * `room_id` - The `RoomId` of the room to leave.
pub async fn leave_room(&self, room_id: &RoomId) -> Result<leave_room::Response> { pub async fn leave_room(&self, room_id: &RoomId) -> Result<leave_room::Response> {
let request = leave_room::Request { let request = leave_room::Request::new(room_id);
room_id: room_id.clone(),
};
self.send(request).await self.send(request).await
} }
@ -761,7 +745,8 @@ impl Client {
/// ``` /// ```
/// # use std::convert::TryFrom; /// # use std::convert::TryFrom;
/// # use matrix_sdk::{Client, RoomListFilterBuilder}; /// # 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 url::Url;
/// # use futures::executor::block_on; /// # use futures::executor::block_on;
/// # let homeserver = Url::parse("http://example.com").unwrap(); /// # let homeserver = Url::parse("http://example.com").unwrap();
@ -847,12 +832,10 @@ impl Client {
/// # use matrix_sdk::js_int::UInt; /// # use matrix_sdk::js_int::UInt;
/// ///
/// # let homeserver = Url::parse("http://example.com").unwrap(); /// # let homeserver = Url::parse("http://example.com").unwrap();
/// let mut builder = MessagesRequestBuilder::new( /// let room_id = room_id!("!roomid:example.com");
/// room_id!("!roomid:example.com"), /// let mut builder = MessagesRequestBuilder::new(&room_id, "t47429-4392820_219380_26003_2265");
/// "t47429-4392820_219380_26003_2265".to_string(),
/// );
/// ///
/// builder.to("t4357353_219380_26003_2265".to_string()) /// builder.to("t4357353_219380_26003_2265")
/// .direction(Direction::Backward) /// .direction(Direction::Backward)
/// .limit(10); /// .limit(10);
/// ///
@ -862,7 +845,7 @@ impl Client {
/// assert!(client.room_messages(builder).await.is_ok()); /// assert!(client.room_messages(builder).await.is_ok());
/// # }); /// # });
/// ``` /// ```
pub async fn room_messages<R: Into<get_message_events::Request>>( pub async fn room_messages<'a, R: Into<get_message_events::Request<'a>>>(
&self, &self,
request: R, request: R,
) -> Result<get_message_events::Response> { ) -> Result<get_message_events::Response> {
@ -1047,13 +1030,11 @@ impl Client {
content: MessageEventContent, content: MessageEventContent,
txn_id: Option<Uuid>, txn_id: Option<Uuid>,
) -> Result<send_message_event::Response> { ) -> Result<send_message_event::Response> {
#[allow(unused_mut)] #[cfg(not(feature = "encryption"))]
let mut event_type = EventType::RoomMessage; let content = AnyMessageEventContent::RoomMessage(content);
#[allow(unused_mut)]
let mut raw_content = serde_json::value::to_raw_value(&content)?;
#[cfg(feature = "encryption")] #[cfg(feature = "encryption")]
{ let content = {
let encrypted = { let encrypted = {
let room = self.base_client.get_joined_room(room_id).await; let room = self.base_client.get_joined_room(room_id).await;
@ -1065,21 +1046,17 @@ impl Client {
if encrypted { if encrypted {
self.preshare_group_session(room_id).await?; self.preshare_group_session(room_id).await?;
AnyMessageEventContent::RoomEncrypted(
raw_content = serde_json::value::to_raw_value( self.base_client.encrypt(room_id, content).await?,
&self.base_client.encrypt(room_id, content).await?, )
)?; } else {
event_type = EventType::RoomEncrypted; 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?; let response = self.send(request).await?;
Ok(response) Ok(response)
} }
@ -1124,8 +1101,8 @@ impl Client {
/// ``` /// ```
pub async fn send<Request>(&self, request: Request) -> Result<Request::IncomingResponse> pub async fn send<Request>(&self, request: Request) -> Result<Request::IncomingResponse>
where where
Request: Endpoint + Debug, Request: OutgoingRequest + Debug,
Error: From<FromHttpResponseError<Request::ResponseError>>, Error: From<FromHttpResponseError<Request::EndpointError>>,
{ {
self.http_client self.http_client
.send(request, self.base_client.session().clone()) .send(request, self.base_client.session().clone())
@ -1152,10 +1129,10 @@ impl Client {
/// ///
/// * `sync_settings` - Settings for the sync call. /// * `sync_settings` - Settings for the sync call.
#[instrument] #[instrument]
pub async fn sync(&self, sync_settings: SyncSettings) -> Result<sync_events::Response> { pub async fn sync(&self, sync_settings: SyncSettings<'_>) -> Result<sync_events::Response> {
let request = sync_events::Request { let request = sync_events::Request {
filter: sync_settings.filter, filter: sync_settings.filter,
since: sync_settings.token, since: sync_settings.token.as_deref(),
full_state: sync_settings.full_state, full_state: sync_settings.full_state,
set_presence: PresenceState::Online, set_presence: PresenceState::Online,
timeout: sync_settings.timeout, timeout: sync_settings.timeout,
@ -1228,7 +1205,7 @@ impl Client {
#[instrument(skip(callback))] #[instrument(skip(callback))]
pub async fn sync_forever<C>( pub async fn sync_forever<C>(
&self, &self,
sync_settings: SyncSettings, sync_settings: SyncSettings<'_>,
callback: impl Fn(sync_events::Response) -> C, callback: impl Fn(sync_events::Response) -> C,
) where ) where
C: Future<Output = ()>, C: Future<Output = ()>,
@ -1559,11 +1536,8 @@ impl Client {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::{ use super::{
ban_user, create_receipt, create_typing_event, forget_room, get_public_rooms, create_typing_event, get_public_rooms, get_public_rooms_filtered,
get_public_rooms_filtered::{self, Filter}, register::RegistrationKind, Client, ClientConfig, Invite3pid, MessageEventContent, Session,
invite_user, kick_user, leave_room,
register::RegistrationKind,
set_read_marker, Client, ClientConfig, Invite3pid, MessageEventContent, Session,
SyncSettings, Url, SyncSettings, Url,
}; };
use crate::{RegistrationBuilder, RoomListFilterBuilder}; use crate::{RegistrationBuilder, RoomListFilterBuilder};
@ -1571,6 +1545,7 @@ mod test {
use matrix_sdk_base::JsonStore; use matrix_sdk_base::JsonStore;
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::uiaa::AuthData, api::r0::uiaa::AuthData,
directory::Filter,
events::room::message::TextMessageEventContent, events::room::message::TextMessageEventContent,
identifiers::{event_id, room_id, user_id}, identifiers::{event_id, room_id, user_id},
thirdparty, thirdparty,
@ -1780,9 +1755,7 @@ mod test {
user.username("user") user.username("user")
.password("password") .password("password")
.auth(AuthData::FallbackAcknowledgement { .auth(AuthData::FallbackAcknowledgement { session: "foobar" })
session: "foobar".to_string(),
})
.kind(RegistrationKind::User); .kind(RegistrationKind::User);
if let Err(err) = client.register_user(user).await { if let Err(err) = client.register_user(user).await {
@ -1852,7 +1825,6 @@ mod test {
} }
#[tokio::test] #[tokio::test]
#[allow(irrefutable_let_patterns)]
async fn invite_user_by_id() { async fn invite_user_by_id() {
let client = logged_in_client().await; let client = logged_in_client().await;
@ -1868,11 +1840,10 @@ mod test {
let user = user_id!("@example:localhost"); let user = user_id!("@example:localhost");
let room_id = room_id!("!testroom:example.org"); 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] #[tokio::test]
#[allow(irrefutable_let_patterns)]
async fn invite_user_by_3pid() { async fn invite_user_by_3pid() {
let client = logged_in_client().await; let client = logged_in_client().await;
@ -1888,7 +1859,7 @@ mod test {
let room_id = room_id!("!testroom:example.org"); let room_id = room_id!("!testroom:example.org");
if let invite_user::Response = client client
.invite_user_by_3pid( .invite_user_by_3pid(
&room_id, &room_id,
&Invite3pid { &Invite3pid {
@ -1899,12 +1870,10 @@ mod test {
}, },
) )
.await .await
.unwrap() .unwrap();
{}
} }
#[tokio::test] #[tokio::test]
#[allow(irrefutable_let_patterns)]
async fn room_search_all() { async fn room_search_all() {
let homeserver = Url::from_str(&mockito::server_url()).unwrap(); let homeserver = Url::from_str(&mockito::server_url()).unwrap();
let client = Client::new(homeserver).unwrap(); let client = Client::new(homeserver).unwrap();
@ -1917,15 +1886,12 @@ mod test {
.with_body(test_json::PUBLIC_ROOMS.to_string()) .with_body(test_json::PUBLIC_ROOMS.to_string())
.create(); .create();
if let get_public_rooms::Response { chunk, .. } = let get_public_rooms::Response { chunk, .. } =
client.public_rooms(Some(10), None, None).await.unwrap() client.public_rooms(Some(10), None, None).await.unwrap();
{ assert_eq!(chunk.len(), 1);
assert_eq!(chunk.len(), 1)
}
} }
#[tokio::test] #[tokio::test]
#[allow(irrefutable_let_patterns)]
async fn room_search_filtered() { async fn room_search_filtered() {
let client = logged_in_client().await; let client = logged_in_client().await;
@ -1944,15 +1910,12 @@ mod test {
generic_search_term, generic_search_term,
}); });
if let get_public_rooms_filtered::Response { chunk, .. } = let get_public_rooms_filtered::Response { chunk, .. } =
client.public_rooms_filtered(request).await.unwrap() client.public_rooms_filtered(request).await.unwrap();
{ assert_eq!(chunk.len(), 1);
assert_eq!(chunk.len(), 1)
}
} }
#[tokio::test] #[tokio::test]
#[allow(irrefutable_let_patterns)]
async fn leave_room() { async fn leave_room() {
let client = logged_in_client().await; let client = logged_in_client().await;
@ -1968,18 +1931,10 @@ mod test {
let room_id = room_id!("!testroom:example.org"); let room_id = room_id!("!testroom:example.org");
let response = client.leave_room(&room_id).await.unwrap(); client.leave_room(&room_id).await.unwrap();
if let leave_room::Response = response {
} else {
panic!(
"expected `ruma_client_api::leave_room::Response` found {:?}",
response
)
}
} }
#[tokio::test] #[tokio::test]
#[allow(irrefutable_let_patterns)]
async fn ban_user() { async fn ban_user() {
let client = logged_in_client().await; let client = logged_in_client().await;
@ -1995,19 +1950,10 @@ mod test {
let user = user_id!("@example:localhost"); let user = user_id!("@example:localhost");
let room_id = room_id!("!testroom:example.org"); let room_id = room_id!("!testroom:example.org");
let response = client.ban_user(&room_id, &user, None).await.unwrap(); 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
)
}
} }
#[tokio::test] #[tokio::test]
#[allow(irrefutable_let_patterns)]
async fn kick_user() { async fn kick_user() {
let client = logged_in_client().await; let client = logged_in_client().await;
@ -2024,19 +1970,10 @@ mod test {
let user = user_id!("@example:localhost"); let user = user_id!("@example:localhost");
let room_id = room_id!("!testroom:example.org"); let room_id = room_id!("!testroom:example.org");
let response = client.kick_user(&room_id, &user, None).await.unwrap(); 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
)
}
} }
#[tokio::test] #[tokio::test]
#[allow(irrefutable_let_patterns)]
async fn forget_room() { async fn forget_room() {
let client = logged_in_client().await; let client = logged_in_client().await;
@ -2052,18 +1989,10 @@ mod test {
let room_id = room_id!("!testroom:example.org"); let room_id = room_id!("!testroom:example.org");
let response = client.forget_room_by_id(&room_id).await.unwrap(); 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
)
}
} }
#[tokio::test] #[tokio::test]
#[allow(irrefutable_let_patterns)]
async fn read_receipt() { async fn read_receipt() {
let client = logged_in_client().await; let client = logged_in_client().await;
@ -2080,18 +2009,10 @@ mod test {
let room_id = room_id!("!testroom:example.org"); let room_id = room_id!("!testroom:example.org");
let event_id = event_id!("$xxxxxx:example.org"); let event_id = event_id!("$xxxxxx:example.org");
let response = client.read_receipt(&room_id, &event_id).await.unwrap(); 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
)
}
} }
#[tokio::test] #[tokio::test]
#[allow(irrefutable_let_patterns)]
async fn read_marker() { async fn read_marker() {
let client = logged_in_client().await; let client = logged_in_client().await;
@ -2108,14 +2029,7 @@ mod test {
let room_id = room_id!("!testroom:example.org"); let room_id = room_id!("!testroom:example.org");
let event_id = event_id!("$xxxxxx:example.org"); let event_id = event_id!("$xxxxxx:example.org");
let response = client.read_marker(&room_id, &event_id, None).await.unwrap(); 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
)
}
} }
#[tokio::test] #[tokio::test]

View file

@ -22,7 +22,7 @@ use url::Url;
use matrix_sdk_common::{locks::RwLock, FromHttpResponseError}; use matrix_sdk_common::{locks::RwLock, FromHttpResponseError};
use matrix_sdk_common_macros::async_trait; 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 /// Abstraction around the http layer. The allows implementors to use different
/// http libraries. /// http libraries.
@ -71,7 +71,7 @@ pub(crate) struct HttpClient {
} }
impl HttpClient { impl HttpClient {
async fn send_request<Request: Endpoint>( async fn send_request<Request: OutgoingRequest>(
&self, &self,
request: Request, request: Request,
session: Arc<RwLock<Option<Session>>>, session: Arc<RwLock<Option<Session>>>,
@ -126,8 +126,8 @@ impl HttpClient {
session: Arc<RwLock<Option<Session>>>, session: Arc<RwLock<Option<Session>>>,
) -> Result<Request::IncomingResponse> ) -> Result<Request::IncomingResponse>
where where
Request: Endpoint, Request: OutgoingRequest,
Error: From<FromHttpResponseError<Request::ResponseError>>, Error: From<FromHttpResponseError<Request::EndpointError>>,
{ {
let response = self.send_request(request, session).await?; let response = self.send_request(request, session).await?;

View file

@ -1,7 +1,7 @@
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::{ api::r0::{
account::register::{self, RegistrationKind}, account::register::{self, RegistrationKind},
directory::get_public_rooms_filtered::{self, Filter, RoomNetwork}, directory::get_public_rooms_filtered,
filter::RoomEventFilter, filter::RoomEventFilter,
membership::Invite3pid, membership::Invite3pid,
message::get_message_events::{self, Direction}, message::get_message_events::{self, Direction},
@ -11,6 +11,7 @@ use matrix_sdk_common::{
}, },
uiaa::AuthData, uiaa::AuthData,
}, },
directory::{Filter, RoomNetwork},
events::room::{create::PreviousRoom, power_levels::PowerLevelsEventContent}, events::room::{create::PreviousRoom, power_levels::PowerLevelsEventContent},
identifiers::{DeviceId, RoomId, UserId}, identifiers::{DeviceId, RoomId, UserId},
js_int::UInt, js_int::UInt,
@ -178,12 +179,10 @@ impl Into<create_room::Request> for RoomBuilder {
/// # let last_sync_token = "".to_string(); /// # let last_sync_token = "".to_string();
/// let mut client = Client::new(homeserver).unwrap(); /// let mut client = Client::new(homeserver).unwrap();
/// ///
/// let mut builder = MessagesRequestBuilder::new( /// let room_id = room_id!("!roomid:example.com");
/// room_id!("!roomid:example.com"), /// let mut builder = MessagesRequestBuilder::new(&room_id, "t47429-4392820_219380_26003_2265");
/// "t47429-4392820_219380_26003_2265".to_string(),
/// );
/// ///
/// builder.to("t4357353_219380_26003_2265".to_string()) /// builder.to("t4357353_219380_26003_2265")
/// .direction(Direction::Backward) /// .direction(Direction::Backward)
/// .limit(10); /// .limit(10);
/// ///
@ -191,9 +190,9 @@ impl Into<create_room::Request> for RoomBuilder {
/// # }) /// # })
/// ``` /// ```
#[derive(Clone, Debug)] #[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`. /// Create a `MessagesRequestBuilder` builder to make a `get_message_events::Request`.
/// ///
/// # Arguments /// # Arguments
@ -203,7 +202,7 @@ impl MessagesRequestBuilder {
/// * `from` - The token to start returning events from. This token can be obtained from /// * `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 /// a `prev_batch` token from a sync response, or a start or end token from a previous request
/// to this endpoint. /// 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( Self(get_message_events::Request::new(
room_id, room_id,
from, from,
@ -214,8 +213,8 @@ impl MessagesRequestBuilder {
/// A `next_batch` token or `start` or `end` from a previous `get_message_events` request. /// A `next_batch` token or `start` or `end` from a previous `get_message_events` request.
/// ///
/// This token signals when to stop receiving events. /// This token signals when to stop receiving events.
pub fn to<S: Into<String>>(&mut self, to: S) -> &mut Self { pub fn to(&mut self, to: &'a str) -> &mut Self {
self.0.to = Some(to.into()); self.0.to = Some(to);
self self
} }
@ -242,8 +241,8 @@ impl MessagesRequestBuilder {
} }
} }
impl Into<get_message_events::Request> for MessagesRequestBuilder { impl<'a> Into<get_message_events::Request<'a>> for MessagesRequestBuilder<'a> {
fn into(self) -> get_message_events::Request { fn into(self) -> get_message_events::Request<'a> {
self.0 self.0
} }
} }
@ -269,17 +268,17 @@ impl Into<get_message_events::Request> for MessagesRequestBuilder {
/// # }) /// # })
/// ``` /// ```
#[derive(Clone, Debug, Default)] #[derive(Clone, Debug, Default)]
pub struct RegistrationBuilder { pub struct RegistrationBuilder<'a> {
password: Option<String>, password: Option<&'a str>,
username: Option<String>, username: Option<&'a str>,
device_id: Option<Box<DeviceId>>, device_id: Option<&'a DeviceId>,
initial_device_display_name: Option<String>, initial_device_display_name: Option<&'a str>,
auth: Option<AuthData>, auth: Option<AuthData<'a>>,
kind: Option<RegistrationKind>, kind: Option<RegistrationKind>,
inhibit_login: bool, inhibit_login: bool,
} }
impl RegistrationBuilder { impl<'a> RegistrationBuilder<'a> {
/// Create a `RegistrationBuilder` builder to make a `register::Request`. /// Create a `RegistrationBuilder` builder to make a `register::Request`.
pub fn new() -> Self { pub fn new() -> Self {
Self::default() Self::default()
@ -289,16 +288,16 @@ impl RegistrationBuilder {
/// ///
/// May be empty for accounts that should not be able to log in again /// 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. /// with a password, e.g., for guest or application service accounts.
pub fn password<S: Into<String>>(&mut self, password: S) -> &mut Self { pub fn password(&mut self, password: &'a str) -> &mut Self {
self.password = Some(password.into()); self.password = Some(password);
self self
} }
/// local part of the desired Matrix ID. /// local part of the desired Matrix ID.
/// ///
/// If omitted, the homeserver MUST generate a Matrix ID local part. /// If omitted, the homeserver MUST generate a Matrix ID local part.
pub fn username<S: Into<String>>(&mut self, username: S) -> &mut Self { pub fn username(&mut self, username: &'a str) -> &mut Self {
self.username = Some(username.into()); self.username = Some(username);
self self
} }
@ -306,19 +305,19 @@ impl RegistrationBuilder {
/// ///
/// If this does not correspond to a known client device, a new device will be created. /// 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. /// The server will auto-generate a device_id if this is not specified.
pub fn device_id<S: Into<Box<DeviceId>>>(&mut self, device_id: S) -> &mut Self { pub fn device_id(&mut self, device_id: &'a DeviceId) -> &mut Self {
self.device_id = Some(device_id.into()); self.device_id = Some(device_id);
self self
} }
/// A display name to assign to the newly-created device. /// A display name to assign to the newly-created device.
/// ///
/// Ignored if `device_id` corresponds to a known device. /// Ignored if `device_id` corresponds to a known device.
pub fn initial_device_display_name<S: Into<String>>( pub fn initial_device_display_name(
&mut self, &mut self,
initial_device_display_name: S, initial_device_display_name: &'a str,
) -> &mut Self { ) -> &mut Self {
self.initial_device_display_name = Some(initial_device_display_name.into()); self.initial_device_display_name = Some(initial_device_display_name);
self self
} }
@ -328,7 +327,7 @@ impl RegistrationBuilder {
/// authenticated, but is instead used to authenticate the register call itself. /// 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 /// It should be left empty, or omitted, unless an earlier call returned an response
/// with status code 401. /// 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.auth = Some(auth);
self self
} }
@ -349,8 +348,8 @@ impl RegistrationBuilder {
} }
} }
impl Into<register::Request> for RegistrationBuilder { impl<'a> Into<register::Request<'a>> for RegistrationBuilder<'a> {
fn into(self) -> register::Request { fn into(self) -> register::Request<'a> {
register::Request { register::Request {
password: self.password, password: self.password,
username: self.username, username: self.username,
@ -369,7 +368,8 @@ impl Into<register::Request> for RegistrationBuilder {
/// ``` /// ```
/// # use std::convert::TryFrom; /// # use std::convert::TryFrom;
/// # use matrix_sdk::{Client, RoomListFilterBuilder}; /// # 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 url::Url;
/// # let homeserver = Url::parse("http://example.com").unwrap(); /// # let homeserver = Url::parse("http://example.com").unwrap();
/// # let mut rt = tokio::runtime::Runtime::new().unwrap(); /// # let mut rt = tokio::runtime::Runtime::new().unwrap();
@ -380,7 +380,7 @@ impl Into<register::Request> for RegistrationBuilder {
/// let generic_search_term = Some("matrix-rust-sdk".to_string()); /// let generic_search_term = Some("matrix-rust-sdk".to_string());
/// let mut builder = RoomListFilterBuilder::new(); /// let mut builder = RoomListFilterBuilder::new();
/// builder /// builder
/// .filter(Filter { generic_search_term, }) /// .filter(Filter { generic_search_term })
/// .since(&last_sync_token) /// .since(&last_sync_token)
/// .room_network(RoomNetwork::Matrix); /// .room_network(RoomNetwork::Matrix);
/// ///
@ -529,12 +529,10 @@ mod test {
device_id: "DEVICEID".into(), device_id: "DEVICEID".into(),
}; };
let mut builder = MessagesRequestBuilder::new( let room_id = room_id!("!roomid:example.com");
room_id!("!roomid:example.com"), let mut builder = MessagesRequestBuilder::new(&room_id, "t47429-4392820_219380_26003_2265");
"t47429-4392820_219380_26003_2265".to_string(),
);
builder builder
.to("t4357353_219380_26003_2265".to_string()) .to("t4357353_219380_26003_2265")
.direction(Direction::Backward) .direction(Direction::Backward)
.limit(10) .limit(10)
.filter(RoomEventFilter { .filter(RoomEventFilter {

View file

@ -44,10 +44,10 @@ use matrix_sdk_common::{
power_levels::{NotificationPowerLevels, PowerLevelsEventContent}, power_levels::{NotificationPowerLevels, PowerLevelsEventContent},
tombstone::TombstoneEventContent, tombstone::TombstoneEventContent,
}, },
Algorithm, AnyStrippedStateEvent, AnySyncRoomEvent, AnySyncStateEvent, EventType, AnyStrippedStateEvent, AnySyncRoomEvent, AnySyncStateEvent, EventType, StrippedStateEvent,
StrippedStateEvent, SyncStateEvent, SyncStateEvent,
}, },
identifiers::{RoomAliasId, RoomId, UserId}, identifiers::{EventEncryptionAlgorithm, RoomAliasId, RoomId, UserId},
js_int::{int, uint, Int, UInt}, js_int::{int, uint, Int, UInt},
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -110,7 +110,7 @@ pub struct PowerLevels {
pub struct EncryptionInfo { pub struct EncryptionInfo {
/// The encryption algorithm that should be used to encrypt messages in the /// The encryption algorithm that should be used to encrypt messages in the
/// room. /// room.
algorithm: Algorithm, algorithm: EventEncryptionAlgorithm,
/// How long should a session be used before it is rotated. /// How long should a session be used before it is rotated.
rotation_period_ms: u64, rotation_period_ms: u64,
/// The maximum amount of messages that should be encrypted using the same /// The maximum amount of messages that should be encrypted using the same
@ -121,7 +121,7 @@ pub struct EncryptionInfo {
impl Default for EncryptionInfo { impl Default for EncryptionInfo {
fn default() -> Self { fn default() -> Self {
Self { Self {
algorithm: Algorithm::MegolmV1AesSha2, algorithm: EventEncryptionAlgorithm::MegolmV1AesSha2,
rotation_period_ms: 604_800_000, rotation_period_ms: 604_800_000,
rotation_period_messages: 100, rotation_period_messages: 100,
} }
@ -131,7 +131,7 @@ impl Default for EncryptionInfo {
impl EncryptionInfo { impl EncryptionInfo {
/// The encryption algorithm that should be used to encrypt messages in the /// The encryption algorithm that should be used to encrypt messages in the
/// room. /// room.
pub fn algorithm(&self) -> &Algorithm { pub fn algorithm(&self) -> &EventEncryptionAlgorithm {
&self.algorithm &self.algorithm
} }
@ -1734,7 +1734,7 @@ mod test {
client.restore_login(session).await.unwrap(); client.restore_login(session).await.unwrap();
client.receive_sync_response(&mut response).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_ms = Some(100_000u32.into());
content.rotation_period_msgs = Some(100u32.into()); content.rotation_period_msgs = Some(100u32.into());
@ -1757,7 +1757,10 @@ mod test {
let room_lock = room.read().await; let room_lock = room.read().await;
let encryption_info = room_lock.encryption_info().unwrap(); 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(), 100_000);
assert_eq!(encryption_info.rotation_period_messages(), 100); assert_eq!(encryption_info.rotation_period_messages(), 100);
} }

View file

@ -11,13 +11,14 @@ repository = "https://github.com/matrix-org/matrix-rust-sdk"
version = "0.1.0" version = "0.1.0"
[dependencies] [dependencies]
assign = "1.1.0"
instant = { version = "0.1.6", features = ["wasm-bindgen", "now"] } instant = { version = "0.1.6", features = ["wasm-bindgen", "now"] }
js_int = "0.1.9" js_int = "0.1.9"
[dependencies.ruma] [dependencies.ruma]
version = "0.0.1" version = "0.0.1"
git = "https://github.com/ruma/ruma" git = "https://github.com/ruma/ruma"
rev = "9cf552f36186eedff44ebe0c6a32d598315f5860" rev = "e74158b2626186ce23d4d3c07782e60b3be39434"
features = ["client-api", "unstable-pre-spec"] features = ["client-api", "unstable-pre-spec"]
[target.'cfg(not(target_arch = "wasm32"))'.dependencies] [target.'cfg(not(target_arch = "wasm32"))'.dependencies]

View file

@ -1,12 +1,13 @@
pub use assign::assign;
pub use instant; pub use instant;
pub use js_int; pub use js_int;
pub use ruma::{ pub use ruma::{
api::{ api::{
client as api, client as api,
error::{FromHttpRequestError, FromHttpResponseError, IntoHttpError, ServerError}, 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; pub use uuid;

View file

@ -23,9 +23,9 @@ use std::{
use atomic::Atomic; use atomic::Atomic;
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::keys::{DeviceKeys, SignedKey}, api::r0::keys::SignedKey,
events::Algorithm, encryption::DeviceKeys,
identifiers::{DeviceId, DeviceKeyAlgorithm, DeviceKeyId, UserId}, identifiers::{DeviceId, DeviceKeyAlgorithm, DeviceKeyId, EventEncryptionAlgorithm, UserId},
}; };
use serde_json::{json, Value}; use serde_json::{json, Value};
@ -39,7 +39,7 @@ use crate::{error::SignatureError, verify_json};
pub struct Device { pub struct Device {
user_id: Arc<UserId>, user_id: Arc<UserId>,
device_id: Arc<Box<DeviceId>>, device_id: Arc<Box<DeviceId>>,
algorithms: Arc<Vec<Algorithm>>, algorithms: Arc<Vec<EventEncryptionAlgorithm>>,
keys: Arc<BTreeMap<DeviceKeyId, String>>, keys: Arc<BTreeMap<DeviceKeyId, String>>,
signatures: Arc<BTreeMap<UserId, BTreeMap<DeviceKeyId, String>>>, signatures: Arc<BTreeMap<UserId, BTreeMap<DeviceKeyId, String>>>,
display_name: Arc<Option<String>>, display_name: Arc<Option<String>>,
@ -79,7 +79,7 @@ impl Device {
device_id: Box<DeviceId>, device_id: Box<DeviceId>,
display_name: Option<String>, display_name: Option<String>,
trust_state: TrustState, trust_state: TrustState,
algorithms: Vec<Algorithm>, algorithms: Vec<EventEncryptionAlgorithm>,
keys: BTreeMap<DeviceKeyId, String>, keys: BTreeMap<DeviceKeyId, String>,
signatures: BTreeMap<UserId, BTreeMap<DeviceKeyId, String>>, signatures: BTreeMap<UserId, BTreeMap<DeviceKeyId, String>>,
) -> Self { ) -> Self {
@ -152,7 +152,7 @@ impl Device {
} }
/// Get the list of algorithms this device supports. /// Get the list of algorithms this device supports.
pub fn algorithms(&self) -> &[Algorithm] { pub fn algorithms(&self) -> &[EventEncryptionAlgorithm] {
&self.algorithms &self.algorithms
} }
@ -274,7 +274,7 @@ pub(crate) mod test {
use crate::device::{Device, TrustState}; use crate::device::{Device, TrustState};
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::keys::DeviceKeys, encryption::DeviceKeys,
identifiers::{user_id, DeviceKeyAlgorithm}, identifiers::{user_id, DeviceKeyAlgorithm},
}; };

View file

@ -27,7 +27,7 @@ use serde_json::Value;
use tracing::{debug, error, info, instrument, trace, warn}; use tracing::{debug, error, info, instrument, trace, warn};
use api::r0::{ 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, sync::sync_events::Response as SyncResponse,
to_device::{ to_device::{
send_event_to_device::IncomingRequest as OwnedToDeviceRequest, DeviceIdOrAllDevices, send_event_to_device::IncomingRequest as OwnedToDeviceRequest, DeviceIdOrAllDevices,
@ -35,14 +35,17 @@ use api::r0::{
}; };
use matrix_sdk_common::{ use matrix_sdk_common::{
api, api,
encryption::DeviceKeys,
events::{ events::{
forwarded_room_key::ForwardedRoomKeyEventContent, forwarded_room_key::ForwardedRoomKeyEventContent,
room::{encrypted::EncryptedEventContent, message::MessageEventContent}, room::{encrypted::EncryptedEventContent, message::MessageEventContent},
room_key::RoomKeyEventContent, room_key::RoomKeyEventContent,
room_key_request::RoomKeyRequestEventContent, 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, uuid::Uuid,
Raw, Raw,
}; };
@ -796,7 +799,7 @@ impl OlmMachine {
event: &mut ToDeviceEvent<RoomKeyEventContent>, event: &mut ToDeviceEvent<RoomKeyEventContent>,
) -> OlmResult<Option<Raw<AnyToDeviceEvent>>> { ) -> OlmResult<Option<Raw<AnyToDeviceEvent>>> {
match event.content.algorithm { match event.content.algorithm {
Algorithm::MegolmV1AesSha2 => { EventEncryptionAlgorithm::MegolmV1AesSha2 => {
let session_key = GroupSessionKey(mem::take(&mut event.content.session_key)); let session_key = GroupSessionKey(mem::take(&mut event.content.session_key));
let session = InboundGroupSession::new( let session = InboundGroupSession::new(

View file

@ -23,9 +23,11 @@ use std::{
}; };
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::keys::{DeviceKeys, OneTimeKey, SignedKey}, api::r0::keys::{OneTimeKey, SignedKey},
events::Algorithm, encryption::DeviceKeys,
identifiers::{DeviceId, DeviceKeyAlgorithm, DeviceKeyId, RoomId, UserId}, identifiers::{
DeviceId, DeviceKeyAlgorithm, DeviceKeyId, EventEncryptionAlgorithm, RoomId, UserId,
},
instant::Instant, instant::Instant,
locks::Mutex, locks::Mutex,
}; };
@ -74,9 +76,9 @@ impl fmt::Debug for Account {
} }
impl Account { impl Account {
const ALGORITHMS: &'static [&'static Algorithm] = &[ const ALGORITHMS: &'static [&'static EventEncryptionAlgorithm] = &[
&Algorithm::OlmV1Curve25519AesSha2, &EventEncryptionAlgorithm::OlmV1Curve25519AesSha2,
&Algorithm::MegolmV1AesSha2, &EventEncryptionAlgorithm::MegolmV1AesSha2,
]; ];
/// Create a fresh new account, this will generate the identity key-pair. /// Create a fresh new account, this will generate the identity key-pair.
@ -314,8 +316,8 @@ impl Account {
user_id: (*self.user_id).clone(), user_id: (*self.user_id).clone(),
device_id: (*self.device_id).clone(), device_id: (*self.device_id).clone(),
algorithms: vec![ algorithms: vec![
Algorithm::OlmV1Curve25519AesSha2, EventEncryptionAlgorithm::OlmV1Curve25519AesSha2,
Algorithm::MegolmV1AesSha2, EventEncryptionAlgorithm::MegolmV1AesSha2,
], ],
keys, keys,
signatures, signatures,
@ -545,7 +547,7 @@ impl Account {
room_id: &RoomId, room_id: &RoomId,
settings: EncryptionSettings, settings: EncryptionSettings,
) -> Result<(OutboundGroupSession, InboundGroupSession), ()> { ) -> Result<(OutboundGroupSession, InboundGroupSession), ()> {
if settings.algorithm != Algorithm::MegolmV1AesSha2 { if settings.algorithm != EventEncryptionAlgorithm::MegolmV1AesSha2 {
return Err(()); return Err(());
} }

View file

@ -28,9 +28,9 @@ use matrix_sdk_common::{
encrypted::EncryptedEventContent, encryption::EncryptionEventContent, encrypted::EncryptedEventContent, encryption::EncryptionEventContent,
message::MessageEventContent, message::MessageEventContent,
}, },
Algorithm, AnySyncRoomEvent, EventType, SyncMessageEvent, AnySyncRoomEvent, EventType, SyncMessageEvent,
}, },
identifiers::{DeviceId, RoomId}, identifiers::{DeviceId, EventEncryptionAlgorithm, RoomId},
instant::Instant, instant::Instant,
locks::Mutex, locks::Mutex,
Raw, Raw,
@ -60,7 +60,7 @@ const ROTATION_MESSAGES: u64 = 100;
#[derive(Debug)] #[derive(Debug)]
pub struct EncryptionSettings { pub struct EncryptionSettings {
/// The encryption algorithm that should be used in the room. /// 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. /// How long the session should be used before changing it.
pub rotation_period: Duration, pub rotation_period: Duration,
/// How many messages should be sent before changing the session. /// How many messages should be sent before changing the session.
@ -70,7 +70,7 @@ pub struct EncryptionSettings {
impl Default for EncryptionSettings { impl Default for EncryptionSettings {
fn default() -> Self { fn default() -> Self {
Self { Self {
algorithm: Algorithm::MegolmV1AesSha2, algorithm: EventEncryptionAlgorithm::MegolmV1AesSha2,
rotation_period: ROTATION_PERIOD, rotation_period: ROTATION_PERIOD,
rotation_period_msgs: ROTATION_MESSAGES, rotation_period_msgs: ROTATION_MESSAGES,
} }
@ -448,7 +448,7 @@ impl OutboundGroupSession {
/// m.room_key. /// m.room_key.
pub async fn as_json(&self) -> Value { pub async fn as_json(&self) -> Value {
json!({ json!({
"algorithm": Algorithm::MegolmV1AesSha2, "algorithm": EventEncryptionAlgorithm::MegolmV1AesSha2,
"room_id": &*self.room_id, "room_id": &*self.room_id,
"session_id": &*self.session_id, "session_id": &*self.session_id,
"session_key": self.session_key().await, "session_key": self.session_key().await,

View file

@ -23,8 +23,9 @@ use std::{
use async_trait::async_trait; use async_trait::async_trait;
use dashmap::DashSet; use dashmap::DashSet;
use matrix_sdk_common::{ use matrix_sdk_common::{
events::Algorithm, identifiers::{
identifiers::{DeviceId, DeviceKeyAlgorithm, DeviceKeyId, RoomId, UserId}, DeviceId, DeviceKeyAlgorithm, DeviceKeyId, EventEncryptionAlgorithm, RoomId, UserId,
},
instant::{Duration, Instant}, instant::{Duration, Instant},
locks::Mutex, locks::Mutex,
}; };
@ -496,9 +497,9 @@ impl SqliteStore {
.iter() .iter()
.map(|row| { .map(|row| {
let algorithm: &str = &row.0; let algorithm: &str = &row.0;
Algorithm::from(algorithm) EventEncryptionAlgorithm::from(algorithm)
}) })
.collect::<Vec<Algorithm>>(); .collect::<Vec<EventEncryptionAlgorithm>>();
let key_rows: Vec<(String, String)> = let key_rows: Vec<(String, String)> =
query_as("SELECT algorithm, key FROM device_keys WHERE device_id = ?") query_as("SELECT algorithm, key FROM device_keys WHERE device_id = ?")