Add rustfmt config file and run over workspace

master
Devin Ragotzy 2021-05-12 06:56:29 -04:00 committed by Devin Ragotzy
parent 9863bc4a1c
commit c85f4d4f0c
71 changed files with 378 additions and 468 deletions

View File

@ -1,5 +1,4 @@
use std::{env, process::exit}; use std::{env, process::exit};
use tokio::time::{sleep, Duration};
use matrix_sdk::{ use matrix_sdk::{
self, async_trait, self, async_trait,
@ -7,6 +6,7 @@ use matrix_sdk::{
room::Room, room::Room,
Client, ClientConfig, EventHandler, SyncSettings, Client, ClientConfig, EventHandler, SyncSettings,
}; };
use tokio::time::{sleep, Duration};
use url::Url; use url::Url;
struct AutoJoinBot { struct AutoJoinBot {

View File

@ -5,12 +5,11 @@ use std::{
sync::atomic::{AtomicBool, Ordering}, sync::atomic::{AtomicBool, Ordering},
}; };
use serde_json::json;
use url::Url;
use matrix_sdk::{ use matrix_sdk::{
self, api::r0::uiaa::AuthData, identifiers::UserId, Client, LoopCtrl, SyncSettings, self, api::r0::uiaa::AuthData, identifiers::UserId, Client, LoopCtrl, SyncSettings,
}; };
use serde_json::json;
use url::Url;
fn auth_data<'a>(user: &UserId, password: &str, session: Option<&'a str>) -> AuthData<'a> { fn auth_data<'a>(user: &UserId, password: &str, session: Option<&'a str>) -> AuthData<'a> {
let mut auth_parameters = BTreeMap::new(); let mut auth_parameters = BTreeMap::new();

View File

@ -6,7 +6,6 @@ use std::{
Arc, Arc,
}, },
}; };
use url::Url;
use matrix_sdk::{ use matrix_sdk::{
self, self,
@ -14,6 +13,7 @@ use matrix_sdk::{
identifiers::UserId, identifiers::UserId,
Client, LoopCtrl, Sas, SyncSettings, Client, LoopCtrl, Sas, SyncSettings,
}; };
use url::Url;
async fn wait_for_confirmation(client: Client, sas: Sas) { async fn wait_for_confirmation(client: Client, sas: Sas) {
println!("Does the emoji match: {:?}", sas.emoji()); println!("Does the emoji match: {:?}", sas.emoji());

View File

@ -1,13 +1,12 @@
use std::{convert::TryFrom, env, process::exit}; use std::{convert::TryFrom, env, process::exit};
use url::Url;
use matrix_sdk::{ use matrix_sdk::{
self, self,
api::r0::profile, api::r0::profile,
identifiers::{MxcUri, UserId}, identifiers::{MxcUri, UserId},
Client, Result as MatrixResult, Client, Result as MatrixResult,
}; };
use url::Url;
#[derive(Debug)] #[derive(Debug)]
struct UserProfile { struct UserProfile {

View File

@ -6,7 +6,6 @@ use std::{
process::exit, process::exit,
sync::Arc, sync::Arc,
}; };
use tokio::sync::Mutex;
use matrix_sdk::{ use matrix_sdk::{
self, async_trait, self, async_trait,
@ -17,6 +16,7 @@ use matrix_sdk::{
room::Room, room::Room,
Client, EventHandler, SyncSettings, Client, EventHandler, SyncSettings,
}; };
use tokio::sync::Mutex;
use url::Url; use url::Url;
struct ImageBot { struct ImageBot {

View File

@ -1,5 +1,4 @@
use std::{env, process::exit}; use std::{env, process::exit};
use url::Url;
use matrix_sdk::{ use matrix_sdk::{
self, async_trait, self, async_trait,
@ -10,6 +9,7 @@ use matrix_sdk::{
room::Room, room::Room,
Client, EventHandler, SyncSettings, Client, EventHandler, SyncSettings,
}; };
use url::Url;
struct EventCallback; struct EventCallback;

View File

@ -35,6 +35,15 @@ use futures_timer::Delay as sleep;
use http::HeaderValue; use http::HeaderValue;
#[cfg(feature = "sso_login")] #[cfg(feature = "sso_login")]
use http::Response; use http::Response;
#[cfg(feature = "encryption")]
use matrix_sdk_base::crypto::{
decrypt_key_export, encrypt_key_export, olm::InboundGroupSession, store::CryptoStoreError,
OutgoingRequests, RoomMessageRequest, ToDeviceRequest,
};
use matrix_sdk_base::{
deserialized_responses::SyncResponse, events::AnyMessageEventContent, identifiers::MxcUri,
BaseClient, BaseClientConfig, SendAccessToken, Session, Store,
};
use mime::{self, Mime}; use mime::{self, Mime};
#[cfg(feature = "sso_login")] #[cfg(feature = "sso_login")]
use rand::{thread_rng, Rng}; use rand::{thread_rng, Rng};
@ -43,27 +52,15 @@ use reqwest::header::InvalidHeaderValue;
use tokio::{net::TcpListener, sync::oneshot}; use tokio::{net::TcpListener, sync::oneshot};
#[cfg(feature = "sso_login")] #[cfg(feature = "sso_login")]
use tokio_stream::wrappers::TcpListenerStream; use tokio_stream::wrappers::TcpListenerStream;
#[cfg(feature = "encryption")]
use tracing::{debug, warn};
use tracing::{error, info, instrument};
use url::Url; use url::Url;
#[cfg(feature = "sso_login")] #[cfg(feature = "sso_login")]
use warp::Filter; use warp::Filter;
#[cfg(feature = "encryption")] #[cfg(feature = "encryption")]
use zeroize::Zeroizing; use zeroize::Zeroizing;
#[cfg(feature = "encryption")]
use tracing::{debug, warn};
use tracing::{error, info, instrument};
use matrix_sdk_base::{
deserialized_responses::SyncResponse, events::AnyMessageEventContent, identifiers::MxcUri,
BaseClient, BaseClientConfig, SendAccessToken, Session, Store,
};
#[cfg(feature = "encryption")]
use matrix_sdk_base::crypto::{
decrypt_key_export, encrypt_key_export, olm::InboundGroupSession, store::CryptoStoreError,
OutgoingRequests, RoomMessageRequest, ToDeviceRequest,
};
/// Enum controlling if a loop running callbacks should continue or abort. /// Enum controlling if a loop running callbacks should continue or abort.
/// ///
/// This is mainly used in the [`sync_with_callback`] method, the return value /// This is mainly used in the [`sync_with_callback`] method, the return value
@ -96,12 +93,11 @@ use matrix_sdk_common::{
assign, assign,
identifiers::{DeviceIdBox, RoomId, RoomIdOrAliasId, ServerName, UserId}, identifiers::{DeviceIdBox, RoomId, RoomIdOrAliasId, ServerName, UserId},
instant::{Duration, Instant}, instant::{Duration, Instant},
locks::RwLock, locks::{Mutex, RwLock},
presence::PresenceState, presence::PresenceState,
uuid::Uuid, uuid::Uuid,
FromHttpResponseError, UInt, FromHttpResponseError, UInt,
}; };
#[cfg(feature = "encryption")] #[cfg(feature = "encryption")]
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::{ api::r0::{
@ -113,15 +109,6 @@ use matrix_sdk_common::{
identifiers::EventId, identifiers::EventId,
}; };
use matrix_sdk_common::locks::Mutex;
use crate::{
error::HttpError,
event_handler::Handler,
http_client::{client_with_config, HttpClient, HttpSend},
room, Error, EventHandler, OutgoingRequest, Result,
};
#[cfg(feature = "encryption")] #[cfg(feature = "encryption")]
use crate::{ use crate::{
device::{Device, UserDevices}, device::{Device, UserDevices},
@ -129,6 +116,12 @@ use crate::{
sas::Sas, sas::Sas,
verification_request::VerificationRequest, verification_request::VerificationRequest,
}; };
use crate::{
error::HttpError,
event_handler::Handler,
http_client::{client_with_config, HttpClient, HttpSend},
room, Error, EventHandler, OutgoingRequest, Result,
};
const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(10); const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
const DEFAULT_SYNC_TIMEOUT: Duration = Duration::from_secs(30); const DEFAULT_SYNC_TIMEOUT: Duration = Duration::from_secs(30);
@ -374,8 +367,7 @@ impl<'a> SyncSettings<'a> {
/// This does nothing if no sync token is set. /// This does nothing if no sync token is set.
/// ///
/// # Arguments /// # Arguments
/// * `full_state` - A boolean deciding if the server should return the full /// * `full_state` - A boolean deciding if the server should return the full state or not.
/// state or not.
pub fn full_state(mut self, full_state: bool) -> Self { pub fn full_state(mut self, full_state: bool) -> Self {
self.full_state = full_state; self.full_state = full_state;
self self
@ -440,8 +432,8 @@ impl RequestConfig {
Default::default() Default::default()
} }
/// This is a convince method to disable the retries of a request. Setting the `retry_limit` to `0` /// This is a convince method to disable the retries of a request. Setting the `retry_limit` to
/// has the same effect. /// `0` has the same effect.
pub fn disable_retry(mut self) -> Self { pub fn disable_retry(mut self) -> Self {
self.retry_limit = Some(0); self.retry_limit = Some(0);
self self
@ -459,7 +451,8 @@ impl RequestConfig {
self self
} }
/// Set a timeout for how long a request should be retried. The default is no timeout, meaning requests are retried forever. /// Set a timeout for how long a request should be retried. The default is no timeout, meaning
/// requests are retried forever.
pub fn retry_timeout(mut self, retry_timeout: Duration) -> Self { pub fn retry_timeout(mut self, retry_timeout: Duration) -> Self {
self.retry_timeout = Some(retry_timeout); self.retry_timeout = Some(retry_timeout);
self self
@ -877,8 +870,7 @@ impl Client {
/// ///
/// # Arguments /// # Arguments
/// ///
/// * `redirect_url` - The URL that will receive a `loginToken` after a /// * `redirect_url` - The URL that will receive a `loginToken` after a successful SSO login.
/// successful SSO login.
/// ///
/// [`login_with_token`]: #method.login_with_token /// [`login_with_token`]: #method.login_with_token
pub fn get_sso_login_url(&self, redirect_url: &str) -> Result<String> { pub fn get_sso_login_url(&self, redirect_url: &str) -> Result<String> {
@ -908,10 +900,10 @@ impl Client {
/// ///
/// * `password` - The password of the user. /// * `password` - The password of the user.
/// ///
/// * `device_id` - A unique id that will be associated with this session. If /// * `device_id` - A unique id that will be associated with this session. If not given the
/// not given the homeserver will create one. Can be an existing /// homeserver will create one. Can be an existing device_id from a previous login call. Note
/// device_id from a previous login call. Note that this should be done /// that this should be done only if the client also holds the encryption keys for this
/// only if the client also holds the encryption keys for this device. /// device.
/// ///
/// # Example /// # Example
/// ```no_run /// ```no_run
@ -986,27 +978,24 @@ impl Client {
/// ///
/// # Arguments /// # Arguments
/// ///
/// * `use_sso_login_url` - A callback that will receive the SSO Login URL. It /// * `use_sso_login_url` - A callback that will receive the SSO Login URL. It should usually be
/// should usually be used to open the SSO URL in a browser and must return /// used to open the SSO URL in a browser and must return `Ok(())` if the URL was successfully
/// `Ok(())` if the URL was successfully opened. If it returns `Err`, the /// opened. If it returns `Err`, the error will be forwarded.
/// error will be forwarded.
/// ///
/// * `server_url` - The local URL the server is going to try to bind to, e.g. /// * `server_url` - The local URL the server is going to try to bind to, e.g. `http://localhost:3030`.
/// `http://localhost:3030`. If `None`, the server will try to open a random /// If `None`, the server will try to open a random port on localhost.
/// port on localhost.
/// ///
/// * `server_response` - The text that will be shown on the webpage at the end /// * `server_response` - The text that will be shown on the webpage at the end of the login
/// of the login process. This can be an HTML page. If `None`, a default /// process. This can be an HTML page. If `None`, a default text will be displayed.
/// text will be displayed.
/// ///
/// * `device_id` - A unique id that will be associated with this session. If /// * `device_id` - A unique id that will be associated with this session. If not given the
/// not given the homeserver will create one. Can be an existing device_id /// homeserver will create one. Can be an existing device_id from a previous login call. Note
/// from a previous login call. Note that this should be provided only /// that this should be provided only if the client also holds the encryption keys for this
/// if the client also holds the encryption keys for this device. /// device.
/// ///
/// * `initial_device_display_name` - A public display name that will be /// * `initial_device_display_name` - A public display name that will be associated with the
/// associated with the device_id. Only necessary the first time you /// device_id. Only necessary the first time you login with this device_id. It can be changed
/// login with this device_id. It can be changed later. /// later.
/// ///
/// # Example /// # Example
/// ```no_run /// ```no_run
@ -1172,14 +1161,14 @@ impl Client {
/// ///
/// * `token` - A login token. /// * `token` - A login token.
/// ///
/// * `device_id` - A unique id that will be associated with this session. If /// * `device_id` - A unique id that will be associated with this session. If not given the
/// not given the homeserver will create one. Can be an existing device_id /// homeserver will create one. Can be an existing device_id from a previous login call. Note
/// from a previous login call. Note that this should be provided only /// that this should be provided only if the client also holds the encryption keys for this
/// if the client also holds the encryption keys for this device. /// device.
/// ///
/// * `initial_device_display_name` - A public display name that will be /// * `initial_device_display_name` - A public display name that will be associated with the
/// associated with the device_id. Only necessary the first time you /// device_id. Only necessary the first time you login with this device_id. It can be changed
/// login with this device_id. It can be changed later. /// later.
/// ///
/// # Example /// # Example
/// ```no_run /// ```no_run
@ -1853,8 +1842,8 @@ impl Client {
/// ///
/// # Arguments /// # Arguments
/// ///
/// * `sync_settings` - Settings for the sync call. Note that those settings /// * `sync_settings` - Settings for the sync call. Note that those settings will be only used
/// will be only used for the first sync call. /// for the first sync call.
/// ///
/// [`sync_with_callback`]: #method.sync_with_callback /// [`sync_with_callback`]: #method.sync_with_callback
pub async fn sync(&self, sync_settings: SyncSettings<'_>) { pub async fn sync(&self, sync_settings: SyncSettings<'_>) {
@ -1866,14 +1855,13 @@ impl Client {
/// ///
/// # Arguments /// # Arguments
/// ///
/// * `sync_settings` - Settings for the sync call. Note that those settings /// * `sync_settings` - Settings for the sync call. Note that those settings will be only used
/// will be only used for the first sync call. /// for the first sync call.
/// ///
/// * `callback` - A callback that will be called every time a successful /// * `callback` - A callback that will be called every time a successful response has been
/// response has been fetched from the server. The callback must return /// fetched from the server. The callback must return a boolean which signalizes if the method
/// a boolean which signalizes if the method should stop syncing. If the /// should stop syncing. If the callback returns `LoopCtrl::Continue` the sync will continue,
/// callback returns `LoopCtrl::Continue` the sync will continue, if the /// if the callback returns `LoopCtrl::Break` the sync will be stopped.
/// callback returns `LoopCtrl::Break` the sync will be stopped.
/// ///
/// # Examples /// # Examples
/// ///
@ -2035,7 +2023,6 @@ impl Client {
/// # Arguments /// # Arguments
/// ///
/// * `users` - The list of user/device pairs that we should claim keys for. /// * `users` - The list of user/device pairs that we should claim keys for.
///
#[cfg(feature = "encryption")] #[cfg(feature = "encryption")]
#[cfg_attr(feature = "docs", doc(cfg(encryption)))] #[cfg_attr(feature = "docs", doc(cfg(encryption)))]
#[instrument(skip(users))] #[instrument(skip(users))]
@ -2453,12 +2440,8 @@ impl Client {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use crate::{ClientConfig, HttpError, RequestConfig, RoomMember}; use std::{collections::BTreeMap, convert::TryInto, io::Cursor, str::FromStr, time::Duration};
use super::{
get_public_rooms, get_public_rooms_filtered, register::RegistrationKind, Client, Session,
SyncSettings, Url,
};
use matrix_sdk_base::identifiers::mxc_uri; use matrix_sdk_base::identifiers::mxc_uri;
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::{ api::r0::{
@ -2476,7 +2459,11 @@ mod test {
use mockito::{mock, Matcher}; use mockito::{mock, Matcher};
use serde_json::json; use serde_json::json;
use std::{collections::BTreeMap, convert::TryInto, io::Cursor, str::FromStr, time::Duration}; use super::{
get_public_rooms, get_public_rooms_filtered, register::RegistrationKind, Client, Session,
SyncSettings, Url,
};
use crate::{ClientConfig, HttpError, RequestConfig, RoomMember};
async fn logged_in_client() -> Client { async fn logged_in_client() -> Client {
let session = Session { let session = Session {
@ -2834,7 +2821,8 @@ mod test {
let room_id = room_id!("!testroom:example.org"); let room_id = room_id!("!testroom:example.org");
assert_eq!( assert_eq!(
// this is the `join_by_room_id::Response` but since no PartialEq we check the RoomId field // this is the `join_by_room_id::Response` but since no PartialEq we check the RoomId
// field
client.join_room_by_id(&room_id).await.unwrap().room_id, client.join_room_by_id(&room_id).await.unwrap().room_id,
room_id room_id
); );
@ -2856,7 +2844,8 @@ mod test {
let room_id = room_id!("!testroom:example.org").into(); let room_id = room_id!("!testroom:example.org").into();
assert_eq!( assert_eq!(
// this is the `join_by_room_id::Response` but since no PartialEq we check the RoomId field // this is the `join_by_room_id::Response` but since no PartialEq we check the RoomId
// field
client client
.join_room_by_id_or_alias(&room_id, &["server.com".try_into().unwrap()]) .join_room_by_id_or_alias(&room_id, &["server.com".try_into().unwrap()])
.await .await

View File

@ -14,7 +14,11 @@
//! Error conditions. //! Error conditions.
use std::io::Error as IoError;
use http::StatusCode; use http::StatusCode;
#[cfg(feature = "encryption")]
use matrix_sdk_base::crypto::store::CryptoStoreError;
use matrix_sdk_base::{Error as MatrixError, StoreError}; use matrix_sdk_base::{Error as MatrixError, StoreError};
use matrix_sdk_common::{ use matrix_sdk_common::{
api::{ api::{
@ -26,12 +30,8 @@ use matrix_sdk_common::{
}; };
use reqwest::Error as ReqwestError; use reqwest::Error as ReqwestError;
use serde_json::Error as JsonError; use serde_json::Error as JsonError;
use std::io::Error as IoError;
use thiserror::Error; use thiserror::Error;
#[cfg(feature = "encryption")]
use matrix_sdk_base::crypto::store::CryptoStoreError;
/// Result type of the rust-sdk. /// Result type of the rust-sdk.
pub type Result<T> = std::result::Result<T, Error>; pub type Result<T> = std::result::Result<T, Error>;

View File

@ -56,7 +56,6 @@ use crate::{
room::Room, room::Room,
Client, Client,
}; };
use matrix_sdk_common::async_trait;
pub(crate) struct Handler { pub(crate) struct Handler {
pub(crate) inner: Box<dyn EventHandler>, pub(crate) inner: Box<dyn EventHandler>,
@ -341,8 +340,8 @@ pub enum CustomEvent<'c> {
StrippedState(&'c StrippedStateEvent<CustomEventContent>), StrippedState(&'c StrippedStateEvent<CustomEventContent>),
} }
/// This trait allows any type implementing `EventHandler` to specify event callbacks for each event. /// This trait allows any type implementing `EventHandler` to specify event callbacks for each
/// The `Client` calls each method when the corresponding event is received. /// event. The `Client` calls each method when the corresponding event is received.
/// ///
/// # Examples /// # Examples
/// ``` /// ```
@ -539,15 +538,16 @@ pub trait EventHandler: Send + Sync {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::*; use std::{sync::Arc, time::Duration};
use matrix_sdk_common::{async_trait, locks::Mutex}; use matrix_sdk_common::{async_trait, locks::Mutex};
use matrix_sdk_test::{async_test, test_json}; use matrix_sdk_test::{async_test, test_json};
use mockito::{mock, Matcher}; use mockito::{mock, Matcher};
use std::{sync::Arc, time::Duration};
#[cfg(target_arch = "wasm32")] #[cfg(target_arch = "wasm32")]
pub use wasm_bindgen_test::*; pub use wasm_bindgen_test::*;
use super::*;
#[derive(Clone)] #[derive(Clone)]
pub struct EvHandlerTest(Arc<Mutex<Vec<String>>>); pub struct EvHandlerTest(Arc<Mutex<Vec<String>>>);
@ -656,7 +656,8 @@ mod test {
async fn on_stripped_state_name(&self, _: Room, _: &StrippedStateEvent<NameEventContent>) { async fn on_stripped_state_name(&self, _: Room, _: &StrippedStateEvent<NameEventContent>) {
self.0.lock().await.push("stripped state name".to_string()) self.0.lock().await.push("stripped state name".to_string())
} }
/// Fires when `Client` receives a `AnyStrippedStateEvent::StrippedRoomCanonicalAlias` event. /// Fires when `Client` receives a `AnyStrippedStateEvent::StrippedRoomCanonicalAlias`
/// event.
async fn on_stripped_state_canonical_alias( async fn on_stripped_state_canonical_alias(
&self, &self,
_: Room, _: Room,

View File

@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
#[cfg(all(not(target_arch = "wasm32")))]
use std::sync::atomic::{AtomicU64, Ordering};
use std::{convert::TryFrom, fmt::Debug, sync::Arc}; use std::{convert::TryFrom, fmt::Debug, sync::Arc};
#[cfg(all(not(target_arch = "wasm32")))] #[cfg(all(not(target_arch = "wasm32")))]
@ -19,16 +21,13 @@ use backoff::{future::retry, Error as RetryError, ExponentialBackoff};
#[cfg(all(not(target_arch = "wasm32")))] #[cfg(all(not(target_arch = "wasm32")))]
use http::StatusCode; use http::StatusCode;
use http::{HeaderValue, Response as HttpResponse}; use http::{HeaderValue, Response as HttpResponse};
use reqwest::{Client, Response};
#[cfg(all(not(target_arch = "wasm32")))]
use std::sync::atomic::{AtomicU64, Ordering};
use tracing::trace;
use url::Url;
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::media::create_content, async_trait, locks::RwLock, AsyncTraitDeps, AuthScheme, api::r0::media::create_content, async_trait, locks::RwLock, AsyncTraitDeps, AuthScheme,
FromHttpResponseError, IncomingResponse, SendAccessToken, FromHttpResponseError, IncomingResponse, SendAccessToken,
}; };
use reqwest::{Client, Response};
use tracing::trace;
use url::Url;
use crate::{ use crate::{
error::HttpError, Bytes, BytesMut, ClientConfig, OutgoingRequest, RequestConfig, Session, error::HttpError, Bytes, BytesMut, ClientConfig, OutgoingRequest, RequestConfig, Session,

View File

@ -71,6 +71,7 @@ compile_error!("only one of 'native-tls' or 'rustls-tls' features can be enabled
#[cfg(all(feature = "sso_login", target_arch = "wasm32"))] #[cfg(all(feature = "sso_login", target_arch = "wasm32"))]
compile_error!("'sso_login' cannot be enabled on 'wasm32' arch"); compile_error!("'sso_login' cannot be enabled on 'wasm32' arch");
pub use bytes::{Bytes, BytesMut};
#[cfg(feature = "encryption")] #[cfg(feature = "encryption")]
#[cfg_attr(feature = "docs", doc(cfg(encryption)))] #[cfg_attr(feature = "docs", doc(cfg(encryption)))]
pub use matrix_sdk_base::crypto::{EncryptionInfo, LocalTrust}; pub use matrix_sdk_base::crypto::{EncryptionInfo, LocalTrust};
@ -78,8 +79,6 @@ pub use matrix_sdk_base::{
Error as BaseError, Room as BaseRoom, RoomInfo, RoomMember as BaseRoomMember, RoomType, Error as BaseError, Room as BaseRoom, RoomInfo, RoomMember as BaseRoomMember, RoomType,
Session, StateChanges, StoreError, Session, StateChanges, StoreError,
}; };
pub use bytes::{Bytes, BytesMut};
pub use matrix_sdk_common::*; pub use matrix_sdk_common::*;
pub use reqwest; pub use reqwest;

View File

@ -1,3 +1,5 @@
use std::{ops::Deref, sync::Arc};
use matrix_sdk_base::{deserialized_responses::MembersResponse, identifiers::UserId}; use matrix_sdk_base::{deserialized_responses::MembersResponse, identifiers::UserId};
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::{ api::r0::{
@ -8,8 +10,6 @@ use matrix_sdk_common::{
locks::Mutex, locks::Mutex,
}; };
use std::{ops::Deref, sync::Arc};
use crate::{BaseRoom, Client, Result, RoomMember}; use crate::{BaseRoom, Client, Result, RoomMember};
/// A struct containing methodes that are common for Joined, Invited and Left Rooms /// A struct containing methodes that are common for Joined, Invited and Left Rooms
@ -295,7 +295,6 @@ impl Common {
/// ///
/// * `user_id` - The ID of the user that should be fetched out of the /// * `user_id` - The ID of the user that should be fetched out of the
/// store. /// store.
///
pub async fn get_member_no_sync(&self, user_id: &UserId) -> Result<Option<RoomMember>> { pub async fn get_member_no_sync(&self, user_id: &UserId) -> Result<Option<RoomMember>> {
Ok(self Ok(self
.inner .inner

View File

@ -1,6 +1,7 @@
use crate::{room::Common, BaseRoom, Client, Result, RoomType};
use std::ops::Deref; use std::ops::Deref;
use crate::{room::Common, BaseRoom, Client, Result, RoomType};
/// A room in the invited state. /// A room in the invited state.
/// ///
/// This struct contains all methodes specific to a `Room` with type `RoomType::Invited`. /// This struct contains all methodes specific to a `Room` with type `RoomType::Invited`.

View File

@ -1,9 +1,11 @@
use crate::{room::Common, BaseRoom, Client, Result, RoomType}; #[cfg(feature = "encryption")]
use std::sync::Arc;
use std::{io::Read, ops::Deref}; use std::{io::Read, ops::Deref};
#[cfg(feature = "encryption")] #[cfg(feature = "encryption")]
use std::sync::Arc; use matrix_sdk_base::crypto::AttachmentEncryptor;
#[cfg(feature = "encryption")]
use matrix_sdk_common::locks::Mutex;
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::{ api::r0::{
membership::{ membership::{
@ -34,18 +36,12 @@ use matrix_sdk_common::{
receipt::ReceiptType, receipt::ReceiptType,
uuid::Uuid, uuid::Uuid,
}; };
use mime::{self, Mime}; use mime::{self, Mime};
#[cfg(feature = "encryption")]
use matrix_sdk_common::locks::Mutex;
#[cfg(feature = "encryption")]
use matrix_sdk_base::crypto::AttachmentEncryptor;
#[cfg(feature = "encryption")] #[cfg(feature = "encryption")]
use tracing::instrument; use tracing::instrument;
use crate::{room::Common, BaseRoom, Client, Result, RoomType};
const TYPING_NOTICE_TIMEOUT: Duration = Duration::from_secs(4); const TYPING_NOTICE_TIMEOUT: Duration = Duration::from_secs(4);
const TYPING_NOTICE_RESEND_TIMEOUT: Duration = Duration::from_secs(3); const TYPING_NOTICE_RESEND_TIMEOUT: Duration = Duration::from_secs(3);
@ -149,9 +145,9 @@ impl Joined {
/// Activate typing notice for this room. /// Activate typing notice for this room.
/// ///
/// The typing notice remains active for 4s. It can be deactivate at any point by setting /// The typing notice remains active for 4s. It can be deactivate at any point by setting
/// typing to `false`. If this method is called while the typing notice is active nothing will happen. /// typing to `false`. If this method is called while the typing notice is active nothing will
/// This method can be called on every key stroke, since it will do nothing while typing is /// happen. This method can be called on every key stroke, since it will do nothing while
/// active. /// typing is active.
/// ///
/// # Arguments /// # Arguments
/// ///

View File

@ -1,8 +1,9 @@
use crate::{room::Common, BaseRoom, Client, Result, RoomType};
use std::ops::Deref; use std::ops::Deref;
use matrix_sdk_common::api::r0::membership::forget_room; use matrix_sdk_common::api::r0::membership::forget_room;
use crate::{room::Common, BaseRoom, Client, Result, RoomType};
/// A room in the left state. /// A room in the left state.
/// ///
/// This struct contains all methodes specific to a `Room` with type `RoomType::Left`. /// This struct contains all methodes specific to a `Room` with type `RoomType::Left`.

View File

@ -1,7 +1,7 @@
use matrix_sdk_common::api::r0::media::{get_content, get_content_thumbnail};
use std::ops::Deref; use std::ops::Deref;
use matrix_sdk_common::api::r0::media::{get_content, get_content_thumbnail};
use crate::{BaseRoomMember, Client, Result}; use crate::{BaseRoomMember, Client, Result};
/// The high-level `RoomMember` representation /// The high-level `RoomMember` representation

View File

@ -17,6 +17,7 @@ use std::{
pin::Pin, pin::Pin,
}; };
pub use actix_web::Scope;
use actix_web::{ use actix_web::{
dev::Payload, dev::Payload,
error::PayloadError, error::PayloadError,
@ -30,8 +31,6 @@ use futures::Future;
use futures_util::{TryFutureExt, TryStreamExt}; use futures_util::{TryFutureExt, TryStreamExt};
use matrix_sdk::api_appservice as api; use matrix_sdk::api_appservice as api;
pub use actix_web::Scope;
use crate::{error::Error, Appservice}; use crate::{error::Error, Appservice};
pub async fn run_server( pub async fn run_server(

View File

@ -18,7 +18,8 @@
//! * ship with functionality to configure your webserver crate or simply run the webserver for you //! * ship with functionality to configure your webserver crate or simply run the webserver for you
//! * receive and validate requests from the homeserver correctly //! * receive and validate requests from the homeserver correctly
//! * allow calling the homeserver with proper virtual user identity assertion //! * allow calling the homeserver with proper virtual user identity assertion
//! * have the goal to have a consistent room state available by leveraging the stores that the matrix-sdk provides //! * have the goal to have a consistent room state available by leveraging the stores that the
//! matrix-sdk provides
//! //!
//! # Quickstart //! # Quickstart
//! //!
@ -62,6 +63,8 @@ use std::{
}; };
use http::Uri; use http::Uri;
#[doc(inline)]
pub use matrix_sdk::api_appservice as api;
use matrix_sdk::{ use matrix_sdk::{
api::{ api::{
error::ErrorKind, error::ErrorKind,
@ -81,9 +84,6 @@ use regex::Regex;
use tracing::error; use tracing::error;
use tracing::warn; use tracing::warn;
#[doc(inline)]
pub use matrix_sdk::api_appservice as api;
#[cfg(feature = "actix")] #[cfg(feature = "actix")]
mod actix; mod actix;
mod error; mod error;

View File

@ -1,8 +1,9 @@
#[cfg(feature = "actix")] #[cfg(feature = "actix")]
mod actix { mod actix {
use std::env;
use actix_web::{test, App}; use actix_web::{test, App};
use matrix_sdk_appservice::*; use matrix_sdk_appservice::*;
use std::env;
async fn appservice() -> Appservice { async fn appservice() -> Appservice {
env::set_var( env::set_var(
@ -109,7 +110,8 @@ mod actix {
let resp = test::call_service(&app, req).await; let resp = test::call_service(&app, req).await;
// TODO: this should actually return a 401 but is 500 because something in the extractor fails // TODO: this should actually return a 401 but is 500 because something in the extractor
// fails
assert_eq!(resp.status(), 500); assert_eq!(resp.status(), 500);
} }
} }

View File

@ -1,12 +1,15 @@
use std::{convert::TryFrom, fmt::Debug, sync::Arc}; use std::{convert::TryFrom, fmt::Debug, sync::Arc};
use futures::executor::block_on;
use serde::Serialize;
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
use atty::Stream; use atty::Stream;
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
use clap::{App as Argparse, AppSettings as ArgParseSettings, Arg, ArgMatches, SubCommand}; use clap::{App as Argparse, AppSettings as ArgParseSettings, Arg, ArgMatches, SubCommand};
use futures::executor::block_on;
use matrix_sdk_base::{
events::EventType,
identifiers::{RoomId, UserId},
RoomInfo, Store,
};
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
use rustyline::{ use rustyline::{
completion::{Completer, Pair}, completion::{Completer, Pair},
@ -18,7 +21,7 @@ use rustyline::{
}; };
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
use rustyline_derive::Helper; use rustyline_derive::Helper;
use serde::Serialize;
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
use syntect::{ use syntect::{
dumps::from_binary, dumps::from_binary,
@ -28,12 +31,6 @@ use syntect::{
util::{as_24_bit_terminal_escaped, LinesWithEndings}, util::{as_24_bit_terminal_escaped, LinesWithEndings},
}; };
use matrix_sdk_base::{
events::EventType,
identifiers::{RoomId, UserId},
RoomInfo, Store,
};
#[derive(Clone)] #[derive(Clone)]
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
struct Inspector { struct Inspector {

View File

@ -1223,11 +1223,10 @@ impl BaseClient {
/// ///
/// # Arguments /// # Arguments
/// ///
/// * `flow_id` - The unique id that identifies a interactive verification /// * `flow_id` - The unique id that identifies a interactive verification flow. For in-room
/// flow. For in-room verifications this will be the event id of the /// verifications this will be the event id of the *m.key.verification.request* event that
/// *m.key.verification.request* event that started the flow, for the /// started the flow, for the to-device verification flows this will be the transaction id of
/// to-device verification flows this will be the transaction id of the /// the *m.key.verification.start* event.
/// *m.key.verification.start* event.
#[cfg(feature = "encryption")] #[cfg(feature = "encryption")]
#[cfg_attr(feature = "docs", doc(cfg(encryption)))] #[cfg_attr(feature = "docs", doc(cfg(encryption)))]
pub async fn get_verification(&self, flow_id: &str) -> Option<Sas> { pub async fn get_verification(&self, flow_id: &str) -> Option<Sas> {

View File

@ -15,12 +15,12 @@
//! Error conditions. //! Error conditions.
use serde_json::Error as JsonError;
use std::io::Error as IoError; use std::io::Error as IoError;
use thiserror::Error;
#[cfg(feature = "encryption")] #[cfg(feature = "encryption")]
use matrix_sdk_crypto::{CryptoStoreError, MegolmError, OlmError}; use matrix_sdk_crypto::{CryptoStoreError, MegolmError, OlmError};
use serde_json::Error as JsonError;
use thiserror::Error;
/// Result type of the rust-sdk. /// Result type of the rust-sdk.
pub type Result<T, E = Error> = std::result::Result<T, E>; pub type Result<T, E = Error> = std::result::Result<T, E>;

View File

@ -36,11 +36,12 @@
)] )]
#![cfg_attr(feature = "docs", feature(doc_cfg))] #![cfg_attr(feature = "docs", feature(doc_cfg))]
pub use matrix_sdk_common::*;
pub use crate::{ pub use crate::{
error::{Error, Result}, error::{Error, Result},
session::Session, session::Session,
}; };
pub use matrix_sdk_common::*;
mod client; mod client;
mod error; mod error;
@ -48,11 +49,9 @@ mod rooms;
mod session; mod session;
mod store; mod store;
pub use rooms::{Room, RoomInfo, RoomMember, RoomType};
pub use store::{StateChanges, StateStore, Store, StoreError};
pub use client::{BaseClient, BaseClientConfig}; pub use client::{BaseClient, BaseClientConfig};
#[cfg(feature = "encryption")] #[cfg(feature = "encryption")]
#[cfg_attr(feature = "docs", doc(cfg(encryption)))] #[cfg_attr(feature = "docs", doc(cfg(encryption)))]
pub use matrix_sdk_crypto as crypto; pub use matrix_sdk_crypto as crypto;
pub use rooms::{Room, RoomInfo, RoomMember, RoomType};
pub use store::{StateChanges, StateStore, Store, StoreError};

View File

@ -1,27 +1,22 @@
mod members; mod members;
mod normal; mod normal;
use matrix_sdk_common::{
events::room::{
create::CreateEventContent, guest_access::GuestAccess,
history_visibility::HistoryVisibility, join_rules::JoinRule,
},
identifiers::{MxcUri, UserId},
};
pub use normal::{Room, RoomInfo, RoomType};
pub use members::RoomMember;
use serde::{Deserialize, Serialize};
use std::cmp::max; use std::cmp::max;
use matrix_sdk_common::{ use matrix_sdk_common::{
events::{ events::{
room::{encryption::EncryptionEventContent, tombstone::TombstoneEventContent}, room::{
create::CreateEventContent, encryption::EncryptionEventContent,
guest_access::GuestAccess, history_visibility::HistoryVisibility, join_rules::JoinRule,
tombstone::TombstoneEventContent,
},
AnyStateEventContent, AnyStateEventContent,
}, },
identifiers::RoomAliasId, identifiers::{MxcUri, RoomAliasId, UserId},
}; };
pub use members::RoomMember;
pub use normal::{Room, RoomInfo, RoomType};
use serde::{Deserialize, Serialize};
/// A base room info struct that is the backbone of normal as well as stripped /// A base room info struct that is the backbone of normal as well as stripped
/// rooms. Holds all the state events that are important to present a room to /// rooms. Holds all the state events that are important to present a room to

View File

@ -37,13 +37,12 @@ use matrix_sdk_common::{
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tracing::info; use tracing::info;
use super::{BaseRoomInfo, RoomMember};
use crate::{ use crate::{
deserialized_responses::UnreadNotificationsCount, deserialized_responses::UnreadNotificationsCount,
store::{Result as StoreResult, StateStore}, store::{Result as StoreResult, StateStore},
}; };
use super::{BaseRoomInfo, RoomMember};
/// The underlying room data structure collecting state for joined, left and invtied rooms. /// The underlying room data structure collecting state for joined, left and invtied rooms.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Room { pub struct Room {

View File

@ -15,9 +15,8 @@
//! User sessions. //! User sessions.
use serde::{Deserialize, Serialize};
use matrix_sdk_common::identifiers::{DeviceId, UserId}; use matrix_sdk_common::identifiers::{DeviceId, UserId};
use serde::{Deserialize, Serialize};
/// A user session, containing an access token and information about the /// A user session, containing an access token and information about the
/// associated user account. /// associated user account.

View File

@ -19,12 +19,10 @@ use matrix_sdk_common::{
events::room::member::MembershipState, events::room::member::MembershipState,
identifiers::{EventId, RoomId, UserId}, identifiers::{EventId, RoomId, UserId},
}; };
use tracing::trace; use tracing::trace;
use crate::Store;
use super::{Result, StateChanges}; use super::{Result, StateChanges};
use crate::Store;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct AmbiguityCache { pub struct AmbiguityCache {

View File

@ -30,12 +30,10 @@ use matrix_sdk_common::{
instant::Instant, instant::Instant,
Raw, Raw,
}; };
use tracing::info; use tracing::info;
use crate::deserialized_responses::{MemberEvent, StrippedMemberEvent};
use super::{Result, RoomInfo, StateChanges, StateStore}; use super::{Result, RoomInfo, StateChanges, StateStore};
use crate::deserialized_responses::{MemberEvent, StrippedMemberEvent};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct MemoryStore { pub struct MemoryStore {

View File

@ -12,15 +12,14 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
#[cfg(feature = "sled_state_store")]
use std::path::Path;
use std::{ use std::{
collections::{BTreeMap, BTreeSet}, collections::{BTreeMap, BTreeSet},
ops::Deref, ops::Deref,
sync::Arc, sync::Arc,
}; };
#[cfg(feature = "sled_state_store")]
use std::path::Path;
use dashmap::DashMap; use dashmap::DashMap;
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::push::get_notifications::Notification, api::r0::push::get_notifications::Notification,
@ -359,7 +358,8 @@ impl Deref for Store {
pub struct StateChanges { pub struct StateChanges {
/// The sync token that relates to this update. /// The sync token that relates to this update.
pub sync_token: Option<String>, pub sync_token: Option<String>,
/// A user session, containing an access token and information about the associated user account. /// A user session, containing an access token and information about the associated user
/// account.
pub session: Option<Session>, pub session: Option<Session>,
/// A mapping of event type string to `AnyBasicEvent`. /// A mapping of event type string to `AnyBasicEvent`.
pub account_data: BTreeMap<String, Raw<AnyGlobalAccountDataEvent>>, pub account_data: BTreeMap<String, Raw<AnyGlobalAccountDataEvent>>,
@ -378,7 +378,8 @@ pub struct StateChanges {
/// A map of `RoomId` to `RoomInfo`. /// A map of `RoomId` to `RoomInfo`.
pub room_infos: BTreeMap<RoomId, RoomInfo>, pub room_infos: BTreeMap<RoomId, RoomInfo>,
/// A mapping of `RoomId` to a map of event type to a map of state key to `AnyStrippedStateEvent`. /// A mapping of `RoomId` to a map of event type to a map of state key to
/// `AnyStrippedStateEvent`.
pub stripped_state: pub stripped_state:
BTreeMap<RoomId, BTreeMap<String, BTreeMap<String, Raw<AnyStrippedStateEvent>>>>, BTreeMap<RoomId, BTreeMap<String, BTreeMap<String, Raw<AnyStrippedStateEvent>>>>,
/// A mapping of `RoomId` to a map of users and their `StrippedMemberEvent`. /// A mapping of `RoomId` to a map of users and their `StrippedMemberEvent`.

View File

@ -37,18 +37,15 @@ use matrix_sdk_common::{
Raw, Raw,
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sled::{ use sled::{
transaction::{ConflictableTransactionError, TransactionError}, transaction::{ConflictableTransactionError, TransactionError},
Config, Db, Transactional, Tree, Config, Db, Transactional, Tree,
}; };
use tracing::info; use tracing::info;
use crate::deserialized_responses::MemberEvent;
use self::store_key::{EncryptedEvent, StoreKey}; use self::store_key::{EncryptedEvent, StoreKey};
use super::{Result, RoomInfo, StateChanges, StateStore, StoreError}; use super::{Result, RoomInfo, StateChanges, StateStore, StoreError};
use crate::deserialized_responses::MemberEvent;
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub enum DatabaseType { pub enum DatabaseType {

View File

@ -21,11 +21,10 @@ use chacha20poly1305::{
use hmac::Hmac; use hmac::Hmac;
use pbkdf2::pbkdf2; use pbkdf2::pbkdf2;
use rand::{thread_rng, Error as RngError, Fill}; use rand::{thread_rng, Error as RngError, Fill};
use serde::{Deserialize, Serialize};
use sha2::Sha256; use sha2::Sha256;
use zeroize::{Zeroize, Zeroizing}; use zeroize::{Zeroize, Zeroizing};
use serde::{Deserialize, Serialize};
use crate::StoreError; use crate::StoreError;
const VERSION: u8 = 1; const VERSION: u8 = 1;
@ -248,9 +247,10 @@ impl StoreKey {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::StoreKey;
use serde_json::{json, Value}; use serde_json::{json, Value};
use super::StoreKey;
#[test] #[test]
fn generating() { fn generating() {
StoreKey::new().unwrap(); StoreKey::new().unwrap();

View File

@ -1,3 +1,5 @@
use std::{collections::BTreeMap, convert::TryFrom, time::SystemTime};
use ruma::{ use ruma::{
api::client::r0::sync::sync_events::{ api::client::r0::sync::sync_events::{
Ephemeral, InvitedRoom, Presence, RoomAccountData, State, ToDevice, Ephemeral, InvitedRoom, Presence, RoomAccountData, State, ToDevice,
@ -6,7 +8,6 @@ use ruma::{
DeviceIdBox, DeviceIdBox,
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, convert::TryFrom, time::SystemTime};
use super::{ use super::{
api::r0::{ api::r0::{

View File

@ -6,14 +6,12 @@ use std::{
task::{Context, Poll}, task::{Context, Poll},
}; };
#[cfg(not(target_arch = "wasm32"))]
pub use tokio::spawn;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_futures::spawn_local;
#[cfg(target_arch = "wasm32")] #[cfg(target_arch = "wasm32")]
use futures::{future::RemoteHandle, Future, FutureExt}; use futures::{future::RemoteHandle, Future, FutureExt};
#[cfg(not(target_arch = "wasm32"))]
pub use tokio::spawn;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_futures::spawn_local;
#[cfg(target_arch = "wasm32")] #[cfg(target_arch = "wasm32")]
pub fn spawn<F, T>(future: F) -> JoinHandle<T> pub fn spawn<F, T>(future: F) -> JoinHandle<T>

View File

@ -17,7 +17,6 @@ pub use ruma::{
serde::{CanonicalJsonValue, Raw}, serde::{CanonicalJsonValue, Raw},
thirdparty, uint, Int, Outgoing, UInt, thirdparty, uint, Int, Outgoing, UInt,
}; };
pub use uuid; pub use uuid;
pub mod deserialized_responses; pub mod deserialized_responses;

View File

@ -4,6 +4,5 @@
#[cfg(target_arch = "wasm32")] #[cfg(target_arch = "wasm32")]
pub use futures_locks::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard}; pub use futures_locks::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
pub use tokio::sync::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard}; pub use tokio::sync::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};

View File

@ -4,7 +4,6 @@ mod perf;
use std::sync::Arc; use std::sync::Arc;
use criterion::*; use criterion::*;
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::{ api::r0::{
keys::{claim_keys, get_keys}, keys::{claim_keys, get_keys},

View File

@ -17,21 +17,17 @@ use std::{
io::{Error as IoError, ErrorKind, Read}, io::{Error as IoError, ErrorKind, Read},
}; };
use thiserror::Error;
use zeroize::Zeroizing;
use serde::{Deserialize, Serialize};
use matrix_sdk_common::events::room::JsonWebKey;
use getrandom::getrandom;
use aes_ctr::{ use aes_ctr::{
cipher::{NewStreamCipher, SyncStreamCipher}, cipher::{NewStreamCipher, SyncStreamCipher},
Aes256Ctr, Aes256Ctr,
}; };
use base64::DecodeError; use base64::DecodeError;
use getrandom::getrandom;
use matrix_sdk_common::events::room::JsonWebKey;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use thiserror::Error;
use zeroize::Zeroizing;
use crate::utilities::{decode, decode_url_safe, encode, encode_url_safe}; use crate::utilities::{decode, decode_url_safe, encode, encode_url_safe};
@ -274,10 +270,12 @@ pub struct EncryptionInfo {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::{AttachmentDecryptor, AttachmentEncryptor, EncryptionInfo};
use serde_json::json;
use std::io::{Cursor, Read}; use std::io::{Cursor, Read};
use serde_json::json;
use super::{AttachmentDecryptor, AttachmentEncryptor, EncryptionInfo};
const EXAMPLE_DATA: &[u8] = &[ const EXAMPLE_DATA: &[u8] = &[
179, 154, 118, 127, 186, 127, 110, 33, 203, 33, 33, 134, 67, 100, 173, 46, 235, 27, 215, 179, 154, 118, 127, 186, 127, 110, 33, 203, 33, 33, 134, 67, 100, 173, 46, 235, 27, 215,
172, 36, 26, 75, 47, 33, 160, 172, 36, 26, 75, 47, 33, 160,

View File

@ -12,20 +12,19 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use serde_json::Error as SerdeError;
use std::io::{Cursor, Read, Seek, SeekFrom}; use std::io::{Cursor, Read, Seek, SeekFrom};
use thiserror::Error;
use byteorder::{BigEndian, ReadBytesExt};
use getrandom::getrandom;
use aes_ctr::{ use aes_ctr::{
cipher::{NewStreamCipher, SyncStreamCipher}, cipher::{NewStreamCipher, SyncStreamCipher},
Aes256Ctr, Aes256Ctr,
}; };
use byteorder::{BigEndian, ReadBytesExt};
use getrandom::getrandom;
use hmac::{Hmac, Mac, NewMac}; use hmac::{Hmac, Mac, NewMac};
use pbkdf2::pbkdf2; use pbkdf2::pbkdf2;
use serde_json::Error as SerdeError;
use sha2::{Sha256, Sha512}; use sha2::{Sha256, Sha512};
use thiserror::Error;
use crate::{ use crate::{
olm::ExportedRoomKey, olm::ExportedRoomKey,
@ -231,12 +230,12 @@ fn decrypt_helper(ciphertext: &str, passphrase: &str) -> Result<String, KeyExpor
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use indoc::indoc;
use proptest::prelude::*;
use std::io::Cursor; use std::io::Cursor;
use indoc::indoc;
use matrix_sdk_common::identifiers::room_id; use matrix_sdk_common::identifiers::room_id;
use matrix_sdk_test::async_test; use matrix_sdk_test::async_test;
use proptest::prelude::*;
use super::{decode, decrypt_helper, decrypt_key_export, encrypt_helper, encrypt_key_export}; use super::{decode, decrypt_helper, decrypt_key_export, encrypt_helper, encrypt_key_export};
use crate::machine::test::get_prepared_machine; use crate::machine::test::get_prepared_machine;

View File

@ -39,24 +39,17 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::{json, Value}; use serde_json::{json, Value};
use tracing::warn; use tracing::warn;
use crate::{ use super::{atomic_bool_deserializer, atomic_bool_serializer};
olm::{InboundGroupSession, PrivateCrossSigningIdentity, Session},
store::{Changes, DeviceChanges},
OutgoingVerificationRequest,
};
#[cfg(test)]
use crate::{OlmMachine, ReadOnlyAccount};
use crate::{ use crate::{
error::{EventError, OlmError, OlmResult, SignatureError}, error::{EventError, OlmError, OlmResult, SignatureError},
identities::{OwnUserIdentity, UserIdentities}, identities::{OwnUserIdentity, UserIdentities},
olm::Utility, olm::{InboundGroupSession, PrivateCrossSigningIdentity, Session, Utility},
store::{CryptoStore, Result as StoreResult}, store::{Changes, CryptoStore, DeviceChanges, Result as StoreResult},
verification::VerificationMachine, verification::VerificationMachine,
Sas, ToDeviceRequest, OutgoingVerificationRequest, Sas, ToDeviceRequest,
}; };
#[cfg(test)]
use super::{atomic_bool_deserializer, atomic_bool_serializer}; use crate::{OlmMachine, ReadOnlyAccount};
/// A read-only version of a `Device`. /// A read-only version of a `Device`.
#[derive(Clone, Serialize, Deserialize)] #[derive(Clone, Serialize, Deserialize)]
@ -590,14 +583,15 @@ impl PartialEq for ReadOnlyDevice {
#[cfg(test)] #[cfg(test)]
pub(crate) mod test { pub(crate) mod test {
use serde_json::json;
use std::convert::TryFrom; use std::convert::TryFrom;
use crate::identities::{LocalTrust, ReadOnlyDevice};
use matrix_sdk_common::{ use matrix_sdk_common::{
encryption::DeviceKeys, encryption::DeviceKeys,
identifiers::{user_id, DeviceKeyAlgorithm}, identifiers::{user_id, DeviceKeyAlgorithm},
}; };
use serde_json::json;
use crate::identities::{LocalTrust, ReadOnlyDevice};
fn device_keys() -> DeviceKeys { fn device_keys() -> DeviceKeys {
let device_keys = json!({ let device_keys = json!({

View File

@ -12,20 +12,20 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use futures::future::join_all;
use std::{ use std::{
collections::{BTreeMap, HashSet}, collections::{BTreeMap, HashSet},
convert::TryFrom, convert::TryFrom,
sync::Arc, sync::Arc,
}; };
use tracing::{trace, warn};
use futures::future::join_all;
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::keys::get_keys::Response as KeysQueryResponse, api::r0::keys::get_keys::Response as KeysQueryResponse,
encryption::DeviceKeys, encryption::DeviceKeys,
executor::spawn, executor::spawn,
identifiers::{DeviceIdBox, UserId}, identifiers::{DeviceIdBox, UserId},
}; };
use tracing::{trace, warn};
use crate::{ use crate::{
error::OlmResult, error::OlmResult,
@ -424,9 +424,7 @@ pub(crate) mod test {
locks::Mutex, locks::Mutex,
IncomingResponse, IncomingResponse,
}; };
use matrix_sdk_test::async_test; use matrix_sdk_test::async_test;
use serde_json::json; use serde_json::json;
use crate::{ use crate::{

View File

@ -44,19 +44,19 @@ pub(crate) mod device;
mod manager; mod manager;
pub(crate) mod user; pub(crate) mod user;
pub use device::{Device, LocalTrust, ReadOnlyDevice, UserDevices};
pub(crate) use manager::IdentityManager;
pub use user::{
MasterPubkey, OwnUserIdentity, SelfSigningPubkey, UserIdentities, UserIdentity,
UserSigningPubkey,
};
use serde::{Deserialize, Deserializer, Serializer};
use std::sync::{ use std::sync::{
atomic::{AtomicBool, Ordering}, atomic::{AtomicBool, Ordering},
Arc, Arc,
}; };
pub use device::{Device, LocalTrust, ReadOnlyDevice, UserDevices};
pub(crate) use manager::IdentityManager;
use serde::{Deserialize, Deserializer, Serializer};
pub use user::{
MasterPubkey, OwnUserIdentity, SelfSigningPubkey, UserIdentities, UserIdentity,
UserSigningPubkey,
};
// These methods are only here because Serialize and Deserialize don't seem to // These methods are only here because Serialize and Deserialize don't seem to
// be implemented for WASM. // be implemented for WASM.
fn atomic_bool_serializer<S>(x: &AtomicBool, s: S) -> Result<S::Ok, S::Error> fn atomic_bool_serializer<S>(x: &AtomicBool, s: S) -> Result<S::Ok, S::Error>

View File

@ -21,20 +21,18 @@ use std::{
}, },
}; };
use serde::{Deserialize, Serialize};
use serde_json::to_value;
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::keys::{CrossSigningKey, KeyUsage}, api::r0::keys::{CrossSigningKey, KeyUsage},
identifiers::{DeviceKeyId, UserId}, identifiers::{DeviceKeyId, UserId},
}; };
use serde::{Deserialize, Serialize};
use serde_json::to_value;
use super::{atomic_bool_deserializer, atomic_bool_serializer};
#[cfg(test)] #[cfg(test)]
use crate::olm::PrivateCrossSigningIdentity; use crate::olm::PrivateCrossSigningIdentity;
use crate::{error::SignatureError, olm::Utility, ReadOnlyDevice}; use crate::{error::SignatureError, olm::Utility, ReadOnlyDevice};
use super::{atomic_bool_deserializer, atomic_bool_serializer};
/// Wrapper for a cross signing key marking it as the master key. /// Wrapper for a cross signing key marking it as the master key.
/// ///
/// Master keys are used to sign other cross signing keys, the self signing and /// Master keys are used to sign other cross signing keys, the self signing and
@ -719,6 +717,12 @@ impl OwnUserIdentity {
pub(crate) mod test { pub(crate) mod test {
use std::{convert::TryFrom, sync::Arc}; use std::{convert::TryFrom, sync::Arc};
use matrix_sdk_common::{
api::r0::keys::get_keys::Response as KeyQueryResponse, identifiers::user_id, locks::Mutex,
};
use matrix_sdk_test::async_test;
use super::{OwnUserIdentity, UserIdentities, UserIdentity};
use crate::{ use crate::{
identities::{ identities::{
manager::test::{other_key_query, own_key_query}, manager::test::{other_key_query, own_key_query},
@ -729,13 +733,6 @@ pub(crate) mod test {
verification::VerificationMachine, verification::VerificationMachine,
}; };
use matrix_sdk_common::{
api::r0::keys::get_keys::Response as KeyQueryResponse, identifiers::user_id, locks::Mutex,
};
use matrix_sdk_test::async_test;
use super::{OwnUserIdentity, UserIdentities, UserIdentity};
fn device(response: &KeyQueryResponse) -> (ReadOnlyDevice, ReadOnlyDevice) { fn device(response: &KeyQueryResponse) -> (ReadOnlyDevice, ReadOnlyDevice) {
let mut devices = response.device_keys.values().next().unwrap().values(); let mut devices = response.device_keys.values().next().unwrap().values();
let first = ReadOnlyDevice::try_from(devices.next().unwrap()).unwrap(); let first = ReadOnlyDevice::try_from(devices.next().unwrap()).unwrap();

View File

@ -20,13 +20,9 @@
// If we don't trust the device store an object that remembers the request and // If we don't trust the device store an object that remembers the request and
// let the users introspect that object. // let the users introspect that object.
use dashmap::{mapref::entry::Entry, DashMap, DashSet};
use serde::{Deserialize, Serialize};
use serde_json::value::to_raw_value;
use std::{collections::BTreeMap, sync::Arc}; use std::{collections::BTreeMap, sync::Arc};
use thiserror::Error;
use tracing::{error, info, trace, warn};
use dashmap::{mapref::entry::Entry, DashMap, DashSet};
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::to_device::DeviceIdOrAllDevices, api::r0::to_device::DeviceIdOrAllDevices,
events::{ events::{
@ -37,6 +33,10 @@ use matrix_sdk_common::{
identifiers::{DeviceId, DeviceIdBox, EventEncryptionAlgorithm, RoomId, UserId}, identifiers::{DeviceId, DeviceIdBox, EventEncryptionAlgorithm, RoomId, UserId},
uuid::Uuid, uuid::Uuid,
}; };
use serde::{Deserialize, Serialize};
use serde_json::value::to_raw_value;
use thiserror::Error;
use tracing::{error, info, trace, warn};
use crate::{ use crate::{
error::{OlmError, OlmResult}, error::{OlmError, OlmResult},
@ -817,6 +817,8 @@ impl KeyRequestMachine {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use std::{convert::TryInto, sync::Arc};
use dashmap::DashMap; use dashmap::DashMap;
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::to_device::DeviceIdOrAllDevices, api::r0::to_device::DeviceIdOrAllDevices,
@ -829,8 +831,8 @@ mod test {
locks::Mutex, locks::Mutex,
}; };
use matrix_sdk_test::async_test; use matrix_sdk_test::async_test;
use std::{convert::TryInto, sync::Arc};
use super::{KeyRequestMachine, KeyshareDecision};
use crate::{ use crate::{
identities::{LocalTrust, ReadOnlyDevice}, identities::{LocalTrust, ReadOnlyDevice},
olm::{Account, PrivateCrossSigningIdentity, ReadOnlyAccount}, olm::{Account, PrivateCrossSigningIdentity, ReadOnlyAccount},
@ -839,8 +841,6 @@ mod test {
verification::VerificationMachine, verification::VerificationMachine,
}; };
use super::{KeyRequestMachine, KeyshareDecision};
fn alice_id() -> UserId { fn alice_id() -> UserId {
user_id!("@alice:example.org") user_id!("@alice:example.org")
} }

View File

@ -17,8 +17,6 @@ use std::path::Path;
use std::{collections::BTreeMap, mem, sync::Arc}; use std::{collections::BTreeMap, mem, sync::Arc};
use dashmap::DashMap; use dashmap::DashMap;
use tracing::{debug, error, info, trace, warn};
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::{ api::r0::{
keys::{ keys::{
@ -44,6 +42,7 @@ use matrix_sdk_common::{
uuid::Uuid, uuid::Uuid,
UInt, UInt,
}; };
use tracing::{debug, error, info, trace, warn};
#[cfg(feature = "sled_cryptostore")] #[cfg(feature = "sled_cryptostore")]
use crate::store::sled::SledStore; use crate::store::sled::SledStore;
@ -1276,15 +1275,6 @@ pub(crate) mod test {
}; };
use http::Response; use http::Response;
use serde_json::json;
use crate::{
machine::OlmMachine,
olm::Utility,
verification::test::{outgoing_request_to_event, request_to_event},
EncryptionSettings, ReadOnlyDevice, ToDeviceRequest,
};
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::keys::{claim_keys, get_keys, upload_keys, OneTimeKey}, api::r0::keys::{claim_keys, get_keys, upload_keys, OneTimeKey},
events::{ events::{
@ -1301,6 +1291,14 @@ pub(crate) mod test {
IncomingResponse, Raw, IncomingResponse, Raw,
}; };
use matrix_sdk_test::test_json; use matrix_sdk_test::test_json;
use serde_json::json;
use crate::{
machine::OlmMachine,
olm::Utility,
verification::test::{outgoing_request_to_event, request_to_event},
EncryptionSettings, ReadOnlyDevice, ToDeviceRequest,
};
/// These keys need to be periodically uploaded to the server. /// These keys need to be periodically uploaded to the server.
type OneTimeKeys = BTreeMap<DeviceKeyId, OneTimeKey>; type OneTimeKeys = BTreeMap<DeviceKeyId, OneTimeKey>;

View File

@ -12,10 +12,6 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use matrix_sdk_common::events::ToDeviceEvent;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use std::{ use std::{
collections::BTreeMap, collections::BTreeMap,
convert::{TryFrom, TryInto}, convert::{TryFrom, TryInto},
@ -26,7 +22,6 @@ use std::{
Arc, Arc,
}, },
}; };
use tracing::{debug, trace, warn};
#[cfg(test)] #[cfg(test)]
use matrix_sdk_common::events::EventType; use matrix_sdk_common::events::EventType;
@ -37,7 +32,7 @@ use matrix_sdk_common::{
encryption::DeviceKeys, encryption::DeviceKeys,
events::{ events::{
room::encrypted::{EncryptedEventContent, EncryptedEventScheme}, room::encrypted::{EncryptedEventContent, EncryptedEventScheme},
AnyToDeviceEvent, AnyToDeviceEvent, ToDeviceEvent,
}, },
identifiers::{ identifiers::{
DeviceId, DeviceIdBox, DeviceKeyAlgorithm, DeviceKeyId, EventEncryptionAlgorithm, RoomId, DeviceId, DeviceIdBox, DeviceKeyAlgorithm, DeviceKeyId, EventEncryptionAlgorithm, RoomId,
@ -53,7 +48,15 @@ use olm_rs::{
session::{OlmMessage, PreKeyMessage}, session::{OlmMessage, PreKeyMessage},
PicklingMode, PicklingMode,
}; };
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use tracing::{debug, trace, warn};
use super::{
EncryptionSettings, InboundGroupSession, OutboundGroupSession, PrivateCrossSigningIdentity,
Session,
};
use crate::{ use crate::{
error::{EventError, OlmResult, SessionCreationError}, error::{EventError, OlmResult, SessionCreationError},
identities::ReadOnlyDevice, identities::ReadOnlyDevice,
@ -63,11 +66,6 @@ use crate::{
OlmError, OlmError,
}; };
use super::{
EncryptionSettings, InboundGroupSession, OutboundGroupSession, PrivateCrossSigningIdentity,
Session,
};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Account { pub struct Account {
pub(crate) inner: ReadOnlyAccount, pub(crate) inner: ReadOnlyAccount,
@ -873,8 +871,8 @@ impl ReadOnlyAccount {
/// # Arguments /// # Arguments
/// * `device` - The other account's device. /// * `device` - The other account's device.
/// ///
/// * `key_map` - A map from the algorithm and device id to the one-time /// * `key_map` - A map from the algorithm and device id to the one-time key that the other
/// key that the other account created and shared with us. /// account created and shared with us.
pub(crate) async fn create_outbound_session( pub(crate) async fn create_outbound_session(
&self, &self,
device: ReadOnlyDevice, device: ReadOnlyDevice,

View File

@ -19,19 +19,6 @@ use std::{
sync::Arc, sync::Arc,
}; };
use olm_rs::{
errors::OlmGroupSessionError, inbound_group_session::OlmInboundGroupSession, PicklingMode,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use zeroize::Zeroizing;
pub use olm_rs::{
account::IdentityKeys,
session::{OlmMessage, PreKeyMessage},
utility::OlmUtility,
};
use matrix_sdk_common::{ use matrix_sdk_common::{
events::{ events::{
forwarded_room_key::ForwardedRoomKeyToDeviceEventContent, forwarded_room_key::ForwardedRoomKeyToDeviceEventContent,
@ -45,6 +32,17 @@ use matrix_sdk_common::{
locks::Mutex, locks::Mutex,
Raw, Raw,
}; };
pub use olm_rs::{
account::IdentityKeys,
session::{OlmMessage, PreKeyMessage},
utility::OlmUtility,
};
use olm_rs::{
errors::OlmGroupSessionError, inbound_group_session::OlmInboundGroupSession, PicklingMode,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use zeroize::Zeroizing;
use super::{ExportedGroupSessionKey, ExportedRoomKey, GroupSessionKey}; use super::{ExportedGroupSessionKey, ExportedRoomKey, GroupSessionKey};
use crate::error::{EventError, MegolmResult}; use crate::error::{EventError, MegolmResult};

View File

@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use std::{collections::BTreeMap, convert::TryInto};
use matrix_sdk_common::{ use matrix_sdk_common::{
events::forwarded_room_key::{ events::forwarded_room_key::{
ForwardedRoomKeyToDeviceEventContent, ForwardedRoomKeyToDeviceEventContentInit, ForwardedRoomKeyToDeviceEventContent, ForwardedRoomKeyToDeviceEventContentInit,
@ -19,7 +21,6 @@ use matrix_sdk_common::{
identifiers::{DeviceKeyAlgorithm, EventEncryptionAlgorithm, RoomId}, identifiers::{DeviceKeyAlgorithm, EventEncryptionAlgorithm, RoomId},
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, convert::TryInto};
use zeroize::Zeroize; use zeroize::Zeroize;
mod inbound; mod inbound;

View File

@ -12,15 +12,6 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use dashmap::DashMap;
use matrix_sdk_common::{
api::r0::to_device::DeviceIdOrAllDevices,
events::room::{
encrypted::MegolmV1AesSha2ContentInit, history_visibility::HistoryVisibility,
message::Relation,
},
uuid::Uuid,
};
use std::{ use std::{
cmp::max, cmp::max,
collections::BTreeMap, collections::BTreeMap,
@ -31,23 +22,24 @@ use std::{
}, },
time::Duration, time::Duration,
}; };
use tracing::{debug, error, trace};
use dashmap::DashMap;
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::to_device::DeviceIdOrAllDevices,
events::{ events::{
room::{ room::{
encrypted::{EncryptedEventContent, EncryptedEventScheme}, encrypted::{EncryptedEventContent, EncryptedEventScheme, MegolmV1AesSha2ContentInit},
encryption::EncryptionEventContent, encryption::EncryptionEventContent,
history_visibility::HistoryVisibility,
message::Relation,
}, },
AnyMessageEventContent, EventContent, AnyMessageEventContent, EventContent,
}, },
identifiers::{DeviceId, DeviceIdBox, EventEncryptionAlgorithm, RoomId, UserId}, identifiers::{DeviceId, DeviceIdBox, EventEncryptionAlgorithm, RoomId, UserId},
instant::Instant, instant::Instant,
locks::Mutex, locks::Mutex,
uuid::Uuid,
}; };
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
pub use olm_rs::{ pub use olm_rs::{
account::IdentityKeys, account::IdentityKeys,
session::{OlmMessage, PreKeyMessage}, session::{OlmMessage, PreKeyMessage},
@ -56,13 +48,15 @@ pub use olm_rs::{
use olm_rs::{ use olm_rs::{
errors::OlmGroupSessionError, outbound_group_session::OlmOutboundGroupSession, PicklingMode, errors::OlmGroupSessionError, outbound_group_session::OlmOutboundGroupSession, PicklingMode,
}; };
use serde::{Deserialize, Serialize};
use crate::ToDeviceRequest; use serde_json::{json, Value};
use tracing::{debug, error, trace};
use super::{ use super::{
super::{deserialize_instant, serialize_instant}, super::{deserialize_instant, serialize_instant},
GroupSessionKey, GroupSessionKey,
}; };
use crate::ToDeviceRequest;
const ROTATION_PERIOD: Duration = Duration::from_millis(604800000); const ROTATION_PERIOD: Duration = Duration::from_millis(604800000);
const ROTATION_MESSAGES: u64 = 100; const ROTATION_MESSAGES: u64 = 100;
@ -461,11 +455,11 @@ impl OutboundGroupSession {
/// ///
/// # Arguments /// # Arguments
/// ///
/// * `device_id` - The device id of the device that created this session. /// * `device_id` - The device id of the device that created this session. Put differently, our
/// Put differently, our own device id. /// own device id.
/// ///
/// * `identity_keys` - The identity keys of the device that created this /// * `identity_keys` - The identity keys of the device that created this session, our own
/// session, our own identity keys. /// identity keys.
/// ///
/// * `pickle` - The pickled version of the `OutboundGroupSession`. /// * `pickle` - The pickled version of the `OutboundGroupSession`.
/// ///

View File

@ -30,14 +30,13 @@ pub use group_sessions::{
OutboundGroupSession, PickledInboundGroupSession, PickledOutboundGroupSession, OutboundGroupSession, PickledInboundGroupSession, PickledOutboundGroupSession,
}; };
pub(crate) use group_sessions::{GroupSessionKey, ShareState}; pub(crate) use group_sessions::{GroupSessionKey, ShareState};
use matrix_sdk_common::instant::{Duration, Instant};
pub use olm_rs::{account::IdentityKeys, PicklingMode}; pub use olm_rs::{account::IdentityKeys, PicklingMode};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
pub use session::{PickledSession, Session, SessionPickle}; pub use session::{PickledSession, Session, SessionPickle};
pub use signing::{PickledCrossSigningIdentity, PrivateCrossSigningIdentity}; pub use signing::{PickledCrossSigningIdentity, PrivateCrossSigningIdentity};
pub(crate) use utility::Utility; pub(crate) use utility::Utility;
use matrix_sdk_common::instant::{Duration, Instant};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
pub(crate) fn serialize_instant<S>(instant: &Instant, serializer: S) -> Result<S::Ok, S::Error> pub(crate) fn serialize_instant<S>(instant: &Instant, serializer: S) -> Result<S::Ok, S::Error>
where where
S: Serializer, S: Serializer,
@ -60,14 +59,16 @@ where
#[cfg(test)] #[cfg(test)]
pub(crate) mod test { pub(crate) mod test {
use crate::olm::{InboundGroupSession, ReadOnlyAccount, Session}; use std::{collections::BTreeMap, convert::TryInto};
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::keys::SignedKey, api::r0::keys::SignedKey,
events::forwarded_room_key::ForwardedRoomKeyToDeviceEventContent, events::forwarded_room_key::ForwardedRoomKeyToDeviceEventContent,
identifiers::{room_id, user_id, DeviceId, UserId}, identifiers::{room_id, user_id, DeviceId, UserId},
}; };
use olm_rs::session::OlmMessage; use olm_rs::session::OlmMessage;
use std::{collections::BTreeMap, convert::TryInto};
use crate::olm::{InboundGroupSession, ReadOnlyAccount, Session};
fn alice_id() -> UserId { fn alice_id() -> UserId {
user_id!("@alice:example.org") user_id!("@alice:example.org")

View File

@ -27,20 +27,18 @@ use matrix_sdk_common::{
locks::Mutex, locks::Mutex,
}; };
use olm_rs::{errors::OlmSessionError, session::OlmSession, PicklingMode}; use olm_rs::{errors::OlmSessionError, session::OlmSession, PicklingMode};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use crate::{
error::{EventError, OlmResult, SessionUnpicklingError},
ReadOnlyDevice,
};
pub use olm_rs::{ pub use olm_rs::{
session::{OlmMessage, PreKeyMessage}, session::{OlmMessage, PreKeyMessage},
utility::OlmUtility, utility::OlmUtility,
}; };
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use super::{deserialize_instant, serialize_instant, IdentityKeys}; use super::{deserialize_instant, serialize_instant, IdentityKeys};
use crate::{
error::{EventError, OlmResult, SessionUnpicklingError},
ReadOnlyDevice,
};
/// Cryptographic session that enables secure communication between two /// Cryptographic session that enables secure communication between two
/// `Account`s /// `Account`s
@ -104,9 +102,8 @@ impl Session {
/// ///
/// # Arguments /// # Arguments
/// ///
/// * `recipient_device` - The device for which this message is going to be /// * `recipient_device` - The device for which this message is going to be encrypted, this
/// encrypted, this needs to be the device that was used to create this /// needs to be the device that was used to create this session with.
/// session with.
/// ///
/// * `event_type` - The type of the event. /// * `event_type` - The type of the event.
/// ///

View File

@ -14,8 +14,6 @@
mod pk_signing; mod pk_signing;
use serde::{Deserialize, Serialize};
use serde_json::Error as JsonError;
use std::{ use std::{
collections::BTreeMap, collections::BTreeMap,
sync::{ sync::{
@ -30,14 +28,15 @@ use matrix_sdk_common::{
identifiers::{DeviceKeyAlgorithm, DeviceKeyId, UserId}, identifiers::{DeviceKeyAlgorithm, DeviceKeyId, UserId},
locks::Mutex, locks::Mutex,
}; };
use pk_signing::{MasterSigning, PickledSignings, SelfSigning, Signing, SigningError, UserSigning};
use serde::{Deserialize, Serialize};
use serde_json::Error as JsonError;
use crate::{ use crate::{
error::SignatureError, requests::UploadSigningKeysRequest, OwnUserIdentity, ReadOnlyAccount, error::SignatureError, requests::UploadSigningKeysRequest, OwnUserIdentity, ReadOnlyAccount,
ReadOnlyDevice, UserIdentity, ReadOnlyDevice, UserIdentity,
}; };
use pk_signing::{MasterSigning, PickledSignings, SelfSigning, Signing, SigningError, UserSigning};
/// Private cross signing identity. /// Private cross signing identity.
/// ///
/// This object holds the private and public ed25519 key triplet that is used /// This object holds the private and public ed25519 key triplet that is used
@ -424,20 +423,20 @@ impl PrivateCrossSigningIdentity {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use crate::{
identities::{ReadOnlyDevice, UserIdentity},
olm::ReadOnlyAccount,
};
use std::{collections::BTreeMap, sync::Arc}; use std::{collections::BTreeMap, sync::Arc};
use super::{PrivateCrossSigningIdentity, Signing};
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::keys::CrossSigningKey, api::r0::keys::CrossSigningKey,
identifiers::{user_id, UserId}, identifiers::{user_id, UserId},
}; };
use matrix_sdk_test::async_test; use matrix_sdk_test::async_test;
use super::{PrivateCrossSigningIdentity, Signing};
use crate::{
identities::{ReadOnlyDevice, UserIdentity},
olm::ReadOnlyAccount,
};
fn user_id() -> UserId { fn user_id() -> UserId {
user_id!("@example:localhost") user_id!("@example:localhost")
} }

View File

@ -12,32 +12,27 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use std::{collections::BTreeMap, convert::TryInto, sync::Arc};
use aes_gcm::{ use aes_gcm::{
aead::{generic_array::GenericArray, Aead, NewAead}, aead::{generic_array::GenericArray, Aead, NewAead},
Aes256Gcm, Aes256Gcm,
}; };
use getrandom::getrandom; use getrandom::getrandom;
use matrix_sdk_common::{
encryption::DeviceKeys,
identifiers::{DeviceKeyAlgorithm, DeviceKeyId},
};
use serde::{Deserialize, Serialize};
use serde_json::{json, Error as JsonError, Value};
use std::{collections::BTreeMap, convert::TryInto, sync::Arc};
use thiserror::Error;
use zeroize::Zeroizing;
use olm_rs::pk::OlmPkSigning;
#[cfg(test)]
use olm_rs::{errors::OlmUtilityError, utility::OlmUtility};
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::keys::{CrossSigningKey, KeyUsage}, api::r0::keys::{CrossSigningKey, KeyUsage},
identifiers::UserId, encryption::DeviceKeys,
identifiers::{DeviceKeyAlgorithm, DeviceKeyId, UserId},
locks::Mutex, locks::Mutex,
CanonicalJsonValue, CanonicalJsonValue,
}; };
use olm_rs::pk::OlmPkSigning;
#[cfg(test)]
use olm_rs::{errors::OlmUtilityError, utility::OlmUtility};
use serde::{Deserialize, Serialize};
use serde_json::{json, Error as JsonError, Value};
use thiserror::Error;
use zeroize::Zeroizing;
use crate::{ use crate::{
error::SignatureError, error::SignatureError,

View File

@ -12,14 +12,14 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use olm_rs::utility::OlmUtility;
use serde_json::Value;
use std::convert::TryInto; use std::convert::TryInto;
use matrix_sdk_common::{ use matrix_sdk_common::{
identifiers::{DeviceKeyAlgorithm, DeviceKeyId, UserId}, identifiers::{DeviceKeyAlgorithm, DeviceKeyId, UserId},
CanonicalJsonValue, CanonicalJsonValue,
}; };
use olm_rs::utility::OlmUtility;
use serde_json::Value;
use crate::error::SignatureError; use crate::error::SignatureError;
@ -48,8 +48,7 @@ impl Utility {
/// ///
/// * `key_id` - The id of the key that signed the JSON object. /// * `key_id` - The id of the key that signed the JSON object.
/// ///
/// * `signing_key` - The public ed25519 key which was used to sign the JSON /// * `signing_key` - The public ed25519 key which was used to sign the JSON object.
/// object.
/// ///
/// * `json` - The JSON object that should be verified. /// * `json` - The JSON object that should be verified.
pub(crate) fn verify_json( pub(crate) fn verify_json(
@ -108,10 +107,11 @@ impl Utility {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::Utility;
use matrix_sdk_common::identifiers::{user_id, DeviceKeyAlgorithm, DeviceKeyId}; use matrix_sdk_common::identifiers::{user_id, DeviceKeyAlgorithm, DeviceKeyId};
use serde_json::json; use serde_json::json;
use super::Utility;
#[test] #[test]
fn signature_test() { fn signature_test() {
let mut device_keys = json!({ let mut device_keys = json!({

View File

@ -35,7 +35,6 @@ use matrix_sdk_common::{
identifiers::{DeviceIdBox, RoomId, UserId}, identifiers::{DeviceIdBox, RoomId, UserId},
uuid::Uuid, uuid::Uuid,
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::value::RawValue as RawJsonValue; use serde_json::value::RawValue as RawJsonValue;

View File

@ -17,9 +17,8 @@ use std::{
sync::Arc, sync::Arc,
}; };
use futures::future::join_all;
use dashmap::DashMap; use dashmap::DashMap;
use futures::future::join_all;
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::to_device::DeviceIdOrAllDevices, api::r0::to_device::DeviceIdOrAllDevices,
events::{ events::{

View File

@ -307,13 +307,13 @@ impl SessionManager {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use dashmap::DashMap;
use matrix_sdk_common::locks::Mutex;
use std::{collections::BTreeMap, sync::Arc}; use std::{collections::BTreeMap, sync::Arc};
use dashmap::DashMap;
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::keys::claim_keys::Response as KeyClaimResponse, api::r0::keys::claim_keys::Response as KeyClaimResponse,
identifiers::{user_id, DeviceIdBox, UserId}, identifiers::{user_id, DeviceIdBox, UserId},
locks::Mutex,
}; };
use matrix_sdk_test::async_test; use matrix_sdk_test::async_test;

View File

@ -195,12 +195,13 @@ impl DeviceStore {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use matrix_sdk_common::identifiers::room_id;
use crate::{ use crate::{
identities::device::test::get_device, identities::device::test::get_device,
olm::{test::get_account_and_session, InboundGroupSession}, olm::{test::get_account_and_session, InboundGroupSession},
store::caches::{DeviceStore, GroupSessionStore, SessionStore}, store::caches::{DeviceStore, GroupSessionStore, SessionStore},
}; };
use matrix_sdk_common::identifiers::room_id;
#[tokio::test] #[tokio::test]
async fn test_session_store() { async fn test_session_store() {

View File

@ -291,12 +291,13 @@ impl CryptoStore for MemoryStore {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use matrix_sdk_common::identifiers::room_id;
use crate::{ use crate::{
identities::device::test::get_device, identities::device::test::get_device,
olm::{test::get_account_and_session, InboundGroupSession, OlmMessageHash}, olm::{test::get_account_and_session, InboundGroupSession, OlmMessageHash},
store::{memorystore::MemoryStore, Changes, CryptoStore}, store::{memorystore::MemoryStore, Changes, CryptoStore},
}; };
use matrix_sdk_common::identifiers::room_id;
#[tokio::test] #[tokio::test]
async fn test_session_store() { async fn test_session_store() {

View File

@ -43,11 +43,6 @@ mod pickle_key;
#[cfg(feature = "sled_cryptostore")] #[cfg(feature = "sled_cryptostore")]
pub(crate) mod sled; pub(crate) mod sled;
#[cfg(feature = "sled_cryptostore")]
pub use self::sled::SledStore;
pub use memorystore::MemoryStore;
pub use pickle_key::{EncryptedPickleKey, PickleKey};
use std::{ use std::{
collections::{HashMap, HashSet}, collections::{HashMap, HashSet},
fmt::Debug, fmt::Debug,
@ -56,10 +51,6 @@ use std::{
sync::Arc, sync::Arc,
}; };
use olm_rs::errors::{OlmAccountError, OlmGroupSessionError, OlmSessionError};
use serde_json::Error as SerdeError;
use thiserror::Error;
use matrix_sdk_common::{ use matrix_sdk_common::{
async_trait, async_trait,
events::room_key_request::RequestedKeyInfo, events::room_key_request::RequestedKeyInfo,
@ -71,7 +62,14 @@ use matrix_sdk_common::{
uuid::Uuid, uuid::Uuid,
AsyncTraitDeps, AsyncTraitDeps,
}; };
pub use memorystore::MemoryStore;
use olm_rs::errors::{OlmAccountError, OlmGroupSessionError, OlmSessionError};
pub use pickle_key::{EncryptedPickleKey, PickleKey};
use serde_json::Error as SerdeError;
use thiserror::Error;
#[cfg(feature = "sled_cryptostore")]
pub use self::sled::SledStore;
use crate::{ use crate::{
error::SessionUnpicklingError, error::SessionUnpicklingError,
identities::{Device, ReadOnlyDevice, UserDevices, UserIdentities}, identities::{Device, ReadOnlyDevice, UserDevices, UserIdentities},

View File

@ -22,11 +22,10 @@ use getrandom::getrandom;
use hmac::Hmac; use hmac::Hmac;
use olm_rs::PicklingMode; use olm_rs::PicklingMode;
use pbkdf2::pbkdf2; use pbkdf2::pbkdf2;
use serde::{Deserialize, Serialize};
use sha2::Sha256; use sha2::Sha256;
use zeroize::{Zeroize, Zeroizing}; use zeroize::{Zeroize, Zeroizing};
use serde::{Deserialize, Serialize};
const KEY_SIZE: usize = 32; const KEY_SIZE: usize = 32;
const NONCE_SIZE: usize = 12; const NONCE_SIZE: usize = 12;
const KDF_SALT_SIZE: usize = 32; const KDF_SALT_SIZE: usize = 32;

View File

@ -20,13 +20,6 @@ use std::{
}; };
use dashmap::DashSet; use dashmap::DashSet;
use olm_rs::{account::IdentityKeys, PicklingMode};
pub use sled::Error;
use sled::{
transaction::{ConflictableTransactionError, TransactionError},
Config, Db, Transactional, Tree,
};
use matrix_sdk_common::{ use matrix_sdk_common::{
async_trait, async_trait,
events::room_key_request::RequestedKeyInfo, events::room_key_request::RequestedKeyInfo,
@ -34,6 +27,12 @@ use matrix_sdk_common::{
locks::Mutex, locks::Mutex,
uuid, uuid,
}; };
use olm_rs::{account::IdentityKeys, PicklingMode};
pub use sled::Error;
use sled::{
transaction::{ConflictableTransactionError, TransactionError},
Config, Db, Transactional, Tree,
};
use uuid::Uuid; use uuid::Uuid;
use super::{ use super::{
@ -793,6 +792,19 @@ impl CryptoStore for SledStore {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use std::collections::BTreeMap;
use matrix_sdk_common::{
api::r0::keys::SignedKey,
events::room_key_request::RequestedKeyInfo,
identifiers::{room_id, user_id, DeviceId, EventEncryptionAlgorithm, UserId},
uuid::Uuid,
};
use matrix_sdk_test::async_test;
use olm_rs::outbound_group_session::OlmOutboundGroupSession;
use tempfile::tempdir;
use super::{CryptoStore, OutgoingKeyRequest, SledStore};
use crate::{ use crate::{
identities::{ identities::{
device::test::get_device, device::test::get_device,
@ -804,18 +816,6 @@ mod test {
}, },
store::{Changes, DeviceChanges, IdentityChanges}, store::{Changes, DeviceChanges, IdentityChanges},
}; };
use matrix_sdk_common::{
api::r0::keys::SignedKey,
events::room_key_request::RequestedKeyInfo,
identifiers::{room_id, user_id, DeviceId, EventEncryptionAlgorithm, UserId},
uuid::Uuid,
};
use matrix_sdk_test::async_test;
use olm_rs::outbound_group_session::OlmOutboundGroupSession;
use std::collections::BTreeMap;
use tempfile::tempdir;
use super::{CryptoStore, OutgoingKeyRequest, SledStore};
fn alice_id() -> UserId { fn alice_id() -> UserId {
user_id!("@alice:example.org") user_id!("@alice:example.org")

View File

@ -15,9 +15,6 @@
use std::{convert::TryFrom, sync::Arc}; use std::{convert::TryFrom, sync::Arc};
use dashmap::DashMap; use dashmap::DashMap;
use tracing::{info, trace, warn};
use matrix_sdk_common::{ use matrix_sdk_common::{
events::{ events::{
room::message::MessageType, AnyMessageEvent, AnySyncMessageEvent, AnySyncRoomEvent, room::message::MessageType, AnyMessageEvent, AnySyncMessageEvent, AnySyncRoomEvent,
@ -27,12 +24,12 @@ use matrix_sdk_common::{
locks::Mutex, locks::Mutex,
uuid::Uuid, uuid::Uuid,
}; };
use tracing::{info, trace, warn};
use super::{ use super::{
requests::VerificationRequest, requests::VerificationRequest,
sas::{content_to_request, OutgoingContent, Sas, VerificationResult}, sas::{content_to_request, OutgoingContent, Sas, VerificationResult},
}; };
use crate::{ use crate::{
olm::PrivateCrossSigningIdentity, olm::PrivateCrossSigningIdentity,
requests::OutgoingRequest, requests::OutgoingRequest,

View File

@ -22,18 +22,17 @@ pub use sas::{AcceptSettings, Sas, VerificationResult};
#[cfg(test)] #[cfg(test)]
pub(crate) mod test { pub(crate) mod test {
use crate::{
requests::{OutgoingRequest, OutgoingRequests},
OutgoingVerificationRequest,
};
use serde_json::Value;
use matrix_sdk_common::{ use matrix_sdk_common::{
events::{AnyToDeviceEvent, AnyToDeviceEventContent, EventType, ToDeviceEvent}, events::{AnyToDeviceEvent, AnyToDeviceEventContent, EventType, ToDeviceEvent},
identifiers::UserId, identifiers::UserId,
}; };
use serde_json::Value;
use super::sas::OutgoingContent; use super::sas::OutgoingContent;
use crate::{
requests::{OutgoingRequest, OutgoingRequests},
OutgoingVerificationRequest,
};
pub(crate) fn request_to_event( pub(crate) fn request_to_event(
sender: &UserId, sender: &UserId,

View File

@ -28,14 +28,13 @@ use matrix_sdk_common::{
identifiers::{DeviceId, DeviceIdBox, EventId, RoomId, UserId}, identifiers::{DeviceId, DeviceIdBox, EventId, RoomId, UserId},
}; };
use super::sas::{OutgoingContent, StartContent};
use crate::{ use crate::{
olm::{PrivateCrossSigningIdentity, ReadOnlyAccount}, olm::{PrivateCrossSigningIdentity, ReadOnlyAccount},
store::CryptoStore, store::CryptoStore,
ReadOnlyDevice, Sas, UserIdentities, ReadOnlyDevice, Sas, UserIdentities,
}; };
use super::sas::{OutgoingContent, StartContent};
const SUPPORTED_METHODS: &[VerificationMethod] = &[VerificationMethod::MSasV1]; const SUPPORTED_METHODS: &[VerificationMethod] = &[VerificationMethod::MSasV1];
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
@ -453,6 +452,7 @@ mod test {
}; };
use matrix_sdk_test::async_test; use matrix_sdk_test::async_test;
use super::VerificationRequest;
use crate::{ use crate::{
olm::{PrivateCrossSigningIdentity, ReadOnlyAccount}, olm::{PrivateCrossSigningIdentity, ReadOnlyAccount},
store::{CryptoStore, MemoryStore}, store::{CryptoStore, MemoryStore},
@ -460,8 +460,6 @@ mod test {
ReadOnlyDevice, ReadOnlyDevice,
}; };
use super::VerificationRequest;
fn alice_id() -> UserId { fn alice_id() -> UserId {
UserId::try_from("@alice:example.org").unwrap() UserId::try_from("@alice:example.org").unwrap()
} }

View File

@ -14,11 +14,6 @@
use std::{collections::BTreeMap, convert::TryInto}; use std::{collections::BTreeMap, convert::TryInto};
use sha2::{Digest, Sha256};
use tracing::{trace, warn};
use olm_rs::sas::OlmSas;
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::to_device::DeviceIdOrAllDevices, api::r0::to_device::DeviceIdOrAllDevices,
events::{ events::{
@ -32,17 +27,19 @@ use matrix_sdk_common::{
identifiers::{DeviceId, DeviceKeyAlgorithm, DeviceKeyId, UserId}, identifiers::{DeviceId, DeviceKeyAlgorithm, DeviceKeyId, UserId},
uuid::Uuid, uuid::Uuid,
}; };
use olm_rs::sas::OlmSas;
use crate::{ use sha2::{Digest, Sha256};
identities::{ReadOnlyDevice, UserIdentities}, use tracing::{trace, warn};
utilities::encode,
ReadOnlyAccount, ToDeviceRequest,
};
use super::{ use super::{
event_enums::{MacContent, StartContent}, event_enums::{MacContent, StartContent},
sas_state::FlowId, sas_state::FlowId,
}; };
use crate::{
identities::{ReadOnlyDevice, UserIdentities},
utilities::encode,
ReadOnlyAccount, ToDeviceRequest,
};
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct SasIds { pub struct SasIds {

View File

@ -12,21 +12,15 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use std::sync::Arc;
#[cfg(test)] #[cfg(test)]
use std::time::Instant; use std::time::Instant;
use std::sync::Arc;
use matrix_sdk_common::{ use matrix_sdk_common::{
events::{key::verification::cancel::CancelCode, AnyMessageEvent, AnyToDeviceEvent}, events::{key::verification::cancel::CancelCode, AnyMessageEvent, AnyToDeviceEvent},
identifiers::{EventId, RoomId}, identifiers::{EventId, RoomId},
}; };
use crate::{
identities::{ReadOnlyDevice, UserIdentities},
ReadOnlyAccount,
};
use super::{ use super::{
event_enums::{AcceptContent, CancelContent, MacContent, OutgoingContent}, event_enums::{AcceptContent, CancelContent, MacContent, OutgoingContent},
sas_state::{ sas_state::{
@ -35,6 +29,10 @@ use super::{
}, },
StartContent, StartContent,
}; };
use crate::{
identities::{ReadOnlyDevice, UserIdentities},
ReadOnlyAccount,
};
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum InnerSas { pub enum InnerSas {

View File

@ -17,13 +17,14 @@ mod helpers;
mod inner_sas; mod inner_sas;
mod sas_state; mod sas_state;
use std::sync::{Arc, Mutex};
#[cfg(test)] #[cfg(test)]
use std::time::Instant; use std::time::Instant;
use event_enums::AcceptContent; use event_enums::AcceptContent;
use std::sync::{Arc, Mutex}; pub use event_enums::{OutgoingContent, StartContent};
use tracing::{error, info, trace, warn}; pub use helpers::content_to_request;
use inner_sas::InnerSas;
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::keys::upload_signatures::Request as SignatureUploadRequest, api::r0::keys::upload_signatures::Request as SignatureUploadRequest,
events::{ events::{
@ -37,7 +38,10 @@ use matrix_sdk_common::{
identifiers::{DeviceId, EventId, RoomId, UserId}, identifiers::{DeviceId, EventId, RoomId, UserId},
uuid::Uuid, uuid::Uuid,
}; };
pub use sas_state::FlowId;
use tracing::{error, info, trace, warn};
use self::event_enums::CancelContent;
use crate::{ use crate::{
error::SignatureError, error::SignatureError,
identities::{LocalTrust, ReadOnlyDevice, UserIdentities}, identities::{LocalTrust, ReadOnlyDevice, UserIdentities},
@ -47,14 +51,6 @@ use crate::{
ReadOnlyAccount, ToDeviceRequest, ReadOnlyAccount, ToDeviceRequest,
}; };
pub use helpers::content_to_request;
use inner_sas::InnerSas;
pub use sas_state::FlowId;
pub use event_enums::{OutgoingContent, StartContent};
use self::event_enums::CancelContent;
#[derive(Debug)] #[derive(Debug)]
/// A result of a verification flow. /// A result of a verification flow.
#[allow(clippy::large_enum_variant)] #[allow(clippy::large_enum_variant)]
@ -741,6 +737,7 @@ mod test {
use matrix_sdk_common::identifiers::{DeviceId, UserId}; use matrix_sdk_common::identifiers::{DeviceId, UserId};
use super::Sas;
use crate::{ use crate::{
olm::PrivateCrossSigningIdentity, olm::PrivateCrossSigningIdentity,
store::{CryptoStore, MemoryStore}, store::{CryptoStore, MemoryStore},
@ -748,8 +745,6 @@ mod test {
ReadOnlyAccount, ReadOnlyDevice, ReadOnlyAccount, ReadOnlyDevice,
}; };
use super::Sas;
fn alice_id() -> UserId { fn alice_id() -> UserId {
UserId::try_from("@alice:example.org").unwrap() UserId::try_from("@alice:example.org").unwrap()
} }

View File

@ -19,8 +19,6 @@ use std::{
time::{Duration, Instant}, time::{Duration, Instant},
}; };
use olm_rs::sas::OlmSas;
use matrix_sdk_common::{ use matrix_sdk_common::{
events::key::verification::{ events::key::verification::{
accept::{ accept::{
@ -40,6 +38,7 @@ use matrix_sdk_common::{
identifiers::{DeviceId, EventId, RoomId, UserId}, identifiers::{DeviceId, EventId, RoomId, UserId},
uuid::Uuid, uuid::Uuid,
}; };
use olm_rs::sas::OlmSas;
use tracing::info; use tracing::info;
use super::{ use super::{
@ -51,7 +50,6 @@ use super::{
receive_mac_event, SasIds, receive_mac_event, SasIds,
}, },
}; };
use crate::{ use crate::{
identities::{ReadOnlyDevice, UserIdentities}, identities::{ReadOnlyDevice, UserIdentities},
ReadOnlyAccount, ReadOnlyAccount,
@ -1182,10 +1180,6 @@ impl SasState<Canceled> {
mod test { mod test {
use std::convert::TryFrom; use std::convert::TryFrom;
use crate::{
verification::sas::{event_enums::AcceptContent, StartContent},
ReadOnlyAccount, ReadOnlyDevice,
};
use matrix_sdk_common::{ use matrix_sdk_common::{
events::key::verification::{ events::key::verification::{
accept::{AcceptMethod, CustomContent}, accept::{AcceptMethod, CustomContent},
@ -1195,6 +1189,10 @@ mod test {
}; };
use super::{Accepted, Created, SasState, Started}; use super::{Accepted, Created, SasState, Started};
use crate::{
verification::sas::{event_enums::AcceptContent, StartContent},
ReadOnlyAccount, ReadOnlyDevice,
};
fn alice_id() -> UserId { fn alice_id() -> UserId {
UserId::try_from("@alice:example.org").unwrap() UserId::try_from("@alice:example.org").unwrap()

View File

@ -1,7 +1,6 @@
use std::{collections::HashMap, panic}; use std::{collections::HashMap, panic};
use http::Response; use http::Response;
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::sync::sync_events::Response as SyncResponse, api::r0::sync::sync_events::Response as SyncResponse,
events::{ events::{
@ -11,9 +10,8 @@ use matrix_sdk_common::{
identifiers::{room_id, RoomId}, identifiers::{room_id, RoomId},
IncomingResponse, IncomingResponse,
}; };
use serde_json::Value as JsonValue;
pub use matrix_sdk_test_macros::async_test; pub use matrix_sdk_test_macros::async_test;
use serde_json::Value as JsonValue;
pub mod test_json; pub mod test_json;

View File

@ -17,12 +17,11 @@ pub use events::{
PUBLIC_ROOMS, REACTION, REDACTED, REDACTED_INVALID, REDACTED_STATE, REDACTION, PUBLIC_ROOMS, REACTION, REDACTED, REDACTED_INVALID, REDACTED_STATE, REDACTION,
REGISTRATION_RESPONSE_ERR, ROOM_ID, ROOM_MESSAGES, TYPING, REGISTRATION_RESPONSE_ERR, ROOM_ID, ROOM_MESSAGES, TYPING,
}; };
pub use members::MEMBERS;
pub use sync::{ pub use sync::{
DEFAULT_SYNC_SUMMARY, INVITE_SYNC, LEAVE_SYNC, LEAVE_SYNC_EVENT, MORE_SYNC, SYNC, VOIP_SYNC, DEFAULT_SYNC_SUMMARY, INVITE_SYNC, LEAVE_SYNC, LEAVE_SYNC_EVENT, MORE_SYNC, SYNC, VOIP_SYNC,
}; };
pub use members::MEMBERS;
lazy_static! { lazy_static! {
pub static ref DEVICES: JsonValue = json!({ pub static ref DEVICES: JsonValue = json!({
"devices": [ "devices": [

5
rustfmt.toml Normal file
View File

@ -0,0 +1,5 @@
comment_width = 100
wrap_comments = true
imports_granularity = "Crate"
max_width = 100
group_imports = "StdExternalCrate"