Skip to content

Commit

Permalink
Merge branch 'main' into feat/subscribe-beacons
Browse files Browse the repository at this point in the history
Signed-off-by: torrybr <[email protected]>
  • Loading branch information
torrybr authored Nov 5, 2024
2 parents c5ec943 + ace96e3 commit 2bf5635
Show file tree
Hide file tree
Showing 77 changed files with 2,763 additions and 1,421 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ jobs:
uses: actions/checkout@v4

- name: Check the spelling of the files in our repo
uses: crate-ci/typos@v1.26.8
uses: crate-ci/typos@v1.27.0

clippy:
name: Run clippy
Expand Down
46 changes: 28 additions & 18 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ once_cell = "1.16.0"
pin-project-lite = "0.2.9"
rand = "0.8.5"
reqwest = { version = "0.12.4", default-features = false }
ruma = { git = "https://github.com/ruma/ruma", rev = "26165b23fc2ae9928c5497a21db3d31f4b44cc2a", features = [
ruma = { version = "0.11.1", features = [
"client-api-c",
"compat-upload-signatures",
"compat-user-id",
Expand All @@ -59,7 +59,7 @@ ruma = { git = "https://github.com/ruma/ruma", rev = "26165b23fc2ae9928c5497a21d
"unstable-msc4075",
"unstable-msc4140",
] }
ruma-common = { git = "https://github.com/ruma/ruma", rev = "26165b23fc2ae9928c5497a21db3d31f4b44cc2a" }
ruma-common = "0.14.1"
serde = "1.0.151"
serde_html_form = "0.2.0"
serde_json = "1.0.91"
Expand Down
10 changes: 6 additions & 4 deletions benchmarks/benches/room_bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,8 +171,9 @@ pub fn load_pinned_events_benchmark(c: &mut Criterion) {
);

let room = client.get_room(&room_id).expect("Room not found");
assert!(!room.pinned_event_ids().is_empty());
assert_eq!(room.pinned_event_ids().len(), PINNED_EVENTS_COUNT);
let pinned_event_ids = room.pinned_event_ids().unwrap_or_default();
assert!(!pinned_event_ids.is_empty());
assert_eq!(pinned_event_ids.len(), PINNED_EVENTS_COUNT);

let count = PINNED_EVENTS_COUNT;
let name = format!("{count} pinned events");
Expand All @@ -191,8 +192,9 @@ pub fn load_pinned_events_benchmark(c: &mut Criterion) {

group.bench_function(BenchmarkId::new("load_pinned_events", name), |b| {
b.to_async(&runtime).iter(|| async {
assert!(!room.pinned_event_ids().is_empty());
assert_eq!(room.pinned_event_ids().len(), PINNED_EVENTS_COUNT);
let pinned_event_ids = room.pinned_event_ids().unwrap_or_default();
assert!(!pinned_event_ids.is_empty());
assert_eq!(pinned_event_ids.len(), PINNED_EVENTS_COUNT);

// Reset cache so it always loads the events from the mocked endpoint
client.event_cache().empty_immutable_cache().await;
Expand Down
11 changes: 6 additions & 5 deletions bindings/matrix-sdk-crypto-ffi/src/machine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ use ruma::{
},
serde::Raw,
to_device::DeviceIdOrAllDevices,
DeviceKeyAlgorithm, EventId, OwnedTransactionId, OwnedUserId, RoomId, UserId,
DeviceKeyAlgorithm, EventId, OneTimeKeyAlgorithm, OwnedTransactionId, OwnedUserId, RoomId,
UserId,
};
use serde::{Deserialize, Serialize};
use serde_json::{value::RawValue, Value};
Expand Down Expand Up @@ -528,20 +529,20 @@ impl OlmMachine {
) -> Result<SyncChangesResult, CryptoStoreError> {
let to_device: ToDevice = serde_json::from_str(&events)?;
let device_changes: RumaDeviceLists = device_changes.into();
let key_counts: BTreeMap<DeviceKeyAlgorithm, UInt> = key_counts
let key_counts: BTreeMap<OneTimeKeyAlgorithm, UInt> = key_counts
.into_iter()
.map(|(k, v)| {
(
DeviceKeyAlgorithm::from(k),
OneTimeKeyAlgorithm::from(k),
v.clamp(0, i32::MAX)
.try_into()
.expect("Couldn't convert key counts into an UInt"),
)
})
.collect();

let unused_fallback_keys: Option<Vec<DeviceKeyAlgorithm>> =
unused_fallback_keys.map(|u| u.into_iter().map(DeviceKeyAlgorithm::from).collect());
let unused_fallback_keys: Option<Vec<OneTimeKeyAlgorithm>> =
unused_fallback_keys.map(|u| u.into_iter().map(OneTimeKeyAlgorithm::from).collect());

let (to_device_events, room_key_infos) = self.runtime.block_on(
self.inner.receive_sync_changes(matrix_sdk_crypto::EncryptionSyncChanges {
Expand Down
6 changes: 6 additions & 0 deletions bindings/matrix-sdk-crypto-ffi/src/users.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ pub enum UserIdentity {
user_signing_key: String,
/// The public self-signing key of our identity.
self_signing_key: String,
/// True if this identity was verified at some point but is not anymore.
has_verification_violation: bool,
},
/// The user identity of other users.
Other {
Expand All @@ -27,6 +29,8 @@ pub enum UserIdentity {
master_key: String,
/// The public self-signing key of our identity.
self_signing_key: String,
/// True if this identity was verified at some point but is not anymore.
has_verification_violation: bool,
},
}

Expand All @@ -44,6 +48,7 @@ impl UserIdentity {
master_key: serde_json::to_string(&master)?,
user_signing_key: serde_json::to_string(&user_signing)?,
self_signing_key: serde_json::to_string(&self_signing)?,
has_verification_violation: i.has_verification_violation(),
}
}
SdkUserIdentity::Other(i) => {
Expand All @@ -54,6 +59,7 @@ impl UserIdentity {
user_id: i.user_id().to_string(),
master_key: serde_json::to_string(&master)?,
self_signing_key: serde_json::to_string(&self_signing)?,
has_verification_violation: i.has_verification_violation(),
}
}
})
Expand Down
63 changes: 41 additions & 22 deletions bindings/matrix-sdk-ffi/src/client.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::{
collections::HashMap,
fmt::Debug,
mem::ManuallyDrop,
path::Path,
sync::{Arc, RwLock},
};
Expand All @@ -23,6 +22,7 @@ use matrix_sdk::{
},
OidcAuthorizationData, OidcSession,
},
reqwest::StatusCode,
ruma::{
api::client::{
media::get_content_thumbnail::v3::Method,
Expand All @@ -41,7 +41,7 @@ use matrix_sdk::{
EventEncryptionAlgorithm, RoomId, TransactionId, UInt, UserId,
},
sliding_sync::Version as SdkSlidingSyncVersion,
AuthApi, AuthSession, Client as MatrixClient, SessionChange, SessionTokens,
AuthApi, AuthSession, Client as MatrixClient, HttpError, SessionChange, SessionTokens,
};
use matrix_sdk_ui::notification_client::{
NotificationClient as MatrixNotificationClient,
Expand Down Expand Up @@ -79,6 +79,7 @@ use crate::{
ruma::AuthData,
sync_service::{SyncService, SyncServiceBuilder},
task_handle::TaskHandle,
utils::AsyncRuntimeDropped,
ClientError,
};

Expand Down Expand Up @@ -184,26 +185,12 @@ impl From<matrix_sdk::TransmissionProgress> for TransmissionProgress {

#[derive(uniffi::Object)]
pub struct Client {
pub(crate) inner: ManuallyDrop<MatrixClient>,
pub(crate) inner: AsyncRuntimeDropped<MatrixClient>,
delegate: RwLock<Option<Arc<dyn ClientDelegate>>>,
session_verification_controller:
Arc<tokio::sync::RwLock<Option<SessionVerificationController>>>,
}

impl Drop for Client {
fn drop(&mut self) {
// Dropping the inner OlmMachine must happen within a tokio context
// because deadpool drops sqlite connections in the DB pool on tokio's
// blocking threadpool to avoid blocking async worker threads.
let _guard = RUNTIME.enter();
// SAFETY: self.inner is never used again, which is the only requirement
// for ManuallyDrop::drop to be used safely.
unsafe {
ManuallyDrop::drop(&mut self.inner);
}
}
}

impl Client {
pub async fn new(
sdk_client: MatrixClient,
Expand All @@ -224,7 +211,7 @@ impl Client {
});

let client = Client {
inner: ManuallyDrop::new(sdk_client),
inner: AsyncRuntimeDropped::new(sdk_client),
delegate: RwLock::new(None),
session_verification_controller,
};
Expand Down Expand Up @@ -503,7 +490,7 @@ impl Client {
Arc::new(TaskHandle::new(RUNTIME.spawn(async move {
// Respawn tasks for rooms that had unsent events. At this point we've just
// created the subscriber, so it'll be notified about errors.
q.respawn_tasks_for_rooms_with_unsent_events().await;
q.respawn_tasks_for_rooms_with_unsent_requests().await;

loop {
match subscriber.recv().await {
Expand Down Expand Up @@ -606,6 +593,10 @@ impl Client {
&self,
action: Option<AccountManagementAction>,
) -> Result<Option<String>, ClientError> {
if !matches!(self.inner.auth_api(), Some(AuthApi::Oidc(..))) {
return Ok(None);
}

match self.inner.oidc().account_management_url(action.map(Into::into)).await {
Ok(url) => Ok(url.map(|u| u.to_string())),
Err(e) => {
Expand Down Expand Up @@ -1037,10 +1028,21 @@ impl Client {
pub async fn resolve_room_alias(
&self,
room_alias: String,
) -> Result<ResolvedRoomAlias, ClientError> {
) -> Result<Option<ResolvedRoomAlias>, ClientError> {
let room_alias = RoomAliasId::parse(&room_alias)?;
let response = self.inner.resolve_room_alias(&room_alias).await?;
Ok(response.into())
match self.inner.resolve_room_alias(&room_alias).await {
Ok(response) => Ok(Some(response.into())),
Err(HttpError::Reqwest(http_error)) => match http_error.status() {
Some(StatusCode::NOT_FOUND) => Ok(None),
_ => Err(http_error.into()),
},
Err(error) => Err(error.into()),
}
}

/// Checks if a room alias exists in the current homeserver.
pub async fn room_alias_exists(&self, room_alias: String) -> Result<bool, ClientError> {
self.resolve_room_alias(room_alias).await.map(|ret| ret.is_some())
}

/// Given a room id, get the preview of a room, to interact with it.
Expand Down Expand Up @@ -1126,6 +1128,23 @@ impl Client {

Ok(())
}

/// Checks if a room alias is available in the current homeserver.
pub async fn is_room_alias_available(&self, alias: String) -> Result<bool, ClientError> {
let alias = RoomAliasId::parse(alias)?;
match self.inner.resolve_room_alias(&alias).await {
// The room alias was resolved, so it's already in use.
Ok(_) => Ok(false),
Err(HttpError::Reqwest(error)) => {
match error.status() {
// The room alias wasn't found, so it's available.
Some(StatusCode::NOT_FOUND) => Ok(true),
_ => Err(HttpError::Reqwest(error).into()),
}
}
Err(error) => Err(error.into()),
}
}
}

#[matrix_sdk_ffi_macros::export(callback_interface)]
Expand Down
Loading

0 comments on commit 2bf5635

Please sign in to comment.