Ruma upgrade

merge-requests/342/head
Timo Kösters 2 years ago
parent 17ad5f0595
commit 2808dd2000
No known key found for this signature in database
GPG Key ID: 24DA7517711A2BA4

102
Cargo.lock generated

@ -2102,19 +2102,16 @@ dependencies = [
[[package]] [[package]]
name = "ruma" name = "ruma"
version = "0.5.0" version = "0.5.0"
source = "git+https://github.com/ruma/ruma?rev=588fe9c006eb140264160e68f4a21ea1fb28af18#588fe9c006eb140264160e68f4a21ea1fb28af18" source = "git+https://github.com/ruma/ruma?rev=d614ad1422d6c4b3437ebc318ca8514ae338fd6d#d614ad1422d6c4b3437ebc318ca8514ae338fd6d"
dependencies = [ dependencies = [
"assign", "assign",
"js_int", "js_int",
"ruma-appservice-api", "ruma-appservice-api",
"ruma-client-api", "ruma-client-api",
"ruma-common", "ruma-common",
"ruma-events",
"ruma-federation-api", "ruma-federation-api",
"ruma-identifiers",
"ruma-identity-service-api", "ruma-identity-service-api",
"ruma-push-gateway-api", "ruma-push-gateway-api",
"ruma-serde",
"ruma-signatures", "ruma-signatures",
"ruma-state-res", "ruma-state-res",
] ]
@ -2122,12 +2119,9 @@ dependencies = [
[[package]] [[package]]
name = "ruma-appservice-api" name = "ruma-appservice-api"
version = "0.5.0" version = "0.5.0"
source = "git+https://github.com/ruma/ruma?rev=588fe9c006eb140264160e68f4a21ea1fb28af18#588fe9c006eb140264160e68f4a21ea1fb28af18" source = "git+https://github.com/ruma/ruma?rev=d614ad1422d6c4b3437ebc318ca8514ae338fd6d#d614ad1422d6c4b3437ebc318ca8514ae338fd6d"
dependencies = [ dependencies = [
"ruma-common", "ruma-common",
"ruma-events",
"ruma-identifiers",
"ruma-serde",
"serde", "serde",
"serde_json", "serde_json",
] ]
@ -2135,7 +2129,7 @@ dependencies = [
[[package]] [[package]]
name = "ruma-client-api" name = "ruma-client-api"
version = "0.13.0" version = "0.13.0"
source = "git+https://github.com/ruma/ruma?rev=588fe9c006eb140264160e68f4a21ea1fb28af18#588fe9c006eb140264160e68f4a21ea1fb28af18" source = "git+https://github.com/ruma/ruma?rev=d614ad1422d6c4b3437ebc318ca8514ae338fd6d#d614ad1422d6c4b3437ebc318ca8514ae338fd6d"
dependencies = [ dependencies = [
"assign", "assign",
"bytes", "bytes",
@ -2144,9 +2138,6 @@ dependencies = [
"maplit", "maplit",
"percent-encoding", "percent-encoding",
"ruma-common", "ruma-common",
"ruma-events",
"ruma-identifiers",
"ruma-serde",
"serde", "serde",
"serde_json", "serde_json",
] ]
@ -2154,73 +2145,44 @@ dependencies = [
[[package]] [[package]]
name = "ruma-common" name = "ruma-common"
version = "0.8.0" version = "0.8.0"
source = "git+https://github.com/ruma/ruma?rev=588fe9c006eb140264160e68f4a21ea1fb28af18#588fe9c006eb140264160e68f4a21ea1fb28af18" source = "git+https://github.com/ruma/ruma?rev=d614ad1422d6c4b3437ebc318ca8514ae338fd6d#d614ad1422d6c4b3437ebc318ca8514ae338fd6d"
dependencies = [ dependencies = [
"base64 0.13.0",
"bytes", "bytes",
"form_urlencoded",
"http", "http",
"indexmap", "indexmap",
"indoc",
"itoa 1.0.1",
"js_int", "js_int",
"percent-encoding", "percent-encoding",
"ruma-identifiers", "rand 0.8.4",
"ruma-identifiers-validation",
"ruma-macros", "ruma-macros",
"ruma-serde",
"serde", "serde",
"serde_json", "serde_json",
"thiserror", "thiserror",
"tracing", "tracing",
"wildmatch", "url",
] "uuid",
[[package]]
name = "ruma-events"
version = "0.26.0"
source = "git+https://github.com/ruma/ruma?rev=588fe9c006eb140264160e68f4a21ea1fb28af18#588fe9c006eb140264160e68f4a21ea1fb28af18"
dependencies = [
"indoc",
"js_int",
"ruma-common",
"ruma-identifiers",
"ruma-macros",
"ruma-serde",
"serde",
"serde_json",
"thiserror",
"wildmatch", "wildmatch",
] ]
[[package]] [[package]]
name = "ruma-federation-api" name = "ruma-federation-api"
version = "0.4.0" version = "0.4.0"
source = "git+https://github.com/ruma/ruma?rev=588fe9c006eb140264160e68f4a21ea1fb28af18#588fe9c006eb140264160e68f4a21ea1fb28af18" source = "git+https://github.com/ruma/ruma?rev=d614ad1422d6c4b3437ebc318ca8514ae338fd6d#d614ad1422d6c4b3437ebc318ca8514ae338fd6d"
dependencies = [ dependencies = [
"js_int", "js_int",
"ruma-common", "ruma-common",
"ruma-events",
"ruma-identifiers",
"ruma-serde",
"serde", "serde",
"serde_json", "serde_json",
] ]
[[package]]
name = "ruma-identifiers"
version = "0.22.0"
source = "git+https://github.com/ruma/ruma?rev=588fe9c006eb140264160e68f4a21ea1fb28af18#588fe9c006eb140264160e68f4a21ea1fb28af18"
dependencies = [
"percent-encoding",
"rand 0.8.4",
"ruma-identifiers-validation",
"ruma-macros",
"ruma-serde",
"serde",
"url",
"uuid",
]
[[package]] [[package]]
name = "ruma-identifiers-validation" name = "ruma-identifiers-validation"
version = "0.7.0" version = "0.7.0"
source = "git+https://github.com/ruma/ruma?rev=588fe9c006eb140264160e68f4a21ea1fb28af18#588fe9c006eb140264160e68f4a21ea1fb28af18" source = "git+https://github.com/ruma/ruma?rev=d614ad1422d6c4b3437ebc318ca8514ae338fd6d#d614ad1422d6c4b3437ebc318ca8514ae338fd6d"
dependencies = [ dependencies = [
"thiserror", "thiserror",
"url", "url",
@ -2229,19 +2191,17 @@ dependencies = [
[[package]] [[package]]
name = "ruma-identity-service-api" name = "ruma-identity-service-api"
version = "0.4.0" version = "0.4.0"
source = "git+https://github.com/ruma/ruma?rev=588fe9c006eb140264160e68f4a21ea1fb28af18#588fe9c006eb140264160e68f4a21ea1fb28af18" source = "git+https://github.com/ruma/ruma?rev=d614ad1422d6c4b3437ebc318ca8514ae338fd6d#d614ad1422d6c4b3437ebc318ca8514ae338fd6d"
dependencies = [ dependencies = [
"js_int", "js_int",
"ruma-common", "ruma-common",
"ruma-identifiers",
"ruma-serde",
"serde", "serde",
] ]
[[package]] [[package]]
name = "ruma-macros" name = "ruma-macros"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/ruma/ruma?rev=588fe9c006eb140264160e68f4a21ea1fb28af18#588fe9c006eb140264160e68f4a21ea1fb28af18" source = "git+https://github.com/ruma/ruma?rev=d614ad1422d6c4b3437ebc318ca8514ae338fd6d#d614ad1422d6c4b3437ebc318ca8514ae338fd6d"
dependencies = [ dependencies = [
"proc-macro-crate", "proc-macro-crate",
"proc-macro2", "proc-macro2",
@ -2253,28 +2213,10 @@ dependencies = [
[[package]] [[package]]
name = "ruma-push-gateway-api" name = "ruma-push-gateway-api"
version = "0.4.0" version = "0.4.0"
source = "git+https://github.com/ruma/ruma?rev=588fe9c006eb140264160e68f4a21ea1fb28af18#588fe9c006eb140264160e68f4a21ea1fb28af18" source = "git+https://github.com/ruma/ruma?rev=d614ad1422d6c4b3437ebc318ca8514ae338fd6d#d614ad1422d6c4b3437ebc318ca8514ae338fd6d"
dependencies = [ dependencies = [
"js_int", "js_int",
"ruma-common", "ruma-common",
"ruma-events",
"ruma-identifiers",
"ruma-serde",
"serde",
"serde_json",
]
[[package]]
name = "ruma-serde"
version = "0.6.0"
source = "git+https://github.com/ruma/ruma?rev=588fe9c006eb140264160e68f4a21ea1fb28af18#588fe9c006eb140264160e68f4a21ea1fb28af18"
dependencies = [
"base64 0.13.0",
"bytes",
"form_urlencoded",
"itoa 1.0.1",
"js_int",
"ruma-macros",
"serde", "serde",
"serde_json", "serde_json",
] ]
@ -2282,14 +2224,13 @@ dependencies = [
[[package]] [[package]]
name = "ruma-signatures" name = "ruma-signatures"
version = "0.10.0" version = "0.10.0"
source = "git+https://github.com/ruma/ruma?rev=588fe9c006eb140264160e68f4a21ea1fb28af18#588fe9c006eb140264160e68f4a21ea1fb28af18" source = "git+https://github.com/ruma/ruma?rev=d614ad1422d6c4b3437ebc318ca8514ae338fd6d#d614ad1422d6c4b3437ebc318ca8514ae338fd6d"
dependencies = [ dependencies = [
"base64 0.13.0", "base64 0.13.0",
"ed25519-dalek", "ed25519-dalek",
"pkcs8", "pkcs8",
"rand 0.7.3", "rand 0.7.3",
"ruma-identifiers", "ruma-common",
"ruma-serde",
"serde_json", "serde_json",
"sha2", "sha2",
"thiserror", "thiserror",
@ -2299,14 +2240,11 @@ dependencies = [
[[package]] [[package]]
name = "ruma-state-res" name = "ruma-state-res"
version = "0.6.0" version = "0.6.0"
source = "git+https://github.com/ruma/ruma?rev=588fe9c006eb140264160e68f4a21ea1fb28af18#588fe9c006eb140264160e68f4a21ea1fb28af18" source = "git+https://github.com/ruma/ruma?rev=d614ad1422d6c4b3437ebc318ca8514ae338fd6d#d614ad1422d6c4b3437ebc318ca8514ae338fd6d"
dependencies = [ dependencies = [
"itertools", "itertools",
"js_int", "js_int",
"ruma-common", "ruma-common",
"ruma-events",
"ruma-identifiers",
"ruma-serde",
"serde", "serde",
"serde_json", "serde_json",
"thiserror", "thiserror",

@ -21,7 +21,7 @@ tower-http = { version = "0.2.1", features = ["add-extension", "cors", "compress
# Used for matrix spec type definitions and helpers # Used for matrix spec type definitions and helpers
#ruma = { version = "0.4.0", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] } #ruma = { version = "0.4.0", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] }
ruma = { git = "https://github.com/ruma/ruma", rev = "588fe9c006eb140264160e68f4a21ea1fb28af18", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-msc2448", "unstable-pre-spec", "unstable-exhaustive-types"] } ruma = { git = "https://github.com/ruma/ruma", rev = "d614ad1422d6c4b3437ebc318ca8514ae338fd6d", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-msc2448", "unstable-pre-spec", "unstable-exhaustive-types"] }
#ruma = { git = "https://github.com/timokoesters/ruma", rev = "50c1db7e0a3a21fc794b0cce3b64285a4c750c71", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] } #ruma = { git = "https://github.com/timokoesters/ruma", rev = "50c1db7e0a3a21fc794b0cce3b64285a4c750c71", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] }
#ruma = { path = "../ruma/crates/ruma", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] } #ruma = { path = "../ruma/crates/ruma", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] }

@ -18,7 +18,7 @@ use ruma::{
events::{ events::{
room::member::{MembershipState, RoomMemberEventContent}, room::member::{MembershipState, RoomMemberEventContent},
room::message::RoomMessageEventContent, room::message::RoomMessageEventContent,
EventType, GlobalAccountDataEventType, RoomAccountDataEventType, RoomEventType,
}, },
push, UserId, push, UserId,
}; };
@ -41,7 +41,7 @@ const GUEST_NAME_LENGTH: usize = 10;
/// Note: This will not reserve the username, so the username might become invalid when trying to register /// Note: This will not reserve the username, so the username might become invalid when trying to register
pub async fn get_register_available_route( pub async fn get_register_available_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_username_availability::v3::Request<'_>>, body: Ruma<get_username_availability::v3::IncomingRequest>,
) -> Result<get_username_availability::v3::Response> { ) -> Result<get_username_availability::v3::Response> {
// Validate user id // Validate user id
let user_id = let user_id =
@ -84,7 +84,7 @@ pub async fn get_register_available_route(
/// - If `inhibit_login` is false: Creates a device and returns device id and access_token /// - If `inhibit_login` is false: Creates a device and returns device id and access_token
pub async fn register_route( pub async fn register_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<register::v3::Request<'_>>, body: Ruma<register::v3::IncomingRequest>,
) -> Result<register::v3::Response> { ) -> Result<register::v3::Response> {
if !db.globals.allow_registration() && !body.from_appservice { if !db.globals.allow_registration() && !body.from_appservice {
return Err(Error::BadRequest( return Err(Error::BadRequest(
@ -194,7 +194,7 @@ pub async fn register_route(
db.account_data.update( db.account_data.update(
None, None,
&user_id, &user_id,
EventType::PushRules, GlobalAccountDataEventType::PushRules.to_string().into(),
&ruma::events::push_rules::PushRulesEvent { &ruma::events::push_rules::PushRulesEvent {
content: ruma::events::push_rules::PushRulesEventContent { content: ruma::events::push_rules::PushRulesEventContent {
global: push::Ruleset::server_default(&user_id), global: push::Ruleset::server_default(&user_id),
@ -271,7 +271,7 @@ pub async fn register_route(
/// - Triggers device list updates /// - Triggers device list updates
pub async fn change_password_route( pub async fn change_password_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<change_password::v3::Request<'_>>, body: Ruma<change_password::v3::IncomingRequest>,
) -> Result<change_password::v3::Response> { ) -> Result<change_password::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated"); let sender_device = body.sender_device.as_ref().expect("user is authenticated");
@ -366,7 +366,7 @@ pub async fn whoami_route(
/// - Removes ability to log in again /// - Removes ability to log in again
pub async fn deactivate_route( pub async fn deactivate_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<deactivate::v3::Request<'_>>, body: Ruma<deactivate::v3::IncomingRequest>,
) -> Result<deactivate::v3::Response> { ) -> Result<deactivate::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated"); let sender_device = body.sender_device.as_ref().expect("user is authenticated");
@ -440,7 +440,7 @@ pub async fn deactivate_route(
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomMember, event_type: RoomEventType::RoomMember,
content: to_raw_value(&event).expect("event is valid, we just created it"), content: to_raw_value(&event).expect("event is valid, we just created it"),
unsigned: None, unsigned: None,
state_key: Some(sender_user.to_string()), state_key: Some(sender_user.to_string()),

@ -17,7 +17,7 @@ use ruma::{
/// Creates a new room alias on this server. /// Creates a new room alias on this server.
pub async fn create_alias_route( pub async fn create_alias_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<create_alias::v3::Request<'_>>, body: Ruma<create_alias::v3::IncomingRequest>,
) -> Result<create_alias::v3::Response> { ) -> Result<create_alias::v3::Response> {
if body.room_alias.server_name() != db.globals.server_name() { if body.room_alias.server_name() != db.globals.server_name() {
return Err(Error::BadRequest( return Err(Error::BadRequest(
@ -46,7 +46,7 @@ pub async fn create_alias_route(
/// - TODO: Update canonical alias event /// - TODO: Update canonical alias event
pub async fn delete_alias_route( pub async fn delete_alias_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<delete_alias::v3::Request<'_>>, body: Ruma<delete_alias::v3::IncomingRequest>,
) -> Result<delete_alias::v3::Response> { ) -> Result<delete_alias::v3::Response> {
if body.room_alias.server_name() != db.globals.server_name() { if body.room_alias.server_name() != db.globals.server_name() {
return Err(Error::BadRequest( return Err(Error::BadRequest(
@ -71,7 +71,7 @@ pub async fn delete_alias_route(
/// - TODO: Suggest more servers to join via /// - TODO: Suggest more servers to join via
pub async fn get_alias_route( pub async fn get_alias_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_alias::v3::Request<'_>>, body: Ruma<get_alias::v3::IncomingRequest>,
) -> Result<get_alias::v3::Response> { ) -> Result<get_alias::v3::Response> {
get_alias_helper(&db, &body.room_alias).await get_alias_helper(&db, &body.room_alias).await
} }

@ -32,7 +32,7 @@ pub async fn create_backup_version_route(
/// Update information about an existing backup. Only `auth_data` can be modified. /// Update information about an existing backup. Only `auth_data` can be modified.
pub async fn update_backup_version_route( pub async fn update_backup_version_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<update_backup_version::v3::Request<'_>>, body: Ruma<update_backup_version::v3::IncomingRequest>,
) -> Result<update_backup_version::v3::Response> { ) -> Result<update_backup_version::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
db.key_backups db.key_backups
@ -73,7 +73,7 @@ pub async fn get_latest_backup_info_route(
/// Get information about an existing backup. /// Get information about an existing backup.
pub async fn get_backup_info_route( pub async fn get_backup_info_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_backup_info::v3::Request<'_>>, body: Ruma<get_backup_info::v3::IncomingRequest>,
) -> Result<get_backup_info::v3::Response> { ) -> Result<get_backup_info::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let algorithm = db let algorithm = db
@ -99,7 +99,7 @@ pub async fn get_backup_info_route(
/// - Deletes both information about the backup, as well as all key data related to the backup /// - Deletes both information about the backup, as well as all key data related to the backup
pub async fn delete_backup_version_route( pub async fn delete_backup_version_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<delete_backup_version::v3::Request<'_>>, body: Ruma<delete_backup_version::v3::IncomingRequest>,
) -> Result<delete_backup_version::v3::Response> { ) -> Result<delete_backup_version::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -119,7 +119,7 @@ pub async fn delete_backup_version_route(
/// - Returns the new number of keys in this backup and the etag /// - Returns the new number of keys in this backup and the etag
pub async fn add_backup_keys_route( pub async fn add_backup_keys_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<add_backup_keys::v3::Request<'_>>, body: Ruma<add_backup_keys::v3::IncomingRequest>,
) -> Result<add_backup_keys::v3::Response> { ) -> Result<add_backup_keys::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -165,7 +165,7 @@ pub async fn add_backup_keys_route(
/// - Returns the new number of keys in this backup and the etag /// - Returns the new number of keys in this backup and the etag
pub async fn add_backup_keys_for_room_route( pub async fn add_backup_keys_for_room_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<add_backup_keys_for_room::v3::Request<'_>>, body: Ruma<add_backup_keys_for_room::v3::IncomingRequest>,
) -> Result<add_backup_keys_for_room::v3::Response> { ) -> Result<add_backup_keys_for_room::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -209,7 +209,7 @@ pub async fn add_backup_keys_for_room_route(
/// - Returns the new number of keys in this backup and the etag /// - Returns the new number of keys in this backup and the etag
pub async fn add_backup_keys_for_session_route( pub async fn add_backup_keys_for_session_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<add_backup_keys_for_session::v3::Request<'_>>, body: Ruma<add_backup_keys_for_session::v3::IncomingRequest>,
) -> Result<add_backup_keys_for_session::v3::Response> { ) -> Result<add_backup_keys_for_session::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -247,7 +247,7 @@ pub async fn add_backup_keys_for_session_route(
/// Retrieves all keys from the backup. /// Retrieves all keys from the backup.
pub async fn get_backup_keys_route( pub async fn get_backup_keys_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_backup_keys::v3::Request<'_>>, body: Ruma<get_backup_keys::v3::IncomingRequest>,
) -> Result<get_backup_keys::v3::Response> { ) -> Result<get_backup_keys::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -261,7 +261,7 @@ pub async fn get_backup_keys_route(
/// Retrieves all keys from the backup for a given room. /// Retrieves all keys from the backup for a given room.
pub async fn get_backup_keys_for_room_route( pub async fn get_backup_keys_for_room_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_backup_keys_for_room::v3::Request<'_>>, body: Ruma<get_backup_keys_for_room::v3::IncomingRequest>,
) -> Result<get_backup_keys_for_room::v3::Response> { ) -> Result<get_backup_keys_for_room::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -277,7 +277,7 @@ pub async fn get_backup_keys_for_room_route(
/// Retrieves a key from the backup. /// Retrieves a key from the backup.
pub async fn get_backup_keys_for_session_route( pub async fn get_backup_keys_for_session_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_backup_keys_for_session::v3::Request<'_>>, body: Ruma<get_backup_keys_for_session::v3::IncomingRequest>,
) -> Result<get_backup_keys_for_session::v3::Response> { ) -> Result<get_backup_keys_for_session::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -297,7 +297,7 @@ pub async fn get_backup_keys_for_session_route(
/// Delete the keys from the backup. /// Delete the keys from the backup.
pub async fn delete_backup_keys_route( pub async fn delete_backup_keys_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<delete_backup_keys::v3::Request<'_>>, body: Ruma<delete_backup_keys::v3::IncomingRequest>,
) -> Result<delete_backup_keys::v3::Response> { ) -> Result<delete_backup_keys::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -316,7 +316,7 @@ pub async fn delete_backup_keys_route(
/// Delete the keys from the backup for a given room. /// Delete the keys from the backup for a given room.
pub async fn delete_backup_keys_for_room_route( pub async fn delete_backup_keys_for_room_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<delete_backup_keys_for_room::v3::Request<'_>>, body: Ruma<delete_backup_keys_for_room::v3::IncomingRequest>,
) -> Result<delete_backup_keys_for_room::v3::Response> { ) -> Result<delete_backup_keys_for_room::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -336,7 +336,7 @@ pub async fn delete_backup_keys_for_room_route(
/// Delete a key from the backup. /// Delete a key from the backup.
pub async fn delete_backup_keys_for_session_route( pub async fn delete_backup_keys_for_session_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<delete_backup_keys_for_session::v3::Request<'_>>, body: Ruma<delete_backup_keys_for_session::v3::IncomingRequest>,
) -> Result<delete_backup_keys_for_session::v3::Response> { ) -> Result<delete_backup_keys_for_session::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");

@ -1,7 +1,7 @@
use crate::{Result, Ruma}; use crate::{Result, Ruma};
use ruma::{ use ruma::{
api::client::capabilities::{ api::client::discovery::get_capabilities::{
get_capabilities, Capabilities, RoomVersionStability, RoomVersionsCapability, self, Capabilities, RoomVersionStability, RoomVersionsCapability,
}, },
RoomVersionId, RoomVersionId,
}; };
@ -11,7 +11,7 @@ use std::collections::BTreeMap;
/// ///
/// Get information on the supported feature set and other relevent capabilities of this server. /// Get information on the supported feature set and other relevent capabilities of this server.
pub async fn get_capabilities_route( pub async fn get_capabilities_route(
_body: Ruma<get_capabilities::v3::Request>, _body: Ruma<get_capabilities::v3::IncomingRequest>,
) -> Result<get_capabilities::v3::Response> { ) -> Result<get_capabilities::v3::Response> {
let mut available = BTreeMap::new(); let mut available = BTreeMap::new();
available.insert(RoomVersionId::V5, RoomVersionStability::Stable); available.insert(RoomVersionId::V5, RoomVersionStability::Stable);

@ -18,7 +18,7 @@ use serde_json::{json, value::RawValue as RawJsonValue};
/// Sets some account data for the sender user. /// Sets some account data for the sender user.
pub async fn set_global_account_data_route( pub async fn set_global_account_data_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<set_global_account_data::v3::Request<'_>>, body: Ruma<set_global_account_data::v3::IncomingRequest>,
) -> Result<set_global_account_data::v3::Response> { ) -> Result<set_global_account_data::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -48,7 +48,7 @@ pub async fn set_global_account_data_route(
/// Sets some room account data for the sender user. /// Sets some room account data for the sender user.
pub async fn set_room_account_data_route( pub async fn set_room_account_data_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<set_room_account_data::v3::Request<'_>>, body: Ruma<set_room_account_data::v3::IncomingRequest>,
) -> Result<set_room_account_data::v3::Response> { ) -> Result<set_room_account_data::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -78,7 +78,7 @@ pub async fn set_room_account_data_route(
/// Gets some account data for the sender user. /// Gets some account data for the sender user.
pub async fn get_global_account_data_route( pub async fn get_global_account_data_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_global_account_data::v3::Request<'_>>, body: Ruma<get_global_account_data::v3::IncomingRequest>,
) -> Result<get_global_account_data::v3::Response> { ) -> Result<get_global_account_data::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -99,7 +99,7 @@ pub async fn get_global_account_data_route(
/// Gets some room account data for the sender user. /// Gets some room account data for the sender user.
pub async fn get_room_account_data_route( pub async fn get_room_account_data_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_room_account_data::v3::Request<'_>>, body: Ruma<get_room_account_data::v3::IncomingRequest>,
) -> Result<get_room_account_data::v3::Response> { ) -> Result<get_room_account_data::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");

@ -1,7 +1,7 @@
use crate::{database::DatabaseGuard, Error, Result, Ruma}; use crate::{database::DatabaseGuard, Error, Result, Ruma};
use ruma::{ use ruma::{
api::client::{context::get_context, error::ErrorKind, filter::LazyLoadOptions}, api::client::{context::get_context, error::ErrorKind, filter::LazyLoadOptions},
events::EventType, events::{EventType, StateEventType},
}; };
use std::{collections::HashSet, convert::TryFrom}; use std::{collections::HashSet, convert::TryFrom};
use tracing::error; use tracing::error;
@ -14,7 +14,7 @@ use tracing::error;
/// joined, depending on history_visibility) /// joined, depending on history_visibility)
pub async fn get_context_route( pub async fn get_context_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_context::v3::Request<'_>>, body: Ruma<get_context::v3::IncomingRequest>,
) -> Result<get_context::v3::Response> { ) -> Result<get_context::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated"); let sender_device = body.sender_device.as_ref().expect("user is authenticated");
@ -154,7 +154,7 @@ pub async fn get_context_route(
for (shortstatekey, id) in state_ids { for (shortstatekey, id) in state_ids {
let (event_type, state_key) = db.rooms.get_statekey_from_short(shortstatekey)?; let (event_type, state_key) = db.rooms.get_statekey_from_short(shortstatekey)?;
if event_type != EventType::RoomMember { if event_type != StateEventType::RoomMember {
let pdu = match db.rooms.get_pdu(&id)? { let pdu = match db.rooms.get_pdu(&id)? {
Some(pdu) => pdu, Some(pdu) => pdu,
None => { None => {

@ -30,7 +30,7 @@ pub async fn get_devices_route(
/// Get metadata on a single device of the sender user. /// Get metadata on a single device of the sender user.
pub async fn get_device_route( pub async fn get_device_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_device::v3::Request<'_>>, body: Ruma<get_device::v3::IncomingRequest>,
) -> Result<get_device::v3::Response> { ) -> Result<get_device::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -47,7 +47,7 @@ pub async fn get_device_route(
/// Updates the metadata on a given device of the sender user. /// Updates the metadata on a given device of the sender user.
pub async fn update_device_route( pub async fn update_device_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<update_device::v3::Request<'_>>, body: Ruma<update_device::v3::IncomingRequest>,
) -> Result<update_device::v3::Response> { ) -> Result<update_device::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -77,7 +77,7 @@ pub async fn update_device_route(
/// - Triggers device list updates /// - Triggers device list updates
pub async fn delete_device_route( pub async fn delete_device_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<delete_device::v3::Request<'_>>, body: Ruma<delete_device::v3::IncomingRequest>,
) -> Result<delete_device::v3::Response> { ) -> Result<delete_device::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated"); let sender_device = body.sender_device.as_ref().expect("user is authenticated");
@ -135,7 +135,7 @@ pub async fn delete_device_route(
/// - Triggers device list updates /// - Triggers device list updates
pub async fn delete_devices_route( pub async fn delete_devices_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<delete_devices::v3::Request<'_>>, body: Ruma<delete_devices::v3::IncomingRequest>,
) -> Result<delete_devices::v3::Response> { ) -> Result<delete_devices::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated"); let sender_device = body.sender_device.as_ref().expect("user is authenticated");

@ -25,7 +25,7 @@ use ruma::{
name::RoomNameEventContent, name::RoomNameEventContent,
topic::RoomTopicEventContent, topic::RoomTopicEventContent,
}, },
EventType, StateEventType,
}, },
ServerName, UInt, ServerName, UInt,
}; };
@ -38,7 +38,7 @@ use tracing::{info, warn};
/// - Rooms are ordered by the number of joined members /// - Rooms are ordered by the number of joined members
pub async fn get_public_rooms_filtered_route( pub async fn get_public_rooms_filtered_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_public_rooms_filtered::v3::Request<'_>>, body: Ruma<get_public_rooms_filtered::v3::IncomingRequest>,
) -> Result<get_public_rooms_filtered::v3::Response> { ) -> Result<get_public_rooms_filtered::v3::Response> {
get_public_rooms_filtered_helper( get_public_rooms_filtered_helper(
&db, &db,
@ -58,7 +58,7 @@ pub async fn get_public_rooms_filtered_route(
/// - Rooms are ordered by the number of joined members /// - Rooms are ordered by the number of joined members
pub async fn get_public_rooms_route( pub async fn get_public_rooms_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_public_rooms::v3::Request<'_>>, body: Ruma<get_public_rooms::v3::IncomingRequest>,
) -> Result<get_public_rooms::v3::Response> { ) -> Result<get_public_rooms::v3::Response> {
let response = get_public_rooms_filtered_helper( let response = get_public_rooms_filtered_helper(
&db, &db,
@ -85,7 +85,7 @@ pub async fn get_public_rooms_route(
/// - TODO: Access control checks /// - TODO: Access control checks
pub async fn set_room_visibility_route( pub async fn set_room_visibility_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<set_room_visibility::v3::Request<'_>>, body: Ruma<set_room_visibility::v3::IncomingRequest>,
) -> Result<set_room_visibility::v3::Response> { ) -> Result<set_room_visibility::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -113,7 +113,7 @@ pub async fn set_room_visibility_route(
/// Gets the visibility of a given room in the room directory. /// Gets the visibility of a given room in the room directory.
pub async fn get_room_visibility_route( pub async fn get_room_visibility_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_room_visibility::v3::Request<'_>>, body: Ruma<get_room_visibility::v3::IncomingRequest>,
) -> Result<get_room_visibility::v3::Response> { ) -> Result<get_room_visibility::v3::Response> {
Ok(get_room_visibility::v3::Response { Ok(get_room_visibility::v3::Response {
visibility: if db.rooms.is_public_room(&body.room_id)? { visibility: if db.rooms.is_public_room(&body.room_id)? {
@ -193,7 +193,7 @@ pub(crate) async fn get_public_rooms_filtered_helper(
let chunk = PublicRoomsChunk { let chunk = PublicRoomsChunk {
canonical_alias: db canonical_alias: db
.rooms .rooms
.room_state_get(&room_id, &EventType::RoomCanonicalAlias, "")? .room_state_get(&room_id, &StateEventType::RoomCanonicalAlias, "")?
.map_or(Ok(None), |s| { .map_or(Ok(None), |s| {
serde_json::from_str(s.content.get()) serde_json::from_str(s.content.get())
.map(|c: RoomCanonicalAliasEventContent| c.alias) .map(|c: RoomCanonicalAliasEventContent| c.alias)
@ -203,7 +203,7 @@ pub(crate) async fn get_public_rooms_filtered_helper(
})?, })?,
name: db name: db
.rooms .rooms
.room_state_get(&room_id, &EventType::RoomName, "")? .room_state_get(&room_id, &StateEventType::RoomName, "")?
.map_or(Ok(None), |s| { .map_or(Ok(None), |s| {
serde_json::from_str(s.content.get()) serde_json::from_str(s.content.get())
.map(|c: RoomNameEventContent| c.name) .map(|c: RoomNameEventContent| c.name)
@ -222,7 +222,7 @@ pub(crate) async fn get_public_rooms_filtered_helper(
.expect("user count should not be that big"), .expect("user count should not be that big"),
topic: db topic: db
.rooms .rooms
.room_state_get(&room_id, &EventType::RoomTopic, "")? .room_state_get(&room_id, &StateEventType::RoomTopic, "")?
.map_or(Ok(None), |s| { .map_or(Ok(None), |s| {
serde_json::from_str(s.content.get()) serde_json::from_str(s.content.get())
.map(|c: RoomTopicEventContent| Some(c.topic)) .map(|c: RoomTopicEventContent| Some(c.topic))
@ -232,7 +232,7 @@ pub(crate) async fn get_public_rooms_filtered_helper(
})?, })?,
world_readable: db world_readable: db
.rooms .rooms
.room_state_get(&room_id, &EventType::RoomHistoryVisibility, "")? .room_state_get(&room_id, &StateEventType::RoomHistoryVisibility, "")?
.map_or(Ok(false), |s| { .map_or(Ok(false), |s| {
serde_json::from_str(s.content.get()) serde_json::from_str(s.content.get())
.map(|c: RoomHistoryVisibilityEventContent| { .map(|c: RoomHistoryVisibilityEventContent| {
@ -246,7 +246,7 @@ pub(crate) async fn get_public_rooms_filtered_helper(
})?, })?,
guest_can_join: db guest_can_join: db
.rooms .rooms
.room_state_get(&room_id, &EventType::RoomGuestAccess, "")? .room_state_get(&room_id, &StateEventType::RoomGuestAccess, "")?
.map_or(Ok(false), |s| { .map_or(Ok(false), |s| {
serde_json::from_str(s.content.get()) serde_json::from_str(s.content.get())
.map(|c: RoomGuestAccessEventContent| { .map(|c: RoomGuestAccessEventContent| {
@ -258,7 +258,7 @@ pub(crate) async fn get_public_rooms_filtered_helper(
})?, })?,
avatar_url: db avatar_url: db
.rooms .rooms
.room_state_get(&room_id, &EventType::RoomAvatar, "")? .room_state_get(&room_id, &StateEventType::RoomAvatar, "")?
.map(|s| { .map(|s| {
serde_json::from_str(s.content.get()) serde_json::from_str(s.content.get())
.map(|c: RoomAvatarEventContent| c.url) .map(|c: RoomAvatarEventContent| c.url)
@ -271,7 +271,7 @@ pub(crate) async fn get_public_rooms_filtered_helper(
.flatten(), .flatten(),
join_rule: db join_rule: db
.rooms .rooms
.room_state_get(&room_id, &EventType::RoomJoinRules, "")? .room_state_get(&room_id, &StateEventType::RoomJoinRules, "")?
.map(|s| { .map(|s| {
serde_json::from_str(s.content.get()) serde_json::from_str(s.content.get())
.map(|c: RoomJoinRulesEventContent| match c.join_rule { .map(|c: RoomJoinRulesEventContent| match c.join_rule {

@ -11,7 +11,7 @@ use ruma::api::client::{
/// - A user can only access their own filters /// - A user can only access their own filters
pub async fn get_filter_route( pub async fn get_filter_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_filter::v3::Request<'_>>, body: Ruma<get_filter::v3::IncomingRequest>,
) -> Result<get_filter::v3::Response> { ) -> Result<get_filter::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let filter = match db.users.get_filter(sender_user, &body.filter_id)? { let filter = match db.users.get_filter(sender_user, &body.filter_id)? {
@ -27,7 +27,7 @@ pub async fn get_filter_route(
/// Creates a new filter to be used by other endpoints. /// Creates a new filter to be used by other endpoints.
pub async fn create_filter_route( pub async fn create_filter_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<create_filter::v3::Request<'_>>, body: Ruma<create_filter::v3::IncomingRequest>,
) -> Result<create_filter::v3::Response> { ) -> Result<create_filter::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
Ok(create_filter::v3::Response::new( Ok(create_filter::v3::Response::new(

@ -71,7 +71,7 @@ pub async fn upload_keys_route(
/// - The master and self-signing keys contain signatures that the user is allowed to see /// - The master and self-signing keys contain signatures that the user is allowed to see
pub async fn get_keys_route( pub async fn get_keys_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_keys::v3::Request<'_>>, body: Ruma<get_keys::v3::IncomingRequest>,
) -> Result<get_keys::v3::Response> { ) -> Result<get_keys::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -107,7 +107,7 @@ pub async fn claim_keys_route(
/// - Requires UIAA to verify password /// - Requires UIAA to verify password
pub async fn upload_signing_keys_route( pub async fn upload_signing_keys_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<upload_signing_keys::v3::Request<'_>>, body: Ruma<upload_signing_keys::v3::IncomingRequest>,
) -> Result<upload_signing_keys::v3::Response> { ) -> Result<upload_signing_keys::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated"); let sender_device = body.sender_device.as_ref().expect("user is authenticated");
@ -231,7 +231,7 @@ pub async fn upload_signatures_route(
/// - TODO: left users /// - TODO: left users
pub async fn get_key_changes_route( pub async fn get_key_changes_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_key_changes::v3::Request<'_>>, body: Ruma<get_key_changes::v3::IncomingRequest>,
) -> Result<get_key_changes::v3::Response> { ) -> Result<get_key_changes::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");

@ -32,7 +32,7 @@ pub async fn get_media_config_route(
/// - Media will be saved in the media/ directory /// - Media will be saved in the media/ directory
pub async fn create_content_route( pub async fn create_content_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<create_content::v3::Request<'_>>, body: Ruma<create_content::v3::IncomingRequest>,
) -> Result<create_content::v3::Response> { ) -> Result<create_content::v3::Response> {
let mxc = format!( let mxc = format!(
"mxc://{}/{}", "mxc://{}/{}",
@ -101,7 +101,7 @@ pub async fn get_remote_content(
/// - Only allows federation if `allow_remote` is true /// - Only allows federation if `allow_remote` is true
pub async fn get_content_route( pub async fn get_content_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_content::v3::Request<'_>>, body: Ruma<get_content::v3::IncomingRequest>,
) -> Result<get_content::v3::Response> { ) -> Result<get_content::v3::Response> {
let mxc = format!("mxc://{}/{}", body.server_name, body.media_id); let mxc = format!("mxc://{}/{}", body.server_name, body.media_id);
@ -132,7 +132,7 @@ pub async fn get_content_route(
/// - Only allows federation if `allow_remote` is true /// - Only allows federation if `allow_remote` is true
pub async fn get_content_as_filename_route( pub async fn get_content_as_filename_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_content_as_filename::v3::Request<'_>>, body: Ruma<get_content_as_filename::v3::IncomingRequest>,
) -> Result<get_content_as_filename::v3::Response> { ) -> Result<get_content_as_filename::v3::Response> {
let mxc = format!("mxc://{}/{}", body.server_name, body.media_id); let mxc = format!("mxc://{}/{}", body.server_name, body.media_id);
@ -168,7 +168,7 @@ pub async fn get_content_as_filename_route(
/// - Only allows federation if `allow_remote` is true /// - Only allows federation if `allow_remote` is true
pub async fn get_content_thumbnail_route( pub async fn get_content_thumbnail_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_content_thumbnail::v3::Request<'_>>, body: Ruma<get_content_thumbnail::v3::IncomingRequest>,
) -> Result<get_content_thumbnail::v3::Response> { ) -> Result<get_content_thumbnail::v3::Response> {
let mxc = format!("mxc://{}/{}", body.server_name, body.media_id); let mxc = format!("mxc://{}/{}", body.server_name, body.media_id);

@ -21,7 +21,7 @@ use ruma::{
create::RoomCreateEventContent, create::RoomCreateEventContent,
member::{MembershipState, RoomMemberEventContent}, member::{MembershipState, RoomMemberEventContent},
}, },
EventType, RoomEventType, StateEventType,
}, },
serde::{to_canonical_value, Base64, CanonicalJsonObject, CanonicalJsonValue}, serde::{to_canonical_value, Base64, CanonicalJsonObject, CanonicalJsonValue},
state_res::{self, RoomVersion}, state_res::{self, RoomVersion},
@ -44,7 +44,7 @@ use tracing::{debug, error, warn};
/// - If the server does not know about the room: asks other servers over federation /// - If the server does not know about the room: asks other servers over federation
pub async fn join_room_by_id_route( pub async fn join_room_by_id_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<join_room_by_id::v3::Request<'_>>, body: Ruma<join_room_by_id::v3::IncomingRequest>,
) -> Result<join_room_by_id::v3::Response> { ) -> Result<join_room_by_id::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -84,7 +84,7 @@ pub async fn join_room_by_id_route(
/// - If the server does not know about the room: asks other servers over federation /// - If the server does not know about the room: asks other servers over federation
pub async fn join_room_by_id_or_alias_route( pub async fn join_room_by_id_or_alias_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<join_room_by_id_or_alias::v3::Request<'_>>, body: Ruma<join_room_by_id_or_alias::v3::IncomingRequest>,
) -> Result<join_room_by_id_or_alias::v3::Response> { ) -> Result<join_room_by_id_or_alias::v3::Response> {
let sender_user = body.sender_user.as_deref().expect("user is authenticated"); let sender_user = body.sender_user.as_deref().expect("user is authenticated");
let body = body.body; let body = body.body;
@ -136,7 +136,7 @@ pub async fn join_room_by_id_or_alias_route(
/// - This should always work if the user is currently joined. /// - This should always work if the user is currently joined.
pub async fn leave_room_route( pub async fn leave_room_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<leave_room::v3::Request<'_>>, body: Ruma<leave_room::v3::IncomingRequest>,
) -> Result<leave_room::v3::Response> { ) -> Result<leave_room::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -152,7 +152,7 @@ pub async fn leave_room_route(
/// Tries to send an invite event into the room. /// Tries to send an invite event into the room.
pub async fn invite_user_route( pub async fn invite_user_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<invite_user::v3::Request<'_>>, body: Ruma<invite_user::v3::IncomingRequest>,
) -> Result<invite_user::v3::Response> { ) -> Result<invite_user::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -170,7 +170,7 @@ pub async fn invite_user_route(
/// Tries to send a kick event into the room. /// Tries to send a kick event into the room.
pub async fn kick_user_route( pub async fn kick_user_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<kick_user::v3::Request<'_>>, body: Ruma<kick_user::v3::IncomingRequest>,
) -> Result<kick_user::v3::Response> { ) -> Result<kick_user::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -178,7 +178,7 @@ pub async fn kick_user_route(
db.rooms db.rooms
.room_state_get( .room_state_get(
&body.room_id, &body.room_id,
&EventType::RoomMember, &StateEventType::RoomMember,
&body.user_id.to_string(), &body.user_id.to_string(),
)? )?
.ok_or(Error::BadRequest( .ok_or(Error::BadRequest(
@ -205,7 +205,7 @@ pub async fn kick_user_route(
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomMember, event_type: RoomEventType::RoomMember,
content: to_raw_value(&event).expect("event is valid, we just created it"), content: to_raw_value(&event).expect("event is valid, we just created it"),
unsigned: None, unsigned: None,
state_key: Some(body.user_id.to_string()), state_key: Some(body.user_id.to_string()),
@ -229,7 +229,7 @@ pub async fn kick_user_route(
/// Tries to send a ban event into the room. /// Tries to send a ban event into the room.
pub async fn ban_user_route( pub async fn ban_user_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<ban_user::v3::Request<'_>>, body: Ruma<ban_user::v3::IncomingRequest>,
) -> Result<ban_user::v3::Response> { ) -> Result<ban_user::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -239,7 +239,7 @@ pub async fn ban_user_route(
.rooms .rooms
.room_state_get( .room_state_get(
&body.room_id, &body.room_id,
&EventType::RoomMember, &StateEventType::RoomMember,
&body.user_id.to_string(), &body.user_id.to_string(),
)? )?
.map_or( .map_or(
@ -275,7 +275,7 @@ pub async fn ban_user_route(
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomMember, event_type: RoomEventType::RoomMember,
content: to_raw_value(&event).expect("event is valid, we just created it"), content: to_raw_value(&event).expect("event is valid, we just created it"),
unsigned: None, unsigned: None,
state_key: Some(body.user_id.to_string()), state_key: Some(body.user_id.to_string()),
@ -299,7 +299,7 @@ pub async fn ban_user_route(
/// Tries to send an unban event into the room. /// Tries to send an unban event into the room.
pub async fn unban_user_route( pub async fn unban_user_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<unban_user::v3::Request<'_>>, body: Ruma<unban_user::v3::IncomingRequest>,
) -> Result<unban_user::v3::Response> { ) -> Result<unban_user::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -307,7 +307,7 @@ pub async fn unban_user_route(
db.rooms db.rooms
.room_state_get( .room_state_get(
&body.room_id, &body.room_id,
&EventType::RoomMember, &StateEventType::RoomMember,
&body.user_id.to_string(), &body.user_id.to_string(),
)? )?
.ok_or(Error::BadRequest( .ok_or(Error::BadRequest(
@ -333,7 +333,7 @@ pub async fn unban_user_route(
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomMember, event_type: RoomEventType::RoomMember,
content: to_raw_value(&event).expect("event is valid, we just created it"), content: to_raw_value(&event).expect("event is valid, we just created it"),
unsigned: None, unsigned: None,
state_key: Some(body.user_id.to_string()), state_key: Some(body.user_id.to_string()),
@ -362,7 +362,7 @@ pub async fn unban_user_route(
/// be called from every device /// be called from every device
pub async fn forget_room_route( pub async fn forget_room_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<forget_room::v3::Request<'_>>, body: Ruma<forget_room::v3::IncomingRequest>,
) -> Result<forget_room::v3::Response> { ) -> Result<forget_room::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -398,7 +398,7 @@ pub async fn joined_rooms_route(
/// - Only works if the user is currently joined /// - Only works if the user is currently joined
pub async fn get_member_events_route( pub async fn get_member_events_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_member_events::v3::Request<'_>>, body: Ruma<get_member_events::v3::IncomingRequest>,
) -> Result<get_member_events::v3::Response> { ) -> Result<get_member_events::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -415,8 +415,8 @@ pub async fn get_member_events_route(
.rooms .rooms
.room_state_full(&body.room_id)? .room_state_full(&body.room_id)?
.iter() .iter()
.filter(|(key, _)| key.0 == EventType::RoomMember) .filter(|(key, _)| key.0 == StateEventType::RoomMember)
.map(|(_, pdu)| pdu.to_member_event()) .map(|(_, pdu)| pdu.to_member_event().into())
.collect(), .collect(),
}) })
} }
@ -429,7 +429,7 @@ pub async fn get_member_events_route(
/// - TODO: An appservice just needs a puppet joined /// - TODO: An appservice just needs a puppet joined
pub async fn joined_members_route( pub async fn joined_members_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<joined_members::v3::Request<'_>>, body: Ruma<joined_members::v3::IncomingRequest>,
) -> Result<joined_members::v3::Response> { ) -> Result<joined_members::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -625,15 +625,17 @@ async fn join_room_by_id_helper(
db.rooms.add_pdu_outlier(&event_id, &value)?; db.rooms.add_pdu_outlier(&event_id, &value)?;
if let Some(state_key) = &pdu.state_key { if let Some(state_key) = &pdu.state_key {
let shortstatekey = let shortstatekey = db.rooms.get_or_create_shortstatekey(
db.rooms &pdu.kind.to_string().into(),
.get_or_create_shortstatekey(&pdu.kind, state_key, &db.globals)?; state_key,
&db.globals,
)?;
state.insert(shortstatekey, pdu.event_id.clone()); state.insert(shortstatekey, pdu.event_id.clone());
} }
} }
let incoming_shortstatekey = db.rooms.get_or_create_shortstatekey( let incoming_shortstatekey = db.rooms.get_or_create_shortstatekey(
&parsed_pdu.kind, &parsed_pdu.kind.to_string().into(),
parsed_pdu parsed_pdu
.state_key .state_key
.as_ref() .as_ref()
@ -645,7 +647,7 @@ async fn join_room_by_id_helper(
let create_shortstatekey = db let create_shortstatekey = db
.rooms .rooms
.get_shortstatekey(&EventType::RoomCreate, "")? .get_shortstatekey(&StateEventType::RoomCreate, "")?
.expect("Room exists"); .expect("Room exists");
if state.get(&create_shortstatekey).is_none() { if state.get(&create_shortstatekey).is_none() {
@ -703,7 +705,7 @@ async fn join_room_by_id_helper(
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomMember, event_type: RoomEventType::RoomMember,
content: to_raw_value(&event).expect("event is valid, we just created it"), content: to_raw_value(&event).expect("event is valid, we just created it"),
unsigned: None, unsigned: None,
state_key: Some(sender_user.to_string()), state_key: Some(sender_user.to_string()),
@ -814,7 +816,7 @@ pub(crate) async fn invite_helper<'a>(
let create_event = db let create_event = db
.rooms .rooms
.room_state_get(room_id, &EventType::RoomCreate, "")?; .room_state_get(room_id, &StateEventType::RoomCreate, "")?;
let create_event_content: Option<RoomCreateEventContent> = create_event let create_event_content: Option<RoomCreateEventContent> = create_event
.as_ref() .as_ref()
@ -853,11 +855,11 @@ pub(crate) async fn invite_helper<'a>(
.expect("member event is valid value"); .expect("member event is valid value");
let state_key = user_id.to_string(); let state_key = user_id.to_string();
let kind = EventType::RoomMember; let kind = StateEventType::RoomMember;
let auth_events = db.rooms.get_auth_events( let auth_events = db.rooms.get_auth_events(
room_id, room_id,
&kind, &kind.to_string().into(),
sender_user, sender_user,
Some(&state_key), Some(&state_key),
&content, &content,
@ -888,7 +890,7 @@ pub(crate) async fn invite_helper<'a>(
origin_server_ts: utils::millis_since_unix_epoch() origin_server_ts: utils::millis_since_unix_epoch()
.try_into() .try_into()
.expect("time is valid"), .expect("time is valid"),
kind, kind: kind.to_string().into(),
content, content,
state_key: Some(state_key), state_key: Some(state_key),
prev_events, prev_events,
@ -912,7 +914,6 @@ pub(crate) async fn invite_helper<'a>(
let auth_check = state_res::auth_check( let auth_check = state_res::auth_check(
&room_version, &room_version,
&pdu, &pdu,
create_prev_event,
None::<PduEvent>, // TODO: third_party_invite None::<PduEvent>, // TODO: third_party_invite
|k, s| auth_events.get(&(k.clone(), s.to_owned())), |k, s| auth_events.get(&(k.clone(), s.to_owned())),
) )
@ -1051,7 +1052,7 @@ pub(crate) async fn invite_helper<'a>(
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomMember, event_type: RoomEventType::RoomMember,
content: to_raw_value(&RoomMemberEventContent { content: to_raw_value(&RoomMemberEventContent {
membership: MembershipState::Invite, membership: MembershipState::Invite,
displayname: db.users.displayname(user_id)?, displayname: db.users.displayname(user_id)?,

@ -4,7 +4,7 @@ use ruma::{
error::ErrorKind, error::ErrorKind,
message::{get_message_events, send_message_event}, message::{get_message_events, send_message_event},
}, },
events::EventType, events::{RoomEventType, StateEventType},
}; };
use std::{ use std::{
collections::{BTreeMap, HashSet}, collections::{BTreeMap, HashSet},
@ -20,7 +20,7 @@ use std::{
/// - Tries to send the event into the room, auth rules will determine if it is allowed /// - Tries to send the event into the room, auth rules will determine if it is allowed
pub async fn send_message_event_route( pub async fn send_message_event_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<send_message_event::v3::Request<'_>>, body: Ruma<send_message_event::v3::IncomingRequest>,
) -> Result<send_message_event::v3::Response> { ) -> Result<send_message_event::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_deref(); let sender_device = body.sender_device.as_deref();
@ -36,7 +36,9 @@ pub async fn send_message_event_route(
let state_lock = mutex_state.lock().await; let state_lock = mutex_state.lock().await;
// Forbid m.room.encrypted if encryption is disabled // Forbid m.room.encrypted if encryption is disabled
if &body.event_type == "m.room.encrypted" && !db.globals.allow_encryption() { if RoomEventType::RoomEncrypted == body.event_type.to_string().into()
&& !db.globals.allow_encryption()
{
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::Forbidden,
"Encryption has been disabled", "Encryption has been disabled",
@ -69,7 +71,7 @@ pub async fn send_message_event_route(
let event_id = db.rooms.build_and_append_pdu( let event_id = db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::from(&*body.event_type), event_type: body.event_type.to_string().into(),
content: serde_json::from_str(body.body.body.json().get()) content: serde_json::from_str(body.body.body.json().get())
.map_err(|_| Error::BadRequest(ErrorKind::BadJson, "Invalid JSON body."))?, .map_err(|_| Error::BadRequest(ErrorKind::BadJson, "Invalid JSON body."))?,
unsigned: Some(unsigned), unsigned: Some(unsigned),
@ -106,7 +108,7 @@ pub async fn send_message_event_route(
/// joined, depending on history_visibility) /// joined, depending on history_visibility)
pub async fn get_message_events_route( pub async fn get_message_events_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_message_events::v3::Request<'_>>, body: Ruma<get_message_events::v3::IncomingRequest>,
) -> Result<get_message_events::v3::Response> { ) -> Result<get_message_events::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated"); let sender_device = body.sender_device.as_ref().expect("user is authenticated");
@ -118,11 +120,16 @@ pub async fn get_message_events_route(
)); ));
} }
let from = body let from = match body.from.clone() {
.from Some(from) => from
.clone() .parse()
.parse() .map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `from` value."))?,
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `from` value."))?;
None => match body.dir {
get_message_events::v3::Direction::Forward => 0,
get_message_events::v3::Direction::Backward => u64::MAX,
},
};
let to = body.to.as_ref().map(|t| t.parse()); let to = body.to.as_ref().map(|t| t.parse());
@ -172,7 +179,7 @@ pub async fn get_message_events_route(
.map(|(_, pdu)| pdu.to_room_event()) .map(|(_, pdu)| pdu.to_room_event())
.collect(); .collect();
resp.start = body.from.to_owned(); resp.start = from.to_string();
resp.end = next_token.map(|count| count.to_string()); resp.end = next_token.map(|count| count.to_string());
resp.chunk = events_after; resp.chunk = events_after;
} }
@ -209,7 +216,7 @@ pub async fn get_message_events_route(
.map(|(_, pdu)| pdu.to_room_event()) .map(|(_, pdu)| pdu.to_room_event())
.collect(); .collect();
resp.start = body.from.to_owned(); resp.start = from.to_string();
resp.end = next_token.map(|count| count.to_string()); resp.end = next_token.map(|count| count.to_string());
resp.chunk = events_before; resp.chunk = events_before;
} }
@ -219,7 +226,7 @@ pub async fn get_message_events_route(
for ll_id in &lazy_loaded { for ll_id in &lazy_loaded {
if let Some(member_event) = if let Some(member_event) =
db.rooms db.rooms
.room_state_get(&body.room_id, &EventType::RoomMember, ll_id.as_str())? .room_state_get(&body.room_id, &StateEventType::RoomMember, ll_id.as_str())?
{ {
resp.state.push(member_event.to_state_event()); resp.state.push(member_event.to_state_event());
} }

@ -7,7 +7,7 @@ use std::time::Duration;
/// Sets the presence state of the sender user. /// Sets the presence state of the sender user.
pub async fn set_presence_route( pub async fn set_presence_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<set_presence::v3::Request<'_>>, body: Ruma<set_presence::v3::IncomingRequest>,
) -> Result<set_presence::v3::Response> { ) -> Result<set_presence::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -48,7 +48,7 @@ pub async fn set_presence_route(
/// - Only works if you share a room with the user /// - Only works if you share a room with the user
pub async fn get_presence_route( pub async fn get_presence_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_presence::v3::Request<'_>>, body: Ruma<get_presence::v3::IncomingRequest>,
) -> Result<get_presence::v3::Response> { ) -> Result<get_presence::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");

@ -9,7 +9,7 @@ use ruma::{
}, },
federation::{self, query::get_profile_information::v1::ProfileField}, federation::{self, query::get_profile_information::v1::ProfileField},
}, },
events::{room::member::RoomMemberEventContent, EventType}, events::{room::member::RoomMemberEventContent, RoomEventType, StateEventType},
}; };
use serde_json::value::to_raw_value; use serde_json::value::to_raw_value;
use std::sync::Arc; use std::sync::Arc;
@ -21,7 +21,7 @@ use std::sync::Arc;
/// - Also makes sure other users receive the update using presence EDUs /// - Also makes sure other users receive the update using presence EDUs
pub async fn set_displayname_route( pub async fn set_displayname_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<set_display_name::v3::Request<'_>>, body: Ruma<set_display_name::v3::IncomingRequest>,
) -> Result<set_display_name::v3::Response> { ) -> Result<set_display_name::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -36,14 +36,14 @@ pub async fn set_displayname_route(
.map(|room_id| { .map(|room_id| {
Ok::<_, Error>(( Ok::<_, Error>((
PduBuilder { PduBuilder {
event_type: EventType::RoomMember, event_type: RoomEventType::RoomMember,
content: to_raw_value(&RoomMemberEventContent { content: to_raw_value(&RoomMemberEventContent {
displayname: body.displayname.clone(), displayname: body.displayname.clone(),
..serde_json::from_str( ..serde_json::from_str(
db.rooms db.rooms
.room_state_get( .room_state_get(
&room_id, &room_id,
&EventType::RoomMember, &StateEventType::RoomMember,
sender_user.as_str(), sender_user.as_str(),
)? )?
.ok_or_else(|| { .ok_or_else(|| {
@ -118,7 +118,7 @@ pub async fn set_displayname_route(
/// - If user is on another server: Fetches displayname over federation /// - If user is on another server: Fetches displayname over federation
pub async fn get_displayname_route( pub async fn get_displayname_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_display_name::v3::Request<'_>>, body: Ruma<get_display_name::v3::IncomingRequest>,
) -> Result<get_display_name::v3::Response> { ) -> Result<get_display_name::v3::Response> {
if body.user_id.server_name() != db.globals.server_name() { if body.user_id.server_name() != db.globals.server_name() {
let response = db let response = db
@ -150,7 +150,7 @@ pub async fn get_displayname_route(
/// - Also makes sure other users receive the update using presence EDUs /// - Also makes sure other users receive the update using presence EDUs
pub async fn set_avatar_url_route( pub async fn set_avatar_url_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<set_avatar_url::v3::Request<'_>>, body: Ruma<set_avatar_url::v3::IncomingRequest>,
) -> Result<set_avatar_url::v3::Response> { ) -> Result<set_avatar_url::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -167,14 +167,14 @@ pub async fn set_avatar_url_route(
.map(|room_id| { .map(|room_id| {
Ok::<_, Error>(( Ok::<_, Error>((
PduBuilder { PduBuilder {
event_type: EventType::RoomMember, event_type: RoomEventType::RoomMember,
content: to_raw_value(&RoomMemberEventContent { content: to_raw_value(&RoomMemberEventContent {
avatar_url: body.avatar_url.clone(), avatar_url: body.avatar_url.clone(),
..serde_json::from_str( ..serde_json::from_str(
db.rooms db.rooms
.room_state_get( .room_state_get(
&room_id, &room_id,
&EventType::RoomMember, &StateEventType::RoomMember,
sender_user.as_str(), sender_user.as_str(),
)? )?
.ok_or_else(|| { .ok_or_else(|| {
@ -249,7 +249,7 @@ pub async fn set_avatar_url_route(
/// - If user is on another server: Fetches avatar_url and blurhash over federation /// - If user is on another server: Fetches avatar_url and blurhash over federation
pub async fn get_avatar_url_route( pub async fn get_avatar_url_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_avatar_url::v3::Request<'_>>, body: Ruma<get_avatar_url::v3::IncomingRequest>,
) -> Result<get_avatar_url::v3::Response> { ) -> Result<get_avatar_url::v3::Response> {
if body.user_id.server_name() != db.globals.server_name() { if body.user_id.server_name() != db.globals.server_name() {
let response = db let response = db
@ -283,7 +283,7 @@ pub async fn get_avatar_url_route(
/// - If user is on another server: Fetches profile over federation /// - If user is on another server: Fetches profile over federation
pub async fn get_profile_route( pub async fn get_profile_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_profile::v3::Request<'_>>, body: Ruma<get_profile::v3::IncomingRequest>,
) -> Result<get_profile::v3::Response> { ) -> Result<get_profile::v3::Response> {
if body.user_id.server_name() != db.globals.server_name() { if body.user_id.server_name() != db.globals.server_name() {
let response = db let response = db

@ -8,7 +8,9 @@ use ruma::{
set_pushrule_enabled, RuleKind, set_pushrule_enabled, RuleKind,
}, },
}, },
events::{push_rules::PushRulesEvent, EventType}, events::{
push_rules::PushRulesEvent, EventType, GlobalAccountDataEventType, RoomAccountDataEventType,
},
push::{ConditionalPushRuleInit, PatternedPushRuleInit, SimplePushRuleInit}, push::{ConditionalPushRuleInit, PatternedPushRuleInit, SimplePushRuleInit},
}; };
@ -23,7 +25,11 @@ pub async fn get_pushrules_all_route(
let event: PushRulesEvent = db let event: PushRulesEvent = db
.account_data .account_data
.get(None, sender_user, EventType::PushRules)? .get(
None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.ok_or(Error::BadRequest( .ok_or(Error::BadRequest(
ErrorKind::NotFound, ErrorKind::NotFound,
"PushRules event not found.", "PushRules event not found.",
@ -39,13 +45,17 @@ pub async fn get_pushrules_all_route(
/// Retrieves a single specified push rule for this user. /// Retrieves a single specified push rule for this user.
pub async fn get_pushrule_route( pub async fn get_pushrule_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_pushrule::v3::Request<'_>>, body: Ruma<get_pushrule::v3::IncomingRequest>,
) -> Result<get_pushrule::v3::Response> { ) -> Result<get_pushrule::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let event: PushRulesEvent = db let event: PushRulesEvent = db
.account_data .account_data
.get(None, sender_user, EventType::PushRules)? .get(
None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.ok_or(Error::BadRequest( .ok_or(Error::BadRequest(
ErrorKind::NotFound, ErrorKind::NotFound,
"PushRules event not found.", "PushRules event not found.",
@ -91,7 +101,7 @@ pub async fn get_pushrule_route(
/// Creates a single specified push rule for this user. /// Creates a single specified push rule for this user.
pub async fn set_pushrule_route( pub async fn set_pushrule_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<set_pushrule::v3::Request<'_>>, body: Ruma<set_pushrule::v3::IncomingRequest>,
) -> Result<set_pushrule::v3::Response> { ) -> Result<set_pushrule::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let body = body.body; let body = body.body;
@ -105,7 +115,11 @@ pub async fn set_pushrule_route(
let mut event: PushRulesEvent = db let mut event: PushRulesEvent = db
.account_data .account_data
.get(None, sender_user, EventType::PushRules)? .get(
None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.ok_or(Error::BadRequest( .ok_or(Error::BadRequest(
ErrorKind::NotFound, ErrorKind::NotFound,
"PushRules event not found.", "PushRules event not found.",
@ -174,8 +188,13 @@ pub async fn set_pushrule_route(
_ => {} _ => {}
} }
db.account_data db.account_data.update(
.update(None, sender_user, EventType::PushRules, &event, &db.globals)?; None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
&event,
&db.globals,
)?;
db.flush()?; db.flush()?;
@ -187,7 +206,7 @@ pub async fn set_pushrule_route(
/// Gets the actions of a single specified push rule for this user. /// Gets the actions of a single specified push rule for this user.
pub async fn get_pushrule_actions_route( pub async fn get_pushrule_actions_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_pushrule_actions::v3::Request<'_>>, body: Ruma<get_pushrule_actions::v3::IncomingRequest>,
) -> Result<get_pushrule_actions::v3::Response> { ) -> Result<get_pushrule_actions::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -200,7 +219,11 @@ pub async fn get_pushrule_actions_route(
let mut event: PushRulesEvent = db let mut event: PushRulesEvent = db
.account_data .account_data
.get(None, sender_user, EventType::PushRules)? .get(
None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.ok_or(Error::BadRequest( .ok_or(Error::BadRequest(
ErrorKind::NotFound, ErrorKind::NotFound,
"PushRules event not found.", "PushRules event not found.",
@ -243,7 +266,7 @@ pub async fn get_pushrule_actions_route(
/// Sets the actions of a single specified push rule for this user. /// Sets the actions of a single specified push rule for this user.
pub async fn set_pushrule_actions_route( pub async fn set_pushrule_actions_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<set_pushrule_actions::v3::Request<'_>>, body: Ruma<set_pushrule_actions::v3::IncomingRequest>,
) -> Result<set_pushrule_actions::v3::Response> { ) -> Result<set_pushrule_actions::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -256,7 +279,11 @@ pub async fn set_pushrule_actions_route(
let mut event: PushRulesEvent = db let mut event: PushRulesEvent = db
.account_data .account_data
.get(None, sender_user, EventType::PushRules)? .get(
None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.ok_or(Error::BadRequest( .ok_or(Error::BadRequest(
ErrorKind::NotFound, ErrorKind::NotFound,
"PushRules event not found.", "PushRules event not found.",
@ -297,8 +324,13 @@ pub async fn set_pushrule_actions_route(
_ => {} _ => {}
}; };
db.account_data db.account_data.update(
.update(None, sender_user, EventType::PushRules, &event, &db.globals)?; None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
&event,
&db.globals,
)?;
db.flush()?; db.flush()?;
@ -310,7 +342,7 @@ pub async fn set_pushrule_actions_route(
/// Gets the enabled status of a single specified push rule for this user. /// Gets the enabled status of a single specified push rule for this user.
pub async fn get_pushrule_enabled_route( pub async fn get_pushrule_enabled_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_pushrule_enabled::v3::Request<'_>>, body: Ruma<get_pushrule_enabled::v3::IncomingRequest>,
) -> Result<get_pushrule_enabled::v3::Response> { ) -> Result<get_pushrule_enabled::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -323,7 +355,11 @@ pub async fn get_pushrule_enabled_route(
let mut event: PushRulesEvent = db let mut event: PushRulesEvent = db
.account_data .account_data
.get(None, sender_user, EventType::PushRules)? .get(
None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.ok_or(Error::BadRequest( .ok_or(Error::BadRequest(
ErrorKind::NotFound, ErrorKind::NotFound,
"PushRules event not found.", "PushRules event not found.",
@ -369,7 +405,7 @@ pub async fn get_pushrule_enabled_route(
/// Sets the enabled status of a single specified push rule for this user. /// Sets the enabled status of a single specified push rule for this user.
pub async fn set_pushrule_enabled_route( pub async fn set_pushrule_enabled_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<set_pushrule_enabled::v3::Request<'_>>, body: Ruma<set_pushrule_enabled::v3::IncomingRequest>,
) -> Result<set_pushrule_enabled::v3::Response> { ) -> Result<set_pushrule_enabled::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -382,7 +418,11 @@ pub async fn set_pushrule_enabled_route(
let mut event: PushRulesEvent = db let mut event: PushRulesEvent = db
.account_data .account_data
.get(None, sender_user, EventType::PushRules)? .get(
None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.ok_or(Error::BadRequest( .ok_or(Error::BadRequest(
ErrorKind::NotFound, ErrorKind::NotFound,
"PushRules event not found.", "PushRules event not found.",
@ -428,8 +468,13 @@ pub async fn set_pushrule_enabled_route(
_ => {} _ => {}
} }
db.account_data db.account_data.update(
.update(None, sender_user, EventType::PushRules, &event, &db.globals)?; None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
&event,
&db.globals,
)?;
db.flush()?; db.flush()?;
@ -441,7 +486,7 @@ pub async fn set_pushrule_enabled_route(
/// Deletes a single specified push rule for this user. /// Deletes a single specified push rule for this user.
pub async fn delete_pushrule_route( pub async fn delete_pushrule_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<delete_pushrule::v3::Request<'_>>, body: Ruma<delete_pushrule::v3::IncomingRequest>,
) -> Result<delete_pushrule::v3::Response> { ) -> Result<delete_pushrule::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -454,7 +499,11 @@ pub async fn delete_pushrule_route(
let mut event: PushRulesEvent = db let mut event: PushRulesEvent = db
.account_data .account_data
.get(None, sender_user, EventType::PushRules)? .get(
None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.ok_or(Error::BadRequest( .ok_or(Error::BadRequest(
ErrorKind::NotFound, ErrorKind::NotFound,
"PushRules event not found.", "PushRules event not found.",
@ -490,8 +539,13 @@ pub async fn delete_pushrule_route(
_ => {} _ => {}
} }
db.account_data db.account_data.update(
.update(None, sender_user, EventType::PushRules, &event, &db.globals)?; None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
&event,
&db.globals,
)?;
db.flush()?; db.flush()?;

@ -1,7 +1,7 @@
use crate::{database::DatabaseGuard, Error, Result, Ruma}; use crate::{database::DatabaseGuard, Error, Result, Ruma};
use ruma::{ use ruma::{
api::client::{error::ErrorKind, read_marker::set_read_marker, receipt::create_receipt}, api::client::{error::ErrorKind, read_marker::set_read_marker, receipt::create_receipt},
events::EventType, events::RoomAccountDataEventType,
receipt::ReceiptType, receipt::ReceiptType,
MilliSecondsSinceUnixEpoch, MilliSecondsSinceUnixEpoch,
}; };
@ -15,7 +15,7 @@ use std::collections::BTreeMap;
/// - If `read_receipt` is set: Update private marker and public read receipt EDU /// - If `read_receipt` is set: Update private marker and public read receipt EDU
pub async fn set_read_marker_route( pub async fn set_read_marker_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<set_read_marker::v3::Request<'_>>, body: Ruma<set_read_marker::v3::IncomingRequest>,
) -> Result<set_read_marker::v3::Response> { ) -> Result<set_read_marker::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -27,7 +27,7 @@ pub async fn set_read_marker_route(
db.account_data.update( db.account_data.update(
Some(&body.room_id), Some(&body.room_id),
sender_user, sender_user,
EventType::FullyRead, RoomAccountDataEventType::FullyRead,
&fully_read_event, &fully_read_event,
&db.globals, &db.globals,
)?; )?;
@ -80,7 +80,7 @@ pub async fn set_read_marker_route(
/// Sets private read marker and public read receipt EDU. /// Sets private read marker and public read receipt EDU.
pub async fn create_receipt_route( pub async fn create_receipt_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<create_receipt::v3::Request<'_>>, body: Ruma<create_receipt::v3::IncomingRequest>,
) -> Result<create_receipt::v3::Response> { ) -> Result<create_receipt::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");

@ -3,7 +3,7 @@ use std::sync::Arc;
use crate::{database::DatabaseGuard, pdu::PduBuilder, Result, Ruma}; use crate::{database::DatabaseGuard, pdu::PduBuilder, Result, Ruma};
use ruma::{ use ruma::{
api::client::redact::redact_event, api::client::redact::redact_event,
events::{room::redaction::RoomRedactionEventContent, EventType}, events::{room::redaction::RoomRedactionEventContent, RoomEventType},
}; };
use serde_json::value::to_raw_value; use serde_json::value::to_raw_value;
@ -15,7 +15,7 @@ use serde_json::value::to_raw_value;
/// - TODO: Handle txn id /// - TODO: Handle txn id
pub async fn redact_event_route( pub async fn redact_event_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<redact_event::v3::Request<'_>>, body: Ruma<redact_event::v3::IncomingRequest>,
) -> Result<redact_event::v3::Response> { ) -> Result<redact_event::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let body = body.body; let body = body.body;
@ -32,7 +32,7 @@ pub async fn redact_event_route(
let event_id = db.rooms.build_and_append_pdu( let event_id = db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomRedaction, event_type: RoomEventType::RoomRedaction,
content: to_raw_value(&RoomRedactionEventContent { content: to_raw_value(&RoomRedactionEventContent {
reason: body.reason.clone(), reason: body.reason.clone(),
}) })

@ -11,7 +11,7 @@ use ruma::{
/// ///
pub async fn report_event_route( pub async fn report_event_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<report_content::v3::Request<'_>>, body: Ruma<report_content::v3::IncomingRequest>,
) -> Result<report_content::v3::Response> { ) -> Result<report_content::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");

@ -19,7 +19,7 @@ use ruma::{
tombstone::RoomTombstoneEventContent, tombstone::RoomTombstoneEventContent,
topic::RoomTopicEventContent, topic::RoomTopicEventContent,
}, },
EventType, RoomEventType, StateEventType,
}, },
int, int,
serde::{CanonicalJsonObject, JsonObject}, serde::{CanonicalJsonObject, JsonObject},
@ -47,7 +47,7 @@ use tracing::{info, warn};
/// - Send invite events /// - Send invite events
pub async fn create_room_route( pub async fn create_room_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<create_room::v3::Request<'_>>, body: Ruma<create_room::v3::IncomingRequest>,
) -> Result<create_room::v3::Response> { ) -> Result<create_room::v3::Response> {
use create_room::v3::RoomPreset; use create_room::v3::RoomPreset;
@ -165,7 +165,7 @@ pub async fn create_room_route(
// 1. The room create event // 1. The room create event
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomCreate, event_type: RoomEventType::RoomCreate,
content: to_raw_value(&content).expect("event is valid, we just created it"), content: to_raw_value(&content).expect("event is valid, we just created it"),
unsigned: None, unsigned: None,
state_key: Some("".to_owned()), state_key: Some("".to_owned()),
@ -180,7 +180,7 @@ pub async fn create_room_route(
// 2. Let the room creator join // 2. Let the room creator join
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomMember, event_type: RoomEventType::RoomMember,
content: to_raw_value(&RoomMemberEventContent { content: to_raw_value(&RoomMemberEventContent {
membership: MembershipState::Join, membership: MembershipState::Join,
displayname: db.users.displayname(sender_user)?, displayname: db.users.displayname(sender_user)?,
@ -242,7 +242,7 @@ pub async fn create_room_route(
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomPowerLevels, event_type: RoomEventType::RoomPowerLevels,
content: to_raw_value(&power_levels_content) content: to_raw_value(&power_levels_content)
.expect("to_raw_value always works on serde_json::Value"), .expect("to_raw_value always works on serde_json::Value"),
unsigned: None, unsigned: None,
@ -259,7 +259,7 @@ pub async fn create_room_route(
if let Some(room_alias_id) = &alias { if let Some(room_alias_id) = &alias {
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomCanonicalAlias, event_type: RoomEventType::RoomCanonicalAlias,
content: to_raw_value(&RoomCanonicalAliasEventContent { content: to_raw_value(&RoomCanonicalAliasEventContent {
alias: Some(room_alias_id.to_owned()), alias: Some(room_alias_id.to_owned()),
alt_aliases: vec![], alt_aliases: vec![],
@ -281,7 +281,7 @@ pub async fn create_room_route(
// 5.1 Join Rules // 5.1 Join Rules
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomJoinRules, event_type: RoomEventType::RoomJoinRules,
content: to_raw_value(&RoomJoinRulesEventContent::new(match preset { content: to_raw_value(&RoomJoinRulesEventContent::new(match preset {
RoomPreset::PublicChat => JoinRule::Public, RoomPreset::PublicChat => JoinRule::Public,
// according to spec "invite" is the default // according to spec "invite" is the default
@ -301,7 +301,7 @@ pub async fn create_room_route(
// 5.2 History Visibility // 5.2 History Visibility
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomHistoryVisibility, event_type: RoomEventType::RoomHistoryVisibility,
content: to_raw_value(&RoomHistoryVisibilityEventContent::new( content: to_raw_value(&RoomHistoryVisibilityEventContent::new(
HistoryVisibility::Shared, HistoryVisibility::Shared,
)) ))
@ -319,7 +319,7 @@ pub async fn create_room_route(
// 5.3 Guest Access // 5.3 Guest Access
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomGuestAccess, event_type: RoomEventType::RoomGuestAccess,
content: to_raw_value(&RoomGuestAccessEventContent::new(match preset { content: to_raw_value(&RoomGuestAccessEventContent::new(match preset {
RoomPreset::PublicChat => GuestAccess::Forbidden, RoomPreset::PublicChat => GuestAccess::Forbidden,
_ => GuestAccess::CanJoin, _ => GuestAccess::CanJoin,
@ -346,7 +346,8 @@ pub async fn create_room_route(
pdu_builder.state_key.get_or_insert_with(|| "".to_owned()); pdu_builder.state_key.get_or_insert_with(|| "".to_owned());
// Silently skip encryption events if they are not allowed // Silently skip encryption events if they are not allowed
if pdu_builder.event_type == EventType::RoomEncryption && !db.globals.allow_encryption() { if pdu_builder.event_type == RoomEventType::RoomEncryption && !db.globals.allow_encryption()
{
continue; continue;
} }
@ -358,7 +359,7 @@ pub async fn create_room_route(
if let Some(name) = &body.name { if let Some(name) = &body.name {
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomName, event_type: RoomEventType::RoomName,
content: to_raw_value(&RoomNameEventContent::new(Some(name.clone()))) content: to_raw_value(&RoomNameEventContent::new(Some(name.clone())))
.expect("event is valid, we just created it"), .expect("event is valid, we just created it"),
unsigned: None, unsigned: None,
@ -375,7 +376,7 @@ pub async fn create_room_route(
if let Some(topic) = &body.topic { if let Some(topic) = &body.topic {
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomTopic, event_type: RoomEventType::RoomTopic,
content: to_raw_value(&RoomTopicEventContent { content: to_raw_value(&RoomTopicEventContent {
topic: topic.clone(), topic: topic.clone(),
}) })
@ -420,7 +421,7 @@ pub async fn create_room_route(
/// - You have to currently be joined to the room (TODO: Respect history visibility) /// - You have to currently be joined to the room (TODO: Respect history visibility)
pub async fn get_room_event_route( pub async fn get_room_event_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_room_event::v3::Request<'_>>, body: Ruma<get_room_event::v3::IncomingRequest>,
) -> Result<get_room_event::v3::Response> { ) -> Result<get_room_event::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -447,7 +448,7 @@ pub async fn get_room_event_route(
/// - Only users joined to the room are allowed to call this TODO: Allow any user to call it if history_visibility is world readable /// - Only users joined to the room are allowed to call this TODO: Allow any user to call it if history_visibility is world readable
pub async fn get_room_aliases_route( pub async fn get_room_aliases_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<aliases::v3::Request<'_>>, body: Ruma<aliases::v3::IncomingRequest>,
) -> Result<aliases::v3::Response> { ) -> Result<aliases::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -479,7 +480,7 @@ pub async fn get_room_aliases_route(
/// - Modifies old room power levels to prevent users from speaking /// - Modifies old room power levels to prevent users from speaking
pub async fn upgrade_room_route( pub async fn upgrade_room_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<upgrade_room::v3::Request<'_>>, body: Ruma<upgrade_room::v3::IncomingRequest>,
) -> Result<upgrade_room::v3::Response> { ) -> Result<upgrade_room::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -509,7 +510,7 @@ pub async fn upgrade_room_route(
// Fail if the sender does not have the required permissions // Fail if the sender does not have the required permissions
let tombstone_event_id = db.rooms.build_and_append_pdu( let tombstone_event_id = db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomTombstone, event_type: RoomEventType::RoomTombstone,
content: to_raw_value(&RoomTombstoneEventContent { content: to_raw_value(&RoomTombstoneEventContent {
body: "This room has been replaced".to_owned(), body: "This room has been replaced".to_owned(),
replacement_room: replacement_room.clone(), replacement_room: replacement_room.clone(),
@ -540,7 +541,7 @@ pub async fn upgrade_room_route(
// Get the old room creation event // Get the old room creation event
let mut create_event_content = serde_json::from_str::<CanonicalJsonObject>( let mut create_event_content = serde_json::from_str::<CanonicalJsonObject>(
db.rooms db.rooms
.room_state_get(&body.room_id, &EventType::RoomCreate, "")? .room_state_get(&body.room_id, &StateEventType::RoomCreate, "")?
.ok_or_else(|| Error::bad_database("Found room without m.room.create event."))? .ok_or_else(|| Error::bad_database("Found room without m.room.create event."))?
.content .content
.get(), .get(),
@ -589,7 +590,7 @@ pub async fn upgrade_room_route(
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomCreate, event_type: RoomEventType::RoomCreate,
content: to_raw_value(&create_event_content) content: to_raw_value(&create_event_content)
.expect("event is valid, we just created it"), .expect("event is valid, we just created it"),
unsigned: None, unsigned: None,
@ -605,7 +606,7 @@ pub async fn upgrade_room_route(
// Join the new room // Join the new room
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomMember, event_type: RoomEventType::RoomMember,
content: to_raw_value(&RoomMemberEventContent { content: to_raw_value(&RoomMemberEventContent {
membership: MembershipState::Join, membership: MembershipState::Join,
displayname: db.users.displayname(sender_user)?, displayname: db.users.displayname(sender_user)?,
@ -629,15 +630,15 @@ pub async fn upgrade_room_route(
// Recommended transferable state events list from the specs // Recommended transferable state events list from the specs
let transferable_state_events = vec![ let transferable_state_events = vec![
EventType::RoomServerAcl, StateEventType::RoomServerAcl,
EventType::RoomEncryption, StateEventType::RoomEncryption,
EventType::RoomName, StateEventType::RoomName,
EventType::RoomAvatar, StateEventType::RoomAvatar,
EventType::RoomTopic, StateEventType::RoomTopic,
EventType::RoomGuestAccess, StateEventType::RoomGuestAccess,
EventType::RoomHistoryVisibility, StateEventType::RoomHistoryVisibility,
EventType::RoomJoinRules, StateEventType::RoomJoinRules,
EventType::RoomPowerLevels, StateEventType::RoomPowerLevels,
]; ];
// Replicate transferable state events to the new room // Replicate transferable state events to the new room
@ -649,7 +650,7 @@ pub async fn upgrade_room_route(
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type, event_type: event_type.to_string().into(),
content: event_content, content: event_content,
unsigned: None, unsigned: None,
state_key: Some("".to_owned()), state_key: Some("".to_owned()),
@ -671,7 +672,7 @@ pub async fn upgrade_room_route(
// Get the old room power levels // Get the old room power levels
let mut power_levels_event_content: RoomPowerLevelsEventContent = serde_json::from_str( let mut power_levels_event_content: RoomPowerLevelsEventContent = serde_json::from_str(
db.rooms db.rooms
.room_state_get(&body.room_id, &EventType::RoomPowerLevels, "")? .room_state_get(&body.room_id, &StateEventType::RoomPowerLevels, "")?
.ok_or_else(|| Error::bad_database("Found room without m.room.create event."))? .ok_or_else(|| Error::bad_database("Found room without m.room.create event."))?
.content .content
.get(), .get(),
@ -686,7 +687,7 @@ pub async fn upgrade_room_route(
// Modify the power levels in the old room to prevent sending of events and inviting new users // Modify the power levels in the old room to prevent sending of events and inviting new users
let _ = db.rooms.build_and_append_pdu( let _ = db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomPowerLevels, event_type: RoomEventType::RoomPowerLevels,
content: to_raw_value(&power_levels_event_content) content: to_raw_value(&power_levels_event_content)
.expect("event is valid, we just created it"), .expect("event is valid, we just created it"),
unsigned: None, unsigned: None,

@ -16,7 +16,7 @@ use std::collections::BTreeMap;
/// - Only works if the user is currently joined to the room (TODO: Respect history visibility) /// - Only works if the user is currently joined to the room (TODO: Respect history visibility)
pub async fn search_events_route( pub async fn search_events_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<search_events::v3::Request<'_>>, body: Ruma<search_events::v3::IncomingRequest>,
) -> Result<search_events::v3::Response> { ) -> Result<search_events::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");

@ -22,7 +22,7 @@ struct Claims {
/// Get the supported login types of this server. One of these should be used as the `type` field /// Get the supported login types of this server. One of these should be used as the `type` field
/// when logging in. /// when logging in.
pub async fn get_login_types_route( pub async fn get_login_types_route(
_body: Ruma<get_login_types::v3::Request>, _body: Ruma<get_login_types::v3::IncomingRequest>,
) -> Result<get_login_types::v3::Response> { ) -> Result<get_login_types::v3::Response> {
Ok(get_login_types::v3::Response::new(vec![ Ok(get_login_types::v3::Response::new(vec![
get_login_types::v3::LoginType::Password(Default::default()), get_login_types::v3::LoginType::Password(Default::default()),
@ -42,7 +42,7 @@ pub async fn get_login_types_route(
/// supported login types. /// supported login types.
pub async fn login_route( pub async fn login_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<login::v3::Request<'_>>, body: Ruma<login::v3::IncomingRequest>,
) -> Result<login::v3::Response> { ) -> Result<login::v3::Response> {
// Validate login method // Validate login method
// TODO: Other login methods // TODO: Other login methods

@ -13,7 +13,7 @@ use ruma::{
canonical_alias::RoomCanonicalAliasEventContent, canonical_alias::RoomCanonicalAliasEventContent,
history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent}, history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent},
}, },
AnyStateEventContent, EventType, AnyStateEventContent, EventType, RoomEventType, StateEventType,
}, },
serde::Raw, serde::Raw,
EventId, RoomId, UserId, EventId, RoomId, UserId,
@ -28,7 +28,7 @@ use ruma::{
/// - If event is new canonical_alias: Rejects if alias is incorrect /// - If event is new canonical_alias: Rejects if alias is incorrect
pub async fn send_state_event_for_key_route( pub async fn send_state_event_for_key_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<send_state_event::v3::Request<'_>>, body: Ruma<send_state_event::v3::IncomingRequest>,
) -> Result<send_state_event::v3::Response> { ) -> Result<send_state_event::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -36,7 +36,7 @@ pub async fn send_state_event_for_key_route(
&db, &db,
sender_user, sender_user,
&body.room_id, &body.room_id,
EventType::from(&*body.event_type), &body.event_type,
&body.body.body, // Yes, I hate it too &body.body.body, // Yes, I hate it too
body.state_key.to_owned(), body.state_key.to_owned(),
) )
@ -57,12 +57,12 @@ pub async fn send_state_event_for_key_route(
/// - If event is new canonical_alias: Rejects if alias is incorrect /// - If event is new canonical_alias: Rejects if alias is incorrect
pub async fn send_state_event_for_empty_key_route( pub async fn send_state_event_for_empty_key_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<send_state_event::v3::Request<'_>>, body: Ruma<send_state_event::v3::IncomingRequest>,
) -> Result<RumaResponse<send_state_event::v3::Response>> { ) -> Result<RumaResponse<send_state_event::v3::Response>> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
// Forbid m.room.encryption if encryption is disabled // Forbid m.room.encryption if encryption is disabled
if &body.event_type == "m.room.encryption" && !db.globals.allow_encryption() { if body.event_type == StateEventType::RoomEncryption && !db.globals.allow_encryption() {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::Forbidden,
"Encryption has been disabled", "Encryption has been disabled",
@ -73,7 +73,7 @@ pub async fn send_state_event_for_empty_key_route(
&db, &db,
sender_user, sender_user,
&body.room_id, &body.room_id,
EventType::from(&*body.event_type), &body.event_type.to_string().into(),
&body.body.body, &body.body.body,
body.state_key.to_owned(), body.state_key.to_owned(),
) )
@ -92,7 +92,7 @@ pub async fn send_state_event_for_empty_key_route(
/// - If not joined: Only works if current room history visibility is world readable /// - If not joined: Only works if current room history visibility is world readable
pub async fn get_state_events_route( pub async fn get_state_events_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_state_events::v3::Request<'_>>, body: Ruma<get_state_events::v3::IncomingRequest>,
) -> Result<get_state_events::v3::Response> { ) -> Result<get_state_events::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -102,7 +102,7 @@ pub async fn get_state_events_route(
if !db.rooms.is_joined(sender_user, &body.room_id)? if !db.rooms.is_joined(sender_user, &body.room_id)?
&& !matches!( && !matches!(
db.rooms db.rooms
.room_state_get(&body.room_id, &EventType::RoomHistoryVisibility, "")? .room_state_get(&body.room_id, &StateEventType::RoomHistoryVisibility, "")?
.map(|event| { .map(|event| {
serde_json::from_str(event.content.get()) serde_json::from_str(event.content.get())
.map(|e: RoomHistoryVisibilityEventContent| e.history_visibility) .map(|e: RoomHistoryVisibilityEventContent| e.history_visibility)
@ -138,7 +138,7 @@ pub async fn get_state_events_route(
/// - If not joined: Only works if current room history visibility is world readable /// - If not joined: Only works if current room history visibility is world readable
pub async fn get_state_events_for_key_route( pub async fn get_state_events_for_key_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_state_events_for_key::v3::Request<'_>>, body: Ruma<get_state_events_for_key::v3::IncomingRequest>,
) -> Result<get_state_events_for_key::v3::Response> { ) -> Result<get_state_events_for_key::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -148,7 +148,7 @@ pub async fn get_state_events_for_key_route(
if !db.rooms.is_joined(sender_user, &body.room_id)? if !db.rooms.is_joined(sender_user, &body.room_id)?
&& !matches!( && !matches!(
db.rooms db.rooms
.room_state_get(&body.room_id, &EventType::RoomHistoryVisibility, "")? .room_state_get(&body.room_id, &StateEventType::RoomHistoryVisibility, "")?
.map(|event| { .map(|event| {
serde_json::from_str(event.content.get()) serde_json::from_str(event.content.get())
.map(|e: RoomHistoryVisibilityEventContent| e.history_visibility) .map(|e: RoomHistoryVisibilityEventContent| e.history_visibility)
@ -188,7 +188,7 @@ pub async fn get_state_events_for_key_route(
/// - If not joined: Only works if current room history visibility is world readable /// - If not joined: Only works if current room history visibility is world readable
pub async fn get_state_events_for_empty_key_route( pub async fn get_state_events_for_empty_key_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_state_events_for_key::v3::Request<'_>>, body: Ruma<get_state_events_for_key::v3::IncomingRequest>,
) -> Result<RumaResponse<get_state_events_for_key::v3::Response>> { ) -> Result<RumaResponse<get_state_events_for_key::v3::Response>> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@ -198,7 +198,7 @@ pub async fn get_state_events_for_empty_key_route(
if !db.rooms.is_joined(sender_user, &body.room_id)? if !db.rooms.is_joined(sender_user, &body.room_id)?
&& !matches!( && !matches!(
db.rooms db.rooms
.room_state_get(&body.room_id, &EventType::RoomHistoryVisibility, "")? .room_state_get(&body.room_id, &StateEventType::RoomHistoryVisibility, "")?
.map(|event| { .map(|event| {
serde_json::from_str(event.content.get()) serde_json::from_str(event.content.get())
.map(|e: RoomHistoryVisibilityEventContent| e.history_visibility) .map(|e: RoomHistoryVisibilityEventContent| e.history_visibility)
@ -236,7 +236,7 @@ async fn send_state_event_for_key_helper(
db: &Database, db: &Database,
sender: &UserId, sender: &UserId,
room_id: &RoomId, room_id: &RoomId,
event_type: EventType, event_type: &StateEventType,
json: &Raw<AnyStateEventContent>, json: &Raw<AnyStateEventContent>,
state_key: String, state_key: String,
) -> Result<Arc<EventId>> { ) -> Result<Arc<EventId>> {
@ -282,7 +282,7 @@ async fn send_state_event_for_key_helper(
let event_id = db.rooms.build_and_append_pdu( let event_id = db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type, event_type: event_type.to_string().into(),
content: serde_json::from_str(json.json().get()).expect("content is valid json"), content: serde_json::from_str(json.json().get()).expect("content is valid json"),
unsigned: None, unsigned: None,
state_key: Some(state_key), state_key: Some(state_key),

@ -7,7 +7,7 @@ use ruma::{
}, },
events::{ events::{
room::member::{MembershipState, RoomMemberEventContent}, room::member::{MembershipState, RoomMemberEventContent},
EventType, EventType, RoomEventType, StateEventType,
}, },
serde::Raw, serde::Raw,
DeviceId, RoomId, UserId, DeviceId, RoomId, UserId,
@ -56,7 +56,7 @@ use tracing::error;
/// `since` will be cached /// `since` will be cached
pub async fn sync_events_route( pub async fn sync_events_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<sync_events::v3::Request<'_>>, body: Ruma<sync_events::v3::IncomingRequest>,
) -> Result<sync_events::v3::Response, RumaResponse<UiaaResponse>> { ) -> Result<sync_events::v3::Response, RumaResponse<UiaaResponse>> {
let sender_user = body.sender_user.expect("user is authenticated"); let sender_user = body.sender_user.expect("user is authenticated");
let sender_device = body.sender_device.expect("user is authenticated"); let sender_device = body.sender_device.expect("user is authenticated");
@ -74,7 +74,7 @@ pub async fn sync_events_route(
Entry::Vacant(v) => { Entry::Vacant(v) => {
let (tx, rx) = tokio::sync::watch::channel(None); let (tx, rx) = tokio::sync::watch::channel(None);
v.insert((body.since.clone(), rx.clone())); v.insert((body.since.to_owned(), rx.clone()));
tokio::spawn(sync_helper_wrapper( tokio::spawn(sync_helper_wrapper(
Arc::clone(&arc_db), Arc::clone(&arc_db),
@ -319,7 +319,7 @@ async fn sync_helper(
.rooms .rooms
.all_pdus(&sender_user, &room_id)? .all_pdus(&sender_user, &room_id)?
.filter_map(|pdu| pdu.ok()) // Ignore all broken pdus .filter_map(|pdu| pdu.ok()) // Ignore all broken pdus
.filter(|(_, pdu)| pdu.kind == EventType::RoomMember) .filter(|(_, pdu)| pdu.kind == RoomEventType::RoomMember)
.map(|(_, pdu)| { .map(|(_, pdu)| {
let content: RoomMemberEventContent = let content: RoomMemberEventContent =
serde_json::from_str(pdu.content.get()).map_err(|_| { serde_json::from_str(pdu.content.get()).map_err(|_| {
@ -385,7 +385,7 @@ async fn sync_helper(
for (shortstatekey, id) in current_state_ids { for (shortstatekey, id) in current_state_ids {
let (event_type, state_key) = db.rooms.get_statekey_from_short(shortstatekey)?; let (event_type, state_key) = db.rooms.get_statekey_from_short(shortstatekey)?;
if event_type != EventType::RoomMember { if event_type != StateEventType::RoomMember {
let pdu = match db.rooms.get_pdu(&id)? { let pdu = match db.rooms.get_pdu(&id)? {
Some(pdu) => pdu, Some(pdu) => pdu,
None => { None => {
@ -446,7 +446,7 @@ async fn sync_helper(
.rooms .rooms
.state_get( .state_get(
since_shortstatehash, since_shortstatehash,
&EventType::RoomMember, &StateEventType::RoomMember,
sender_user.as_str(), sender_user.as_str(),
)? )?
.and_then(|pdu| { .and_then(|pdu| {
@ -475,7 +475,7 @@ async fn sync_helper(
} }
}; };
if pdu.kind == EventType::RoomMember { if pdu.kind == RoomEventType::RoomMember {
match UserId::parse( match UserId::parse(
pdu.state_key pdu.state_key
.as_ref() .as_ref()
@ -508,7 +508,7 @@ async fn sync_helper(
{ {
if let Some(member_event) = db.rooms.room_state_get( if let Some(member_event) = db.rooms.room_state_get(
&room_id, &room_id,
&EventType::RoomMember, &StateEventType::RoomMember,
event.sender.as_str(), event.sender.as_str(),
)? { )? {
lazy_loaded.insert(event.sender.clone()); lazy_loaded.insert(event.sender.clone());
@ -527,23 +527,23 @@ async fn sync_helper(
let encrypted_room = db let encrypted_room = db
.rooms .rooms
.state_get(current_shortstatehash, &EventType::RoomEncryption, "")? .state_get(current_shortstatehash, &StateEventType::RoomEncryption, "")?
.is_some(); .is_some();
let since_encryption = let since_encryption =
db.rooms db.rooms
.state_get(since_shortstatehash, &EventType::RoomEncryption, "")?; .state_get(since_shortstatehash, &StateEventType::RoomEncryption, "")?;
// Calculations: // Calculations:
let new_encrypted_room = encrypted_room && since_encryption.is_none(); let new_encrypted_room = encrypted_room && since_encryption.is_none();
let send_member_count = state_events let send_member_count = state_events
.iter() .iter()
.any(|event| event.kind == EventType::RoomMember); .any(|event| event.kind == RoomEventType::RoomMember);
if encrypted_room { if encrypted_room {
for state_event in &state_events { for state_event in &state_events {
if state_event.kind != EventType::RoomMember { if state_event.kind != RoomEventType::RoomMember {
continue; continue;
} }
@ -830,7 +830,7 @@ async fn sync_helper(
.filter_map(|other_room_id| { .filter_map(|other_room_id| {
Some( Some(
db.rooms db.rooms
.room_state_get(&other_room_id, &EventType::RoomEncryption, "") .room_state_get(&other_room_id, &StateEventType::RoomEncryption, "")
.ok()? .ok()?
.is_some(), .is_some(),
) )
@ -923,7 +923,7 @@ fn share_encrypted_room(
.filter_map(|other_room_id| { .filter_map(|other_room_id| {
Some( Some(
db.rooms db.rooms
.room_state_get(&other_room_id, &EventType::RoomEncryption, "") .room_state_get(&other_room_id, &StateEventType::RoomEncryption, "")
.ok()? .ok()?
.is_some(), .is_some(),
) )

@ -3,7 +3,7 @@ use ruma::{
api::client::tag::{create_tag, delete_tag, get_tags}, api::client::tag::{create_tag, delete_tag, get_tags},
events::{ events::{
tag::{TagEvent, TagEventContent}, tag::{TagEvent, TagEventContent},
EventType, EventType, RoomAccountDataEventType,
}, },
}; };
use std::collections::BTreeMap; use std::collections::BTreeMap;
@ -15,13 +15,17 @@ use std::collections::BTreeMap;
/// - Inserts the tag into the tag event of the room account data. /// - Inserts the tag into the tag event of the room account data.
pub async fn update_tag_route( pub async fn update_tag_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<create_tag::v3::Request<'_>>, body: Ruma<create_tag::v3::IncomingRequest>,
) -> Result<create_tag::v3::Response> { ) -> Result<create_tag::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let mut tags_event = db let mut tags_event = db
.account_data .account_data
.get(Some(&body.room_id), sender_user, EventType::Tag)? .get(
Some(&body.room_id),
sender_user,
RoomAccountDataEventType::Tag,
)?
.unwrap_or_else(|| TagEvent { .unwrap_or_else(|| TagEvent {
content: TagEventContent { content: TagEventContent {
tags: BTreeMap::new(), tags: BTreeMap::new(),
@ -35,7 +39,7 @@ pub async fn update_tag_route(
db.account_data.update( db.account_data.update(
Some(&body.room_id), Some(&body.room_id),
sender_user, sender_user,
EventType::Tag, RoomAccountDataEventType::Tag,
&tags_event, &tags_event,
&db.globals, &db.globals,
)?; )?;
@ -52,13 +56,17 @@ pub async fn update_tag_route(
/// - Removes the tag from the tag event of the room account data. /// - Removes the tag from the tag event of the room account data.
pub async fn delete_tag_route( pub async fn delete_tag_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<delete_tag::v3::Request<'_>>, body: Ruma<delete_tag::v3::IncomingRequest>,
) -> Result<delete_tag::v3::Response> { ) -> Result<delete_tag::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let mut tags_event = db let mut tags_event = db
.account_data .account_data
.get(Some(&body.room_id), sender_user, EventType::Tag)? .get(
Some(&body.room_id),
sender_user,
RoomAccountDataEventType::Tag,
)?
.unwrap_or_else(|| TagEvent { .unwrap_or_else(|| TagEvent {
content: TagEventContent { content: TagEventContent {
tags: BTreeMap::new(), tags: BTreeMap::new(),
@ -69,7 +77,7 @@ pub async fn delete_tag_route(
db.account_data.update( db.account_data.update(
Some(&body.room_id), Some(&body.room_id),
sender_user, sender_user,
EventType::Tag, RoomAccountDataEventType::Tag,
&tags_event, &tags_event,
&db.globals, &db.globals,
)?; )?;
@ -86,14 +94,18 @@ pub async fn delete_tag_route(
/// - Gets the tag event of the room account data. /// - Gets the tag event of the room account data.
pub async fn get_tags_route( pub async fn get_tags_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_tags::v3::Request<'_>>, body: Ruma<get_tags::v3::IncomingRequest>,
) -> Result<get_tags::v3::Response> { ) -> Result<get_tags::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
Ok(get_tags::v3::Response { Ok(get_tags::v3::Response {
tags: db tags: db
.account_data .account_data
.get(Some(&body.room_id), sender_user, EventType::Tag)? .get(
Some(&body.room_id),
sender_user,
RoomAccountDataEventType::Tag,
)?
.unwrap_or_else(|| TagEvent { .unwrap_or_else(|| TagEvent {
content: TagEventContent { content: TagEventContent {
tags: BTreeMap::new(), tags: BTreeMap::new(),

@ -7,7 +7,7 @@ use std::collections::BTreeMap;
/// ///
/// TODO: Fetches all metadata about protocols supported by the homeserver. /// TODO: Fetches all metadata about protocols supported by the homeserver.
pub async fn get_protocols_route( pub async fn get_protocols_route(
_body: Ruma<get_protocols::v3::Request>, _body: Ruma<get_protocols::v3::IncomingRequest>,
) -> Result<get_protocols::v3::Response> { ) -> Result<get_protocols::v3::Response> {
// TODO // TODO
Ok(get_protocols::v3::Response { Ok(get_protocols::v3::Response {

@ -1,3 +1,4 @@
use ruma::events::ToDeviceEventType;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use crate::{database::DatabaseGuard, Error, Result, Ruma}; use crate::{database::DatabaseGuard, Error, Result, Ruma};
@ -15,7 +16,7 @@ use ruma::{
/// Send a to-device event to a set of client devices. /// Send a to-device event to a set of client devices.
pub async fn send_event_to_device_route( pub async fn send_event_to_device_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<send_event_to_device::v3::Request<'_>>, body: Ruma<send_event_to_device::v3::IncomingRequest>,
) -> Result<send_event_to_device::v3::Response> { ) -> Result<send_event_to_device::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_deref(); let sender_device = body.sender_device.as_deref();
@ -45,8 +46,8 @@ pub async fn send_event_to_device_route(
serde_json::to_vec(&federation::transactions::edu::Edu::DirectToDevice( serde_json::to_vec(&federation::transactions::edu::Edu::DirectToDevice(
DirectDeviceContent { DirectDeviceContent {
sender: sender_user.clone(), sender: sender_user.clone(),
ev_type: EventType::from(&*body.event_type), ev_type: ToDeviceEventType::from(&*body.event_type),
message_id: body.txn_id.clone(), message_id: body.txn_id.to_owned(),
messages, messages,
}, },
)) ))
@ -61,7 +62,7 @@ pub async fn send_event_to_device_route(
DeviceIdOrAllDevices::DeviceId(target_device_id) => db.users.add_to_device_event( DeviceIdOrAllDevices::DeviceId(target_device_id) => db.users.add_to_device_event(
sender_user, sender_user,
target_user_id, target_user_id,
target_device_id, &target_device_id,
&body.event_type, &body.event_type,
event.deserialize_as().map_err(|_| { event.deserialize_as().map_err(|_| {
Error::BadRequest(ErrorKind::InvalidParam, "Event is invalid") Error::BadRequest(ErrorKind::InvalidParam, "Event is invalid")

@ -6,7 +6,7 @@ use ruma::api::client::typing::create_typing_event;
/// Sets the typing state of the sender user. /// Sets the typing state of the sender user.
pub async fn create_typing_event_route( pub async fn create_typing_event_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<create_typing_event::v3::Request<'_>>, body: Ruma<create_typing_event::v3::IncomingRequest>,
) -> Result<create_typing_event::v3::Response> { ) -> Result<create_typing_event::v3::Response> {
use create_typing_event::v3::Typing; use create_typing_event::v3::Typing;

@ -1,7 +1,8 @@
use std::{collections::BTreeMap, iter::FromIterator}; use std::{collections::BTreeMap, iter::FromIterator};
use ruma::api::client::discovery::get_supported_versions;
use crate::{Result, Ruma}; use crate::{Result, Ruma};
use ruma::api::client::discover::get_supported_versions;
/// # `GET /_matrix/client/versions` /// # `GET /_matrix/client/versions`
/// ///
@ -14,7 +15,7 @@ use ruma::api::client::discover::get_supported_versions;
/// Note: Unstable features are used while developing new features. Clients should avoid using /// Note: Unstable features are used while developing new features. Clients should avoid using
/// unstable features in their stable releases /// unstable features in their stable releases
pub async fn get_supported_versions_route( pub async fn get_supported_versions_route(
_body: Ruma<get_supported_versions::Request>, _body: Ruma<get_supported_versions::IncomingRequest>,
) -> Result<get_supported_versions::Response> { ) -> Result<get_supported_versions::Response> {
let resp = get_supported_versions::Response { let resp = get_supported_versions::Response {
versions: vec!["r0.5.0".to_owned(), "r0.6.0".to_owned()], versions: vec!["r0.5.0".to_owned(), "r0.6.0".to_owned()],

@ -8,7 +8,7 @@ use ruma::api::client::user_directory::search_users;
/// - TODO: Hide users that are not in any public rooms? /// - TODO: Hide users that are not in any public rooms?
pub async fn search_users_route( pub async fn search_users_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<search_users::v3::Request<'_>>, body: Ruma<search_users::v3::IncomingRequest>,
) -> Result<search_users::v3::Response> { ) -> Result<search_users::v3::Response> {
let limit = u64::from(body.limit) as usize; let limit = u64::from(body.limit) as usize;

@ -11,7 +11,7 @@ type HmacSha1 = Hmac<Sha1>;
/// TODO: Returns information about the recommended turn server. /// TODO: Returns information about the recommended turn server.
pub async fn turn_server_route( pub async fn turn_server_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_turn_server_info::v3::Request>, body: Ruma<get_turn_server_info::v3::IncomingRequest>,
) -> Result<get_turn_server_info::v3::Response> { ) -> Result<get_turn_server_info::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");

@ -1,7 +1,7 @@
use crate::{utils, Error, Result}; use crate::{utils, Error, Result};
use ruma::{ use ruma::{
api::client::error::ErrorKind, api::client::error::ErrorKind,
events::{AnyEphemeralRoomEvent, EventType}, events::{AnyEphemeralRoomEvent, RoomAccountDataEventType},
serde::Raw, serde::Raw,
RoomId, UserId, RoomId, UserId,
}; };
@ -22,7 +22,7 @@ impl AccountData {
&self, &self,
room_id: Option<&RoomId>, room_id: Option<&RoomId>,
user_id: &UserId, user_id: &UserId,
event_type: EventType, event_type: RoomAccountDataEventType,
data: &T, data: &T,
globals: &super::globals::Globals, globals: &super::globals::Globals,
) -> Result<()> { ) -> Result<()> {
@ -38,10 +38,10 @@ impl AccountData {
let mut roomuserdataid = prefix.clone(); let mut roomuserdataid = prefix.clone();
roomuserdataid.extend_from_slice(&globals.next_count()?.to_be_bytes()); roomuserdataid.extend_from_slice(&globals.next_count()?.to_be_bytes());
roomuserdataid.push(0xff); roomuserdataid.push(0xff);
roomuserdataid.extend_from_slice(event_type.as_bytes()); roomuserdataid.extend_from_slice(event_type.to_string().as_bytes());
let mut key = prefix; let mut key = prefix;
key.extend_from_slice(event_type.as_bytes()); key.extend_from_slice(event_type.to_string().as_bytes());
let json = serde_json::to_value(data).expect("all types here can be serialized"); // TODO: maybe add error handling let json = serde_json::to_value(data).expect("all types here can be serialized"); // TODO: maybe add error handling
if json.get("type").is_none() || json.get("content").is_none() { if json.get("type").is_none() || json.get("content").is_none() {
@ -75,7 +75,7 @@ impl AccountData {
&self, &self,
room_id: Option<&RoomId>, room_id: Option<&RoomId>,
user_id: &UserId, user_id: &UserId,
kind: EventType, kind: RoomAccountDataEventType,
) -> Result<Option<T>> { ) -> Result<Option<T>> {
let mut key = room_id let mut key = room_id
.map(|r| r.to_string()) .map(|r| r.to_string())
@ -85,7 +85,7 @@ impl AccountData {
key.push(0xff); key.push(0xff);
key.extend_from_slice(user_id.as_bytes()); key.extend_from_slice(user_id.as_bytes());
key.push(0xff); key.push(0xff);
key.extend_from_slice(kind.as_ref().as_bytes()); key.extend_from_slice(kind.to_string().as_bytes());
self.roomusertype_roomuserdataid self.roomusertype_roomuserdataid
.get(&key)? .get(&key)?
@ -109,7 +109,7 @@ impl AccountData {
room_id: Option<&RoomId>, room_id: Option<&RoomId>,
user_id: &UserId, user_id: &UserId,
since: u64, since: u64,
) -> Result<HashMap<EventType, Raw<AnyEphemeralRoomEvent>>> { ) -> Result<HashMap<RoomAccountDataEventType, Raw<AnyEphemeralRoomEvent>>> {
let mut userdata = HashMap::new(); let mut userdata = HashMap::new();
let mut prefix = room_id let mut prefix = room_id
@ -131,7 +131,7 @@ impl AccountData {
.take_while(move |(k, _)| k.starts_with(&prefix)) .take_while(move |(k, _)| k.starts_with(&prefix))
.map(|(k, v)| { .map(|(k, v)| {
Ok::<_, Error>(( Ok::<_, Error>((
EventType::try_from( RoomAccountDataEventType::try_from(
utils::string_from_bytes(k.rsplit(|&b| b == 0xff).next().ok_or_else( utils::string_from_bytes(k.rsplit(|&b| b == 0xff).next().ok_or_else(
|| Error::bad_database("RoomUserData ID in db is invalid."), || Error::bad_database("RoomUserData ID in db is invalid."),
)?) )?)

@ -28,9 +28,9 @@ use ruma::{
power_levels::RoomPowerLevelsEventContent, power_levels::RoomPowerLevelsEventContent,
topic::RoomTopicEventContent, topic::RoomTopicEventContent,
}, },
EventType, RoomEventType,
}, },
identifiers::{EventId, RoomAliasId, RoomId, RoomName, RoomVersionId, ServerName, UserId}, EventId, RoomAliasId, RoomId, RoomName, RoomVersionId, ServerName, UserId,
}; };
use serde_json::value::to_raw_value; use serde_json::value::to_raw_value;
use tokio::sync::{mpsc, MutexGuard, RwLock, RwLockReadGuard}; use tokio::sync::{mpsc, MutexGuard, RwLock, RwLockReadGuard};
@ -81,7 +81,7 @@ impl Admin {
.rooms .rooms
.build_and_append_pdu( .build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomMessage, event_type: RoomEventType::RoomMessage,
content: to_raw_value(&message) content: to_raw_value(&message)
.expect("event is valid, we just created it"), .expect("event is valid, we just created it"),
unsigned: None, unsigned: None,
@ -553,7 +553,7 @@ pub(crate) async fn create_admin_room(db: &Database) -> Result<()> {
// 1. The room create event // 1. The room create event
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomCreate, event_type: RoomEventType::RoomCreate,
content: to_raw_value(&content).expect("event is valid, we just created it"), content: to_raw_value(&content).expect("event is valid, we just created it"),
unsigned: None, unsigned: None,
state_key: Some("".to_owned()), state_key: Some("".to_owned()),
@ -568,7 +568,7 @@ pub(crate) async fn create_admin_room(db: &Database) -> Result<()> {
// 2. Make conduit bot join // 2. Make conduit bot join
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomMember, event_type: RoomEventType::RoomMember,
content: to_raw_value(&RoomMemberEventContent { content: to_raw_value(&RoomMemberEventContent {
membership: MembershipState::Join, membership: MembershipState::Join,
displayname: None, displayname: None,
@ -596,7 +596,7 @@ pub(crate) async fn create_admin_room(db: &Database) -> Result<()> {
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomPowerLevels, event_type: RoomEventType::RoomPowerLevels,
content: to_raw_value(&RoomPowerLevelsEventContent { content: to_raw_value(&RoomPowerLevelsEventContent {
users, users,
..Default::default() ..Default::default()
@ -615,7 +615,7 @@ pub(crate) async fn create_admin_room(db: &Database) -> Result<()> {
// 4.1 Join Rules // 4.1 Join Rules
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomJoinRules, event_type: RoomEventType::RoomJoinRules,
content: to_raw_value(&RoomJoinRulesEventContent::new(JoinRule::Invite)) content: to_raw_value(&RoomJoinRulesEventContent::new(JoinRule::Invite))
.expect("event is valid, we just created it"), .expect("event is valid, we just created it"),
unsigned: None, unsigned: None,
@ -631,7 +631,7 @@ pub(crate) async fn create_admin_room(db: &Database) -> Result<()> {
// 4.2 History Visibility // 4.2 History Visibility
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomHistoryVisibility, event_type: RoomEventType::RoomHistoryVisibility,
content: to_raw_value(&RoomHistoryVisibilityEventContent::new( content: to_raw_value(&RoomHistoryVisibilityEventContent::new(
HistoryVisibility::Shared, HistoryVisibility::Shared,
)) ))
@ -649,7 +649,7 @@ pub(crate) async fn create_admin_room(db: &Database) -> Result<()> {
// 4.3 Guest Access // 4.3 Guest Access
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomGuestAccess, event_type: RoomEventType::RoomGuestAccess,
content: to_raw_value(&RoomGuestAccessEventContent::new(GuestAccess::Forbidden)) content: to_raw_value(&RoomGuestAccessEventContent::new(GuestAccess::Forbidden))
.expect("event is valid, we just created it"), .expect("event is valid, we just created it"),
unsigned: None, unsigned: None,
@ -667,7 +667,7 @@ pub(crate) async fn create_admin_room(db: &Database) -> Result<()> {
.expect("Room name is valid"); .expect("Room name is valid");
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomName, event_type: RoomEventType::RoomName,
content: to_raw_value(&RoomNameEventContent::new(Some(room_name))) content: to_raw_value(&RoomNameEventContent::new(Some(room_name)))
.expect("event is valid, we just created it"), .expect("event is valid, we just created it"),
unsigned: None, unsigned: None,
@ -682,7 +682,7 @@ pub(crate) async fn create_admin_room(db: &Database) -> Result<()> {
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomTopic, event_type: RoomEventType::RoomTopic,
content: to_raw_value(&RoomTopicEventContent { content: to_raw_value(&RoomTopicEventContent {
topic: format!("Manage {}", db.globals.server_name()), topic: format!("Manage {}", db.globals.server_name()),
}) })
@ -704,7 +704,7 @@ pub(crate) async fn create_admin_room(db: &Database) -> Result<()> {
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomCanonicalAlias, event_type: RoomEventType::RoomCanonicalAlias,
content: to_raw_value(&RoomCanonicalAliasEventContent { content: to_raw_value(&RoomCanonicalAliasEventContent {
alias: Some(alias.clone()), alias: Some(alias.clone()),
alt_aliases: Vec::new(), alt_aliases: Vec::new(),
@ -758,7 +758,7 @@ pub(crate) async fn make_user_admin(
// Invite and join the real user // Invite and join the real user
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomMember, event_type: RoomEventType::RoomMember,
content: to_raw_value(&RoomMemberEventContent { content: to_raw_value(&RoomMemberEventContent {
membership: MembershipState::Invite, membership: MembershipState::Invite,
displayname: None, displayname: None,
@ -781,7 +781,7 @@ pub(crate) async fn make_user_admin(
)?; )?;
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomMember, event_type: RoomEventType::RoomMember,
content: to_raw_value(&RoomMemberEventContent { content: to_raw_value(&RoomMemberEventContent {
membership: MembershipState::Join, membership: MembershipState::Join,
displayname: Some(displayname), displayname: Some(displayname),
@ -810,7 +810,7 @@ pub(crate) async fn make_user_admin(
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomPowerLevels, event_type: RoomEventType::RoomPowerLevels,
content: to_raw_value(&RoomPowerLevelsEventContent { content: to_raw_value(&RoomPowerLevelsEventContent {
users, users,
..Default::default() ..Default::default()
@ -829,7 +829,7 @@ pub(crate) async fn make_user_admin(
// Send welcome message // Send welcome message
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomMessage, event_type: RoomEventType::RoomMessage,
content: to_raw_value(&RoomMessageEventContent::text_html( content: to_raw_value(&RoomMessageEventContent::text_html(
format!("## Thank you for trying out Conduit!\n\nConduit is currently in Beta. This means you can join and participate in most Matrix rooms, but not all features are supported and you might run into bugs from time to time.\n\nHelpful links:\n> Website: https://conduit.rs\n> Git and Documentation: https://gitlab.com/famedly/conduit\n> Report issues: https://gitlab.com/famedly/conduit/-/issues\n\nFor a list of available commands, send the following message in this room: `@conduit:{}: --help`\n\nHere are some rooms you can join (by typing the command):\n\nConduit room (Ask questions and get notified on updates):\n`/join #conduit:fachschaften.org`\n\nConduit lounge (Off-topic, only Conduit users are allowed to join)\n`/join #conduit-lounge:conduit.rs`", db.globals.server_name()).to_owned(), format!("## Thank you for trying out Conduit!\n\nConduit is currently in Beta. This means you can join and participate in most Matrix rooms, but not all features are supported and you might run into bugs from time to time.\n\nHelpful links:\n> Website: https://conduit.rs\n> Git and Documentation: https://gitlab.com/famedly/conduit\n> Report issues: https://gitlab.com/famedly/conduit/-/issues\n\nFor a list of available commands, send the following message in this room: `@conduit:{}: --help`\n\nHere are some rooms you can join (by typing the command):\n\nConduit room (Ask questions and get notified on updates):\n`/join #conduit:fachschaften.org`\n\nConduit lounge (Off-topic, only Conduit users are allowed to join)\n`/join #conduit-lounge:conduit.rs`", db.globals.server_name()).to_owned(),
format!("<h2>Thank you for trying out Conduit!</h2>\n<p>Conduit is currently in Beta. This means you can join and participate in most Matrix rooms, but not all features are supported and you might run into bugs from time to time.</p>\n<p>Helpful links:</p>\n<blockquote>\n<p>Website: https://conduit.rs<br>Git and Documentation: https://gitlab.com/famedly/conduit<br>Report issues: https://gitlab.com/famedly/conduit/-/issues</p>\n</blockquote>\n<p>For a list of available commands, send the following message in this room: <code>@conduit:{}: --help</code></p>\n<p>Here are some rooms you can join (by typing the command):</p>\n<p>Conduit room (Ask questions and get notified on updates):<br><code>/join #conduit:fachschaften.org</code></p>\n<p>Conduit lounge (Off-topic, only Conduit users are allowed to join)<br><code>/join #conduit-lounge:conduit.rs</code></p>\n", db.globals.server_name()).to_owned(), format!("<h2>Thank you for trying out Conduit!</h2>\n<p>Conduit is currently in Beta. This means you can join and participate in most Matrix rooms, but not all features are supported and you might run into bugs from time to time.</p>\n<p>Helpful links:</p>\n<blockquote>\n<p>Website: https://conduit.rs<br>Git and Documentation: https://gitlab.com/famedly/conduit<br>Report issues: https://gitlab.com/famedly/conduit/-/issues</p>\n</blockquote>\n<p>For a list of available commands, send the following message in this room: <code>@conduit:{}: --help</code></p>\n<p>Here are some rooms you can join (by typing the command):</p>\n<p>Conduit room (Ask questions and get notified on updates):<br><code>/join #conduit:fachschaften.org</code></p>\n<p>Conduit lounge (Off-topic, only Conduit users are allowed to join)<br><code>/join #conduit-lounge:conduit.rs</code></p>\n", db.globals.server_name()).to_owned(),

@ -11,7 +11,7 @@ use ruma::{
}, },
events::{ events::{
room::{name::RoomNameEventContent, power_levels::RoomPowerLevelsEventContent}, room::{name::RoomNameEventContent, power_levels::RoomPowerLevelsEventContent},
AnySyncRoomEvent, EventType, AnySyncRoomEvent, EventType, RoomEventType, StateEventType,
}, },
push::{Action, PushConditionRoomCtx, PushFormat, Ruleset, Tweak}, push::{Action, PushConditionRoomCtx, PushFormat, Ruleset, Tweak},
serde::Raw, serde::Raw,
@ -181,7 +181,7 @@ pub async fn send_push_notice(
let power_levels: RoomPowerLevelsEventContent = db let power_levels: RoomPowerLevelsEventContent = db
.rooms .rooms
.room_state_get(&pdu.room_id, &EventType::RoomPowerLevels, "")? .room_state_get(&pdu.room_id, &StateEventType::RoomPowerLevels, "")?
.map(|ev| { .map(|ev| {
serde_json::from_str(ev.content.get()) serde_json::from_str(ev.content.get())
.map_err(|_| Error::bad_database("invalid m.room.power_levels event")) .map_err(|_| Error::bad_database("invalid m.room.power_levels event"))
@ -293,7 +293,7 @@ async fn send_notice(
// TODO: missed calls // TODO: missed calls
notifi.counts = NotificationCounts::new(unread, uint!(0)); notifi.counts = NotificationCounts::new(unread, uint!(0));
if event.kind == EventType::RoomEncrypted if event.kind == RoomEventType::RoomEncrypted
|| tweaks || tweaks
.iter() .iter()
.any(|t| matches!(t, Tweak::Highlight(true) | Tweak::Sound(_))) .any(|t| matches!(t, Tweak::Highlight(true) | Tweak::Sound(_)))
@ -314,7 +314,7 @@ async fn send_notice(
let content = serde_json::value::to_raw_value(&event.content).ok(); let content = serde_json::value::to_raw_value(&event.content).ok();
notifi.content = content.as_deref(); notifi.content = content.as_deref();
if event.kind == EventType::RoomMember { if event.kind == RoomEventType::RoomMember {
notifi.user_is_target = event.state_key.as_deref() == Some(event.sender.as_str()); notifi.user_is_target = event.state_key.as_deref() == Some(event.sender.as_str());
} }
@ -323,7 +323,7 @@ async fn send_notice(
let room_name = if let Some(room_name_pdu) = let room_name = if let Some(room_name_pdu) =
db.rooms db.rooms
.room_state_get(&event.room_id, &EventType::RoomName, "")? .room_state_get(&event.room_id, &StateEventType::RoomName, "")?
{ {
serde_json::from_str::<RoomNameEventContent>(room_name_pdu.content.get()) serde_json::from_str::<RoomNameEventContent>(room_name_pdu.content.get())
.map_err(|_| Error::bad_database("Invalid room name event in database."))? .map_err(|_| Error::bad_database("Invalid room name event in database."))?

@ -21,7 +21,8 @@ use ruma::{
power_levels::RoomPowerLevelsEventContent, power_levels::RoomPowerLevelsEventContent,
}, },
tag::TagEvent, tag::TagEvent,
AnyStrippedStateEvent, AnySyncStateEvent, EventType, AnyStrippedStateEvent, AnySyncStateEvent, GlobalAccountDataEventType,
RoomAccountDataEventType, RoomEventType, StateEventType,
}, },
push::{Action, Ruleset, Tweak}, push::{Action, Ruleset, Tweak},
serde::{CanonicalJsonObject, CanonicalJsonValue, Raw}, serde::{CanonicalJsonObject, CanonicalJsonValue, Raw},
@ -111,8 +112,8 @@ pub struct Rooms {
pub(super) shorteventid_cache: Mutex<LruCache<u64, Arc<EventId>>>, pub(super) shorteventid_cache: Mutex<LruCache<u64, Arc<EventId>>>,
pub(super) auth_chain_cache: Mutex<LruCache<Vec<u64>, Arc<HashSet<u64>>>>, pub(super) auth_chain_cache: Mutex<LruCache<Vec<u64>, Arc<HashSet<u64>>>>,
pub(super) eventidshort_cache: Mutex<LruCache<Box<EventId>, u64>>, pub(super) eventidshort_cache: Mutex<LruCache<Box<EventId>, u64>>,
pub(super) statekeyshort_cache: Mutex<LruCache<(EventType, String), u64>>, pub(super) statekeyshort_cache: Mutex<LruCache<(StateEventType, String), u64>>,
pub(super) shortstatekey_cache: Mutex<LruCache<u64, (EventType, String)>>, pub(super) shortstatekey_cache: Mutex<LruCache<u64, (StateEventType, String)>>,
pub(super) our_real_users_cache: RwLock<HashMap<Box<RoomId>, Arc<HashSet<Box<UserId>>>>>, pub(super) our_real_users_cache: RwLock<HashMap<Box<RoomId>, Arc<HashSet<Box<UserId>>>>>,
pub(super) appservice_in_room_cache: RwLock<HashMap<Box<RoomId>, HashMap<String, bool>>>, pub(super) appservice_in_room_cache: RwLock<HashMap<Box<RoomId>, HashMap<String, bool>>>,
pub(super) lazy_load_waiting: pub(super) lazy_load_waiting:
@ -151,7 +152,7 @@ impl Rooms {
pub fn state_full( pub fn state_full(
&self, &self,
shortstatehash: u64, shortstatehash: u64,
) -> Result<HashMap<(EventType, String), Arc<PduEvent>>> { ) -> Result<HashMap<(StateEventType, String), Arc<PduEvent>>> {
let full_state = self let full_state = self
.load_shortstatehash_info(shortstatehash)? .load_shortstatehash_info(shortstatehash)?
.pop() .pop()
@ -166,7 +167,7 @@ impl Rooms {
.map(|pdu| { .map(|pdu| {
Ok::<_, Error>(( Ok::<_, Error>((
( (
pdu.kind.clone(), pdu.kind.to_string().into(),
pdu.state_key pdu.state_key
.as_ref() .as_ref()
.ok_or_else(|| Error::bad_database("State event has no state key."))? .ok_or_else(|| Error::bad_database("State event has no state key."))?
@ -184,7 +185,7 @@ impl Rooms {
pub fn state_get_id( pub fn state_get_id(
&self, &self,
shortstatehash: u64, shortstatehash: u64,
event_type: &EventType, event_type: &StateEventType,
state_key: &str, state_key: &str,
) -> Result<Option<Arc<EventId>>> { ) -> Result<Option<Arc<EventId>>> {
let shortstatekey = match self.get_shortstatekey(event_type, state_key)? { let shortstatekey = match self.get_shortstatekey(event_type, state_key)? {
@ -211,7 +212,7 @@ impl Rooms {
pub fn state_get( pub fn state_get(
&self, &self,
shortstatehash: u64, shortstatehash: u64,
event_type: &EventType, event_type: &StateEventType,
state_key: &str, state_key: &str,
) -> Result<Option<Arc<PduEvent>>> { ) -> Result<Option<Arc<PduEvent>>> {
self.state_get_id(shortstatehash, event_type, state_key)? self.state_get_id(shortstatehash, event_type, state_key)?
@ -254,7 +255,7 @@ impl Rooms {
pub fn get_auth_events( pub fn get_auth_events(
&self, &self,
room_id: &RoomId, room_id: &RoomId,
kind: &EventType, kind: &RoomEventType,
sender: &UserId, sender: &UserId,
state_key: Option<&str>, state_key: Option<&str>,
content: &serde_json::value::RawValue, content: &serde_json::value::RawValue,
@ -272,7 +273,7 @@ impl Rooms {
let mut sauthevents = auth_events let mut sauthevents = auth_events
.into_iter() .into_iter()
.filter_map(|(event_type, state_key)| { .filter_map(|(event_type, state_key)| {
self.get_shortstatekey(&event_type, &state_key) self.get_shortstatekey(&event_type.to_string().into(), &state_key)
.ok() .ok()
.flatten() .flatten()
.map(|s| (s, (event_type, state_key))) .map(|s| (s, (event_type, state_key)))
@ -764,7 +765,7 @@ impl Rooms {
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
pub fn get_shortstatekey( pub fn get_shortstatekey(
&self, &self,
event_type: &EventType, event_type: &StateEventType,
state_key: &str, state_key: &str,
) -> Result<Option<u64>> { ) -> Result<Option<u64>> {
if let Some(short) = self if let Some(short) = self
@ -776,7 +777,7 @@ impl Rooms {
return Ok(Some(*short)); return Ok(Some(*short));
} }
let mut statekey = event_type.as_ref().as_bytes().to_vec(); let mut statekey = event_type.to_string().as_bytes().to_vec();
statekey.push(0xff); statekey.push(0xff);
statekey.extend_from_slice(state_key.as_bytes()); statekey.extend_from_slice(state_key.as_bytes());
@ -820,7 +821,7 @@ impl Rooms {
#[tracing::instrument(skip(self, globals))] #[tracing::instrument(skip(self, globals))]
pub fn get_or_create_shortstatekey( pub fn get_or_create_shortstatekey(
&self, &self,
event_type: &EventType, event_type: &StateEventType,
state_key: &str, state_key: &str,
globals: &super::globals::Globals, globals: &super::globals::Globals,
) -> Result<u64> { ) -> Result<u64> {
@ -833,7 +834,7 @@ impl Rooms {
return Ok(*short); return Ok(*short);
} }
let mut statekey = event_type.as_ref().as_bytes().to_vec(); let mut statekey = event_type.to_string().as_bytes().to_vec();
statekey.push(0xff); statekey.push(0xff);
statekey.extend_from_slice(state_key.as_bytes()); statekey.extend_from_slice(state_key.as_bytes());
@ -888,7 +889,7 @@ impl Rooms {
} }
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
pub fn get_statekey_from_short(&self, shortstatekey: u64) -> Result<(EventType, String)> { pub fn get_statekey_from_short(&self, shortstatekey: u64) -> Result<(StateEventType, String)> {
if let Some(id) = self if let Some(id) = self
.shortstatekey_cache .shortstatekey_cache
.lock() .lock()
@ -910,7 +911,7 @@ impl Rooms {
.ok_or_else(|| Error::bad_database("Invalid statekey in shortstatekey_statekey."))?; .ok_or_else(|| Error::bad_database("Invalid statekey in shortstatekey_statekey."))?;
let event_type = let event_type =
EventType::try_from(utils::string_from_bytes(eventtype_bytes).map_err(|_| { StateEventType::try_from(utils::string_from_bytes(eventtype_bytes).map_err(|_| {
Error::bad_database("Event type in shortstatekey_statekey is invalid unicode.") Error::bad_database("Event type in shortstatekey_statekey is invalid unicode.")
})?) })?)
.map_err(|_| Error::bad_database("Event type in shortstatekey_statekey is invalid."))?; .map_err(|_| Error::bad_database("Event type in shortstatekey_statekey is invalid."))?;
@ -934,7 +935,7 @@ impl Rooms {
pub fn room_state_full( pub fn room_state_full(
&self, &self,
room_id: &RoomId, room_id: &RoomId,
) -> Result<HashMap<(EventType, String), Arc<PduEvent>>> { ) -> Result<HashMap<(StateEventType, String), Arc<PduEvent>>> {
if let Some(current_shortstatehash) = self.current_shortstatehash(room_id)? { if let Some(current_shortstatehash) = self.current_shortstatehash(room_id)? {
self.state_full(current_shortstatehash) self.state_full(current_shortstatehash)
} else { } else {
@ -947,7 +948,7 @@ impl Rooms {
pub fn room_state_get_id( pub fn room_state_get_id(
&self, &self,
room_id: &RoomId, room_id: &RoomId,
event_type: &EventType, event_type: &StateEventType,
state_key: &str, state_key: &str,
) -> Result<Option<Arc<EventId>>> { ) -> Result<Option<Arc<EventId>>> {
if let Some(current_shortstatehash) = self.current_shortstatehash(room_id)? { if let Some(current_shortstatehash) = self.current_shortstatehash(room_id)? {
@ -962,7 +963,7 @@ impl Rooms {
pub fn room_state_get( pub fn room_state_get(
&self, &self,
room_id: &RoomId, room_id: &RoomId,
event_type: &EventType, event_type: &StateEventType,
state_key: &str, state_key: &str,
) -> Result<Option<Arc<PduEvent>>> { ) -> Result<Option<Arc<PduEvent>>> {
if let Some(current_shortstatehash) = self.current_shortstatehash(room_id)? { if let Some(current_shortstatehash) = self.current_shortstatehash(room_id)? {
@ -1281,7 +1282,7 @@ impl Rooms {
{ {
if let Some(shortstatehash) = self.pdu_shortstatehash(&pdu.event_id).unwrap() { if let Some(shortstatehash) = self.pdu_shortstatehash(&pdu.event_id).unwrap() {
if let Some(prev_state) = self if let Some(prev_state) = self
.state_get(shortstatehash, &pdu.kind, state_key) .state_get(shortstatehash, &pdu.kind.to_string().into(), state_key)
.unwrap() .unwrap()
{ {
unsigned.insert( unsigned.insert(
@ -1346,7 +1347,7 @@ impl Rooms {
// See if the event matches any known pushers // See if the event matches any known pushers
let power_levels: RoomPowerLevelsEventContent = db let power_levels: RoomPowerLevelsEventContent = db
.rooms .rooms
.room_state_get(&pdu.room_id, &EventType::RoomPowerLevels, "")? .room_state_get(&pdu.room_id, &StateEventType::RoomPowerLevels, "")?
.map(|ev| { .map(|ev| {
serde_json::from_str(ev.content.get()) serde_json::from_str(ev.content.get())
.map_err(|_| Error::bad_database("invalid m.room.power_levels event")) .map_err(|_| Error::bad_database("invalid m.room.power_levels event"))
@ -1367,7 +1368,11 @@ impl Rooms {
let rules_for_user = db let rules_for_user = db
.account_data .account_data
.get(None, user, EventType::PushRules)? .get(
None,
user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.map(|ev: PushRulesEvent| ev.content.global) .map(|ev: PushRulesEvent| ev.content.global)
.unwrap_or_else(|| Ruleset::server_default(user)); .unwrap_or_else(|| Ruleset::server_default(user));
@ -1416,12 +1421,12 @@ impl Rooms {
.increment_batch(&mut highlights.into_iter())?; .increment_batch(&mut highlights.into_iter())?;
match pdu.kind { match pdu.kind {
EventType::RoomRedaction => { RoomEventType::RoomRedaction => {
if let Some(redact_id) = &pdu.redacts { if let Some(redact_id) = &pdu.redacts {
self.redact_pdu(redact_id, pdu)?; self.redact_pdu(redact_id, pdu)?;
} }
} }
EventType::RoomMember => { RoomEventType::RoomMember => {
if let Some(state_key) = &pdu.state_key { if let Some(state_key) = &pdu.state_key {
#[derive(Deserialize)] #[derive(Deserialize)]
struct ExtractMembership { struct ExtractMembership {
@ -1456,7 +1461,7 @@ impl Rooms {
)?; )?;
} }
} }
EventType::RoomMessage => { RoomEventType::RoomMessage => {
#[derive(Deserialize)] #[derive(Deserialize)]
struct ExtractBody<'a> { struct ExtractBody<'a> {
#[serde(borrow)] #[serde(borrow)]
@ -1663,8 +1668,11 @@ impl Rooms {
let states_parents = previous_shortstatehash let states_parents = previous_shortstatehash
.map_or_else(|| Ok(Vec::new()), |p| self.load_shortstatehash_info(p))?; .map_or_else(|| Ok(Vec::new()), |p| self.load_shortstatehash_info(p))?;
let shortstatekey = let shortstatekey = self.get_or_create_shortstatekey(
self.get_or_create_shortstatekey(&new_pdu.kind, state_key, globals)?; &new_pdu.kind.to_string().into(),
state_key,
globals,
)?;
let new = self.compress_state_event(shortstatekey, &new_pdu.event_id, globals)?; let new = self.compress_state_event(shortstatekey, &new_pdu.event_id, globals)?;
@ -1713,28 +1721,36 @@ impl Rooms {
) -> Result<Vec<Raw<AnyStrippedStateEvent>>> { ) -> Result<Vec<Raw<AnyStrippedStateEvent>>> {
let mut state = Vec::new(); let mut state = Vec::new();
// Add recommended events // Add recommended events
if let Some(e) = self.room_state_get(&invite_event.room_id, &EventType::RoomCreate, "")? {
state.push(e.to_stripped_state_event());
}
if let Some(e) = if let Some(e) =
self.room_state_get(&invite_event.room_id, &EventType::RoomJoinRules, "")? self.room_state_get(&invite_event.room_id, &StateEventType::RoomCreate, "")?
{ {
state.push(e.to_stripped_state_event()); state.push(e.to_stripped_state_event());
} }
if let Some(e) = if let Some(e) =
self.room_state_get(&invite_event.room_id, &EventType::RoomCanonicalAlias, "")? self.room_state_get(&invite_event.room_id, &StateEventType::RoomJoinRules, "")?
{ {
state.push(e.to_stripped_state_event()); state.push(e.to_stripped_state_event());
} }
if let Some(e) = self.room_state_get(&invite_event.room_id, &EventType::RoomAvatar, "")? { if let Some(e) = self.room_state_get(
&invite_event.room_id,
&StateEventType::RoomCanonicalAlias,
"",
)? {
state.push(e.to_stripped_state_event());
}
if let Some(e) =
self.room_state_get(&invite_event.room_id, &StateEventType::RoomAvatar, "")?
{
state.push(e.to_stripped_state_event()); state.push(e.to_stripped_state_event());
} }
if let Some(e) = self.room_state_get(&invite_event.room_id, &EventType::RoomName, "")? { if let Some(e) =
self.room_state_get(&invite_event.room_id, &StateEventType::RoomName, "")?
{
state.push(e.to_stripped_state_event()); state.push(e.to_stripped_state_event());
} }
if let Some(e) = self.room_state_get( if let Some(e) = self.room_state_get(
&invite_event.room_id, &invite_event.room_id,
&EventType::RoomMember, &StateEventType::RoomMember,
invite_event.sender.as_str(), invite_event.sender.as_str(),
)? { )? {
state.push(e.to_stripped_state_event()); state.push(e.to_stripped_state_event());
@ -1807,7 +1823,7 @@ impl Rooms {
.take(20) .take(20)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let create_event = self.room_state_get(room_id, &EventType::RoomCreate, "")?; let create_event = self.room_state_get(room_id, &StateEventType::RoomCreate, "")?;
let create_event_content: Option<RoomCreateEventContent> = create_event let create_event_content: Option<RoomCreateEventContent> = create_event
.as_ref() .as_ref()
@ -1845,7 +1861,9 @@ impl Rooms {
let mut unsigned = unsigned.unwrap_or_default(); let mut unsigned = unsigned.unwrap_or_default();
if let Some(state_key) = &state_key { if let Some(state_key) = &state_key {
if let Some(prev_pdu) = self.room_state_get(room_id, &event_type, state_key)? { if let Some(prev_pdu) =
self.room_state_get(room_id, &event_type.to_string().into(), state_key)?
{
unsigned.insert( unsigned.insert(
"prev_content".to_owned(), "prev_content".to_owned(),
serde_json::from_str(prev_pdu.content.get()).expect("string is valid json"), serde_json::from_str(prev_pdu.content.get()).expect("string is valid json"),
@ -1888,7 +1906,6 @@ impl Rooms {
let auth_check = state_res::auth_check( let auth_check = state_res::auth_check(
&room_version, &room_version,
&pdu, &pdu,
create_prev_event,
None::<PduEvent>, // TODO: third_party_invite None::<PduEvent>, // TODO: third_party_invite
|k, s| auth_events.get(&(k.clone(), s.to_owned())), |k, s| auth_events.get(&(k.clone(), s.to_owned())),
) )
@ -2031,7 +2048,7 @@ impl Rooms {
let matching_users = |users: &Regex| { let matching_users = |users: &Regex| {
users.is_match(pdu.sender.as_str()) users.is_match(pdu.sender.as_str())
|| pdu.kind == EventType::RoomMember || pdu.kind == RoomEventType::RoomMember
&& pdu && pdu
.state_key .state_key
.as_ref() .as_ref()
@ -2231,7 +2248,7 @@ impl Rooms {
// Check if the room has a predecessor // Check if the room has a predecessor
if let Some(predecessor) = self if let Some(predecessor) = self
.room_state_get(room_id, &EventType::RoomCreate, "")? .room_state_get(room_id, &StateEventType::RoomCreate, "")?
.and_then(|create| serde_json::from_str(create.content.get()).ok()) .and_then(|create| serde_json::from_str(create.content.get()).ok())
.and_then(|content: RoomCreateEventContent| content.predecessor) .and_then(|content: RoomCreateEventContent| content.predecessor)
{ {
@ -2264,13 +2281,13 @@ impl Rooms {
if let Some(tag_event) = db.account_data.get::<TagEvent>( if let Some(tag_event) = db.account_data.get::<TagEvent>(
Some(&predecessor.room_id), Some(&predecessor.room_id),
user_id, user_id,
EventType::Tag, RoomAccountDataEventType::Tag,
)? { )? {
db.account_data db.account_data
.update( .update(
Some(room_id), Some(room_id),
user_id, user_id,
EventType::Tag, RoomAccountDataEventType::Tag,
&tag_event, &tag_event,
&db.globals, &db.globals,
) )
@ -2278,10 +2295,11 @@ impl Rooms {
}; };
// Copy direct chat flag // Copy direct chat flag
if let Some(mut direct_event) = if let Some(mut direct_event) = db.account_data.get::<DirectEvent>(
db.account_data None,
.get::<DirectEvent>(None, user_id, EventType::Direct)? user_id,
{ GlobalAccountDataEventType::Direct.to_string().into(),
)? {
let mut room_ids_updated = false; let mut room_ids_updated = false;
for room_ids in direct_event.content.0.values_mut() { for room_ids in direct_event.content.0.values_mut() {
@ -2295,7 +2313,7 @@ impl Rooms {
db.account_data.update( db.account_data.update(
None, None,
user_id, user_id,
EventType::Direct, GlobalAccountDataEventType::Direct.to_string().into(),
&direct_event, &direct_event,
&db.globals, &db.globals,
)?; )?;
@ -2322,7 +2340,9 @@ impl Rooms {
.get::<IgnoredUserListEvent>( .get::<IgnoredUserListEvent>(
None, // Ignored users are in global account data None, // Ignored users are in global account data
user_id, // Receiver user_id, // Receiver
EventType::IgnoredUserList, GlobalAccountDataEventType::IgnoredUserList
.to_string()
.into(),
)? )?
.map_or(false, |ignored| { .map_or(false, |ignored| {
ignored ignored
@ -2578,7 +2598,7 @@ impl Rooms {
let state_lock = mutex_state.lock().await; let state_lock = mutex_state.lock().await;
let mut event: RoomMemberEventContent = serde_json::from_str( let mut event: RoomMemberEventContent = serde_json::from_str(
self.room_state_get(room_id, &EventType::RoomMember, user_id.as_str())? self.room_state_get(room_id, &StateEventType::RoomMember, user_id.as_str())?
.ok_or(Error::BadRequest( .ok_or(Error::BadRequest(
ErrorKind::BadState, ErrorKind::BadState,
"Cannot leave a room you are not a member of.", "Cannot leave a room you are not a member of.",
@ -2592,7 +2612,7 @@ impl Rooms {
self.build_and_append_pdu( self.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: EventType::RoomMember, event_type: RoomEventType::RoomMember,
content: to_raw_value(&event).expect("event is valid, we just created it"), content: to_raw_value(&event).expect("event is valid, we just created it"),
unsigned: None, unsigned: None,
state_key: Some(user_id.to_string()), state_key: Some(user_id.to_string()),

@ -23,7 +23,10 @@ use ruma::{
OutgoingRequest, OutgoingRequest,
}, },
device_id, device_id,
events::{push_rules::PushRulesEvent, AnySyncEphemeralRoomEvent, EventType}, events::{
push_rules::PushRulesEvent, AnySyncEphemeralRoomEvent, EventType,
GlobalAccountDataEventType,
},
push, push,
receipt::ReceiptType, receipt::ReceiptType,
uint, MilliSecondsSinceUnixEpoch, ServerName, UInt, UserId, uint, MilliSecondsSinceUnixEpoch, ServerName, UInt, UserId,
@ -635,7 +638,11 @@ impl Sending {
let rules_for_user = db let rules_for_user = db
.account_data .account_data
.get(None, &userid, EventType::PushRules) .get(
None,
&userid,
GlobalAccountDataEventType::PushRules.to_string().into(),
)
.unwrap_or_default() .unwrap_or_default()
.map(|ev: PushRulesEvent| ev.content.global) .map(|ev: PushRulesEvent| ev.content.global)
.unwrap_or_else(|| push::Ruleset::server_default(&userid)); .unwrap_or_else(|| push::Ruleset::server_default(&userid));

@ -1,7 +1,7 @@
use std::sync::Arc; use std::sync::Arc;
use crate::Result; use crate::Result;
use ruma::{identifiers::TransactionId, DeviceId, UserId}; use ruma::{DeviceId, TransactionId, UserId};
use super::abstraction::Tree; use super::abstraction::Tree;

@ -2,11 +2,10 @@ use crate::{utils, Error, Result};
use ruma::{ use ruma::{
api::client::{device::Device, error::ErrorKind, filter::IncomingFilterDefinition}, api::client::{device::Device, error::ErrorKind, filter::IncomingFilterDefinition},
encryption::{CrossSigningKey, DeviceKeys, OneTimeKey}, encryption::{CrossSigningKey, DeviceKeys, OneTimeKey},
events::{AnyToDeviceEvent, EventType}, events::{AnyToDeviceEvent, StateEventType},
identifiers::MxcUri,
serde::Raw, serde::Raw,
DeviceId, DeviceKeyAlgorithm, DeviceKeyId, MilliSecondsSinceUnixEpoch, RoomAliasId, UInt, DeviceId, DeviceKeyAlgorithm, DeviceKeyId, MilliSecondsSinceUnixEpoch, MxcUri, RoomAliasId,
UserId, UInt, UserId,
}; };
use std::{collections::BTreeMap, mem, sync::Arc}; use std::{collections::BTreeMap, mem, sync::Arc};
use tracing::warn; use tracing::warn;
@ -754,7 +753,7 @@ impl Users {
for room_id in rooms.rooms_joined(user_id).filter_map(|r| r.ok()) { for room_id in rooms.rooms_joined(user_id).filter_map(|r| r.ok()) {
// Don't send key updates to unencrypted rooms // Don't send key updates to unencrypted rooms
if rooms if rooms
.room_state_get(&room_id, &EventType::RoomEncryption, "")? .room_state_get(&room_id, &StateEventType::RoomEncryption, "")?
.is_none() .is_none()
{ {
continue; continue;

@ -26,10 +26,7 @@ use http::{
Method, Uri, Method, Uri,
}; };
use opentelemetry::trace::{FutureExt, Tracer}; use opentelemetry::trace::{FutureExt, Tracer};
use ruma::{ use ruma::api::{client::error::ErrorKind, IncomingRequest};
api::{client::error::ErrorKind, IncomingRequest},
Outgoing,
};
use tokio::{signal, sync::RwLock}; use tokio::{signal, sync::RwLock};
use tower::ServiceBuilder; use tower::ServiceBuilder;
use tower_http::{ use tower_http::{
@ -408,16 +405,15 @@ macro_rules! impl_ruma_handler {
#[allow(non_snake_case)] #[allow(non_snake_case)]
impl<Req, E, F, Fut, $($ty,)*> RumaHandler<($($ty,)* Ruma<Req>,)> for F impl<Req, E, F, Fut, $($ty,)*> RumaHandler<($($ty,)* Ruma<Req>,)> for F
where where
Req: Outgoing + 'static, Req: IncomingRequest + Send + 'static,
Req::Incoming: IncomingRequest + Send,
F: FnOnce($($ty,)* Ruma<Req>) -> Fut + Clone + Send + 'static, F: FnOnce($($ty,)* Ruma<Req>) -> Fut + Clone + Send + 'static,
Fut: Future<Output = Result<<Req::Incoming as IncomingRequest>::OutgoingResponse, E>> Fut: Future<Output = Result<Req::OutgoingResponse, E>>
+ Send, + Send,
E: IntoResponse, E: IntoResponse,
$( $ty: FromRequest<axum::body::Body> + Send + 'static, )* $( $ty: FromRequest<axum::body::Body> + Send + 'static, )*
{ {
fn add_to_router(self, mut router: Router) -> Router { fn add_to_router(self, mut router: Router) -> Router {
let meta = Req::Incoming::METADATA; let meta = Req::METADATA;
let method_filter = method_to_filter(meta.method); let method_filter = method_to_filter(meta.method);
for path in IntoIterator::into_iter([meta.unstable_path, meta.r0_path, meta.stable_path]).flatten() { for path in IntoIterator::into_iter([meta.unstable_path, meta.r0_path, meta.stable_path]).flatten() {

@ -2,7 +2,7 @@ use crate::Error;
use ruma::{ use ruma::{
events::{ events::{
room::member::RoomMemberEventContent, AnyEphemeralRoomEvent, AnyRoomEvent, AnyStateEvent, room::member::RoomMemberEventContent, AnyEphemeralRoomEvent, AnyRoomEvent, AnyStateEvent,
AnyStrippedStateEvent, AnySyncRoomEvent, AnySyncStateEvent, EventType, StateEvent, AnyStrippedStateEvent, AnySyncRoomEvent, AnySyncStateEvent, RoomEventType, StateEvent,
}, },
serde::{CanonicalJsonObject, CanonicalJsonValue, Raw}, serde::{CanonicalJsonObject, CanonicalJsonValue, Raw},
state_res, EventId, MilliSecondsSinceUnixEpoch, RoomId, RoomVersionId, UInt, UserId, state_res, EventId, MilliSecondsSinceUnixEpoch, RoomId, RoomVersionId, UInt, UserId,
@ -29,7 +29,7 @@ pub struct PduEvent {
pub sender: Box<UserId>, pub sender: Box<UserId>,
pub origin_server_ts: UInt, pub origin_server_ts: UInt,
#[serde(rename = "type")] #[serde(rename = "type")]
pub kind: EventType, pub kind: RoomEventType,
pub content: Box<RawJsonValue>, pub content: Box<RawJsonValue>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub state_key: Option<String>, pub state_key: Option<String>,
@ -51,10 +51,10 @@ impl PduEvent {
self.unsigned = None; self.unsigned = None;
let allowed: &[&str] = match self.kind { let allowed: &[&str] = match self.kind {
EventType::RoomMember => &["membership"], RoomEventType::RoomMember => &["membership"],
EventType::RoomCreate => &["creator"], RoomEventType::RoomCreate => &["creator"],
EventType::RoomJoinRules => &["join_rule"], RoomEventType::RoomJoinRules => &["join_rule"],
EventType::RoomPowerLevels => &[ RoomEventType::RoomPowerLevels => &[
"ban", "ban",
"events", "events",
"events_default", "events_default",
@ -64,7 +64,7 @@ impl PduEvent {
"users", "users",
"users_default", "users_default",
], ],
EventType::RoomHistoryVisibility => &["history_visibility"], RoomEventType::RoomHistoryVisibility => &["history_visibility"],
_ => &[], _ => &[],
}; };
@ -279,7 +279,7 @@ impl state_res::Event for PduEvent {
&self.sender &self.sender
} }
fn event_type(&self) -> &EventType { fn event_type(&self) -> &RoomEventType {
&self.kind &self.kind
} }
@ -354,7 +354,7 @@ pub(crate) fn gen_event_id_canonical_json(
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
pub struct PduBuilder { pub struct PduBuilder {
#[serde(rename = "type")] #[serde(rename = "type")]
pub event_type: EventType, pub event_type: RoomEventType,
pub content: Box<RawJsonValue>, pub content: Box<RawJsonValue>,
pub unsigned: Option<BTreeMap<String, serde_json::Value>>, pub unsigned: Option<BTreeMap<String, serde_json::Value>>,
pub state_key: Option<String>, pub state_key: Option<String>,

@ -1,9 +1,6 @@
use crate::Error; use crate::Error;
use ruma::{ use ruma::{
api::client::uiaa::UiaaResponse, api::client::uiaa::UiaaResponse, signatures::CanonicalJsonValue, DeviceId, ServerName, UserId,
identifiers::{DeviceId, UserId},
signatures::CanonicalJsonValue,
Outgoing, ServerName,
}; };
use std::ops::Deref; use std::ops::Deref;
@ -11,8 +8,8 @@ use std::ops::Deref;
mod axum; mod axum;
/// Extractor for Ruma request structs /// Extractor for Ruma request structs
pub struct Ruma<T: Outgoing> { pub struct Ruma<T> {
pub body: T::Incoming, pub body: T,
pub sender_user: Option<Box<UserId>>, pub sender_user: Option<Box<UserId>>,
pub sender_device: Option<Box<DeviceId>>, pub sender_device: Option<Box<DeviceId>>,
pub sender_servername: Option<Box<ServerName>>, pub sender_servername: Option<Box<ServerName>>,
@ -21,8 +18,8 @@ pub struct Ruma<T: Outgoing> {
pub from_appservice: bool, pub from_appservice: bool,
} }
impl<T: Outgoing> Deref for Ruma<T> { impl<T> Deref for Ruma<T> {
type Target = T::Incoming; type Target = T;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
&self.body &self.body

@ -18,7 +18,7 @@ use http::StatusCode;
use ruma::{ use ruma::{
api::{client::error::ErrorKind, AuthScheme, IncomingRequest, OutgoingResponse}, api::{client::error::ErrorKind, AuthScheme, IncomingRequest, OutgoingResponse},
signatures::CanonicalJsonValue, signatures::CanonicalJsonValue,
DeviceId, Outgoing, ServerName, UserId, DeviceId, ServerName, UserId,
}; };
use serde::Deserialize; use serde::Deserialize;
use tracing::{debug, error, warn}; use tracing::{debug, error, warn};
@ -29,8 +29,7 @@ use crate::{database::DatabaseGuard, server_server, Error, Result};
#[async_trait] #[async_trait]
impl<T, B> FromRequest<B> for Ruma<T> impl<T, B> FromRequest<B> for Ruma<T>
where where
T: Outgoing, T: IncomingRequest,
T::Incoming: IncomingRequest,
B: HttpBody + Send, B: HttpBody + Send,
B::Data: Send, B::Data: Send,
B::Error: Into<BoxError>, B::Error: Into<BoxError>,
@ -44,7 +43,7 @@ where
user_id: Option<String>, user_id: Option<String>,
} }
let metadata = T::Incoming::METADATA; let metadata = T::METADATA;
let db = DatabaseGuard::from_request(req).await?; let db = DatabaseGuard::from_request(req).await?;
let auth_header = Option::<TypedHeader<Authorization<Bearer>>>::from_request(req).await?; let auth_header = Option::<TypedHeader<Authorization<Bearer>>>::from_request(req).await?;
let path_params = Path::<Vec<String>>::from_request(req).await?; let path_params = Path::<Vec<String>>::from_request(req).await?;
@ -284,7 +283,7 @@ where
debug!("{:?}", http_request); debug!("{:?}", http_request);
let body = T::Incoming::try_from_http_request(http_request, &path_params).map_err(|e| { let body = T::try_from_http_request(http_request, &path_params).map_err(|e| {
warn!("{:?}", e); warn!("{:?}", e);
Error::BadRequest(ErrorKind::BadJson, "Failed to deserialize request.") Error::BadRequest(ErrorKind::BadJson, "Failed to deserialize request.")
})?; })?;
@ -358,10 +357,7 @@ impl Credentials for XMatrix {
} }
} }
impl<T> IntoResponse for RumaResponse<T> impl<T: OutgoingResponse> IntoResponse for RumaResponse<T> {
where
T: OutgoingResponse,
{
fn into_response(self) -> Response { fn into_response(self) -> Response {
match self.0.try_into_http_response::<BytesMut>() { match self.0.try_into_http_response::<BytesMut>() {
Ok(res) => res.map(BytesMut::freeze).map(Full::new).into_response(), Ok(res) => res.map(BytesMut::freeze).map(Full::new).into_response(),

@ -45,7 +45,7 @@ use ruma::{
member::{MembershipState, RoomMemberEventContent}, member::{MembershipState, RoomMemberEventContent},
server_acl::RoomServerAclEventContent, server_acl::RoomServerAclEventContent,
}, },
EventType, RoomEventType, StateEventType,
}, },
int, int,
receipt::ReceiptType, receipt::ReceiptType,
@ -575,7 +575,7 @@ pub async fn get_server_keys_deprecated_route(db: DatabaseGuard) -> impl IntoRes
/// Lists the public rooms on this server. /// Lists the public rooms on this server.
pub async fn get_public_rooms_filtered_route( pub async fn get_public_rooms_filtered_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_public_rooms_filtered::v1::Request<'_>>, body: Ruma<get_public_rooms_filtered::v1::IncomingRequest>,
) -> Result<get_public_rooms_filtered::v1::Response> { ) -> Result<get_public_rooms_filtered::v1::Response> {
if !db.globals.allow_federation() { if !db.globals.allow_federation() {
return Err(Error::bad_config("Federation is disabled.")); return Err(Error::bad_config("Federation is disabled."));
@ -604,7 +604,7 @@ pub async fn get_public_rooms_filtered_route(
/// Lists the public rooms on this server. /// Lists the public rooms on this server.
pub async fn get_public_rooms_route( pub async fn get_public_rooms_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_public_rooms::v1::Request<'_>>, body: Ruma<get_public_rooms::v1::IncomingRequest>,
) -> Result<get_public_rooms::v1::Response> { ) -> Result<get_public_rooms::v1::Response> {
if !db.globals.allow_federation() { if !db.globals.allow_federation() {
return Err(Error::bad_config("Federation is disabled.")); return Err(Error::bad_config("Federation is disabled."));
@ -633,7 +633,7 @@ pub async fn get_public_rooms_route(
/// Push EDUs and PDUs to this server. /// Push EDUs and PDUs to this server.
pub async fn send_transaction_message_route( pub async fn send_transaction_message_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<send_transaction_message::v1::Request<'_>>, body: Ruma<send_transaction_message::v1::IncomingRequest>,
) -> Result<send_transaction_message::v1::Response> { ) -> Result<send_transaction_message::v1::Response> {
if !db.globals.allow_federation() { if !db.globals.allow_federation() {
return Err(Error::bad_config("Federation is disabled.")); return Err(Error::bad_config("Federation is disabled."));
@ -924,7 +924,7 @@ pub(crate) async fn handle_incoming_pdu<'a>(
let create_event = db let create_event = db
.rooms .rooms
.room_state_get(room_id, &EventType::RoomCreate, "") .room_state_get(room_id, &StateEventType::RoomCreate, "")
.map_err(|_| "Failed to ask database for event.".to_owned())? .map_err(|_| "Failed to ask database for event.".to_owned())?
.ok_or_else(|| "Failed to find create event in db.".to_owned())?; .ok_or_else(|| "Failed to find create event in db.".to_owned())?;
@ -1174,7 +1174,7 @@ fn handle_outlier_pdu<'a>(
}; };
match auth_events.entry(( match auth_events.entry((
auth_event.kind.clone(), auth_event.kind.to_string().into(),
auth_event auth_event
.state_key .state_key
.clone() .clone()
@ -1194,7 +1194,7 @@ fn handle_outlier_pdu<'a>(
// The original create event must be in the auth events // The original create event must be in the auth events
if auth_events if auth_events
.get(&(EventType::RoomCreate, "".to_owned())) .get(&(StateEventType::RoomCreate, "".to_owned()))
.map(|a| a.as_ref()) .map(|a| a.as_ref())
!= Some(create_event) != Some(create_event)
{ {
@ -1216,9 +1216,8 @@ fn handle_outlier_pdu<'a>(
if !state_res::event_auth::auth_check( if !state_res::event_auth::auth_check(
&room_version, &room_version,
&incoming_pdu, &incoming_pdu,
previous_create.as_ref(),
None::<PduEvent>, // TODO: third party invite None::<PduEvent>, // TODO: third party invite
|k, s| auth_events.get(&(k.clone(), s.to_owned())), |k, s| auth_events.get(&(k.to_string().into(), s.to_owned())),
) )
.map_err(|_e| "Auth check failed".to_owned())? .map_err(|_e| "Auth check failed".to_owned())?
{ {
@ -1297,7 +1296,11 @@ async fn upgrade_outlier_to_timeline_pdu(
if let Some(state_key) = &prev_pdu.state_key { if let Some(state_key) = &prev_pdu.state_key {
let shortstatekey = db let shortstatekey = db
.rooms .rooms
.get_or_create_shortstatekey(&prev_pdu.kind, state_key, &db.globals) .get_or_create_shortstatekey(
&prev_pdu.kind.to_string().into(),
state_key,
&db.globals,
)
.map_err(|_| "Failed to create shortstatekey.".to_owned())?; .map_err(|_| "Failed to create shortstatekey.".to_owned())?;
state.insert(shortstatekey, Arc::from(prev_event)); state.insert(shortstatekey, Arc::from(prev_event));
@ -1342,7 +1345,11 @@ async fn upgrade_outlier_to_timeline_pdu(
if let Some(state_key) = &prev_event.state_key { if let Some(state_key) = &prev_event.state_key {
let shortstatekey = db let shortstatekey = db
.rooms .rooms
.get_or_create_shortstatekey(&prev_event.kind, state_key, &db.globals) .get_or_create_shortstatekey(
&prev_event.kind.to_string().into(),
state_key,
&db.globals,
)
.map_err(|_| "Failed to create shortstatekey.".to_owned())?; .map_err(|_| "Failed to create shortstatekey.".to_owned())?;
leaf_state.insert(shortstatekey, Arc::from(&*prev_event.event_id)); leaf_state.insert(shortstatekey, Arc::from(&*prev_event.event_id));
// Now it's the state after the pdu // Now it's the state after the pdu
@ -1352,8 +1359,10 @@ async fn upgrade_outlier_to_timeline_pdu(
let mut starting_events = Vec::with_capacity(leaf_state.len()); let mut starting_events = Vec::with_capacity(leaf_state.len());
for (k, id) in leaf_state { for (k, id) in leaf_state {
if let Ok(k) = db.rooms.get_statekey_from_short(k) { if let Ok((ty, st_key)) = db.rooms.get_statekey_from_short(k) {
state.insert(k, id.clone()); // FIXME: Undo .to_string().into() when StateMap
// is updated to use StateEventType
state.insert((ty.to_string().into(), st_key), id.clone());
} else { } else {
warn!("Failed to get_statekey_from_short."); warn!("Failed to get_statekey_from_short.");
} }
@ -1387,7 +1396,11 @@ async fn upgrade_outlier_to_timeline_pdu(
.map(|((event_type, state_key), event_id)| { .map(|((event_type, state_key), event_id)| {
let shortstatekey = db let shortstatekey = db
.rooms .rooms
.get_or_create_shortstatekey(&event_type, &state_key, &db.globals) .get_or_create_shortstatekey(
&event_type.to_string().into(),
&state_key,
&db.globals,
)
.map_err(|_| "Failed to get_or_create_shortstatekey".to_owned())?; .map_err(|_| "Failed to get_or_create_shortstatekey".to_owned())?;
Ok((shortstatekey, event_id)) Ok((shortstatekey, event_id))
}) })
@ -1441,7 +1454,11 @@ async fn upgrade_outlier_to_timeline_pdu(
let shortstatekey = db let shortstatekey = db
.rooms .rooms
.get_or_create_shortstatekey(&pdu.kind, &state_key, &db.globals) .get_or_create_shortstatekey(
&pdu.kind.to_string().into(),
&state_key,
&db.globals,
)
.map_err(|_| "Failed to create shortstatekey.".to_owned())?; .map_err(|_| "Failed to create shortstatekey.".to_owned())?;
match state.entry(shortstatekey) { match state.entry(shortstatekey) {
@ -1458,7 +1475,7 @@ async fn upgrade_outlier_to_timeline_pdu(
// The original create event must still be in the state // The original create event must still be in the state
let create_shortstatekey = db let create_shortstatekey = db
.rooms .rooms
.get_shortstatekey(&EventType::RoomCreate, "") .get_shortstatekey(&StateEventType::RoomCreate, "")
.map_err(|_| "Failed to talk to db.")? .map_err(|_| "Failed to talk to db.")?
.expect("Room exists"); .expect("Room exists");
@ -1496,11 +1513,10 @@ async fn upgrade_outlier_to_timeline_pdu(
let check_result = state_res::event_auth::auth_check( let check_result = state_res::event_auth::auth_check(
&room_version, &room_version,
&incoming_pdu, &incoming_pdu,
previous_create.as_ref(),
None::<PduEvent>, // TODO: third party invite None::<PduEvent>, // TODO: third party invite
|k, s| { |k, s| {
db.rooms db.rooms
.get_shortstatekey(k, s) .get_shortstatekey(&k.to_string().into(), s)
.ok() .ok()
.flatten() .flatten()
.and_then(|shortstatekey| state_at_incoming_event.get(&shortstatekey)) .and_then(|shortstatekey| state_at_incoming_event.get(&shortstatekey))
@ -1580,7 +1596,6 @@ async fn upgrade_outlier_to_timeline_pdu(
let soft_fail = !state_res::event_auth::auth_check( let soft_fail = !state_res::event_auth::auth_check(
&room_version, &room_version,
&incoming_pdu, &incoming_pdu,
previous_create.as_ref(),
None::<PduEvent>, None::<PduEvent>,
|k, s| auth_events.get(&(k.clone(), s.to_owned())), |k, s| auth_events.get(&(k.clone(), s.to_owned())),
) )
@ -1655,7 +1670,11 @@ async fn upgrade_outlier_to_timeline_pdu(
if let Some(state_key) = &incoming_pdu.state_key { if let Some(state_key) = &incoming_pdu.state_key {
let shortstatekey = db let shortstatekey = db
.rooms .rooms
.get_or_create_shortstatekey(&incoming_pdu.kind, state_key, &db.globals) .get_or_create_shortstatekey(
&incoming_pdu.kind.to_string().into(),
state_key,
&db.globals,
)
.map_err(|_| "Failed to create shortstatekey.".to_owned())?; .map_err(|_| "Failed to create shortstatekey.".to_owned())?;
state_after.insert(shortstatekey, Arc::from(&*incoming_pdu.event_id)); state_after.insert(shortstatekey, Arc::from(&*incoming_pdu.event_id));
@ -1701,7 +1720,9 @@ async fn upgrade_outlier_to_timeline_pdu(
.filter_map(|(k, id)| { .filter_map(|(k, id)| {
db.rooms db.rooms
.get_statekey_from_short(k) .get_statekey_from_short(k)
.map(|k| (k, id)) // FIXME: Undo .to_string().into() when StateMap
// is updated to use StateEventType
.map(|(ty, st_key)| ((ty.to_string().into(), st_key), id))
.map_err(|e| warn!("Failed to get_statekey_from_short: {}", e)) .map_err(|e| warn!("Failed to get_statekey_from_short: {}", e))
.ok() .ok()
}) })
@ -1732,7 +1753,11 @@ async fn upgrade_outlier_to_timeline_pdu(
.map(|((event_type, state_key), event_id)| { .map(|((event_type, state_key), event_id)| {
let shortstatekey = db let shortstatekey = db
.rooms .rooms
.get_or_create_shortstatekey(&event_type, &state_key, &db.globals) .get_or_create_shortstatekey(
&event_type.to_string().into(),
&state_key,
&db.globals,
)
.map_err(|_| "Failed to get_or_create_shortstatekey".to_owned())?; .map_err(|_| "Failed to get_or_create_shortstatekey".to_owned())?;
db.rooms db.rooms
.compress_state_event(shortstatekey, &event_id, &db.globals) .compress_state_event(shortstatekey, &event_id, &db.globals)
@ -2151,7 +2176,7 @@ fn append_incoming_pdu<'a>(
let matching_users = |users: &Regex| { let matching_users = |users: &Regex| {
users.is_match(pdu.sender.as_str()) users.is_match(pdu.sender.as_str())
|| pdu.kind == EventType::RoomMember || pdu.kind == RoomEventType::RoomMember
&& pdu && pdu
.state_key .state_key
.as_ref() .as_ref()
@ -2298,7 +2323,7 @@ fn get_auth_chain_inner(
/// - Only works if a user of this server is currently invited or joined the room /// - Only works if a user of this server is currently invited or joined the room
pub async fn get_event_route( pub async fn get_event_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_event::v1::Request<'_>>, body: Ruma<get_event::v1::IncomingRequest>,
) -> Result<get_event::v1::Response> { ) -> Result<get_event::v1::Response> {
if !db.globals.allow_federation() { if !db.globals.allow_federation() {
return Err(Error::bad_config("Federation is disabled.")); return Err(Error::bad_config("Federation is disabled."));
@ -2341,7 +2366,7 @@ pub async fn get_event_route(
/// Retrieves events that the sender is missing. /// Retrieves events that the sender is missing.
pub async fn get_missing_events_route( pub async fn get_missing_events_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_missing_events::v1::Request<'_>>, body: Ruma<get_missing_events::v1::IncomingRequest>,
) -> Result<get_missing_events::v1::Response> { ) -> Result<get_missing_events::v1::Response> {
if !db.globals.allow_federation() { if !db.globals.allow_federation() {
return Err(Error::bad_config("Federation is disabled.")); return Err(Error::bad_config("Federation is disabled."));
@ -2414,7 +2439,7 @@ pub async fn get_missing_events_route(
/// - This does not include the event itself /// - This does not include the event itself
pub async fn get_event_authorization_route( pub async fn get_event_authorization_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_event_authorization::v1::Request<'_>>, body: Ruma<get_event_authorization::v1::IncomingRequest>,
) -> Result<get_event_authorization::v1::Response> { ) -> Result<get_event_authorization::v1::Response> {
if !db.globals.allow_federation() { if !db.globals.allow_federation() {
return Err(Error::bad_config("Federation is disabled.")); return Err(Error::bad_config("Federation is disabled."));
@ -2462,7 +2487,7 @@ pub async fn get_event_authorization_route(
/// Retrieves the current state of the room. /// Retrieves the current state of the room.
pub async fn get_room_state_route( pub async fn get_room_state_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_room_state::v1::Request<'_>>, body: Ruma<get_room_state::v1::IncomingRequest>,
) -> Result<get_room_state::v1::Response> { ) -> Result<get_room_state::v1::Response> {
if !db.globals.allow_federation() { if !db.globals.allow_federation() {
return Err(Error::bad_config("Federation is disabled.")); return Err(Error::bad_config("Federation is disabled."));
@ -2521,7 +2546,7 @@ pub async fn get_room_state_route(
/// Retrieves the current state of the room. /// Retrieves the current state of the room.
pub async fn get_room_state_ids_route( pub async fn get_room_state_ids_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_room_state_ids::v1::Request<'_>>, body: Ruma<get_room_state_ids::v1::IncomingRequest>,
) -> Result<get_room_state_ids::v1::Response> { ) -> Result<get_room_state_ids::v1::Response> {
if !db.globals.allow_federation() { if !db.globals.allow_federation() {
return Err(Error::bad_config("Federation is disabled.")); return Err(Error::bad_config("Federation is disabled."));
@ -2569,7 +2594,7 @@ pub async fn get_room_state_ids_route(
/// Creates a join template. /// Creates a join template.
pub async fn create_join_event_template_route( pub async fn create_join_event_template_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<prepare_join_event::v1::Request<'_>>, body: Ruma<prepare_join_event::v1::IncomingRequest>,
) -> Result<prepare_join_event::v1::Response> { ) -> Result<prepare_join_event::v1::Response> {
if !db.globals.allow_federation() { if !db.globals.allow_federation() {
return Err(Error::bad_config("Federation is disabled.")); return Err(Error::bad_config("Federation is disabled."));
@ -2598,7 +2623,7 @@ pub async fn create_join_event_template_route(
let create_event = db let create_event = db
.rooms .rooms
.room_state_get(&body.room_id, &EventType::RoomCreate, "")?; .room_state_get(&body.room_id, &StateEventType::RoomCreate, "")?;
let create_event_content: Option<RoomCreateEventContent> = create_event let create_event_content: Option<RoomCreateEventContent> = create_event
.as_ref() .as_ref()
@ -2645,11 +2670,11 @@ pub async fn create_join_event_template_route(
.expect("member event is valid value"); .expect("member event is valid value");
let state_key = body.user_id.to_string(); let state_key = body.user_id.to_string();
let kind = EventType::RoomMember; let kind = StateEventType::RoomMember;
let auth_events = db.rooms.get_auth_events( let auth_events = db.rooms.get_auth_events(
&body.room_id, &body.room_id,
&kind, &kind.to_string().into(),
&body.user_id, &body.user_id,
Some(&state_key), Some(&state_key),
&content, &content,
@ -2680,7 +2705,7 @@ pub async fn create_join_event_template_route(
origin_server_ts: utils::millis_since_unix_epoch() origin_server_ts: utils::millis_since_unix_epoch()
.try_into() .try_into()
.expect("time is valid"), .expect("time is valid"),
kind, kind: kind.to_string().into(),
content, content,
state_key: Some(state_key), state_key: Some(state_key),
prev_events, prev_events,
@ -2704,7 +2729,6 @@ pub async fn create_join_event_template_route(
let auth_check = state_res::auth_check( let auth_check = state_res::auth_check(
&room_version, &room_version,
&pdu, &pdu,
create_prev_event,
None::<PduEvent>, // TODO: third_party_invite None::<PduEvent>, // TODO: third_party_invite
|k, s| auth_events.get(&(k.clone(), s.to_owned())), |k, s| auth_events.get(&(k.clone(), s.to_owned())),
) )
@ -2849,7 +2873,7 @@ async fn create_join_event(
/// Submits a signed join event. /// Submits a signed join event.
pub async fn create_join_event_v1_route( pub async fn create_join_event_v1_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<create_join_event::v1::Request<'_>>, body: Ruma<create_join_event::v1::IncomingRequest>,
) -> Result<create_join_event::v1::Response> { ) -> Result<create_join_event::v1::Response> {
let sender_servername = body let sender_servername = body
.sender_servername .sender_servername
@ -2866,7 +2890,7 @@ pub async fn create_join_event_v1_route(
/// Submits a signed join event. /// Submits a signed join event.
pub async fn create_join_event_v2_route( pub async fn create_join_event_v2_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<create_join_event::v2::Request<'_>>, body: Ruma<create_join_event::v2::IncomingRequest>,
) -> Result<create_join_event::v2::Response> { ) -> Result<create_join_event::v2::Response> {
let sender_servername = body let sender_servername = body
.sender_servername .sender_servername
@ -2883,7 +2907,7 @@ pub async fn create_join_event_v2_route(
/// Invites a remote user to a room. /// Invites a remote user to a room.
pub async fn create_invite_route( pub async fn create_invite_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<create_invite::v2::Request<'_>>, body: Ruma<create_invite::v2::IncomingRequest>,
) -> Result<create_invite::v2::Response> { ) -> Result<create_invite::v2::Response> {
if !db.globals.allow_federation() { if !db.globals.allow_federation() {
return Err(Error::bad_config("Federation is disabled.")); return Err(Error::bad_config("Federation is disabled."));
@ -2993,7 +3017,7 @@ pub async fn create_invite_route(
/// Gets information on all devices of the user. /// Gets information on all devices of the user.
pub async fn get_devices_route( pub async fn get_devices_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_devices::v1::Request<'_>>, body: Ruma<get_devices::v1::IncomingRequest>,
) -> Result<get_devices::v1::Response> { ) -> Result<get_devices::v1::Response> {
if !db.globals.allow_federation() { if !db.globals.allow_federation() {
return Err(Error::bad_config("Federation is disabled.")); return Err(Error::bad_config("Federation is disabled."));
@ -3041,7 +3065,7 @@ pub async fn get_devices_route(
/// Resolve a room alias to a room id. /// Resolve a room alias to a room id.
pub async fn get_room_information_route( pub async fn get_room_information_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_room_information::v1::Request<'_>>, body: Ruma<get_room_information::v1::IncomingRequest>,
) -> Result<get_room_information::v1::Response> { ) -> Result<get_room_information::v1::Response> {
if !db.globals.allow_federation() { if !db.globals.allow_federation() {
return Err(Error::bad_config("Federation is disabled.")); return Err(Error::bad_config("Federation is disabled."));
@ -3066,7 +3090,7 @@ pub async fn get_room_information_route(
/// Gets information on a profile. /// Gets information on a profile.
pub async fn get_profile_information_route( pub async fn get_profile_information_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<get_profile_information::v1::Request<'_>>, body: Ruma<get_profile_information::v1::IncomingRequest>,
) -> Result<get_profile_information::v1::Response> { ) -> Result<get_profile_information::v1::Response> {
if !db.globals.allow_federation() { if !db.globals.allow_federation() {
return Err(Error::bad_config("Federation is disabled.")); return Err(Error::bad_config("Federation is disabled."));
@ -3395,7 +3419,7 @@ pub(crate) async fn fetch_join_signing_keys(
fn acl_check(server_name: &ServerName, room_id: &RoomId, db: &Database) -> Result<()> { fn acl_check(server_name: &ServerName, room_id: &RoomId, db: &Database) -> Result<()> {
let acl_event = match db let acl_event = match db
.rooms .rooms
.room_state_get(room_id, &EventType::RoomServerAcl, "")? .room_state_get(room_id, &StateEventType::RoomServerAcl, "")?
{ {
Some(acl) => acl, Some(acl) => acl,
None => return Ok(()), None => return Ok(()),

Loading…
Cancel
Save