From 4865fac3b2af781d9a200aa2eca0cca5fb60ca84 Mon Sep 17 00:00:00 2001 From: Johannes Becker Date: Mon, 23 May 2022 10:52:27 +0200 Subject: [PATCH] feat(appservice): Improve autojoin example --- .../examples/appservice_autojoin.rs | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/matrix-sdk-appservice/examples/appservice_autojoin.rs b/crates/matrix-sdk-appservice/examples/appservice_autojoin.rs index 1f7b1b71a11..c654adfe464 100644 --- a/crates/matrix-sdk-appservice/examples/appservice_autojoin.rs +++ b/crates/matrix-sdk-appservice/examples/appservice_autojoin.rs @@ -8,9 +8,14 @@ use matrix_sdk_appservice::{ events::room::member::{MembershipState, OriginalSyncRoomMemberEvent}, UserId, }, + HttpError, }, AppService, AppServiceRegistration, Result, }; +use ruma::api::{ + client::{error::ErrorKind, uiaa::UiaaResponse}, + error::{FromHttpResponseError, ServerError}, +}; use tracing::trace; pub async fn handle_room_member( @@ -22,7 +27,9 @@ pub async fn handle_room_member( trace!("not an appservice user: {}", event.state_key); } else if let MembershipState::Invite = event.content.membership { let user_id = UserId::parse(event.state_key.as_str())?; - appservice.register_virtual_user(user_id.localpart()).await?; + if let Err(error) = appservice.register_virtual_user(user_id.localpart()).await { + error_if_user_not_in_use(error)?; + } let client = appservice.virtual_user_client(user_id.localpart()).await?; client.join_room_by_id(room.room_id()).await?; @@ -31,6 +38,17 @@ pub async fn handle_room_member( Ok(()) } +pub fn error_if_user_not_in_use(error: matrix_sdk_appservice::Error) -> Result<()> { + match error { + // If user is already in use that's OK. + matrix_sdk_appservice::Error::Matrix(matrix_sdk::Error::Http(HttpError::UiaaError( + FromHttpResponseError::Server(ServerError::Known(UiaaResponse::MatrixError(error))), + ))) if matches!(error.kind, ErrorKind::UserInUse) => Ok(()), + // In all other cases return with an error. + error => Err(error), + } +} + #[tokio::main] pub async fn main() -> Result<(), Box> { env::set_var("RUST_LOG", "matrix_sdk=debug,matrix_sdk_appservice=debug"); @@ -41,6 +59,7 @@ pub async fn main() -> Result<(), Box> { let registration = AppServiceRegistration::try_from_yaml_file("./tests/registration.yaml")?; let appservice = AppService::new(homeserver_url, server_name, registration).await?; + appservice.register_user_query(Box::new(|_, _| Box::pin(async { true }))).await; appservice .register_event_handler_context(appservice.clone())? .register_event_handler(