diff --git a/crates/matrix-sdk/src/client/mod.rs b/crates/matrix-sdk/src/client/mod.rs index 900c9fe22f..12eb9fb88a 100644 --- a/crates/matrix-sdk/src/client/mod.rs +++ b/crates/matrix-sdk/src/client/mod.rs @@ -45,7 +45,7 @@ use ruma::{ api::{ client::{ account::whoami, - alias::get_alias, + alias::{create_alias, get_alias}, device::{delete_devices, get_devices, update_device}, directory::{get_public_rooms, get_public_rooms_filtered}, discovery::{ @@ -1060,6 +1060,13 @@ impl Client { } } + /// Creates a new room alias associated with a room. + pub async fn create_room_alias(&self, alias: &RoomAliasId, room_id: &RoomId) -> HttpResult<()> { + let request = create_alias::v3::Request::new(alias.to_owned(), room_id.to_owned()); + self.send(request, None).await?; + Ok(()) + } + /// Update the homeserver from the login response well-known if needed. /// /// # Arguments @@ -2975,4 +2982,20 @@ pub(crate) mod tests { let ret = client.is_room_alias_available(room_alias_id!("#some_alias:matrix.org")).await; assert_matches!(ret, Err(_)); } + + #[async_test] + async fn test_create_room_alias() { + let server = MatrixMockServer::new().await; + let client = logged_in_client(Some(server.server().uri())).await; + + server.mock_create_room_alias().ok().expect(1).mount().await; + + let ret = client + .create_room_alias( + room_alias_id!("#some_alias:matrix.org"), + room_id!("!some_room:matrix.org"), + ) + .await; + assert_matches!(ret, Ok(())); + } } diff --git a/crates/matrix-sdk/src/test_utils/mocks.rs b/crates/matrix-sdk/src/test_utils/mocks.rs index cee3deeee9..35f6970e2a 100644 --- a/crates/matrix-sdk/src/test_utils/mocks.rs +++ b/crates/matrix-sdk/src/test_utils/mocks.rs @@ -208,6 +208,13 @@ impl MatrixMockServer { Mock::given(method("GET")).and(path_regex(r"/_matrix/client/r0/directory/room/.*")); MockResolveRoomAlias { mock, server: &self.server } } + + /// Create a prebuilt mock for creating room aliases. + pub fn mock_create_room_alias(&self) -> MockCreateRoomAlias<'_> { + let mock = + Mock::given(method("PUT")).and(path_regex(r"/_matrix/client/r0/directory/room/.*")); + MockCreateRoomAlias { mock, server: &self.server } + } } /// Parameter to [`MatrixMockServer::sync_room`]. @@ -550,3 +557,17 @@ impl<'a> MockResolveRoomAlias<'a> { MatrixMock { server: self.server, mock } } } + +/// A prebuilt mock for creating a room alias. +pub struct MockCreateRoomAlias<'a> { + server: &'a MockServer, + mock: MockBuilder, +} + +impl<'a> MockCreateRoomAlias<'a> { + /// Returns a data endpoint for creating a room alias. + pub fn ok(self) -> MatrixMock<'a> { + let mock = self.mock.respond_with(ResponseTemplate::new(200).set_body_json(json!({}))); + MatrixMock { server: self.server, mock } + } +}