Skip to content

feat(sdk): Spaces #5509

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 24 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
84209fd
chore(spaces): setup a simple space service and some unit tests
stefanceriu Aug 1, 2025
7ff3034
chore(spaces): move space specific test fixtures from `test_event` an…
stefanceriu Aug 4, 2025
1970b49
chore(spaces): introduce a `SpaceServiceRoom`
stefanceriu Aug 4, 2025
417d376
feat(spaces): introduce a `SpaceRoomList` that allows pagination and …
stefanceriu Aug 6, 2025
6d8961d
feat(spaces): add a reactive version of the `joined_spaces` method
stefanceriu Aug 7, 2025
304e282
change(spaces): return only top level joined rooms from `SpaceService…
stefanceriu Aug 7, 2025
c9d46de
feat(spaces): have the `SpaceRoomList` publish updates as known room …
stefanceriu Aug 8, 2025
bdc7d83
fix(spaces): fix complement-crypto failures because of using an outda…
stefanceriu Aug 8, 2025
90059a2
fix(spaces): use wasm compatible executor `spawn` and `JoinHandle`
stefanceriu Aug 8, 2025
beae1f9
fix(room): fix event types in `matrix_sdk::Room::parent_spaces` metho…
stefanceriu Aug 11, 2025
d6f0126
change(room_list): request both `m.space.parent` and `m.space.child` …
stefanceriu Aug 11, 2025
b41157e
chore(spaces): build a graph from joined spaces parent and child rela…
stefanceriu Aug 11, 2025
36867e7
feat(ffi): expose `SpaceService::subscribe_to_joined_spaces` and `Spa…
stefanceriu Aug 11, 2025
76c51f8
fix(spaces): return the TaskHandle from the FFI space service subscri…
stefanceriu Aug 11, 2025
7c12725
feat(spaces): expose the number of children each space room has
stefanceriu Aug 11, 2025
004df0f
change(spaces): put a limit of 1 on the max depth of the /hierarchy c…
stefanceriu Aug 11, 2025
1ac356a
fix(spaces): filter out the current parent space from the `/hierarchy…
stefanceriu Aug 11, 2025
9168c30
change(spaces): make the `SpaceService` constructor non-async and ins…
stefanceriu Aug 11, 2025
511c975
chore(spaces): converge on single naming scheme for all spaces relate…
stefanceriu Aug 12, 2025
b13fb14
chore(spaces): add changelog
stefanceriu Aug 13, 2025
5e546f6
change(spaces): publish VectorDiffs instead of a full vectors for joi…
stefanceriu Aug 14, 2025
571daa7
chore(spaces): ignore room list change updates if empty
stefanceriu Aug 18, 2025
c6a25e9
docs(spaces): add documentation, comments and examples
stefanceriu Aug 19, 2025
71bbeb2
chore(ffi): expose sliding sync's `expire_sessions` method
stefanceriu Aug 19, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

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

7 changes: 7 additions & 0 deletions bindings/matrix-sdk-ffi/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ use matrix_sdk_ui::{
NotificationClient as MatrixNotificationClient,
NotificationProcessSetup as MatrixNotificationProcessSetup,
},
spaces::SpaceService as UISpaceService,
unable_to_decrypt_hook::UtdHookManager,
};
use mime::Mime;
Expand Down Expand Up @@ -111,6 +112,7 @@ use crate::{
MediaPreviews, MediaSource, RoomAccountDataEvent, RoomAccountDataEventType,
},
runtime::get_runtime_handle,
spaces::SpaceService,
sync_service::{SyncService, SyncServiceBuilder},
task_handle::TaskHandle,
utd::{UnableToDecryptDelegate, UtdHook},
Expand Down Expand Up @@ -1257,6 +1259,11 @@ impl Client {
SyncServiceBuilder::new((*self.inner).clone(), self.utd_hook_manager.get().cloned())
}

pub fn space_service(&self) -> Arc<SpaceService> {
let inner = UISpaceService::new((*self.inner).clone());
Arc::new(SpaceService::new(inner))
}

pub async fn get_notification_settings(&self) -> Arc<NotificationSettings> {
let inner = self.inner.notification_settings().await;

Expand Down
1 change: 1 addition & 0 deletions bindings/matrix-sdk-ffi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ mod room_preview;
mod ruma;
mod runtime;
mod session_verification;
mod spaces;
mod sync_service;
mod task_handle;
mod timeline;
Expand Down
12 changes: 6 additions & 6 deletions bindings/matrix-sdk-ffi/src/room_preview.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ impl RoomPreview {
avatar_url: info.avatar_url.as_ref().map(|url| url.to_string()),
num_joined_members: info.num_joined_members,
num_active_members: info.num_active_members,
room_type: info.room_type.as_ref().into(),
room_type: info.room_type.clone().into(),
is_history_world_readable: info.is_world_readable,
membership: info.state.map(|state| state.into()),
join_rule: info.join_rule.as_ref().map(Into::into),
join_rule: info.join_rule.clone().map(Into::into),
is_direct: info.is_direct,
heroes: info
.heroes
Expand Down Expand Up @@ -116,8 +116,8 @@ pub struct RoomPreviewInfo {
pub heroes: Option<Vec<RoomHero>>,
}

impl From<&JoinRuleSummary> for JoinRule {
fn from(join_rule: &JoinRuleSummary) -> Self {
impl From<JoinRuleSummary> for JoinRule {
fn from(join_rule: JoinRuleSummary) -> Self {
match join_rule {
JoinRuleSummary::Invite => JoinRule::Invite,
JoinRuleSummary::Knock => JoinRule::Knock,
Expand Down Expand Up @@ -153,8 +153,8 @@ pub enum RoomType {
Custom { value: String },
}

impl From<Option<&RumaRoomType>> for RoomType {
fn from(value: Option<&RumaRoomType>) -> Self {
impl From<Option<RumaRoomType>> for RoomType {
fn from(value: Option<RumaRoomType>) -> Self {
match value {
Some(RumaRoomType::Space) => RoomType::Space,
Some(RumaRoomType::_Custom(_)) => RoomType::Custom {
Expand Down
237 changes: 237 additions & 0 deletions bindings/matrix-sdk-ffi/src/spaces.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,237 @@
// Copyright 2025 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::{fmt::Debug, sync::Arc};

use eyeball_im::VectorDiff;
use futures_util::{pin_mut, StreamExt};
use matrix_sdk_common::{SendOutsideWasm, SyncOutsideWasm};
use matrix_sdk_ui::spaces::{
room_list::SpaceRoomListPaginationState, SpaceRoom as UISpaceRoom,
SpaceRoomList as UISpaceRoomList, SpaceService as UISpaceService,
};
use ruma::RoomId;

use crate::{
client::JoinRule,
error::ClientError,
room::{Membership, RoomHero},
room_preview::RoomType,
runtime::get_runtime_handle,
TaskHandle,
};

#[derive(uniffi::Object)]
pub struct SpaceService {
inner: UISpaceService,
}

impl SpaceService {
pub(crate) fn new(inner: UISpaceService) -> Self {
Self { inner }
}
}

#[matrix_sdk_ffi_macros::export]
impl SpaceService {
pub async fn joined_spaces(&self) -> Vec<SpaceRoom> {
self.inner.joined_spaces().await.into_iter().map(Into::into).collect()
}

#[allow(clippy::unused_async)]
// This method doesn't need to be async but if its not the FFI layer panics
// with "there is no no reactor running, must be called from the context
// of a Tokio 1.x runtime" error because the underlying method spawns an
// async task.
pub async fn subscribe_to_joined_spaces(
&self,
listener: Box<dyn SpaceServiceJoinedSpacesListener>,
) -> Arc<TaskHandle> {
let (initial_values, mut stream) = self.inner.subscribe_to_joined_spaces();

listener.on_update(vec![SpaceListUpdate::Reset {
values: initial_values.into_iter().map(Into::into).collect(),
}]);

Arc::new(TaskHandle::new(get_runtime_handle().spawn(async move {
while let Some(diffs) = stream.next().await {
listener.on_update(diffs.into_iter().map(Into::into).collect());
}
})))
}
#[allow(clippy::unused_async)]
// This method doesn't need to be async but if its not the FFI layer panics
// with "there is no no reactor running, must be called from the context
// of a Tokio 1.x runtime" error because the underlying constructor spawns
// an async task.
pub async fn space_room_list(
&self,
space_id: String,
) -> Result<Arc<SpaceRoomList>, ClientError> {
let space_id = RoomId::parse(space_id)?;
Ok(Arc::new(SpaceRoomList::new(self.inner.space_room_list(space_id))))
}
}

#[derive(uniffi::Object)]
pub struct SpaceRoomList {
inner: UISpaceRoomList,
}

impl SpaceRoomList {
fn new(inner: UISpaceRoomList) -> Self {
Self { inner }
}
}

#[matrix_sdk_ffi_macros::export]
impl SpaceRoomList {
pub fn pagination_state(&self) -> SpaceRoomListPaginationState {
self.inner.pagination_state()
}

pub fn subscribe_to_pagination_state_updates(
&self,
listener: Box<dyn SpaceRoomListPaginationStateListener>,
) -> Arc<TaskHandle> {
let pagination_state = self.inner.subscribe_to_pagination_state_updates();

Arc::new(TaskHandle::new(get_runtime_handle().spawn(async move {
pin_mut!(pagination_state);

while let Some(state) = pagination_state.next().await {
listener.on_update(state);
}
})))
}

pub fn rooms(&self) -> Vec<SpaceRoom> {
self.inner.rooms().into_iter().map(Into::into).collect()
}

pub fn subscribe_to_room_update(
&self,
listener: Box<dyn SpaceRoomListEntriesListener>,
) -> Arc<TaskHandle> {
let (initial_values, mut stream) = self.inner.subscribe_to_room_updates();

listener.on_update(vec![SpaceListUpdate::Reset {
values: initial_values.into_iter().map(Into::into).collect(),
}]);

Arc::new(TaskHandle::new(get_runtime_handle().spawn(async move {
while let Some(diffs) = stream.next().await {
listener.on_update(diffs.into_iter().map(Into::into).collect());
}
})))
}

pub async fn paginate(&self) -> Result<(), ClientError> {
self.inner.paginate().await.map_err(ClientError::from)
}
}

#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait SpaceRoomListPaginationStateListener: SendOutsideWasm + SyncOutsideWasm + Debug {
fn on_update(&self, pagination_state: SpaceRoomListPaginationState);
}

#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait SpaceRoomListEntriesListener: SendOutsideWasm + SyncOutsideWasm + Debug {
fn on_update(&self, rooms: Vec<SpaceListUpdate>);
}

#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait SpaceServiceJoinedSpacesListener: SendOutsideWasm + SyncOutsideWasm + Debug {
fn on_update(&self, room_updates: Vec<SpaceListUpdate>);
}

#[derive(uniffi::Record)]
pub struct SpaceRoom {
pub room_id: String,
pub canonical_alias: Option<String>,
pub name: Option<String>,
pub topic: Option<String>,
pub avatar_url: Option<String>,
pub room_type: RoomType,
pub num_joined_members: u64,
pub join_rule: Option<JoinRule>,
pub world_readable: Option<bool>,
pub guest_can_join: bool,

pub children_count: u64,
pub state: Option<Membership>,
pub heroes: Option<Vec<RoomHero>>,
}

impl From<UISpaceRoom> for SpaceRoom {
fn from(room: UISpaceRoom) -> Self {
Self {
room_id: room.room_id.into(),
canonical_alias: room.canonical_alias.map(|alias| alias.into()),
name: room.name,
topic: room.topic,
avatar_url: room.avatar_url.map(|url| url.into()),
room_type: room.room_type.into(),
num_joined_members: room.num_joined_members,
join_rule: room.join_rule.map(Into::into),
world_readable: room.world_readable,
guest_can_join: room.guest_can_join,
children_count: room.children_count,
state: room.state.map(Into::into),
heroes: room.heroes.map(|heroes| heroes.into_iter().map(Into::into).collect()),
}
}
}

#[derive(uniffi::Enum)]
pub enum SpaceListUpdate {
Append { values: Vec<SpaceRoom> },
Clear,
PushFront { value: SpaceRoom },
PushBack { value: SpaceRoom },
PopFront,
PopBack,
Insert { index: u32, value: SpaceRoom },
Set { index: u32, value: SpaceRoom },
Remove { index: u32 },
Truncate { length: u32 },
Reset { values: Vec<SpaceRoom> },
}

impl From<VectorDiff<UISpaceRoom>> for SpaceListUpdate {
fn from(diff: VectorDiff<UISpaceRoom>) -> Self {
match diff {
VectorDiff::Append { values } => {
Self::Append { values: values.into_iter().map(|v| v.into()).collect() }
}
VectorDiff::Clear => Self::Clear,
VectorDiff::PushFront { value } => Self::PushFront { value: value.into() },
VectorDiff::PushBack { value } => Self::PushBack { value: value.into() },
VectorDiff::PopFront => Self::PopFront,
VectorDiff::PopBack => Self::PopBack,
VectorDiff::Insert { index, value } => {
Self::Insert { index: index as u32, value: value.into() }
}
VectorDiff::Set { index, value } => {
Self::Set { index: index as u32, value: value.into() }
}
VectorDiff::Remove { index } => Self::Remove { index: index as u32 },
VectorDiff::Truncate { length } => Self::Truncate { length: length as u32 },
VectorDiff::Reset { values } => {
Self::Reset { values: values.into_iter().map(|v| v.into()).collect() }
}
}
}
}
9 changes: 9 additions & 0 deletions bindings/matrix-sdk-ffi/src/sync_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,15 @@ impl SyncService {
}
})))
}

/// Force expiring both sliding sync sessions.
///
/// This ensures that the sync service is stopped before expiring both
/// sessions. It should be used sparingly, as it will cause a restart of
/// the sessions on the server as well.
pub async fn expire_sessions(&self) {
self.inner.expire_sessions().await;
}
}

#[derive(Clone, uniffi::Object)]
Expand Down
Loading
Loading