Add rustfmt config file and run over workspace

This commit is contained in:
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 tokio::time::{sleep, Duration};
use matrix_sdk::{
self, async_trait,
@ -7,6 +6,7 @@ use matrix_sdk::{
room::Room,
Client, ClientConfig, EventHandler, SyncSettings,
};
use tokio::time::{sleep, Duration};
use url::Url;
struct AutoJoinBot {

View file

@ -5,12 +5,11 @@ use std::{
sync::atomic::{AtomicBool, Ordering},
};
use serde_json::json;
use url::Url;
use matrix_sdk::{
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> {
let mut auth_parameters = BTreeMap::new();

View file

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

View file

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

View file

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

View file

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

View file

@ -35,6 +35,15 @@ use futures_timer::Delay as sleep;
use http::HeaderValue;
#[cfg(feature = "sso_login")]
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};
#[cfg(feature = "sso_login")]
use rand::{thread_rng, Rng};
@ -43,27 +52,15 @@ use reqwest::header::InvalidHeaderValue;
use tokio::{net::TcpListener, sync::oneshot};
#[cfg(feature = "sso_login")]
use tokio_stream::wrappers::TcpListenerStream;
#[cfg(feature = "encryption")]
use tracing::{debug, warn};
use tracing::{error, info, instrument};
use url::Url;
#[cfg(feature = "sso_login")]
use warp::Filter;
#[cfg(feature = "encryption")]
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.
///
/// This is mainly used in the [`sync_with_callback`] method, the return value
@ -96,12 +93,11 @@ use matrix_sdk_common::{
assign,
identifiers::{DeviceIdBox, RoomId, RoomIdOrAliasId, ServerName, UserId},
instant::{Duration, Instant},
locks::RwLock,
locks::{Mutex, RwLock},
presence::PresenceState,
uuid::Uuid,
FromHttpResponseError, UInt,
};
#[cfg(feature = "encryption")]
use matrix_sdk_common::{
api::r0::{
@ -113,15 +109,6 @@ use matrix_sdk_common::{
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")]
use crate::{
device::{Device, UserDevices},
@ -129,6 +116,12 @@ use crate::{
sas::Sas,
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_SYNC_TIMEOUT: Duration = Duration::from_secs(30);
@ -374,8 +367,7 @@ impl<'a> SyncSettings<'a> {
/// This does nothing if no sync token is set.
///
/// # Arguments
/// * `full_state` - A boolean deciding if the server should return the full
/// state or not.
/// * `full_state` - A boolean deciding if the server should return the full state or not.
pub fn full_state(mut self, full_state: bool) -> Self {
self.full_state = full_state;
self
@ -440,8 +432,8 @@ impl RequestConfig {
Default::default()
}
/// This is a convince method to disable the retries of a request. Setting the `retry_limit` to `0`
/// has the same effect.
/// This is a convince method to disable the retries of a request. Setting the `retry_limit` to
/// `0` has the same effect.
pub fn disable_retry(mut self) -> Self {
self.retry_limit = Some(0);
self
@ -459,7 +451,8 @@ impl RequestConfig {
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 {
self.retry_timeout = Some(retry_timeout);
self
@ -877,8 +870,7 @@ impl Client {
///
/// # Arguments
///
/// * `redirect_url` - The URL that will receive a `loginToken` after a
/// successful SSO login.
/// * `redirect_url` - The URL that will receive a `loginToken` after a successful SSO login.
///
/// [`login_with_token`]: #method.login_with_token
pub fn get_sso_login_url(&self, redirect_url: &str) -> Result<String> {
@ -908,10 +900,10 @@ impl Client {
///
/// * `password` - The password of the user.
///
/// * `device_id` - A unique id that will be associated with this session. If
/// not given the homeserver will create one. Can be an existing
/// device_id from a previous login call. Note that this should be done
/// only if the client also holds the encryption keys for this device.
/// * `device_id` - A unique id that will be associated with this session. If not given the
/// homeserver will create one. Can be an existing device_id from a previous login call. Note
/// that this should be done only if the client also holds the encryption keys for this
/// device.
///
/// # Example
/// ```no_run
@ -986,27 +978,24 @@ impl Client {
///
/// # Arguments
///
/// * `use_sso_login_url` - A callback that will receive the SSO Login URL. It
/// should usually be used to open the SSO URL in a browser and must return
/// `Ok(())` if the URL was successfully opened. If it returns `Err`, the
/// error will be forwarded.
/// * `use_sso_login_url` - A callback that will receive the SSO Login URL. It should usually be
/// used to open the SSO URL in a browser and must return `Ok(())` if the URL was successfully
/// opened. If it returns `Err`, the error will be forwarded.
///
/// * `server_url` - The local URL the server is going to try to bind to, e.g.
/// `http://localhost:3030`. If `None`, the server will try to open a random
/// port on localhost.
/// * `server_url` - The local URL the server is going to try to bind to, e.g. `http://localhost:3030`.
/// If `None`, the server will try to open a random port on localhost.
///
/// * `server_response` - The text that will be shown on the webpage at the end
/// of the login process. This can be an HTML page. If `None`, a default
/// text will be displayed.
/// * `server_response` - The text that will be shown on the webpage at the end of the login
/// process. This can be an HTML page. If `None`, a default text will be displayed.
///
/// * `device_id` - A unique id that will be associated with this session. If
/// not given the homeserver will create one. Can be an existing device_id
/// from a previous login call. Note that this should be provided only
/// if the client also holds the encryption keys for this device.
/// * `device_id` - A unique id that will be associated with this session. If not given the
/// homeserver will create one. Can be an existing device_id from a previous login call. Note
/// that this should be provided only if the client also holds the encryption keys for this
/// device.
///
/// * `initial_device_display_name` - A public display name that will be
/// associated with the device_id. Only necessary the first time you
/// login with this device_id. It can be changed later.
/// * `initial_device_display_name` - A public display name that will be associated with the
/// device_id. Only necessary the first time you login with this device_id. It can be changed
/// later.
///
/// # Example
/// ```no_run
@ -1172,14 +1161,14 @@ impl Client {
///
/// * `token` - A login token.
///
/// * `device_id` - A unique id that will be associated with this session. If
/// not given the homeserver will create one. Can be an existing device_id
/// from a previous login call. Note that this should be provided only
/// if the client also holds the encryption keys for this device.
/// * `device_id` - A unique id that will be associated with this session. If not given the
/// homeserver will create one. Can be an existing device_id from a previous login call. Note
/// that this should be provided only if the client also holds the encryption keys for this
/// device.
///
/// * `initial_device_display_name` - A public display name that will be
/// associated with the device_id. Only necessary the first time you
/// login with this device_id. It can be changed later.
/// * `initial_device_display_name` - A public display name that will be associated with the
/// device_id. Only necessary the first time you login with this device_id. It can be changed
/// later.
///
/// # Example
/// ```no_run
@ -1853,8 +1842,8 @@ impl Client {
///
/// # Arguments
///
/// * `sync_settings` - Settings for the sync call. Note that those settings
/// will be only used for the first sync call.
/// * `sync_settings` - Settings for the sync call. Note that those settings will be only used
/// for the first sync call.
///
/// [`sync_with_callback`]: #method.sync_with_callback
pub async fn sync(&self, sync_settings: SyncSettings<'_>) {
@ -1866,14 +1855,13 @@ impl Client {
///
/// # Arguments
///
/// * `sync_settings` - Settings for the sync call. Note that those settings
/// will be only used for the first sync call.
/// * `sync_settings` - Settings for the sync call. Note that those settings will be only used
/// for the first sync call.
///
/// * `callback` - A callback that will be called every time a successful
/// response has been fetched from the server. The callback must return
/// a boolean which signalizes if the method should stop syncing. If the
/// callback returns `LoopCtrl::Continue` the sync will continue, if the
/// callback returns `LoopCtrl::Break` the sync will be stopped.
/// * `callback` - A callback that will be called every time a successful response has been
/// fetched from the server. The callback must return a boolean which signalizes if the method
/// should stop syncing. If the callback returns `LoopCtrl::Continue` the sync will continue,
/// if the callback returns `LoopCtrl::Break` the sync will be stopped.
///
/// # Examples
///
@ -2035,7 +2023,6 @@ impl Client {
/// # Arguments
///
/// * `users` - The list of user/device pairs that we should claim keys for.
///
#[cfg(feature = "encryption")]
#[cfg_attr(feature = "docs", doc(cfg(encryption)))]
#[instrument(skip(users))]
@ -2453,12 +2440,8 @@ impl Client {
#[cfg(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_common::{
api::r0::{
@ -2476,7 +2459,11 @@ mod test {
use mockito::{mock, Matcher};
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 {
let session = Session {
@ -2834,7 +2821,8 @@ mod test {
let room_id = room_id!("!testroom:example.org");
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,
room_id
);
@ -2856,7 +2844,8 @@ mod test {
let room_id = room_id!("!testroom:example.org").into();
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_or_alias(&room_id, &["server.com".try_into().unwrap()])
.await

View file

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

View file

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

View file

@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#[cfg(all(not(target_arch = "wasm32")))]
use std::sync::atomic::{AtomicU64, Ordering};
use std::{convert::TryFrom, fmt::Debug, sync::Arc};
#[cfg(all(not(target_arch = "wasm32")))]
@ -19,16 +21,13 @@ use backoff::{future::retry, Error as RetryError, ExponentialBackoff};
#[cfg(all(not(target_arch = "wasm32")))]
use http::StatusCode;
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::{
api::r0::media::create_content, async_trait, locks::RwLock, AsyncTraitDeps, AuthScheme,
FromHttpResponseError, IncomingResponse, SendAccessToken,
};
use reqwest::{Client, Response};
use tracing::trace;
use url::Url;
use crate::{
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"))]
compile_error!("'sso_login' cannot be enabled on 'wasm32' arch");
pub use bytes::{Bytes, BytesMut};
#[cfg(feature = "encryption")]
#[cfg_attr(feature = "docs", doc(cfg(encryption)))]
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,
Session, StateChanges, StoreError,
};
pub use bytes::{Bytes, BytesMut};
pub use matrix_sdk_common::*;
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_common::{
api::r0::{
@ -8,8 +10,6 @@ use matrix_sdk_common::{
locks::Mutex,
};
use std::{ops::Deref, sync::Arc};
use crate::{BaseRoom, Client, Result, RoomMember};
/// 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
/// store.
///
pub async fn get_member_no_sync(&self, user_id: &UserId) -> Result<Option<RoomMember>> {
Ok(self
.inner

View file

@ -1,6 +1,7 @@
use crate::{room::Common, BaseRoom, Client, Result, RoomType};
use std::ops::Deref;
use crate::{room::Common, BaseRoom, Client, Result, RoomType};
/// A room in the invited state.
///
/// 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};
#[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::{
api::r0::{
membership::{
@ -34,18 +36,12 @@ use matrix_sdk_common::{
receipt::ReceiptType,
uuid::Uuid,
};
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")]
use tracing::instrument;
use crate::{room::Common, BaseRoom, Client, Result, RoomType};
const TYPING_NOTICE_TIMEOUT: Duration = Duration::from_secs(4);
const TYPING_NOTICE_RESEND_TIMEOUT: Duration = Duration::from_secs(3);
@ -149,9 +145,9 @@ impl Joined {
/// Activate typing notice for this room.
///
/// 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.
/// This method can be called on every key stroke, since it will do nothing while typing is
/// active.
/// typing to `false`. If this method is called while the typing notice is active nothing will
/// happen. This method can be called on every key stroke, since it will do nothing while
/// typing is active.
///
/// # Arguments
///

View file

@ -1,8 +1,9 @@
use crate::{room::Common, BaseRoom, Client, Result, RoomType};
use std::ops::Deref;
use matrix_sdk_common::api::r0::membership::forget_room;
use crate::{room::Common, BaseRoom, Client, Result, RoomType};
/// A room in the left state.
///
/// 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 matrix_sdk_common::api::r0::media::{get_content, get_content_thumbnail};
use crate::{BaseRoomMember, Client, Result};
/// The high-level `RoomMember` representation

View file

@ -17,6 +17,7 @@ use std::{
pin::Pin,
};
pub use actix_web::Scope;
use actix_web::{
dev::Payload,
error::PayloadError,
@ -30,8 +31,6 @@ use futures::Future;
use futures_util::{TryFutureExt, TryStreamExt};
use matrix_sdk::api_appservice as api;
pub use actix_web::Scope;
use crate::{error::Error, Appservice};
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
//! * receive and validate requests from the homeserver correctly
//! * 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
//!
@ -62,6 +63,8 @@ use std::{
};
use http::Uri;
#[doc(inline)]
pub use matrix_sdk::api_appservice as api;
use matrix_sdk::{
api::{
error::ErrorKind,
@ -81,9 +84,6 @@ use regex::Regex;
use tracing::error;
use tracing::warn;
#[doc(inline)]
pub use matrix_sdk::api_appservice as api;
#[cfg(feature = "actix")]
mod actix;
mod error;

View file

@ -1,8 +1,9 @@
#[cfg(feature = "actix")]
mod actix {
use std::env;
use actix_web::{test, App};
use matrix_sdk_appservice::*;
use std::env;
async fn appservice() -> Appservice {
env::set_var(
@ -109,7 +110,8 @@ mod actix {
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);
}
}

View file

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

View file

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

View file

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

View file

@ -36,11 +36,12 @@
)]
#![cfg_attr(feature = "docs", feature(doc_cfg))]
pub use matrix_sdk_common::*;
pub use crate::{
error::{Error, Result},
session::Session,
};
pub use matrix_sdk_common::*;
mod client;
mod error;
@ -48,11 +49,9 @@ mod rooms;
mod session;
mod store;
pub use rooms::{Room, RoomInfo, RoomMember, RoomType};
pub use store::{StateChanges, StateStore, Store, StoreError};
pub use client::{BaseClient, BaseClientConfig};
#[cfg(feature = "encryption")]
#[cfg_attr(feature = "docs", doc(cfg(encryption)))]
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 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 matrix_sdk_common::{
events::{
room::{encryption::EncryptionEventContent, tombstone::TombstoneEventContent},
room::{
create::CreateEventContent, encryption::EncryptionEventContent,
guest_access::GuestAccess, history_visibility::HistoryVisibility, join_rules::JoinRule,
tombstone::TombstoneEventContent,
},
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
/// 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 tracing::info;
use super::{BaseRoomInfo, RoomMember};
use crate::{
deserialized_responses::UnreadNotificationsCount,
store::{Result as StoreResult, StateStore},
};
use super::{BaseRoomInfo, RoomMember};
/// The underlying room data structure collecting state for joined, left and invtied rooms.
#[derive(Debug, Clone)]
pub struct Room {

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -6,14 +6,12 @@ use std::{
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")]
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")]
pub fn spawn<F, T>(future: F) -> JoinHandle<T>

View file

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

View file

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

View file

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

View file

@ -17,21 +17,17 @@ use std::{
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::{
cipher::{NewStreamCipher, SyncStreamCipher},
Aes256Ctr,
};
use base64::DecodeError;
use getrandom::getrandom;
use matrix_sdk_common::events::room::JsonWebKey;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use thiserror::Error;
use zeroize::Zeroizing;
use crate::utilities::{decode, decode_url_safe, encode, encode_url_safe};
@ -274,10 +270,12 @@ pub struct EncryptionInfo {
#[cfg(test)]
mod test {
use super::{AttachmentDecryptor, AttachmentEncryptor, EncryptionInfo};
use serde_json::json;
use std::io::{Cursor, Read};
use serde_json::json;
use super::{AttachmentDecryptor, AttachmentEncryptor, EncryptionInfo};
const EXAMPLE_DATA: &[u8] = &[
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,

View file

@ -12,20 +12,19 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use serde_json::Error as SerdeError;
use std::io::{Cursor, Read, Seek, SeekFrom};
use thiserror::Error;
use byteorder::{BigEndian, ReadBytesExt};
use getrandom::getrandom;
use aes_ctr::{
cipher::{NewStreamCipher, SyncStreamCipher},
Aes256Ctr,
};
use byteorder::{BigEndian, ReadBytesExt};
use getrandom::getrandom;
use hmac::{Hmac, Mac, NewMac};
use pbkdf2::pbkdf2;
use serde_json::Error as SerdeError;
use sha2::{Sha256, Sha512};
use thiserror::Error;
use crate::{
olm::ExportedRoomKey,
@ -231,12 +230,12 @@ fn decrypt_helper(ciphertext: &str, passphrase: &str) -> Result<String, KeyExpor
#[cfg(test)]
mod test {
use indoc::indoc;
use proptest::prelude::*;
use std::io::Cursor;
use indoc::indoc;
use matrix_sdk_common::identifiers::room_id;
use matrix_sdk_test::async_test;
use proptest::prelude::*;
use super::{decode, decrypt_helper, decrypt_key_export, encrypt_helper, encrypt_key_export};
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 tracing::warn;
use crate::{
olm::{InboundGroupSession, PrivateCrossSigningIdentity, Session},
store::{Changes, DeviceChanges},
OutgoingVerificationRequest,
};
#[cfg(test)]
use crate::{OlmMachine, ReadOnlyAccount};
use super::{atomic_bool_deserializer, atomic_bool_serializer};
use crate::{
error::{EventError, OlmError, OlmResult, SignatureError},
identities::{OwnUserIdentity, UserIdentities},
olm::Utility,
store::{CryptoStore, Result as StoreResult},
olm::{InboundGroupSession, PrivateCrossSigningIdentity, Session, Utility},
store::{Changes, CryptoStore, DeviceChanges, Result as StoreResult},
verification::VerificationMachine,
Sas, ToDeviceRequest,
OutgoingVerificationRequest, Sas, ToDeviceRequest,
};
use super::{atomic_bool_deserializer, atomic_bool_serializer};
#[cfg(test)]
use crate::{OlmMachine, ReadOnlyAccount};
/// A read-only version of a `Device`.
#[derive(Clone, Serialize, Deserialize)]
@ -590,14 +583,15 @@ impl PartialEq for ReadOnlyDevice {
#[cfg(test)]
pub(crate) mod test {
use serde_json::json;
use std::convert::TryFrom;
use crate::identities::{LocalTrust, ReadOnlyDevice};
use matrix_sdk_common::{
encryption::DeviceKeys,
identifiers::{user_id, DeviceKeyAlgorithm},
};
use serde_json::json;
use crate::identities::{LocalTrust, ReadOnlyDevice};
fn device_keys() -> DeviceKeys {
let device_keys = json!({

View file

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

View file

@ -44,19 +44,19 @@ pub(crate) mod device;
mod manager;
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::{
atomic::{AtomicBool, Ordering},
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
// be implemented for WASM.
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::{
api::r0::keys::{CrossSigningKey, KeyUsage},
identifiers::{DeviceKeyId, UserId},
};
use serde::{Deserialize, Serialize};
use serde_json::to_value;
use super::{atomic_bool_deserializer, atomic_bool_serializer};
#[cfg(test)]
use crate::olm::PrivateCrossSigningIdentity;
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.
///
/// Master keys are used to sign other cross signing keys, the self signing and
@ -719,6 +717,12 @@ impl OwnUserIdentity {
pub(crate) mod test {
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::{
identities::{
manager::test::{other_key_query, own_key_query},
@ -729,13 +733,6 @@ pub(crate) mod test {
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) {
let mut devices = response.device_keys.values().next().unwrap().values();
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
// 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 thiserror::Error;
use tracing::{error, info, trace, warn};
use dashmap::{mapref::entry::Entry, DashMap, DashSet};
use matrix_sdk_common::{
api::r0::to_device::DeviceIdOrAllDevices,
events::{
@ -37,6 +33,10 @@ use matrix_sdk_common::{
identifiers::{DeviceId, DeviceIdBox, EventEncryptionAlgorithm, RoomId, UserId},
uuid::Uuid,
};
use serde::{Deserialize, Serialize};
use serde_json::value::to_raw_value;
use thiserror::Error;
use tracing::{error, info, trace, warn};
use crate::{
error::{OlmError, OlmResult},
@ -817,6 +817,8 @@ impl KeyRequestMachine {
#[cfg(test)]
mod test {
use std::{convert::TryInto, sync::Arc};
use dashmap::DashMap;
use matrix_sdk_common::{
api::r0::to_device::DeviceIdOrAllDevices,
@ -829,8 +831,8 @@ mod test {
locks::Mutex,
};
use matrix_sdk_test::async_test;
use std::{convert::TryInto, sync::Arc};
use super::{KeyRequestMachine, KeyshareDecision};
use crate::{
identities::{LocalTrust, ReadOnlyDevice},
olm::{Account, PrivateCrossSigningIdentity, ReadOnlyAccount},
@ -839,8 +841,6 @@ mod test {
verification::VerificationMachine,
};
use super::{KeyRequestMachine, KeyshareDecision};
fn alice_id() -> UserId {
user_id!("@alice:example.org")
}

View file

@ -17,8 +17,6 @@ use std::path::Path;
use std::{collections::BTreeMap, mem, sync::Arc};
use dashmap::DashMap;
use tracing::{debug, error, info, trace, warn};
use matrix_sdk_common::{
api::r0::{
keys::{
@ -44,6 +42,7 @@ use matrix_sdk_common::{
uuid::Uuid,
UInt,
};
use tracing::{debug, error, info, trace, warn};
#[cfg(feature = "sled_cryptostore")]
use crate::store::sled::SledStore;
@ -1276,15 +1275,6 @@ pub(crate) mod test {
};
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::{
api::r0::keys::{claim_keys, get_keys, upload_keys, OneTimeKey},
events::{
@ -1301,6 +1291,14 @@ pub(crate) mod test {
IncomingResponse, Raw,
};
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.
type OneTimeKeys = BTreeMap<DeviceKeyId, OneTimeKey>;

View file

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

View file

@ -19,19 +19,6 @@ use std::{
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::{
events::{
forwarded_room_key::ForwardedRoomKeyToDeviceEventContent,
@ -45,6 +32,17 @@ use matrix_sdk_common::{
locks::Mutex,
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 crate::error::{EventError, MegolmResult};

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -12,32 +12,27 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use std::{collections::BTreeMap, convert::TryInto, sync::Arc};
use aes_gcm::{
aead::{generic_array::GenericArray, Aead, NewAead},
Aes256Gcm,
};
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::{
api::r0::keys::{CrossSigningKey, KeyUsage},
identifiers::UserId,
encryption::DeviceKeys,
identifiers::{DeviceKeyAlgorithm, DeviceKeyId, UserId},
locks::Mutex,
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::{
error::SignatureError,

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -43,11 +43,6 @@ mod pickle_key;
#[cfg(feature = "sled_cryptostore")]
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::{
collections::{HashMap, HashSet},
fmt::Debug,
@ -56,10 +51,6 @@ use std::{
sync::Arc,
};
use olm_rs::errors::{OlmAccountError, OlmGroupSessionError, OlmSessionError};
use serde_json::Error as SerdeError;
use thiserror::Error;
use matrix_sdk_common::{
async_trait,
events::room_key_request::RequestedKeyInfo,
@ -71,7 +62,14 @@ use matrix_sdk_common::{
uuid::Uuid,
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::{
error::SessionUnpicklingError,
identities::{Device, ReadOnlyDevice, UserDevices, UserIdentities},

View file

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

View file

@ -20,13 +20,6 @@ use std::{
};
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::{
async_trait,
events::room_key_request::RequestedKeyInfo,
@ -34,6 +27,12 @@ use matrix_sdk_common::{
locks::Mutex,
uuid,
};
use olm_rs::{account::IdentityKeys, PicklingMode};
pub use sled::Error;
use sled::{
transaction::{ConflictableTransactionError, TransactionError},
Config, Db, Transactional, Tree,
};
use uuid::Uuid;
use super::{
@ -793,6 +792,19 @@ impl CryptoStore for SledStore {
#[cfg(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::{
identities::{
device::test::get_device,
@ -804,18 +816,6 @@ mod test {
},
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 {
user_id!("@alice:example.org")

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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