Skip to content
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

feat(appservice): Improve autojoin example #703

Merged
merged 1 commit into from
May 23, 2022
Merged
Changes from all commits
Commits
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
21 changes: 20 additions & 1 deletion crates/matrix-sdk-appservice/examples/appservice_autojoin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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?;
Expand All @@ -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<dyn std::error::Error>> {
env::set_var("RUST_LOG", "matrix_sdk=debug,matrix_sdk_appservice=debug");
Expand All @@ -41,6 +59,7 @@ pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
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(
Expand Down