1
0
Fork 0
mirror of https://gitlab.com/famedly/conduit.git synced 2024-11-17 16:20:50 +01:00

Merge branch 'pushrules' into 'next'

Improvements to pushrules endpoints

Closes #316

See merge request famedly/conduit!461
This commit is contained in:
Timo Kösters 2023-05-21 10:41:31 +00:00
commit 1f1444da8c
19 changed files with 363 additions and 386 deletions

143
Cargo.lock generated
View file

@ -183,9 +183,9 @@ checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"
[[package]] [[package]]
name = "base64" name = "base64"
version = "0.20.0" version = "0.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ea22880d78093b0cbe17c89f64a7d457941e65759157ec6cb31a31d652b05e5" checksum = "a4a4ddaa51a5bc52a6948f74c06d20aaaddb71924eab79b8c97a8c556e942d6a"
[[package]] [[package]]
name = "base64ct" name = "base64ct"
@ -412,6 +412,7 @@ dependencies = [
"rust-argon2", "rust-argon2",
"sd-notify", "sd-notify",
"serde", "serde",
"serde_html_form",
"serde_json", "serde_json",
"serde_yaml", "serde_yaml",
"sha-1", "sha-1",
@ -669,7 +670,7 @@ dependencies = [
"ed25519", "ed25519",
"rand 0.7.3", "rand 0.7.3",
"serde", "serde",
"sha2", "sha2 0.9.9",
"zeroize", "zeroize",
] ]
@ -721,7 +722,7 @@ dependencies = [
"atomic", "atomic",
"pear", "pear",
"serde", "serde",
"toml", "toml 0.5.9",
"uncased", "uncased",
"version_check", "version_check",
] ]
@ -1819,7 +1820,7 @@ checksum = "eda0fc3b0fb7c975631757e14d9049da17374063edb6ebbcbc54d880d4fe94e9"
dependencies = [ dependencies = [
"once_cell", "once_cell",
"thiserror", "thiserror",
"toml", "toml 0.5.9",
] ]
[[package]] [[package]]
@ -2075,8 +2076,8 @@ dependencies = [
[[package]] [[package]]
name = "ruma" name = "ruma"
version = "0.7.4" version = "0.8.2"
source = "git+https://github.com/ruma/ruma?rev=67d0f3cc04a8d1dc4a8a1ec947519967ce11ce26#67d0f3cc04a8d1dc4a8a1ec947519967ce11ce26" source = "git+https://github.com/ruma/ruma?rev=8eea3e05490fa9a318f9ed66c3a75272e6ef0ee5#8eea3e05490fa9a318f9ed66c3a75272e6ef0ee5"
dependencies = [ dependencies = [
"assign", "assign",
"js_int", "js_int",
@ -2093,8 +2094,8 @@ dependencies = [
[[package]] [[package]]
name = "ruma-appservice-api" name = "ruma-appservice-api"
version = "0.7.0" version = "0.8.1"
source = "git+https://github.com/ruma/ruma?rev=67d0f3cc04a8d1dc4a8a1ec947519967ce11ce26#67d0f3cc04a8d1dc4a8a1ec947519967ce11ce26" source = "git+https://github.com/ruma/ruma?rev=8eea3e05490fa9a318f9ed66c3a75272e6ef0ee5#8eea3e05490fa9a318f9ed66c3a75272e6ef0ee5"
dependencies = [ dependencies = [
"js_int", "js_int",
"ruma-common", "ruma-common",
@ -2104,8 +2105,8 @@ dependencies = [
[[package]] [[package]]
name = "ruma-client-api" name = "ruma-client-api"
version = "0.15.3" version = "0.16.2"
source = "git+https://github.com/ruma/ruma?rev=67d0f3cc04a8d1dc4a8a1ec947519967ce11ce26#67d0f3cc04a8d1dc4a8a1ec947519967ce11ce26" source = "git+https://github.com/ruma/ruma?rev=8eea3e05490fa9a318f9ed66c3a75272e6ef0ee5#8eea3e05490fa9a318f9ed66c3a75272e6ef0ee5"
dependencies = [ dependencies = [
"assign", "assign",
"bytes", "bytes",
@ -2113,23 +2114,22 @@ dependencies = [
"js_int", "js_int",
"js_option", "js_option",
"maplit", "maplit",
"percent-encoding",
"ruma-common", "ruma-common",
"serde", "serde",
"serde_html_form",
"serde_json", "serde_json",
] ]
[[package]] [[package]]
name = "ruma-common" name = "ruma-common"
version = "0.10.5" version = "0.11.3"
source = "git+https://github.com/ruma/ruma?rev=67d0f3cc04a8d1dc4a8a1ec947519967ce11ce26#67d0f3cc04a8d1dc4a8a1ec947519967ce11ce26" source = "git+https://github.com/ruma/ruma?rev=8eea3e05490fa9a318f9ed66c3a75272e6ef0ee5#8eea3e05490fa9a318f9ed66c3a75272e6ef0ee5"
dependencies = [ dependencies = [
"base64 0.20.0", "base64 0.21.0",
"bytes", "bytes",
"form_urlencoded", "form_urlencoded",
"http", "http",
"indexmap", "indexmap",
"itoa",
"js_int", "js_int",
"js_option", "js_option",
"konst", "konst",
@ -2139,6 +2139,7 @@ dependencies = [
"ruma-identifiers-validation", "ruma-identifiers-validation",
"ruma-macros", "ruma-macros",
"serde", "serde",
"serde_html_form",
"serde_json", "serde_json",
"thiserror", "thiserror",
"tracing", "tracing",
@ -2149,8 +2150,8 @@ dependencies = [
[[package]] [[package]]
name = "ruma-federation-api" name = "ruma-federation-api"
version = "0.6.0" version = "0.7.1"
source = "git+https://github.com/ruma/ruma?rev=67d0f3cc04a8d1dc4a8a1ec947519967ce11ce26#67d0f3cc04a8d1dc4a8a1ec947519967ce11ce26" source = "git+https://github.com/ruma/ruma?rev=8eea3e05490fa9a318f9ed66c3a75272e6ef0ee5#8eea3e05490fa9a318f9ed66c3a75272e6ef0ee5"
dependencies = [ dependencies = [
"js_int", "js_int",
"ruma-common", "ruma-common",
@ -2160,8 +2161,8 @@ dependencies = [
[[package]] [[package]]
name = "ruma-identifiers-validation" name = "ruma-identifiers-validation"
version = "0.9.0" version = "0.9.1"
source = "git+https://github.com/ruma/ruma?rev=67d0f3cc04a8d1dc4a8a1ec947519967ce11ce26#67d0f3cc04a8d1dc4a8a1ec947519967ce11ce26" source = "git+https://github.com/ruma/ruma?rev=8eea3e05490fa9a318f9ed66c3a75272e6ef0ee5#8eea3e05490fa9a318f9ed66c3a75272e6ef0ee5"
dependencies = [ dependencies = [
"js_int", "js_int",
"thiserror", "thiserror",
@ -2169,8 +2170,8 @@ dependencies = [
[[package]] [[package]]
name = "ruma-identity-service-api" name = "ruma-identity-service-api"
version = "0.6.0" version = "0.7.1"
source = "git+https://github.com/ruma/ruma?rev=67d0f3cc04a8d1dc4a8a1ec947519967ce11ce26#67d0f3cc04a8d1dc4a8a1ec947519967ce11ce26" source = "git+https://github.com/ruma/ruma?rev=8eea3e05490fa9a318f9ed66c3a75272e6ef0ee5#8eea3e05490fa9a318f9ed66c3a75272e6ef0ee5"
dependencies = [ dependencies = [
"js_int", "js_int",
"ruma-common", "ruma-common",
@ -2179,8 +2180,8 @@ dependencies = [
[[package]] [[package]]
name = "ruma-macros" name = "ruma-macros"
version = "0.10.5" version = "0.11.3"
source = "git+https://github.com/ruma/ruma?rev=67d0f3cc04a8d1dc4a8a1ec947519967ce11ce26#67d0f3cc04a8d1dc4a8a1ec947519967ce11ce26" source = "git+https://github.com/ruma/ruma?rev=8eea3e05490fa9a318f9ed66c3a75272e6ef0ee5#8eea3e05490fa9a318f9ed66c3a75272e6ef0ee5"
dependencies = [ dependencies = [
"once_cell", "once_cell",
"proc-macro-crate", "proc-macro-crate",
@ -2189,13 +2190,13 @@ dependencies = [
"ruma-identifiers-validation", "ruma-identifiers-validation",
"serde", "serde",
"syn", "syn",
"toml", "toml 0.7.2",
] ]
[[package]] [[package]]
name = "ruma-push-gateway-api" name = "ruma-push-gateway-api"
version = "0.6.0" version = "0.7.1"
source = "git+https://github.com/ruma/ruma?rev=67d0f3cc04a8d1dc4a8a1ec947519967ce11ce26#67d0f3cc04a8d1dc4a8a1ec947519967ce11ce26" source = "git+https://github.com/ruma/ruma?rev=8eea3e05490fa9a318f9ed66c3a75272e6ef0ee5#8eea3e05490fa9a318f9ed66c3a75272e6ef0ee5"
dependencies = [ dependencies = [
"js_int", "js_int",
"ruma-common", "ruma-common",
@ -2205,24 +2206,24 @@ dependencies = [
[[package]] [[package]]
name = "ruma-signatures" name = "ruma-signatures"
version = "0.12.0" version = "0.13.1"
source = "git+https://github.com/ruma/ruma?rev=67d0f3cc04a8d1dc4a8a1ec947519967ce11ce26#67d0f3cc04a8d1dc4a8a1ec947519967ce11ce26" source = "git+https://github.com/ruma/ruma?rev=8eea3e05490fa9a318f9ed66c3a75272e6ef0ee5#8eea3e05490fa9a318f9ed66c3a75272e6ef0ee5"
dependencies = [ dependencies = [
"base64 0.20.0", "base64 0.21.0",
"ed25519-dalek", "ed25519-dalek",
"pkcs8", "pkcs8",
"rand 0.7.3", "rand 0.7.3",
"ruma-common", "ruma-common",
"serde_json", "serde_json",
"sha2", "sha2 0.10.6",
"subslice", "subslice",
"thiserror", "thiserror",
] ]
[[package]] [[package]]
name = "ruma-state-res" name = "ruma-state-res"
version = "0.8.0" version = "0.9.1"
source = "git+https://github.com/ruma/ruma?rev=67d0f3cc04a8d1dc4a8a1ec947519967ce11ce26#67d0f3cc04a8d1dc4a8a1ec947519967ce11ce26" source = "git+https://github.com/ruma/ruma?rev=8eea3e05490fa9a318f9ed66c3a75272e6ef0ee5#8eea3e05490fa9a318f9ed66c3a75272e6ef0ee5"
dependencies = [ dependencies = [
"itertools", "itertools",
"js_int", "js_int",
@ -2388,6 +2389,19 @@ dependencies = [
"syn", "syn",
] ]
[[package]]
name = "serde_html_form"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53192e38d5c88564b924dbe9b60865ecbb71b81d38c4e61c817cffd3e36ef696"
dependencies = [
"form_urlencoded",
"indexmap",
"itoa",
"ryu",
"serde",
]
[[package]] [[package]]
name = "serde_json" name = "serde_json"
version = "1.0.89" version = "1.0.89"
@ -2399,6 +2413,15 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "serde_spanned"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0efd8caf556a6cebd3b285caf480045fcc1ac04f6bd786b09a6f11af30c4fcf4"
dependencies = [
"serde",
]
[[package]] [[package]]
name = "serde_urlencoded" name = "serde_urlencoded"
version = "0.7.1" version = "0.7.1"
@ -2459,6 +2482,17 @@ dependencies = [
"opaque-debug", "opaque-debug",
] ]
[[package]]
name = "sha2"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82e6b795fe2e3b1e845bafcb27aa35405c4d47cdfc92af5fc8d3002f76cebdc0"
dependencies = [
"cfg-if",
"cpufeatures",
"digest 0.10.6",
]
[[package]] [[package]]
name = "sharded-slab" name = "sharded-slab"
version = "0.1.4" version = "0.1.4"
@ -2807,6 +2841,40 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "toml"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7afcae9e3f0fe2c370fd4657108972cbb2fa9db1b9f84849cefd80741b01cb6"
dependencies = [
"serde",
"serde_spanned",
"toml_datetime",
"toml_edit",
]
[[package]]
name = "toml_datetime"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ab8ed2edee10b50132aed5f331333428b011c99402b5a534154ed15746f9622"
dependencies = [
"serde",
]
[[package]]
name = "toml_edit"
version = "0.19.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a1eb0622d28f4b9c90adc4ea4b2b46b47663fde9ac5fafcb14a1369d5508825"
dependencies = [
"indexmap",
"serde",
"serde_spanned",
"toml_datetime",
"winnow",
]
[[package]] [[package]]
name = "tower" name = "tower"
version = "0.4.13" version = "0.4.13"
@ -3343,6 +3411,15 @@ version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f40009d85759725a34da6d89a94e63d7bdc50a862acf0dbc7c8e488f1edcb6f5" checksum = "f40009d85759725a34da6d89a94e63d7bdc50a862acf0dbc7c8e488f1edcb6f5"
[[package]]
name = "winnow"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "faf09497b8f8b5ac5d3bb4d05c0a99be20f26fd3d5f2db7b0716e946d5103658"
dependencies = [
"memchr",
]
[[package]] [[package]]
name = "winreg" name = "winreg"
version = "0.7.0" version = "0.7.0"

View file

@ -26,7 +26,7 @@ tower-http = { version = "0.3.4", 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 = "67d0f3cc04a8d1dc4a8a1ec947519967ce11ce26", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-msc2448", "unstable-exhaustive-types", "ring-compat", "unstable-unspecified" ] } ruma = { git = "https://github.com/ruma/ruma", rev = "8eea3e05490fa9a318f9ed66c3a75272e6ef0ee5", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-msc2448", "unstable-exhaustive-types", "ring-compat", "unstable-unspecified" ] }
#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"] }
@ -83,6 +83,8 @@ num_cpus = "1.13.0"
threadpool = "1.8.1" threadpool = "1.8.1"
heed = { git = "https://github.com/timokoesters/heed.git", rev = "f6f825da7fb2c758867e05ad973ef800a6fe1d5d", optional = true } heed = { git = "https://github.com/timokoesters/heed.git", rev = "f6f825da7fb2c758867e05ad973ef800a6fe1d5d", optional = true }
rocksdb = { version = "0.17.0", default-features = true, features = ["multi-threaded-cf", "zstd"], optional = true } rocksdb = { version = "0.17.0", default-features = true, features = ["multi-threaded-cf", "zstd"], optional = true }
# Used for ruma wrapper
serde_html_form = "0.2.0"
thread_local = "1.1.3" thread_local = "1.1.3"
# used for TURN server authentication # used for TURN server authentication

View file

@ -75,7 +75,7 @@ pub async fn get_global_account_data_route(
let event: Box<RawJsonValue> = services() let event: Box<RawJsonValue> = services()
.account_data .account_data
.get(None, sender_user, body.event_type.clone().into())? .get(None, sender_user, body.event_type.to_string().into())?
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Data not found."))?; .ok_or(Error::BadRequest(ErrorKind::NotFound, "Data not found."))?;
let account_data = serde_json::from_str::<ExtractGlobalEventContent>(event.get()) let account_data = serde_json::from_str::<ExtractGlobalEventContent>(event.get())
@ -95,11 +95,7 @@ pub async fn get_room_account_data_route(
let event: Box<RawJsonValue> = services() let event: Box<RawJsonValue> = services()
.account_data .account_data
.get( .get(Some(&body.room_id), sender_user, body.event_type.clone())?
Some(&body.room_id),
sender_user,
body.event_type.clone().into(),
)?
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Data not found."))?; .ok_or(Error::BadRequest(ErrorKind::NotFound, "Data not found."))?;
let account_data = serde_json::from_str::<ExtractRoomEventContent>(event.get()) let account_data = serde_json::from_str::<ExtractRoomEventContent>(event.get())

View file

@ -17,7 +17,7 @@ use ruma::{
member::{MembershipState, RoomMemberEventContent}, member::{MembershipState, RoomMemberEventContent},
power_levels::RoomPowerLevelsEventContent, power_levels::RoomPowerLevelsEventContent,
}, },
RoomEventType, StateEventType, StateEventType, TimelineEventType,
}, },
serde::Base64, serde::Base64,
state_res, CanonicalJsonObject, CanonicalJsonValue, EventId, OwnedEventId, OwnedRoomId, state_res, CanonicalJsonObject, CanonicalJsonValue, EventId, OwnedEventId, OwnedRoomId,
@ -209,7 +209,7 @@ pub async fn kick_user_route(
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomMember, event_type: TimelineEventType::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()),
@ -273,7 +273,7 @@ pub async fn ban_user_route(body: Ruma<ban_user::v3::Request>) -> Result<ban_use
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomMember, event_type: TimelineEventType::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()),
@ -331,7 +331,7 @@ pub async fn unban_user_route(
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomMember, event_type: TimelineEventType::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()),
@ -590,6 +590,7 @@ async fn join_room_by_id_helper(
room_id: room_id.to_owned(), room_id: room_id.to_owned(),
event_id: event_id.to_owned(), event_id: event_id.to_owned(),
pdu: PduEvent::convert_to_outgoing_federation_event(join_event.clone()), pdu: PduEvent::convert_to_outgoing_federation_event(join_event.clone()),
omit_members: false,
}, },
) )
.await?; .await?;
@ -886,7 +887,7 @@ async fn join_room_by_id_helper(
// Try normal join first // Try normal join first
let error = match services().rooms.timeline.build_and_append_pdu( let error = match services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomMember, event_type: TimelineEventType::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()),
@ -996,6 +997,7 @@ async fn join_room_by_id_helper(
room_id: room_id.to_owned(), room_id: room_id.to_owned(),
event_id: event_id.to_owned(), event_id: event_id.to_owned(),
pdu: PduEvent::convert_to_outgoing_federation_event(join_event.clone()), pdu: PduEvent::convert_to_outgoing_federation_event(join_event.clone()),
omit_members: false,
}, },
) )
.await?; .await?;
@ -1186,7 +1188,7 @@ pub(crate) async fn invite_helper<'a>(
let (pdu, pdu_json) = services().rooms.timeline.create_hash_and_sign_event( let (pdu, pdu_json) = services().rooms.timeline.create_hash_and_sign_event(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomMember, event_type: TimelineEventType::RoomMember,
content, content,
unsigned: None, unsigned: None,
state_key: Some(user_id.to_string()), state_key: Some(user_id.to_string()),
@ -1295,7 +1297,7 @@ pub(crate) async fn invite_helper<'a>(
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomMember, event_type: TimelineEventType::RoomMember,
content: to_raw_value(&RoomMemberEventContent { content: to_raw_value(&RoomMemberEventContent {
membership: MembershipState::Invite, membership: MembershipState::Invite,
displayname: services().users.displayname(user_id)?, displayname: services().users.displayname(user_id)?,
@ -1420,7 +1422,7 @@ pub async fn leave_room(user_id: &UserId, room_id: &RoomId, reason: Option<Strin
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomMember, event_type: TimelineEventType::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()),

View file

@ -7,7 +7,7 @@ use ruma::{
error::ErrorKind, error::ErrorKind,
message::{get_message_events, send_message_event}, message::{get_message_events, send_message_event},
}, },
events::{RoomEventType, StateEventType}, events::{StateEventType, TimelineEventType},
}; };
use std::{ use std::{
collections::{BTreeMap, HashSet}, collections::{BTreeMap, HashSet},
@ -39,7 +39,7 @@ 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 RoomEventType::RoomEncrypted == body.event_type.to_string().into() if TimelineEventType::RoomEncrypted == body.event_type.to_string().into()
&& !services().globals.allow_encryption() && !services().globals.allow_encryption()
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
@ -116,8 +116,8 @@ pub async fn get_message_events_route(
let from = match body.from.clone() { let from = match body.from.clone() {
Some(from) => PduCount::try_from_string(&from)?, Some(from) => PduCount::try_from_string(&from)?,
None => match body.dir { None => match body.dir {
ruma::api::client::Direction::Forward => PduCount::min(), ruma::api::Direction::Forward => PduCount::min(),
ruma::api::client::Direction::Backward => PduCount::max(), ruma::api::Direction::Backward => PduCount::max(),
}, },
}; };
@ -143,7 +143,7 @@ pub async fn get_message_events_route(
let mut lazy_loaded = HashSet::new(); let mut lazy_loaded = HashSet::new();
match body.dir { match body.dir {
ruma::api::client::Direction::Forward => { ruma::api::Direction::Forward => {
let events_after: Vec<_> = services() let events_after: Vec<_> = services()
.rooms .rooms
.timeline .timeline
@ -187,7 +187,7 @@ pub async fn get_message_events_route(
resp.end = next_token.map(|count| count.stringify()); resp.end = next_token.map(|count| count.stringify());
resp.chunk = events_after; resp.chunk = events_after;
} }
ruma::api::client::Direction::Backward => { ruma::api::Direction::Backward => {
services() services()
.rooms .rooms
.timeline .timeline

View file

@ -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, RoomEventType, StateEventType}, events::{room::member::RoomMemberEventContent, StateEventType, TimelineEventType},
}; };
use serde_json::value::to_raw_value; use serde_json::value::to_raw_value;
use std::sync::Arc; use std::sync::Arc;
@ -37,7 +37,7 @@ pub async fn set_displayname_route(
.map(|room_id| { .map(|room_id| {
Ok::<_, Error>(( Ok::<_, Error>((
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomMember, event_type: TimelineEventType::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(
@ -172,7 +172,7 @@ pub async fn set_avatar_url_route(
.map(|room_id| { .map(|room_id| {
Ok::<_, Error>(( Ok::<_, Error>((
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomMember, event_type: TimelineEventType::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(

View file

@ -5,11 +5,11 @@ use ruma::{
push::{ push::{
delete_pushrule, get_pushers, get_pushrule, get_pushrule_actions, get_pushrule_enabled, delete_pushrule, get_pushers, get_pushrule, get_pushrule_actions, get_pushrule_enabled,
get_pushrules_all, set_pusher, set_pushrule, set_pushrule_actions, get_pushrules_all, set_pusher, set_pushrule, set_pushrule_actions,
set_pushrule_enabled, RuleKind, RuleScope, set_pushrule_enabled, RuleScope,
}, },
}, },
events::{push_rules::PushRulesEvent, GlobalAccountDataEventType}, events::{push_rules::PushRulesEvent, GlobalAccountDataEventType},
push::{ConditionalPushRuleInit, NewPushRule, PatternedPushRuleInit, SimplePushRuleInit}, push::{InsertPushRuleError, RemovePushRuleError},
}; };
/// # `GET /_matrix/client/r0/pushrules` /// # `GET /_matrix/client/r0/pushrules`
@ -65,30 +65,10 @@ pub async fn get_pushrule_route(
.map_err(|_| Error::bad_database("Invalid account data event in db."))? .map_err(|_| Error::bad_database("Invalid account data event in db."))?
.content; .content;
let global = account_data.global; let rule = account_data
let rule = match body.kind { .global
RuleKind::Override => global .get(body.kind.clone(), &body.rule_id)
.override_ .map(Into::into);
.get(body.rule_id.as_str())
.map(|rule| rule.clone().into()),
RuleKind::Underride => global
.underride
.get(body.rule_id.as_str())
.map(|rule| rule.clone().into()),
RuleKind::Sender => global
.sender
.get(body.rule_id.as_str())
.map(|rule| rule.clone().into()),
RuleKind::Room => global
.room
.get(body.rule_id.as_str())
.map(|rule| rule.clone().into()),
RuleKind::Content => global
.content
.get(body.rule_id.as_str())
.map(|rule| rule.clone().into()),
_ => None,
};
if let Some(rule) = rule { if let Some(rule) = rule {
Ok(get_pushrule::v3::Response { rule }) Ok(get_pushrule::v3::Response { rule })
@ -131,66 +111,36 @@ pub async fn set_pushrule_route(
let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get()) let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))?; .map_err(|_| Error::bad_database("Invalid account data event in db."))?;
let global = &mut account_data.content.global; if let Err(error) = account_data.content.global.insert(
match body.rule { body.rule.clone(),
NewPushRule::Override(rule) => { body.after.as_deref(),
global.override_.replace( body.before.as_deref(),
ConditionalPushRuleInit { ) {
actions: rule.actions, let err = match error {
default: false, InsertPushRuleError::ServerDefaultRuleId => Error::BadRequest(
enabled: true, ErrorKind::InvalidParam,
rule_id: rule.rule_id, "Rule IDs starting with a dot are reserved for server-default rules.",
conditions: rule.conditions, ),
} InsertPushRuleError::InvalidRuleId => Error::BadRequest(
.into(), ErrorKind::InvalidParam,
); "Rule ID containing invalid characters.",
} ),
NewPushRule::Underride(rule) => { InsertPushRuleError::RelativeToServerDefaultRule => Error::BadRequest(
global.underride.replace( ErrorKind::InvalidParam,
ConditionalPushRuleInit { "Can't place a push rule relatively to a server-default rule.",
actions: rule.actions, ),
default: false, InsertPushRuleError::UnknownRuleId => Error::BadRequest(
enabled: true, ErrorKind::NotFound,
rule_id: rule.rule_id, "The before or after rule could not be found.",
conditions: rule.conditions, ),
} InsertPushRuleError::BeforeHigherThanAfter => Error::BadRequest(
.into(), ErrorKind::InvalidParam,
); "The before rule has a higher priority than the after rule.",
} ),
NewPushRule::Sender(rule) => { _ => Error::BadRequest(ErrorKind::InvalidParam, "Invalid data."),
global.sender.replace( };
SimplePushRuleInit {
actions: rule.actions, return Err(err);
default: false,
enabled: true,
rule_id: rule.rule_id,
}
.into(),
);
}
NewPushRule::Room(rule) => {
global.room.replace(
SimplePushRuleInit {
actions: rule.actions,
default: false,
enabled: true,
rule_id: rule.rule_id,
}
.into(),
);
}
NewPushRule::Content(rule) => {
global.content.replace(
PatternedPushRuleInit {
actions: rule.actions,
default: false,
enabled: true,
rule_id: rule.rule_id,
pattern: rule.pattern,
}
.into(),
);
}
} }
services().account_data.update( services().account_data.update(
@ -235,33 +185,15 @@ pub async fn get_pushrule_actions_route(
.content; .content;
let global = account_data.global; let global = account_data.global;
let actions = match body.kind { let actions = global
RuleKind::Override => global .get(body.kind.clone(), &body.rule_id)
.override_ .map(|rule| rule.actions().to_owned())
.get(body.rule_id.as_str()) .ok_or(Error::BadRequest(
.map(|rule| rule.actions.clone()), ErrorKind::NotFound,
RuleKind::Underride => global "Push rule not found.",
.underride ))?;
.get(body.rule_id.as_str())
.map(|rule| rule.actions.clone()),
RuleKind::Sender => global
.sender
.get(body.rule_id.as_str())
.map(|rule| rule.actions.clone()),
RuleKind::Room => global
.room
.get(body.rule_id.as_str())
.map(|rule| rule.actions.clone()),
RuleKind::Content => global
.content
.get(body.rule_id.as_str())
.map(|rule| rule.actions.clone()),
_ => None,
};
Ok(get_pushrule_actions::v3::Response { Ok(get_pushrule_actions::v3::Response { actions })
actions: actions.unwrap_or_default(),
})
} }
/// # `PUT /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/actions` /// # `PUT /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/actions`
@ -294,40 +226,17 @@ pub async fn set_pushrule_actions_route(
let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get()) let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))?; .map_err(|_| Error::bad_database("Invalid account data event in db."))?;
let global = &mut account_data.content.global; if account_data
match body.kind { .content
RuleKind::Override => { .global
if let Some(mut rule) = global.override_.get(body.rule_id.as_str()).cloned() { .set_actions(body.kind.clone(), &body.rule_id, body.actions.clone())
rule.actions = body.actions.clone(); .is_err()
global.override_.replace(rule); {
return Err(Error::BadRequest(
ErrorKind::NotFound,
"Push rule not found.",
));
} }
}
RuleKind::Underride => {
if let Some(mut rule) = global.underride.get(body.rule_id.as_str()).cloned() {
rule.actions = body.actions.clone();
global.underride.replace(rule);
}
}
RuleKind::Sender => {
if let Some(mut rule) = global.sender.get(body.rule_id.as_str()).cloned() {
rule.actions = body.actions.clone();
global.sender.replace(rule);
}
}
RuleKind::Room => {
if let Some(mut rule) = global.room.get(body.rule_id.as_str()).cloned() {
rule.actions = body.actions.clone();
global.room.replace(rule);
}
}
RuleKind::Content => {
if let Some(mut rule) = global.content.get(body.rule_id.as_str()).cloned() {
rule.actions = body.actions.clone();
global.content.replace(rule);
}
}
_ => {}
};
services().account_data.update( services().account_data.update(
None, None,
@ -370,34 +279,13 @@ pub async fn get_pushrule_enabled_route(
.map_err(|_| Error::bad_database("Invalid account data event in db."))?; .map_err(|_| Error::bad_database("Invalid account data event in db."))?;
let global = account_data.content.global; let global = account_data.content.global;
let enabled = match body.kind { let enabled = global
RuleKind::Override => global .get(body.kind.clone(), &body.rule_id)
.override_ .map(|r| r.enabled())
.iter() .ok_or(Error::BadRequest(
.find(|rule| rule.rule_id == body.rule_id) ErrorKind::NotFound,
.map_or(false, |rule| rule.enabled), "Push rule not found.",
RuleKind::Underride => global ))?;
.underride
.iter()
.find(|rule| rule.rule_id == body.rule_id)
.map_or(false, |rule| rule.enabled),
RuleKind::Sender => global
.sender
.iter()
.find(|rule| rule.rule_id == body.rule_id)
.map_or(false, |rule| rule.enabled),
RuleKind::Room => global
.room
.iter()
.find(|rule| rule.rule_id == body.rule_id)
.map_or(false, |rule| rule.enabled),
RuleKind::Content => global
.content
.iter()
.find(|rule| rule.rule_id == body.rule_id)
.map_or(false, |rule| rule.enabled),
_ => false,
};
Ok(get_pushrule_enabled::v3::Response { enabled }) Ok(get_pushrule_enabled::v3::Response { enabled })
} }
@ -432,44 +320,16 @@ pub async fn set_pushrule_enabled_route(
let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get()) let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))?; .map_err(|_| Error::bad_database("Invalid account data event in db."))?;
let global = &mut account_data.content.global; if account_data
match body.kind { .content
RuleKind::Override => { .global
if let Some(mut rule) = global.override_.get(body.rule_id.as_str()).cloned() { .set_enabled(body.kind.clone(), &body.rule_id, body.enabled)
global.override_.remove(&rule); .is_err()
rule.enabled = body.enabled; {
global.override_.insert(rule); return Err(Error::BadRequest(
} ErrorKind::NotFound,
} "Push rule not found.",
RuleKind::Underride => { ));
if let Some(mut rule) = global.underride.get(body.rule_id.as_str()).cloned() {
global.underride.remove(&rule);
rule.enabled = body.enabled;
global.underride.insert(rule);
}
}
RuleKind::Sender => {
if let Some(mut rule) = global.sender.get(body.rule_id.as_str()).cloned() {
global.sender.remove(&rule);
rule.enabled = body.enabled;
global.sender.insert(rule);
}
}
RuleKind::Room => {
if let Some(mut rule) = global.room.get(body.rule_id.as_str()).cloned() {
global.room.remove(&rule);
rule.enabled = body.enabled;
global.room.insert(rule);
}
}
RuleKind::Content => {
if let Some(mut rule) = global.content.get(body.rule_id.as_str()).cloned() {
global.content.remove(&rule);
rule.enabled = body.enabled;
global.content.insert(rule);
}
}
_ => {}
} }
services().account_data.update( services().account_data.update(
@ -512,34 +372,23 @@ pub async fn delete_pushrule_route(
let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get()) let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))?; .map_err(|_| Error::bad_database("Invalid account data event in db."))?;
let global = &mut account_data.content.global; if let Err(error) = account_data
match body.kind { .content
RuleKind::Override => { .global
if let Some(rule) = global.override_.get(body.rule_id.as_str()).cloned() { .remove(body.kind.clone(), &body.rule_id)
global.override_.remove(&rule); {
let err = match error {
RemovePushRuleError::ServerDefault => Error::BadRequest(
ErrorKind::InvalidParam,
"Cannot delete a server-default pushrule.",
),
RemovePushRuleError::NotFound => {
Error::BadRequest(ErrorKind::NotFound, "Push rule not found.")
} }
} _ => Error::BadRequest(ErrorKind::InvalidParam, "Invalid data."),
RuleKind::Underride => { };
if let Some(rule) = global.underride.get(body.rule_id.as_str()).cloned() {
global.underride.remove(&rule); return Err(err);
}
}
RuleKind::Sender => {
if let Some(rule) = global.sender.get(body.rule_id.as_str()).cloned() {
global.sender.remove(&rule);
}
}
RuleKind::Room => {
if let Some(rule) = global.room.get(body.rule_id.as_str()).cloned() {
global.room.remove(&rule);
}
}
RuleKind::Content => {
if let Some(rule) = global.content.get(body.rule_id.as_str()).cloned() {
global.content.remove(&rule);
}
}
_ => {}
} }
services().account_data.update( services().account_data.update(

View file

@ -3,7 +3,7 @@ use std::sync::Arc;
use crate::{service::pdu::PduBuilder, services, Result, Ruma}; use crate::{service::pdu::PduBuilder, services, Result, Ruma};
use ruma::{ use ruma::{
api::client::redact::redact_event, api::client::redact::redact_event,
events::{room::redaction::RoomRedactionEventContent, RoomEventType}, events::{room::redaction::RoomRedactionEventContent, TimelineEventType},
}; };
use serde_json::value::to_raw_value; use serde_json::value::to_raw_value;
@ -32,7 +32,7 @@ pub async fn redact_event_route(
let event_id = services().rooms.timeline.build_and_append_pdu( let event_id = services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomRedaction, event_type: TimelineEventType::RoomRedaction,
content: to_raw_value(&RoomRedactionEventContent { content: to_raw_value(&RoomRedactionEventContent {
reason: body.reason.clone(), reason: body.reason.clone(),
}) })

View file

@ -19,7 +19,7 @@ use ruma::{
tombstone::RoomTombstoneEventContent, tombstone::RoomTombstoneEventContent,
topic::RoomTopicEventContent, topic::RoomTopicEventContent,
}, },
RoomEventType, StateEventType, StateEventType, TimelineEventType,
}, },
int, int,
serde::JsonObject, serde::JsonObject,
@ -175,7 +175,7 @@ pub async fn create_room_route(
// 1. The room create event // 1. The room create event
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomCreate, event_type: TimelineEventType::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()),
@ -189,7 +189,7 @@ pub async fn create_room_route(
// 2. Let the room creator join // 2. Let the room creator join
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomMember, event_type: TimelineEventType::RoomMember,
content: to_raw_value(&RoomMemberEventContent { content: to_raw_value(&RoomMemberEventContent {
membership: MembershipState::Join, membership: MembershipState::Join,
displayname: services().users.displayname(sender_user)?, displayname: services().users.displayname(sender_user)?,
@ -247,7 +247,7 @@ pub async fn create_room_route(
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomPowerLevels, event_type: TimelineEventType::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,
@ -263,7 +263,7 @@ pub async fn create_room_route(
if let Some(room_alias_id) = &alias { if let Some(room_alias_id) = &alias {
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomCanonicalAlias, event_type: TimelineEventType::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![],
@ -284,7 +284,7 @@ pub async fn create_room_route(
// 5.1 Join Rules // 5.1 Join Rules
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomJoinRules, event_type: TimelineEventType::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
@ -303,7 +303,7 @@ pub async fn create_room_route(
// 5.2 History Visibility // 5.2 History Visibility
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomHistoryVisibility, event_type: TimelineEventType::RoomHistoryVisibility,
content: to_raw_value(&RoomHistoryVisibilityEventContent::new( content: to_raw_value(&RoomHistoryVisibilityEventContent::new(
HistoryVisibility::Shared, HistoryVisibility::Shared,
)) ))
@ -320,7 +320,7 @@ pub async fn create_room_route(
// 5.3 Guest Access // 5.3 Guest Access
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomGuestAccess, event_type: TimelineEventType::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,7 @@ 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 == RoomEventType::RoomEncryption if pdu_builder.event_type == TimelineEventType::RoomEncryption
&& !services().globals.allow_encryption() && !services().globals.allow_encryption()
{ {
continue; continue;
@ -364,7 +364,7 @@ pub async fn create_room_route(
if let Some(name) = &body.name { if let Some(name) = &body.name {
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomName, event_type: TimelineEventType::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,
@ -380,7 +380,7 @@ pub async fn create_room_route(
if let Some(topic) = &body.topic { if let Some(topic) = &body.topic {
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomTopic, event_type: TimelineEventType::RoomTopic,
content: to_raw_value(&RoomTopicEventContent { content: to_raw_value(&RoomTopicEventContent {
topic: topic.clone(), topic: topic.clone(),
}) })
@ -526,7 +526,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 = services().rooms.timeline.build_and_append_pdu( let tombstone_event_id = services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomTombstone, event_type: TimelineEventType::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(),
@ -608,7 +608,7 @@ pub async fn upgrade_room_route(
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomCreate, event_type: TimelineEventType::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,
@ -623,7 +623,7 @@ pub async fn upgrade_room_route(
// Join the new room // Join the new room
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomMember, event_type: TimelineEventType::RoomMember,
content: to_raw_value(&RoomMemberEventContent { content: to_raw_value(&RoomMemberEventContent {
membership: MembershipState::Join, membership: MembershipState::Join,
displayname: services().users.displayname(sender_user)?, displayname: services().users.displayname(sender_user)?,
@ -716,7 +716,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 _ = services().rooms.timeline.build_and_append_pdu( let _ = services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomPowerLevels, event_type: TimelineEventType::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,

View file

@ -14,7 +14,7 @@ use ruma::{
}, },
events::{ events::{
room::member::{MembershipState, RoomMemberEventContent}, room::member::{MembershipState, RoomMemberEventContent},
RoomEventType, StateEventType, StateEventType, TimelineEventType,
}, },
serde::Raw, serde::Raw,
DeviceId, OwnedDeviceId, OwnedUserId, RoomId, UserId, DeviceId, OwnedDeviceId, OwnedUserId, RoomId, UserId,
@ -678,7 +678,7 @@ async fn load_joined_room(
.timeline .timeline
.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 == RoomEventType::RoomMember) .filter(|(_, pdu)| pdu.kind == TimelineEventType::RoomMember)
.map(|(_, pdu)| { .map(|(_, pdu)| {
let content: RoomMemberEventContent = serde_json::from_str(pdu.content.get()) let content: RoomMemberEventContent = serde_json::from_str(pdu.content.get())
.map_err(|_| { .map_err(|_| {
@ -868,7 +868,7 @@ async fn load_joined_room(
} }
}; };
if pdu.kind == RoomEventType::RoomMember { if pdu.kind == TimelineEventType::RoomMember {
match UserId::parse( match UserId::parse(
pdu.state_key pdu.state_key
.as_ref() .as_ref()
@ -936,11 +936,11 @@ async fn load_joined_room(
let send_member_count = state_events let send_member_count = state_events
.iter() .iter()
.any(|event| event.kind == RoomEventType::RoomMember); .any(|event| event.kind == TimelineEventType::RoomMember);
if encrypted_room { if encrypted_room {
for state_event in &state_events { for state_event in &state_events {
if state_event.kind != RoomEventType::RoomMember { if state_event.kind != TimelineEventType::RoomMember {
continue; continue;
} }

View file

@ -1,4 +1,3 @@
use ruma::events::ToDeviceEventType;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use crate::{services, Error, Result, Ruma}; use crate::{services, Error, Result, Ruma};
@ -42,7 +41,7 @@ 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: ToDeviceEventType::from(&*body.event_type), ev_type: body.event_type.clone(),
message_id: count.to_string().into(), message_id: count.to_string().into(),
messages, messages,
}, },
@ -60,7 +59,7 @@ pub async fn send_event_to_device_route(
sender_user, sender_user,
target_user_id, target_user_id,
target_device_id, target_device_id,
&body.event_type, &body.event_type.to_string(),
event.deserialize_as().map_err(|_| { event.deserialize_as().map_err(|_| {
Error::BadRequest(ErrorKind::InvalidParam, "Event is invalid") Error::BadRequest(ErrorKind::InvalidParam, "Event is invalid")
})?, })?,
@ -73,7 +72,7 @@ pub async fn send_event_to_device_route(
sender_user, sender_user,
target_user_id, target_user_id,
&target_device_id?, &target_device_id?,
&body.event_type, &body.event_type.to_string(),
event.deserialize_as().map_err(|_| { event.deserialize_as().map_err(|_| {
Error::BadRequest(ErrorKind::InvalidParam, "Event is invalid") Error::BadRequest(ErrorKind::InvalidParam, "Event is invalid")
})?, })?,

View file

@ -47,7 +47,7 @@ where
let path_params = Path::<Vec<String>>::from_request(req).await?; let path_params = Path::<Vec<String>>::from_request(req).await?;
let query = req.uri().query().unwrap_or_default(); let query = req.uri().query().unwrap_or_default();
let query_params: QueryParams = match ruma::serde::urlencoded::from_str(query) { let query_params: QueryParams = match serde_html_form::from_str(query) {
Ok(params) => params, Ok(params) => params,
Err(e) => { Err(e) => {
error!(%query, "Failed to deserialize query parameters: {}", e); error!(%query, "Failed to deserialize query parameters: {}", e);

View file

@ -18,11 +18,7 @@ use ruma::{
discovery::{get_server_keys, get_server_version, ServerSigningKeys, VerifyKey}, discovery::{get_server_keys, get_server_version, ServerSigningKeys, VerifyKey},
event::{get_event, get_missing_events, get_room_state, get_room_state_ids}, event::{get_event, get_missing_events, get_room_state, get_room_state_ids},
keys::{claim_keys, get_keys}, keys::{claim_keys, get_keys},
membership::{ membership::{create_invite, create_join_event, prepare_join_event},
create_invite,
create_join_event::{self, RoomState},
prepare_join_event,
},
query::{get_profile_information, get_room_information}, query::{get_profile_information, get_room_information},
transactions::{ transactions::{
edu::{DeviceListUpdateContent, DirectDeviceContent, Edu, SigningKeyUpdateContent}, edu::{DeviceListUpdateContent, DirectDeviceContent, Edu, SigningKeyUpdateContent},
@ -39,7 +35,7 @@ use ruma::{
join_rules::{JoinRule, RoomJoinRulesEventContent}, join_rules::{JoinRule, RoomJoinRulesEventContent},
member::{MembershipState, RoomMemberEventContent}, member::{MembershipState, RoomMemberEventContent},
}, },
RoomEventType, StateEventType, StateEventType, TimelineEventType,
}, },
serde::{Base64, JsonObject, Raw}, serde::{Base64, JsonObject, Raw},
to_device::DeviceIdOrAllDevices, to_device::DeviceIdOrAllDevices,
@ -1440,7 +1436,7 @@ pub async fn create_join_event_template_route(
let (_pdu, mut pdu_json) = services().rooms.timeline.create_hash_and_sign_event( let (_pdu, mut pdu_json) = services().rooms.timeline.create_hash_and_sign_event(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomMember, event_type: TimelineEventType::RoomMember,
content, content,
unsigned: None, unsigned: None,
state_key: Some(body.user_id.to_string()), state_key: Some(body.user_id.to_string()),
@ -1465,7 +1461,7 @@ async fn create_join_event(
sender_servername: &ServerName, sender_servername: &ServerName,
room_id: &RoomId, room_id: &RoomId,
pdu: &RawJsonValue, pdu: &RawJsonValue,
) -> Result<RoomState> { ) -> Result<create_join_event::v1::RoomState> {
if !services().globals.allow_federation() { if !services().globals.allow_federation() {
return Err(Error::bad_config("Federation is disabled.")); return Err(Error::bad_config("Federation is disabled."));
} }
@ -1587,7 +1583,7 @@ async fn create_join_event(
services().sending.send_pdu(servers, &pdu_id)?; services().sending.send_pdu(servers, &pdu_id)?;
Ok(RoomState { Ok(create_join_event::v1::RoomState {
auth_chain: auth_chain_ids auth_chain: auth_chain_ids
.filter_map(|id| services().rooms.timeline.get_pdu_json(&id).ok().flatten()) .filter_map(|id| services().rooms.timeline.get_pdu_json(&id).ok().flatten())
.map(PduEvent::convert_to_outgoing_federation_event) .map(PduEvent::convert_to_outgoing_federation_event)
@ -1628,7 +1624,18 @@ pub async fn create_join_event_v2_route(
.as_ref() .as_ref()
.expect("server is authenticated"); .expect("server is authenticated");
let room_state = create_join_event(sender_servername, &body.room_id, &body.pdu).await?; let create_join_event::v1::RoomState {
auth_chain,
state,
event,
} = create_join_event(sender_servername, &body.room_id, &body.pdu).await?;
let room_state = create_join_event::v2::RoomState {
members_omitted: false,
auth_chain,
state,
event,
servers_in_room: None,
};
Ok(create_join_event::v2::Response { room_state }) Ok(create_join_event::v2::Response { room_state })
} }

View file

@ -411,7 +411,7 @@ impl KeyValueDatabase {
} }
// If the database has any data, perform data migrations before starting // If the database has any data, perform data migrations before starting
let latest_database_version = 12; let latest_database_version = 13;
if services().users.count()? > 0 { if services().users.count()? > 0 {
// MIGRATIONS // MIGRATIONS
@ -880,6 +880,52 @@ impl KeyValueDatabase {
warn!("Migration: 11 -> 12 finished"); warn!("Migration: 11 -> 12 finished");
} }
// This migration can be reused as-is anytime the server-default rules are updated.
if services().globals.database_version()? < 13 {
for username in services().users.list_local_users()? {
let user = match UserId::parse_with_server_name(
username.clone(),
services().globals.server_name(),
) {
Ok(u) => u,
Err(e) => {
warn!("Invalid username {username}: {e}");
continue;
}
};
let raw_rules_list = services()
.account_data
.get(
None,
&user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)
.unwrap()
.expect("Username is invalid");
let mut account_data =
serde_json::from_str::<PushRulesEvent>(raw_rules_list.get()).unwrap();
let user_default_rules = ruma::push::Ruleset::server_default(&user);
account_data
.content
.global
.update_with_server_default(user_default_rules);
services().account_data.update(
None,
&user,
GlobalAccountDataEventType::PushRules.to_string().into(),
&serde_json::to_value(account_data).expect("to json value always works"),
)?;
}
services().globals.bump_database_version(13)?;
warn!("Migration: 12 -> 13 finished");
}
assert_eq!( assert_eq!(
services().globals.database_version().unwrap(), services().globals.database_version().unwrap(),
latest_database_version latest_database_version

View file

@ -21,7 +21,7 @@ use ruma::{
power_levels::RoomPowerLevelsEventContent, power_levels::RoomPowerLevelsEventContent,
topic::RoomTopicEventContent, topic::RoomTopicEventContent,
}, },
RoomEventType, TimelineEventType,
}, },
EventId, OwnedRoomAliasId, RoomAliasId, RoomId, RoomVersionId, ServerName, UserId, EventId, OwnedRoomAliasId, RoomAliasId, RoomId, RoomVersionId, ServerName, UserId,
}; };
@ -212,7 +212,7 @@ impl Service {
.timeline .timeline
.build_and_append_pdu( .build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomMessage, event_type: TimelineEventType::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,
@ -854,7 +854,7 @@ impl Service {
// 1. The room create event // 1. The room create event
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomCreate, event_type: TimelineEventType::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()),
@ -868,7 +868,7 @@ impl Service {
// 2. Make conduit bot join // 2. Make conduit bot join
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomMember, event_type: TimelineEventType::RoomMember,
content: to_raw_value(&RoomMemberEventContent { content: to_raw_value(&RoomMemberEventContent {
membership: MembershipState::Join, membership: MembershipState::Join,
displayname: None, displayname: None,
@ -895,7 +895,7 @@ impl Service {
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomPowerLevels, event_type: TimelineEventType::RoomPowerLevels,
content: to_raw_value(&RoomPowerLevelsEventContent { content: to_raw_value(&RoomPowerLevelsEventContent {
users, users,
..Default::default() ..Default::default()
@ -913,7 +913,7 @@ impl Service {
// 4.1 Join Rules // 4.1 Join Rules
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomJoinRules, event_type: TimelineEventType::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,
@ -928,7 +928,7 @@ impl Service {
// 4.2 History Visibility // 4.2 History Visibility
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomHistoryVisibility, event_type: TimelineEventType::RoomHistoryVisibility,
content: to_raw_value(&RoomHistoryVisibilityEventContent::new( content: to_raw_value(&RoomHistoryVisibilityEventContent::new(
HistoryVisibility::Shared, HistoryVisibility::Shared,
)) ))
@ -945,7 +945,7 @@ impl Service {
// 4.3 Guest Access // 4.3 Guest Access
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomGuestAccess, event_type: TimelineEventType::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,
@ -961,7 +961,7 @@ impl Service {
let room_name = format!("{} Admin Room", services().globals.server_name()); let room_name = format!("{} Admin Room", services().globals.server_name());
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomName, event_type: TimelineEventType::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,
@ -975,7 +975,7 @@ impl Service {
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomTopic, event_type: TimelineEventType::RoomTopic,
content: to_raw_value(&RoomTopicEventContent { content: to_raw_value(&RoomTopicEventContent {
topic: format!("Manage {}", services().globals.server_name()), topic: format!("Manage {}", services().globals.server_name()),
}) })
@ -996,7 +996,7 @@ impl Service {
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomCanonicalAlias, event_type: TimelineEventType::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(),
@ -1053,7 +1053,7 @@ impl Service {
// Invite and join the real user // Invite and join the real user
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomMember, event_type: TimelineEventType::RoomMember,
content: to_raw_value(&RoomMemberEventContent { content: to_raw_value(&RoomMemberEventContent {
membership: MembershipState::Invite, membership: MembershipState::Invite,
displayname: None, displayname: None,
@ -1075,7 +1075,7 @@ impl Service {
)?; )?;
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomMember, event_type: TimelineEventType::RoomMember,
content: to_raw_value(&RoomMemberEventContent { content: to_raw_value(&RoomMemberEventContent {
membership: MembershipState::Join, membership: MembershipState::Join,
displayname: Some(displayname), displayname: Some(displayname),
@ -1103,7 +1103,7 @@ impl Service {
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomPowerLevels, event_type: TimelineEventType::RoomPowerLevels,
content: to_raw_value(&RoomPowerLevelsEventContent { content: to_raw_value(&RoomPowerLevelsEventContent {
users, users,
..Default::default() ..Default::default()
@ -1121,7 +1121,7 @@ impl Service {
// Send welcome message // Send welcome message
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomMessage, event_type: TimelineEventType::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`", services().globals.server_name()), 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`", services().globals.server_name()),
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", services().globals.server_name()), 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", services().globals.server_name()),

View file

@ -3,7 +3,7 @@ use ruma::{
events::{ events::{
room::member::RoomMemberEventContent, AnyEphemeralRoomEvent, AnyStateEvent, room::member::RoomMemberEventContent, AnyEphemeralRoomEvent, AnyStateEvent,
AnyStrippedStateEvent, AnySyncStateEvent, AnySyncTimelineEvent, AnyTimelineEvent, AnyStrippedStateEvent, AnySyncStateEvent, AnySyncTimelineEvent, AnyTimelineEvent,
RoomEventType, StateEvent, StateEvent, TimelineEventType,
}, },
serde::Raw, serde::Raw,
state_res, CanonicalJsonObject, CanonicalJsonValue, EventId, MilliSecondsSinceUnixEpoch, state_res, CanonicalJsonObject, CanonicalJsonValue, EventId, MilliSecondsSinceUnixEpoch,
@ -31,7 +31,7 @@ pub struct PduEvent {
pub sender: OwnedUserId, pub sender: OwnedUserId,
pub origin_server_ts: UInt, pub origin_server_ts: UInt,
#[serde(rename = "type")] #[serde(rename = "type")]
pub kind: RoomEventType, pub kind: TimelineEventType,
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>,
@ -53,10 +53,10 @@ impl PduEvent {
self.unsigned = None; self.unsigned = None;
let allowed: &[&str] = match self.kind { let allowed: &[&str] = match self.kind {
RoomEventType::RoomMember => &["join_authorised_via_users_server", "membership"], TimelineEventType::RoomMember => &["join_authorised_via_users_server", "membership"],
RoomEventType::RoomCreate => &["creator"], TimelineEventType::RoomCreate => &["creator"],
RoomEventType::RoomJoinRules => &["join_rule"], TimelineEventType::RoomJoinRules => &["join_rule"],
RoomEventType::RoomPowerLevels => &[ TimelineEventType::RoomPowerLevels => &[
"ban", "ban",
"events", "events",
"events_default", "events_default",
@ -66,7 +66,7 @@ impl PduEvent {
"users", "users",
"users_default", "users_default",
], ],
RoomEventType::RoomHistoryVisibility => &["history_visibility"], TimelineEventType::RoomHistoryVisibility => &["history_visibility"],
_ => &[], _ => &[],
}; };
@ -296,7 +296,7 @@ impl state_res::Event for PduEvent {
&self.sender &self.sender
} }
fn event_type(&self) -> &RoomEventType { fn event_type(&self) -> &TimelineEventType {
&self.kind &self.kind
} }
@ -372,7 +372,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: RoomEventType, pub event_type: TimelineEventType,
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>,

View file

@ -15,7 +15,7 @@ use ruma::{
}, },
events::{ events::{
room::{name::RoomNameEventContent, power_levels::RoomPowerLevelsEventContent}, room::{name::RoomNameEventContent, power_levels::RoomPowerLevelsEventContent},
RoomEventType, StateEventType, StateEventType, TimelineEventType,
}, },
push::{Action, PushConditionRoomCtx, PushFormat, Ruleset, Tweak}, push::{Action, PushConditionRoomCtx, PushFormat, Ruleset, Tweak},
serde::Raw, serde::Raw,
@ -169,6 +169,7 @@ impl Service {
tweaks.push(tweak.clone()); tweaks.push(tweak.clone());
continue; continue;
} }
_ => false,
}; };
if notify.is_some() { if notify.is_some() {
@ -248,7 +249,7 @@ impl Service {
// TODO: missed calls // TODO: missed calls
notifi.counts = NotificationCounts::new(unread, uint!(0)); notifi.counts = NotificationCounts::new(unread, uint!(0));
if event.kind == RoomEventType::RoomEncrypted if event.kind == TimelineEventType::RoomEncrypted
|| tweaks || tweaks
.iter() .iter()
.any(|t| matches!(t, Tweak::Highlight(true) | Tweak::Sound(_))) .any(|t| matches!(t, Tweak::Highlight(true) | Tweak::Sound(_)))
@ -264,7 +265,7 @@ impl Service {
notifi.event_type = Some(event.kind.clone()); notifi.event_type = Some(event.kind.clone());
notifi.content = serde_json::value::to_raw_value(&event.content).ok(); notifi.content = serde_json::value::to_raw_value(&event.content).ok();
if event.kind == RoomEventType::RoomMember { if event.kind == TimelineEventType::RoomMember {
notifi.user_is_target = notifi.user_is_target =
event.state_key.as_deref() == Some(event.sender.as_str()); event.state_key.as_deref() == Some(event.sender.as_str());
} }

View file

@ -8,7 +8,7 @@ pub use data::Data;
use ruma::{ use ruma::{
events::{ events::{
room::{create::RoomCreateEventContent, member::MembershipState}, room::{create::RoomCreateEventContent, member::MembershipState},
AnyStrippedStateEvent, RoomEventType, StateEventType, AnyStrippedStateEvent, StateEventType, TimelineEventType,
}, },
serde::Raw, serde::Raw,
state_res::{self, StateMap}, state_res::{self, StateMap},
@ -358,7 +358,7 @@ impl Service {
pub fn get_auth_events( pub fn get_auth_events(
&self, &self,
room_id: &RoomId, room_id: &RoomId,
kind: &RoomEventType, kind: &TimelineEventType,
sender: &UserId, sender: &UserId,
state_key: Option<&str>, state_key: Option<&str>,
content: &serde_json::value::RawValue, content: &serde_json::value::RawValue,

View file

@ -1,20 +1,19 @@
mod data; mod data;
use std::cmp::Ordering; use std::{
use std::collections::{BTreeMap, HashMap}; cmp::Ordering,
collections::{BTreeMap, HashMap},
};
use std::sync::RwLock;
use std::{ use std::{
collections::HashSet, collections::HashSet,
sync::{Arc, Mutex}, sync::{Arc, Mutex, RwLock},
}; };
pub use data::Data; pub use data::Data;
use regex::Regex; use regex::Regex;
use ruma::api::federation;
use ruma::serde::Base64;
use ruma::{ use ruma::{
api::client::error::ErrorKind, api::{client::error::ErrorKind, federation},
canonical_json::to_canonical_value, canonical_json::to_canonical_value,
events::{ events::{
push_rules::PushRulesEvent, push_rules::PushRulesEvent,
@ -22,23 +21,22 @@ use ruma::{
create::RoomCreateEventContent, member::MembershipState, create::RoomCreateEventContent, member::MembershipState,
power_levels::RoomPowerLevelsEventContent, power_levels::RoomPowerLevelsEventContent,
}, },
GlobalAccountDataEventType, RoomEventType, StateEventType, GlobalAccountDataEventType, StateEventType, TimelineEventType,
}, },
push::{Action, Ruleset, Tweak}, push::{Action, Ruleset, Tweak},
serde::Base64,
state_res, state_res,
state_res::Event, state_res::{Event, RoomVersion},
state_res::RoomVersion, uint, user_id, CanonicalJsonObject, CanonicalJsonValue, EventId, OwnedEventId, OwnedRoomId,
uint, CanonicalJsonObject, CanonicalJsonValue, EventId, OwnedEventId, OwnedRoomId, OwnedServerName, RoomAliasId, RoomId, ServerName, UserId,
OwnedServerName, RoomAliasId, RoomId, UserId,
}; };
use ruma::{user_id, ServerName};
use serde::Deserialize; use serde::Deserialize;
use serde_json::value::{to_raw_value, RawValue as RawJsonValue}; use serde_json::value::{to_raw_value, RawValue as RawJsonValue};
use tokio::sync::MutexGuard; use tokio::sync::MutexGuard;
use tracing::{error, info, warn}; use tracing::{error, info, warn};
use crate::api::server_server;
use crate::{ use crate::{
api::server_server,
service::pdu::{EventHash, PduBuilder}, service::pdu::{EventHash, PduBuilder},
services, utils, Error, PduEvent, Result, services, utils, Error, PduEvent, Result,
}; };
@ -381,12 +379,12 @@ impl Service {
.increment_notification_counts(&pdu.room_id, notifies, highlights)?; .increment_notification_counts(&pdu.room_id, notifies, highlights)?;
match pdu.kind { match pdu.kind {
RoomEventType::RoomRedaction => { TimelineEventType::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)?;
} }
} }
RoomEventType::RoomMember => { TimelineEventType::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 {
@ -420,7 +418,7 @@ impl Service {
)?; )?;
} }
} }
RoomEventType::RoomMessage => { TimelineEventType::RoomMessage => {
#[derive(Deserialize)] #[derive(Deserialize)]
struct ExtractBody { struct ExtractBody {
body: Option<String>, body: Option<String>,
@ -473,7 +471,7 @@ impl Service {
// If the RoomMember event has a non-empty state_key, it is targeted at someone. // If the RoomMember event has a non-empty state_key, it is targeted at someone.
// If it is our appservice user, we send this PDU to it. // If it is our appservice user, we send this PDU to it.
if pdu.kind == RoomEventType::RoomMember { if pdu.kind == TimelineEventType::RoomMember {
if let Some(state_key_uid) = &pdu if let Some(state_key_uid) = &pdu
.state_key .state_key
.as_ref() .as_ref()
@ -523,7 +521,7 @@ impl Service {
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 == RoomEventType::RoomMember || pdu.kind == TimelineEventType::RoomMember
&& pdu && pdu
.state_key .state_key
.as_ref() .as_ref()
@ -757,14 +755,14 @@ impl Service {
)?; )?;
if admin_room.filter(|v| v == room_id).is_some() { if admin_room.filter(|v| v == room_id).is_some() {
match pdu.event_type() { match pdu.event_type() {
RoomEventType::RoomEncryption => { TimelineEventType::RoomEncryption => {
warn!("Encryption is not allowed in the admins room"); warn!("Encryption is not allowed in the admins room");
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::Forbidden,
"Encryption is not allowed in the admins room.", "Encryption is not allowed in the admins room.",
)); ));
} }
RoomEventType::RoomMember => { TimelineEventType::RoomMember => {
#[derive(Deserialize)] #[derive(Deserialize)]
struct ExtractMembership { struct ExtractMembership {
membership: MembershipState, membership: MembershipState,
@ -863,7 +861,7 @@ impl Service {
.collect(); .collect();
// In case we are kicking or banning a user, we need to inform their server of the change // In case we are kicking or banning a user, we need to inform their server of the change
if pdu.kind == RoomEventType::RoomMember { if pdu.kind == TimelineEventType::RoomMember {
if let Some(state_key_uid) = &pdu if let Some(state_key_uid) = &pdu
.state_key .state_key
.as_ref() .as_ref()
@ -1101,7 +1099,7 @@ impl Service {
drop(insert_lock); drop(insert_lock);
match pdu.kind { match pdu.kind {
RoomEventType::RoomMessage => { TimelineEventType::RoomMessage => {
#[derive(Deserialize)] #[derive(Deserialize)]
struct ExtractBody { struct ExtractBody {
body: Option<String>, body: Option<String>,