Merge branch 'up-ruma' into master

master
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(
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(())
}

View File

@ -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);

View File

@ -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
}

View File

@ -37,8 +37,8 @@ async fn get_profile(client: Client, mxid: UserId) -> MatrixResult<UserProfile>
async fn login(
homeserver_url: String,
username: String,
password: String,
username: &str,
password: &str,
) -> Result<Client, matrix_sdk::Error> {
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(())

View File

@ -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
}

View File

@ -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<sync_events::Filter>,
pub struct SyncSettings<'a> {
pub(crate) filter: Option<sync_events::Filter<'a>>,
pub(crate) timeout: Option<Duration>,
pub(crate) token: Option<String>,
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<S: Into<String> + Debug>(
pub async fn login(
&self,
user: S,
password: S,
device_id: Option<S>,
initial_device_display_name: Option<S>,
user: &str,
password: &str,
device_id: Option<&str>,
initial_device_display_name: Option<&str>,
) -> Result<login::Response> {
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<R: Into<register::Request>>(
pub async fn register_user<'a, R: Into<register::Request<'a>>>(
&self,
registration: R,
) -> Result<register::Response> {
@ -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<join_room_by_id::Response> {
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<join_room_by_id_or_alias::Response> {
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<forget_room::Response> {
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<String>,
reason: Option<&str>,
) -> Result<ban_user::Response> {
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<String>,
reason: Option<&str>,
) -> Result<kick_user::Response> {
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<leave_room::Response> {
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<R: Into<get_message_events::Request>>(
pub async fn room_messages<'a, R: Into<get_message_events::Request<'a>>>(
&self,
request: R,
) -> Result<get_message_events::Response> {
@ -1047,13 +1030,11 @@ impl Client {
content: MessageEventContent,
txn_id: Option<Uuid>,
) -> Result<send_message_event::Response> {
#[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<Request>(&self, request: Request) -> Result<Request::IncomingResponse>
where
Request: Endpoint + Debug,
Error: From<FromHttpResponseError<Request::ResponseError>>,
Request: OutgoingRequest + Debug,
Error: From<FromHttpResponseError<Request::EndpointError>>,
{
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<sync_events::Response> {
pub async fn sync(&self, sync_settings: SyncSettings<'_>) -> Result<sync_events::Response> {
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<C>(
&self,
sync_settings: SyncSettings,
sync_settings: SyncSettings<'_>,
callback: impl Fn(sync_events::Response) -> C,
) where
C: Future<Output = ()>,
@ -1559,11 +1536,8 @@ impl Client {
#[cfg(test)]
mod test {
use super::{
ban_user, create_receipt, create_typing_event, forget_room, 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,
create_typing_event, get_public_rooms, get_public_rooms_filtered,
register::RegistrationKind, Client, ClientConfig, Invite3pid, MessageEventContent, Session,
SyncSettings, Url,
};
use crate::{RegistrationBuilder, RoomListFilterBuilder};
@ -1571,6 +1545,7 @@ mod test {
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,
@ -1780,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 {
@ -1852,7 +1825,6 @@ mod test {
}
#[tokio::test]
#[allow(irrefutable_let_patterns)]
async fn invite_user_by_id() {
let client = logged_in_client().await;
@ -1868,11 +1840,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 +1859,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 +1870,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 +1886,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 +1910,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 +1931,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 +1950,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 +1970,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 +1989,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 +2009,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 +2029,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]

View File

@ -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<Request: Endpoint>(
async fn send_request<Request: OutgoingRequest>(
&self,
request: Request,
session: Arc<RwLock<Option<Session>>>,
@ -126,8 +126,8 @@ impl HttpClient {
session: Arc<RwLock<Option<Session>>>,
) -> Result<Request::IncomingResponse>
where
Request: Endpoint,
Error: From<FromHttpResponseError<Request::ResponseError>>,
Request: OutgoingRequest,
Error: From<FromHttpResponseError<Request::EndpointError>>,
{
let response = self.send_request(request, session).await?;

View File

@ -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<create_room::Request> 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<create_room::Request> 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<S: Into<String>>(&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<get_message_events::Request> for MessagesRequestBuilder {
fn into(self) -> get_message_events::Request {
impl<'a> Into<get_message_events::Request<'a>> for MessagesRequestBuilder<'a> {
fn into(self) -> get_message_events::Request<'a> {
self.0
}
}
@ -269,17 +268,17 @@ impl Into<get_message_events::Request> for MessagesRequestBuilder {
/// # })
/// ```
#[derive(Clone, Debug, Default)]
pub struct RegistrationBuilder {
password: Option<String>,
username: Option<String>,
device_id: Option<Box<DeviceId>>,
initial_device_display_name: Option<String>,
auth: Option<AuthData>,
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<AuthData<'a>>,
kind: Option<RegistrationKind>,
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<S: Into<String>>(&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<S: Into<String>>(&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<S: Into<Box<DeviceId>>>(&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<S: Into<String>>(
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<register::Request> for RegistrationBuilder {
fn into(self) -> register::Request {
impl<'a> Into<register::Request<'a>> for RegistrationBuilder<'a> {
fn into(self) -> register::Request<'a> {
register::Request {
password: self.password,
username: self.username,
@ -369,7 +368,8 @@ impl Into<register::Request> 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<register::Request> 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 {

View File

@ -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);
}

View File

@ -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]

View File

@ -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;

View File

@ -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<UserId>,
device_id: Arc<Box<DeviceId>>,
algorithms: Arc<Vec<Algorithm>>,
algorithms: Arc<Vec<EventEncryptionAlgorithm>>,
keys: Arc<BTreeMap<DeviceKeyId, String>>,
signatures: Arc<BTreeMap<UserId, BTreeMap<DeviceKeyId, String>>>,
display_name: Arc<Option<String>>,
@ -79,7 +79,7 @@ impl Device {
device_id: Box<DeviceId>,
display_name: Option<String>,
trust_state: TrustState,
algorithms: Vec<Algorithm>,
algorithms: Vec<EventEncryptionAlgorithm>,
keys: BTreeMap<DeviceKeyId, String>,
signatures: BTreeMap<UserId, BTreeMap<DeviceKeyId, String>>,
) -> 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},
};

View File

@ -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<RoomKeyEventContent>,
) -> OlmResult<Option<Raw<AnyToDeviceEvent>>> {
match event.content.algorithm {
Algorithm::MegolmV1AesSha2 => {
EventEncryptionAlgorithm::MegolmV1AesSha2 => {
let session_key = GroupSessionKey(mem::take(&mut event.content.session_key));
let session = InboundGroupSession::new(

View File

@ -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(());
}

View File

@ -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,

View File

@ -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::<Vec<Algorithm>>();
.collect::<Vec<EventEncryptionAlgorithm>>();
let key_rows: Vec<(String, String)> =
query_as("SELECT algorithm, key FROM device_keys WHERE device_id = ?")