diff --git a/Cargo.lock b/Cargo.lock
index 70d7f4b4..293bcff7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1968,7 +1968,7 @@ dependencies = [
[[package]]
name = "ruma"
version = "0.4.0"
-source = "git+https://github.com/ruma/ruma?rev=a6a1224652912a957b09f136ec5da2686be6e0e2#a6a1224652912a957b09f136ec5da2686be6e0e2"
+source = "git+https://github.com/ruma/ruma?rev=44cfd0adbc83303c19aef590ad0d71647e19f197#44cfd0adbc83303c19aef590ad0d71647e19f197"
dependencies = [
"assign",
"js_int",
@@ -1988,8 +1988,8 @@ dependencies = [
[[package]]
name = "ruma-api"
-version = "0.18.3"
-source = "git+https://github.com/ruma/ruma?rev=a6a1224652912a957b09f136ec5da2686be6e0e2#a6a1224652912a957b09f136ec5da2686be6e0e2"
+version = "0.18.5"
+source = "git+https://github.com/ruma/ruma?rev=44cfd0adbc83303c19aef590ad0d71647e19f197#44cfd0adbc83303c19aef590ad0d71647e19f197"
dependencies = [
"bytes",
"http",
@@ -2004,8 +2004,8 @@ dependencies = [
[[package]]
name = "ruma-api-macros"
-version = "0.18.3"
-source = "git+https://github.com/ruma/ruma?rev=a6a1224652912a957b09f136ec5da2686be6e0e2#a6a1224652912a957b09f136ec5da2686be6e0e2"
+version = "0.18.5"
+source = "git+https://github.com/ruma/ruma?rev=44cfd0adbc83303c19aef590ad0d71647e19f197#44cfd0adbc83303c19aef590ad0d71647e19f197"
dependencies = [
"proc-macro-crate",
"proc-macro2",
@@ -2016,7 +2016,7 @@ dependencies = [
[[package]]
name = "ruma-appservice-api"
version = "0.4.0"
-source = "git+https://github.com/ruma/ruma?rev=a6a1224652912a957b09f136ec5da2686be6e0e2#a6a1224652912a957b09f136ec5da2686be6e0e2"
+source = "git+https://github.com/ruma/ruma?rev=44cfd0adbc83303c19aef590ad0d71647e19f197#44cfd0adbc83303c19aef590ad0d71647e19f197"
dependencies = [
"ruma-api",
"ruma-common",
@@ -2029,8 +2029,8 @@ dependencies = [
[[package]]
name = "ruma-client-api"
-version = "0.12.2"
-source = "git+https://github.com/ruma/ruma?rev=a6a1224652912a957b09f136ec5da2686be6e0e2#a6a1224652912a957b09f136ec5da2686be6e0e2"
+version = "0.12.3"
+source = "git+https://github.com/ruma/ruma?rev=44cfd0adbc83303c19aef590ad0d71647e19f197#44cfd0adbc83303c19aef590ad0d71647e19f197"
dependencies = [
"assign",
"bytes",
@@ -2050,7 +2050,7 @@ dependencies = [
[[package]]
name = "ruma-common"
version = "0.6.0"
-source = "git+https://github.com/ruma/ruma?rev=a6a1224652912a957b09f136ec5da2686be6e0e2#a6a1224652912a957b09f136ec5da2686be6e0e2"
+source = "git+https://github.com/ruma/ruma?rev=44cfd0adbc83303c19aef590ad0d71647e19f197#44cfd0adbc83303c19aef590ad0d71647e19f197"
dependencies = [
"indexmap",
"js_int",
@@ -2064,8 +2064,8 @@ dependencies = [
[[package]]
name = "ruma-events"
-version = "0.24.5"
-source = "git+https://github.com/ruma/ruma?rev=a6a1224652912a957b09f136ec5da2686be6e0e2#a6a1224652912a957b09f136ec5da2686be6e0e2"
+version = "0.24.6"
+source = "git+https://github.com/ruma/ruma?rev=44cfd0adbc83303c19aef590ad0d71647e19f197#44cfd0adbc83303c19aef590ad0d71647e19f197"
dependencies = [
"indoc",
"js_int",
@@ -2080,8 +2080,8 @@ dependencies = [
[[package]]
name = "ruma-events-macros"
-version = "0.24.5"
-source = "git+https://github.com/ruma/ruma?rev=a6a1224652912a957b09f136ec5da2686be6e0e2#a6a1224652912a957b09f136ec5da2686be6e0e2"
+version = "0.24.6"
+source = "git+https://github.com/ruma/ruma?rev=44cfd0adbc83303c19aef590ad0d71647e19f197#44cfd0adbc83303c19aef590ad0d71647e19f197"
dependencies = [
"proc-macro-crate",
"proc-macro2",
@@ -2092,7 +2092,7 @@ dependencies = [
[[package]]
name = "ruma-federation-api"
version = "0.3.1"
-source = "git+https://github.com/ruma/ruma?rev=a6a1224652912a957b09f136ec5da2686be6e0e2#a6a1224652912a957b09f136ec5da2686be6e0e2"
+source = "git+https://github.com/ruma/ruma?rev=44cfd0adbc83303c19aef590ad0d71647e19f197#44cfd0adbc83303c19aef590ad0d71647e19f197"
dependencies = [
"js_int",
"ruma-api",
@@ -2107,9 +2107,10 @@ dependencies = [
[[package]]
name = "ruma-identifiers"
version = "0.20.0"
-source = "git+https://github.com/ruma/ruma?rev=a6a1224652912a957b09f136ec5da2686be6e0e2#a6a1224652912a957b09f136ec5da2686be6e0e2"
+source = "git+https://github.com/ruma/ruma?rev=44cfd0adbc83303c19aef590ad0d71647e19f197#44cfd0adbc83303c19aef590ad0d71647e19f197"
dependencies = [
"paste",
+ "percent-encoding",
"rand 0.8.4",
"ruma-identifiers-macros",
"ruma-identifiers-validation",
@@ -2121,7 +2122,7 @@ dependencies = [
[[package]]
name = "ruma-identifiers-macros"
version = "0.20.0"
-source = "git+https://github.com/ruma/ruma?rev=a6a1224652912a957b09f136ec5da2686be6e0e2#a6a1224652912a957b09f136ec5da2686be6e0e2"
+source = "git+https://github.com/ruma/ruma?rev=44cfd0adbc83303c19aef590ad0d71647e19f197#44cfd0adbc83303c19aef590ad0d71647e19f197"
dependencies = [
"quote",
"ruma-identifiers-validation",
@@ -2131,12 +2132,15 @@ dependencies = [
[[package]]
name = "ruma-identifiers-validation"
version = "0.5.0"
-source = "git+https://github.com/ruma/ruma?rev=a6a1224652912a957b09f136ec5da2686be6e0e2#a6a1224652912a957b09f136ec5da2686be6e0e2"
+source = "git+https://github.com/ruma/ruma?rev=44cfd0adbc83303c19aef590ad0d71647e19f197#44cfd0adbc83303c19aef590ad0d71647e19f197"
+dependencies = [
+ "thiserror",
+]
[[package]]
name = "ruma-identity-service-api"
version = "0.3.0"
-source = "git+https://github.com/ruma/ruma?rev=a6a1224652912a957b09f136ec5da2686be6e0e2#a6a1224652912a957b09f136ec5da2686be6e0e2"
+source = "git+https://github.com/ruma/ruma?rev=44cfd0adbc83303c19aef590ad0d71647e19f197#44cfd0adbc83303c19aef590ad0d71647e19f197"
dependencies = [
"js_int",
"ruma-api",
@@ -2149,7 +2153,7 @@ dependencies = [
[[package]]
name = "ruma-push-gateway-api"
version = "0.3.0"
-source = "git+https://github.com/ruma/ruma?rev=a6a1224652912a957b09f136ec5da2686be6e0e2#a6a1224652912a957b09f136ec5da2686be6e0e2"
+source = "git+https://github.com/ruma/ruma?rev=44cfd0adbc83303c19aef590ad0d71647e19f197#44cfd0adbc83303c19aef590ad0d71647e19f197"
dependencies = [
"js_int",
"ruma-api",
@@ -2164,7 +2168,7 @@ dependencies = [
[[package]]
name = "ruma-serde"
version = "0.5.0"
-source = "git+https://github.com/ruma/ruma?rev=a6a1224652912a957b09f136ec5da2686be6e0e2#a6a1224652912a957b09f136ec5da2686be6e0e2"
+source = "git+https://github.com/ruma/ruma?rev=44cfd0adbc83303c19aef590ad0d71647e19f197#44cfd0adbc83303c19aef590ad0d71647e19f197"
dependencies = [
"bytes",
"form_urlencoded",
@@ -2178,7 +2182,7 @@ dependencies = [
[[package]]
name = "ruma-serde-macros"
version = "0.5.0"
-source = "git+https://github.com/ruma/ruma?rev=a6a1224652912a957b09f136ec5da2686be6e0e2#a6a1224652912a957b09f136ec5da2686be6e0e2"
+source = "git+https://github.com/ruma/ruma?rev=44cfd0adbc83303c19aef590ad0d71647e19f197#44cfd0adbc83303c19aef590ad0d71647e19f197"
dependencies = [
"proc-macro-crate",
"proc-macro2",
@@ -2189,7 +2193,7 @@ dependencies = [
[[package]]
name = "ruma-signatures"
version = "0.9.0"
-source = "git+https://github.com/ruma/ruma?rev=a6a1224652912a957b09f136ec5da2686be6e0e2#a6a1224652912a957b09f136ec5da2686be6e0e2"
+source = "git+https://github.com/ruma/ruma?rev=44cfd0adbc83303c19aef590ad0d71647e19f197#44cfd0adbc83303c19aef590ad0d71647e19f197"
dependencies = [
"base64 0.13.0",
"ed25519-dalek",
@@ -2206,7 +2210,7 @@ dependencies = [
[[package]]
name = "ruma-state-res"
version = "0.4.1"
-source = "git+https://github.com/ruma/ruma?rev=a6a1224652912a957b09f136ec5da2686be6e0e2#a6a1224652912a957b09f136ec5da2686be6e0e2"
+source = "git+https://github.com/ruma/ruma?rev=44cfd0adbc83303c19aef590ad0d71647e19f197#44cfd0adbc83303c19aef590ad0d71647e19f197"
dependencies = [
"itertools 0.10.1",
"js_int",
diff --git a/Cargo.toml b/Cargo.toml
index 593a1fd3..0f246733 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -19,7 +19,7 @@ rocket = { version = "0.5.0-rc.1", features = ["tls"] } # Used to handle request
# 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 = { git = "https://github.com/ruma/ruma", rev = "a6a1224652912a957b09f136ec5da2686be6e0e2", 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 = "44cfd0adbc83303c19aef590ad0d71647e19f197", 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"] }
diff --git a/conduit-example.toml b/conduit-example.toml
index 80082568..4275f528 100644
--- a/conduit-example.toml
+++ b/conduit-example.toml
@@ -40,6 +40,7 @@ trusted_servers = ["matrix.org"]
#workers = 4 # default: cpu core count * 2
address = "127.0.0.1" # This makes sure Conduit can only be reached using the reverse proxy
+#address = "0.0.0.0" # If Conduit is running in a container, make sure the reverse proxy (ie. Traefik) can reach it.
proxy = "none" # more examples can be found at src/database/proxy.rs:6
diff --git a/rust-toolchain b/rust-toolchain
index d96ae405..74df8b16 100644
--- a/rust-toolchain
+++ b/rust-toolchain
@@ -1 +1 @@
-1.52
+1.53
diff --git a/src/client_server/account.rs b/src/client_server/account.rs
index fb338422..4b3ad0d4 100644
--- a/src/client_server/account.rs
+++ b/src/client_server/account.rs
@@ -15,19 +15,28 @@ use ruma::{
ThirdPartyIdRemovalStatus,
},
contact::get_contacts,
- uiaa::{AuthFlow, UiaaInfo},
+ uiaa::{AuthFlow, AuthType, UiaaInfo},
},
},
events::{
room::{
- canonical_alias, guest_access, history_visibility, join_rules, member, message, name,
- topic,
+ canonical_alias::RoomCanonicalAliasEventContent,
+ create::RoomCreateEventContent,
+ guest_access::{GuestAccess, RoomGuestAccessEventContent},
+ history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent},
+ join_rules::{JoinRule, RoomJoinRulesEventContent},
+ member::{MembershipState, RoomMemberEventContent},
+ message::RoomMessageEventContent,
+ name::RoomNameEventContent,
+ power_levels::RoomPowerLevelsEventContent,
+ topic::RoomTopicEventContent,
},
EventType,
},
identifiers::RoomName,
push, RoomAliasId, RoomId, RoomVersionId, UserId,
};
+use serde_json::value::to_raw_value;
use tracing::info;
use register::RegistrationKind;
@@ -147,7 +156,7 @@ pub async fn register_route(
// UIAA
let mut uiaainfo = UiaaInfo {
flows: vec![AuthFlow {
- stages: vec!["m.login.dummy".to_owned()],
+ stages: vec![AuthType::Dummy],
}],
completed: Vec::new(),
params: Default::default(),
@@ -270,7 +279,7 @@ pub async fn register_route(
);
let state_lock = mutex_state.lock().await;
- let mut content = ruma::events::room::create::CreateEventContent::new(conduit_user.clone());
+ let mut content = RoomCreateEventContent::new(conduit_user.clone());
content.federate = true;
content.predecessor = None;
content.room_version = RoomVersionId::Version6;
@@ -279,7 +288,7 @@ pub async fn register_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomCreate,
- content: serde_json::to_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,
state_key: Some("".to_owned()),
redacts: None,
@@ -294,8 +303,8 @@ pub async fn register_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomMember,
- content: serde_json::to_value(member::MemberEventContent {
- membership: member::MembershipState::Join,
+ content: to_raw_value(&RoomMemberEventContent {
+ membership: MembershipState::Join,
displayname: None,
avatar_url: None,
is_direct: None,
@@ -322,12 +331,10 @@ pub async fn register_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomPowerLevels,
- content: serde_json::to_value(
- ruma::events::room::power_levels::PowerLevelsEventContent {
- users,
- ..Default::default()
- },
- )
+ content: to_raw_value(&RoomPowerLevelsEventContent {
+ users,
+ ..Default::default()
+ })
.expect("event is valid, we just created it"),
unsigned: None,
state_key: Some("".to_owned()),
@@ -343,10 +350,8 @@ pub async fn register_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomJoinRules,
- content: serde_json::to_value(join_rules::JoinRulesEventContent::new(
- join_rules::JoinRule::Invite,
- ))
- .expect("event is valid, we just created it"),
+ content: to_raw_value(&RoomJoinRulesEventContent::new(JoinRule::Invite))
+ .expect("event is valid, we just created it"),
unsigned: None,
state_key: Some("".to_owned()),
redacts: None,
@@ -361,11 +366,9 @@ pub async fn register_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomHistoryVisibility,
- content: serde_json::to_value(
- history_visibility::HistoryVisibilityEventContent::new(
- history_visibility::HistoryVisibility::Shared,
- ),
- )
+ content: to_raw_value(&RoomHistoryVisibilityEventContent::new(
+ HistoryVisibility::Shared,
+ ))
.expect("event is valid, we just created it"),
unsigned: None,
state_key: Some("".to_owned()),
@@ -381,10 +384,8 @@ pub async fn register_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomGuestAccess,
- content: serde_json::to_value(guest_access::GuestAccessEventContent::new(
- guest_access::GuestAccess::Forbidden,
- ))
- .expect("event is valid, we just created it"),
+ content: to_raw_value(&RoomGuestAccessEventContent::new(GuestAccess::Forbidden))
+ .expect("event is valid, we just created it"),
unsigned: None,
state_key: Some("".to_owned()),
redacts: None,
@@ -402,7 +403,7 @@ pub async fn register_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomName,
- content: serde_json::to_value(name::NameEventContent::new(Some(room_name)))
+ content: to_raw_value(&RoomNameEventContent::new(Some(room_name)))
.expect("event is valid, we just created it"),
unsigned: None,
state_key: Some("".to_owned()),
@@ -417,7 +418,7 @@ pub async fn register_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomTopic,
- content: serde_json::to_value(topic::TopicEventContent {
+ content: to_raw_value(&RoomTopicEventContent {
topic: format!("Manage {}", db.globals.server_name()),
})
.expect("event is valid, we just created it"),
@@ -439,7 +440,7 @@ pub async fn register_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomCanonicalAlias,
- content: serde_json::to_value(canonical_alias::CanonicalAliasEventContent {
+ content: to_raw_value(&RoomCanonicalAliasEventContent {
alias: Some(alias.clone()),
alt_aliases: Vec::new(),
})
@@ -460,8 +461,8 @@ pub async fn register_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomMember,
- content: serde_json::to_value(member::MemberEventContent {
- membership: member::MembershipState::Invite,
+ content: to_raw_value(&RoomMemberEventContent {
+ membership: MembershipState::Invite,
displayname: None,
avatar_url: None,
is_direct: None,
@@ -482,8 +483,8 @@ pub async fn register_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomMember,
- content: serde_json::to_value(member::MemberEventContent {
- membership: member::MembershipState::Join,
+ content: to_raw_value(&RoomMemberEventContent {
+ membership: MembershipState::Join,
displayname: Some(displayname),
avatar_url: None,
is_direct: None,
@@ -506,7 +507,7 @@ pub async fn register_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomMessage,
- content: serde_json::to_value(message::MessageEventContent::text_html(
+ content: to_raw_value(&RoomMessageEventContent::text_html(
"## 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\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`".to_owned(),
"
Thank you for trying out Conduit!
\n
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.
\n
Helpful links:
\n
\n
Website: https://conduit.rs Git and Documentation: https://gitlab.com/famedly/conduit Report issues: https://gitlab.com/famedly/conduit/-/issues
\n
\n
Here are some rooms you can join (by typing the command):
\n
Conduit room (Ask questions and get notified on updates): /join #conduit:fachschaften.org
\n
Conduit lounge (Off-topic, only Conduit users are allowed to join) /join #conduit-lounge:conduit.rs
\n".to_owned(),
))
@@ -562,7 +563,7 @@ pub async fn change_password_route(
let mut uiaainfo = UiaaInfo {
flows: vec![AuthFlow {
- stages: vec!["m.login.password".to_owned()],
+ stages: vec![AuthType::Password],
}],
completed: Vec::new(),
params: Default::default(),
@@ -654,7 +655,7 @@ pub async fn deactivate_route(
let mut uiaainfo = UiaaInfo {
flows: vec![AuthFlow {
- stages: vec!["m.login.password".to_owned()],
+ stages: vec![AuthType::Password],
}],
completed: Vec::new(),
params: Default::default(),
@@ -698,8 +699,8 @@ pub async fn deactivate_route(
for room_id in all_rooms {
let room_id = room_id?;
- let event = member::MemberEventContent {
- membership: member::MembershipState::Leave,
+ let event = RoomMemberEventContent {
+ membership: MembershipState::Leave,
displayname: None,
avatar_url: None,
is_direct: None,
@@ -721,7 +722,7 @@ pub async fn deactivate_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomMember,
- content: serde_json::to_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,
state_key: Some(sender_user.to_string()),
redacts: None,
diff --git a/src/client_server/config.rs b/src/client_server/config.rs
index bd897bab..0c668ff1 100644
--- a/src/client_server/config.rs
+++ b/src/client_server/config.rs
@@ -30,7 +30,7 @@ pub async fn set_global_account_data_route(
) -> ConduitResult {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
- let data = serde_json::from_str::(body.data.get())
+ let data: serde_json::Value = serde_json::from_str(body.data.get())
.map_err(|_| Error::BadRequest(ErrorKind::BadJson, "Data is invalid."))?;
let event_type = body.event_type.to_string();
@@ -68,7 +68,7 @@ pub async fn set_room_account_data_route(
) -> ConduitResult {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
- let data = serde_json::from_str::(body.data.get())
+ let data: serde_json::Value = serde_json::from_str(body.data.get())
.map_err(|_| Error::BadRequest(ErrorKind::BadJson, "Data is invalid."))?;
let event_type = body.event_type.to_string();
@@ -103,9 +103,9 @@ pub async fn get_global_account_data_route(
) -> ConduitResult {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
- let event = db
+ let event: Box = db
.account_data
- .get::>(None, sender_user, body.event_type.clone().into())?
+ .get(None, sender_user, body.event_type.clone().into())?
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Data not found."))?;
let account_data = serde_json::from_str::(event.get())
@@ -132,9 +132,9 @@ pub async fn get_room_account_data_route(
) -> ConduitResult {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
- let event = db
+ let event: Box = db
.account_data
- .get::>(
+ .get(
Some(&body.room_id),
sender_user,
body.event_type.clone().into(),
diff --git a/src/client_server/context.rs b/src/client_server/context.rs
index b2346f5e..97fc4fd8 100644
--- a/src/client_server/context.rs
+++ b/src/client_server/context.rs
@@ -48,7 +48,7 @@ pub async fn get_context_route(
))?
.to_room_event();
- let events_before = db
+ let events_before: Vec<_> = db
.rooms
.pdus_until(sender_user, &body.room_id, base_token)?
.take(
@@ -58,19 +58,19 @@ pub async fn get_context_route(
/ 2,
)
.filter_map(|r| r.ok()) // Remove buggy events
- .collect::>();
+ .collect();
let start_token = events_before
.last()
.and_then(|(pdu_id, _)| db.rooms.pdu_count(pdu_id).ok())
.map(|count| count.to_string());
- let events_before = events_before
+ let events_before: Vec<_> = events_before
.into_iter()
.map(|(_, pdu)| pdu.to_room_event())
- .collect::>();
+ .collect();
- let events_after = db
+ let events_after: Vec<_> = db
.rooms
.pdus_after(sender_user, &body.room_id, base_token)?
.take(
@@ -80,17 +80,17 @@ pub async fn get_context_route(
/ 2,
)
.filter_map(|r| r.ok()) // Remove buggy events
- .collect::>();
+ .collect();
let end_token = events_after
.last()
.and_then(|(pdu_id, _)| db.rooms.pdu_count(pdu_id).ok())
.map(|count| count.to_string());
- let events_after = events_after
+ let events_after: Vec<_> = events_after
.into_iter()
.map(|(_, pdu)| pdu.to_room_event())
- .collect::>();
+ .collect();
let mut resp = get_context::Response::new();
resp.start = start_token;
diff --git a/src/client_server/device.rs b/src/client_server/device.rs
index 100b591f..03a3004b 100644
--- a/src/client_server/device.rs
+++ b/src/client_server/device.rs
@@ -3,7 +3,7 @@ use ruma::api::client::{
error::ErrorKind,
r0::{
device::{self, delete_device, delete_devices, get_device, get_devices, update_device},
- uiaa::{AuthFlow, UiaaInfo},
+ uiaa::{AuthFlow, AuthType, UiaaInfo},
},
};
@@ -25,11 +25,11 @@ pub async fn get_devices_route(
) -> ConduitResult {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
- let devices = db
+ let devices: Vec = db
.users
.all_devices_metadata(sender_user)
.filter_map(|r| r.ok()) // Filter out buggy devices
- .collect::>();
+ .collect();
Ok(get_devices::Response { devices }.into())
}
@@ -109,7 +109,7 @@ pub async fn delete_device_route(
// UIAA
let mut uiaainfo = UiaaInfo {
flows: vec![AuthFlow {
- stages: vec!["m.login.password".to_owned()],
+ stages: vec![AuthType::Password],
}],
completed: Vec::new(),
params: Default::default(),
@@ -172,7 +172,7 @@ pub async fn delete_devices_route(
// UIAA
let mut uiaainfo = UiaaInfo {
flows: vec![AuthFlow {
- stages: vec!["m.login.password".to_owned()],
+ stages: vec![AuthType::Password],
}],
completed: Vec::new(),
params: Default::default(),
diff --git a/src/client_server/directory.rs b/src/client_server/directory.rs
index 0065e51a..490f7524 100644
--- a/src/client_server/directory.rs
+++ b/src/client_server/directory.rs
@@ -17,10 +17,16 @@ use ruma::{
},
directory::{Filter, IncomingFilter, IncomingRoomNetwork, PublicRoomsChunk, RoomNetwork},
events::{
- room::{avatar, canonical_alias, guest_access, history_visibility, name, topic},
+ room::{
+ avatar::RoomAvatarEventContent,
+ canonical_alias::RoomCanonicalAliasEventContent,
+ guest_access::{GuestAccess, RoomGuestAccessEventContent},
+ history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent},
+ name::RoomNameEventContent,
+ topic::RoomTopicEventContent,
+ },
EventType,
},
- serde::Raw,
ServerName, UInt,
};
use tracing::{info, warn};
@@ -217,167 +223,139 @@ pub(crate) async fn get_public_rooms_filtered_helper(
}
}
- let mut all_rooms =
- db.rooms
- .public_rooms()
- .map(|room_id| {
- let room_id = room_id?;
+ let mut all_rooms: Vec<_> = db
+ .rooms
+ .public_rooms()
+ .map(|room_id| {
+ let room_id = room_id?;
- let chunk = PublicRoomsChunk {
- aliases: Vec::new(),
- canonical_alias: db
- .rooms
- .room_state_get(&room_id, &EventType::RoomCanonicalAlias, "")?
- .map_or(Ok::<_, Error>(None), |s| {
- Ok(serde_json::from_value::<
- Raw,
- >(s.content.clone())
- .expect("from_value::> can never fail")
- .deserialize()
+ let chunk = PublicRoomsChunk {
+ aliases: Vec::new(),
+ canonical_alias: db
+ .rooms
+ .room_state_get(&room_id, &EventType::RoomCanonicalAlias, "")?
+ .map_or(Ok(None), |s| {
+ serde_json::from_str(s.content.get())
+ .map(|c: RoomCanonicalAliasEventContent| c.alias)
.map_err(|_| {
Error::bad_database("Invalid canonical alias event in database.")
- })?
- .alias)
- })?,
- name: db
- .rooms
- .room_state_get(&room_id, &EventType::RoomName, "")?
- .map_or(Ok::<_, Error>(None), |s| {
- Ok(serde_json::from_value::>(
- s.content.clone(),
- )
- .expect("from_value::> can never fail")
- .deserialize()
+ })
+ })?,
+ name: db
+ .rooms
+ .room_state_get(&room_id, &EventType::RoomName, "")?
+ .map_or(Ok(None), |s| {
+ serde_json::from_str(s.content.get())
+ .map(|c: RoomNameEventContent| c.name)
.map_err(|_| {
Error::bad_database("Invalid room name event in database.")
- })?
- .name)
- })?,
- num_joined_members: db
- .rooms
- .room_joined_count(&room_id)?
- .unwrap_or_else(|| {
- warn!("Room {} has no member count", room_id);
- 0
- })
- .try_into()
- .expect("user count should not be that big"),
- topic: db
- .rooms
- .room_state_get(&room_id, &EventType::RoomTopic, "")?
- .map_or(Ok::<_, Error>(None), |s| {
- Ok(Some(
- serde_json::from_value::>(
- s.content.clone(),
- )
- .expect("from_value::> can never fail")
- .deserialize()
- .map_err(|_| {
- Error::bad_database("Invalid room topic event in database.")
- })?
- .topic,
- ))
- })?,
- world_readable: db
- .rooms
- .room_state_get(&room_id, &EventType::RoomHistoryVisibility, "")?
- .map_or(Ok::<_, Error>(false), |s| {
- Ok(serde_json::from_value::<
- Raw,
- >(s.content.clone())
- .expect("from_value::> can never fail")
- .deserialize()
+ })
+ })?,
+ num_joined_members: db
+ .rooms
+ .room_joined_count(&room_id)?
+ .unwrap_or_else(|| {
+ warn!("Room {} has no member count", room_id);
+ 0
+ })
+ .try_into()
+ .expect("user count should not be that big"),
+ topic: db
+ .rooms
+ .room_state_get(&room_id, &EventType::RoomTopic, "")?
+ .map_or(Ok(None), |s| {
+ serde_json::from_str(s.content.get())
+ .map(|c: RoomTopicEventContent| Some(c.topic))
+ .map_err(|_| {
+ Error::bad_database("Invalid room topic event in database.")
+ })
+ })?,
+ world_readable: db
+ .rooms
+ .room_state_get(&room_id, &EventType::RoomHistoryVisibility, "")?
+ .map_or(Ok(false), |s| {
+ serde_json::from_str(s.content.get())
+ .map(|c: RoomHistoryVisibilityEventContent| {
+ c.history_visibility == HistoryVisibility::WorldReadable
+ })
.map_err(|_| {
Error::bad_database(
"Invalid room history visibility event in database.",
)
- })?
- .history_visibility
- == history_visibility::HistoryVisibility::WorldReadable)
- })?,
- guest_can_join: db
- .rooms
- .room_state_get(&room_id, &EventType::RoomGuestAccess, "")?
- .map_or(Ok::<_, Error>(false), |s| {
- Ok(
- serde_json::from_value::>(
- s.content.clone(),
- )
- .expect("from_value::> can never fail")
- .deserialize()
+ })
+ })?,
+ guest_can_join: db
+ .rooms
+ .room_state_get(&room_id, &EventType::RoomGuestAccess, "")?
+ .map_or(Ok(false), |s| {
+ serde_json::from_str(s.content.get())
+ .map(|c: RoomGuestAccessEventContent| {
+ c.guest_access == GuestAccess::CanJoin
+ })
.map_err(|_| {
Error::bad_database("Invalid room guest access event in database.")
- })?
- .guest_access
- == guest_access::GuestAccess::CanJoin,
- )
- })?,
- avatar_url: db
- .rooms
- .room_state_get(&room_id, &EventType::RoomAvatar, "")?
- .map(|s| {
- Ok::<_, Error>(
- serde_json::from_value::>(
- s.content.clone(),
- )
- .expect("from_value::> can never fail")
- .deserialize()
- .map_err(|_| {
- Error::bad_database("Invalid room avatar event in database.")
- })?
- .url,
- )
- })
- .transpose()?
- // url is now an Option so we must flatten
- .flatten(),
- room_id,
- };
- Ok(chunk)
- })
- .filter_map(|r: Result<_>| r.ok()) // Filter out buggy rooms
- .filter(|chunk| {
- if let Some(query) = filter
- .generic_search_term
- .as_ref()
- .map(|q| q.to_lowercase())
- {
- if let Some(name) = &chunk.name {
- if name.as_str().to_lowercase().contains(&query) {
- return true;
- }
+ })
+ })?,
+ avatar_url: db
+ .rooms
+ .room_state_get(&room_id, &EventType::RoomAvatar, "")?
+ .map(|s| {
+ serde_json::from_str(s.content.get())
+ .map(|c: RoomAvatarEventContent| c.url)
+ .map_err(|_| {
+ Error::bad_database("Invalid room avatar event in database.")
+ })
+ })
+ .transpose()?
+ // url is now an Option so we must flatten
+ .flatten(),
+ room_id,
+ };
+ Ok(chunk)
+ })
+ .filter_map(|r: Result<_>| r.ok()) // Filter out buggy rooms
+ .filter(|chunk| {
+ if let Some(query) = filter
+ .generic_search_term
+ .as_ref()
+ .map(|q| q.to_lowercase())
+ {
+ if let Some(name) = &chunk.name {
+ if name.as_str().to_lowercase().contains(&query) {
+ return true;
}
-
- if let Some(topic) = &chunk.topic {
- if topic.to_lowercase().contains(&query) {
- return true;
- }
- }
-
- if let Some(canonical_alias) = &chunk.canonical_alias {
- if canonical_alias.as_str().to_lowercase().contains(&query) {
- return true;
- }
- }
-
- false
- } else {
- // No search term
- true
}
- })
- // We need to collect all, so we can sort by member count
- .collect::>();
+
+ if let Some(topic) = &chunk.topic {
+ if topic.to_lowercase().contains(&query) {
+ return true;
+ }
+ }
+
+ if let Some(canonical_alias) = &chunk.canonical_alias {
+ if canonical_alias.as_str().to_lowercase().contains(&query) {
+ return true;
+ }
+ }
+
+ false
+ } else {
+ // No search term
+ true
+ }
+ })
+ // We need to collect all, so we can sort by member count
+ .collect();
all_rooms.sort_by(|l, r| r.num_joined_members.cmp(&l.num_joined_members));
let total_room_count_estimate = (all_rooms.len() as u32).into();
- let chunk = all_rooms
+ let chunk: Vec<_> = all_rooms
.into_iter()
.skip(num_since as usize)
.take(limit as usize)
- .collect::>();
+ .collect();
let prev_batch = if num_since == 0 {
None
diff --git a/src/client_server/keys.rs b/src/client_server/keys.rs
index a74c4097..a44f5e9c 100644
--- a/src/client_server/keys.rs
+++ b/src/client_server/keys.rs
@@ -10,7 +10,7 @@ use ruma::{
claim_keys, get_key_changes, get_keys, upload_keys, upload_signatures,
upload_signing_keys,
},
- uiaa::{AuthFlow, UiaaInfo},
+ uiaa::{AuthFlow, AuthType, UiaaInfo},
},
},
federation,
@@ -148,7 +148,7 @@ pub async fn upload_signing_keys_route(
// UIAA
let mut uiaainfo = UiaaInfo {
flows: vec![AuthFlow {
- stages: vec!["m.login.password".to_owned()],
+ stages: vec![AuthType::Password],
}],
completed: Vec::new(),
params: Default::default(),
@@ -395,7 +395,7 @@ pub(crate) async fn get_keys_helper bool>(
let mut failures = BTreeMap::new();
- let mut futures = get_over_federation
+ let mut futures: FuturesUnordered<_> = get_over_federation
.into_iter()
.map(|(server, vec)| async move {
let mut device_keys_input_fed = BTreeMap::new();
@@ -415,7 +415,7 @@ pub(crate) async fn get_keys_helper bool>(
.await,
)
})
- .collect::>();
+ .collect();
while let Some((server, response)) = futures.next().await {
match response {
diff --git a/src/client_server/membership.rs b/src/client_server/membership.rs
index 146af791..732f6162 100644
--- a/src/client_server/membership.rs
+++ b/src/client_server/membership.rs
@@ -1,10 +1,9 @@
use crate::{
client_server,
database::DatabaseGuard,
- pdu::{PduBuilder, PduEvent},
+ pdu::{EventHash, PduBuilder, PduEvent},
server_server, utils, ConduitResult, Database, Error, Result, Ruma,
};
-use member::{MemberEventContent, MembershipState};
use ruma::{
api::{
client::{
@@ -18,14 +17,17 @@ use ruma::{
federation::{self, membership::create_invite},
},
events::{
- pdu::Pdu,
- room::{create::CreateEventContent, member},
+ room::{
+ create::RoomCreateEventContent,
+ member::{MembershipState, RoomMemberEventContent},
+ },
EventType,
},
- serde::{to_canonical_value, CanonicalJsonObject, CanonicalJsonValue, Raw},
+ serde::{to_canonical_value, CanonicalJsonObject, CanonicalJsonValue},
state_res::{self, RoomVersion},
uint, EventId, RoomId, RoomVersionId, ServerName, UserId,
};
+use serde_json::value::{to_raw_value, RawValue as RawJsonValue};
use std::{
collections::{hash_map::Entry, BTreeMap, HashMap, HashSet},
convert::{TryFrom, TryInto},
@@ -54,19 +56,17 @@ pub async fn join_room_by_id_route(
) -> ConduitResult {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
- let mut servers = db
+ let mut servers: HashSet<_> = db
.rooms
.invite_state(sender_user, &body.room_id)?
.unwrap_or_default()
.iter()
- .filter_map(|event| {
- serde_json::from_str::(&event.json().to_string()).ok()
- })
- .filter_map(|event| event.get("sender").cloned())
+ .filter_map(|event| serde_json::from_str(event.json().get()).ok())
+ .filter_map(|event: serde_json::Value| event.get("sender").cloned())
.filter_map(|sender| sender.as_str().map(|s| s.to_owned()))
.filter_map(|sender| UserId::try_from(sender).ok())
.map(|user| user.server_name().to_owned())
- .collect::>();
+ .collect();
servers.insert(body.room_id.server_name().to_owned());
@@ -103,19 +103,17 @@ pub async fn join_room_by_id_or_alias_route(
let (servers, room_id) = match RoomId::try_from(body.room_id_or_alias.clone()) {
Ok(room_id) => {
- let mut servers = db
+ let mut servers: HashSet<_> = db
.rooms
.invite_state(sender_user, &room_id)?
.unwrap_or_default()
.iter()
- .filter_map(|event| {
- serde_json::from_str::(&event.json().to_string()).ok()
- })
- .filter_map(|event| event.get("sender").cloned())
+ .filter_map(|event| serde_json::from_str(event.json().get()).ok())
+ .filter_map(|event: serde_json::Value| event.get("sender").cloned())
.filter_map(|sender| sender.as_str().map(|s| s.to_owned()))
.filter_map(|sender| UserId::try_from(sender).ok())
.map(|user| user.server_name().to_owned())
- .collect::>();
+ .collect();
servers.insert(room_id.server_name().to_owned());
(servers, room_id)
@@ -204,7 +202,7 @@ pub async fn kick_user_route(
) -> ConduitResult {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
- let mut event = serde_json::from_value::>(
+ let mut event: RoomMemberEventContent = serde_json::from_str(
db.rooms
.room_state_get(
&body.room_id,
@@ -216,13 +214,11 @@ pub async fn kick_user_route(
"Cannot kick member that's not in the room.",
))?
.content
- .clone(),
+ .get(),
)
- .expect("Raw::from_value always works")
- .deserialize()
.map_err(|_| Error::bad_database("Invalid member event in database."))?;
- event.membership = ruma::events::room::member::MembershipState::Leave;
+ event.membership = MembershipState::Leave;
// TODO: reason
let mutex_state = Arc::clone(
@@ -238,7 +234,7 @@ pub async fn kick_user_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomMember,
- content: serde_json::to_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,
state_key: Some(body.user_id.to_string()),
redacts: None,
@@ -280,8 +276,8 @@ pub async fn ban_user_route(
&body.user_id.to_string(),
)?
.map_or(
- Ok::<_, Error>(member::MemberEventContent {
- membership: member::MembershipState::Ban,
+ Ok(RoomMemberEventContent {
+ membership: MembershipState::Ban,
displayname: db.users.displayname(&body.user_id)?,
avatar_url: db.users.avatar_url(&body.user_id)?,
is_direct: None,
@@ -290,14 +286,12 @@ pub async fn ban_user_route(
reason: None,
}),
|event| {
- let mut event = serde_json::from_value::>(
- event.content.clone(),
- )
- .expect("Raw::from_value always works")
- .deserialize()
- .map_err(|_| Error::bad_database("Invalid member event in database."))?;
- event.membership = ruma::events::room::member::MembershipState::Ban;
- Ok(event)
+ serde_json::from_str(event.content.get())
+ .map(|event: RoomMemberEventContent| RoomMemberEventContent {
+ membership: MembershipState::Ban,
+ ..event
+ })
+ .map_err(|_| Error::bad_database("Invalid member event in database."))
},
)?;
@@ -314,7 +308,7 @@ pub async fn ban_user_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomMember,
- content: serde_json::to_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,
state_key: Some(body.user_id.to_string()),
redacts: None,
@@ -346,7 +340,7 @@ pub async fn unban_user_route(
) -> ConduitResult {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
- let mut event = serde_json::from_value::>(
+ let mut event: RoomMemberEventContent = serde_json::from_str(
db.rooms
.room_state_get(
&body.room_id,
@@ -358,13 +352,11 @@ pub async fn unban_user_route(
"Cannot unban a user who is not banned.",
))?
.content
- .clone(),
+ .get(),
)
- .expect("from_value::> can never fail")
- .deserialize()
.map_err(|_| Error::bad_database("Invalid member event in database."))?;
- event.membership = ruma::events::room::member::MembershipState::Leave;
+ event.membership = MembershipState::Leave;
let mutex_state = Arc::clone(
db.globals
@@ -379,7 +371,7 @@ pub async fn unban_user_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomMember,
- content: serde_json::to_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,
state_key: Some(body.user_id.to_string()),
redacts: None,
@@ -583,11 +575,10 @@ async fn join_room_by_id_helper(
_ => return Err(Error::BadServerResponse("Room version is not supported")),
};
- let mut join_event_stub =
- serde_json::from_str::(make_join_response.event.json().get())
- .map_err(|_| {
- Error::BadServerResponse("Invalid make_join event json received from server.")
- })?;
+ let mut join_event_stub: CanonicalJsonObject =
+ serde_json::from_str(make_join_response.event.get()).map_err(|_| {
+ Error::BadServerResponse("Invalid make_join event json received from server.")
+ })?;
// TODO: Is origin needed?
join_event_stub.insert(
@@ -604,8 +595,8 @@ async fn join_room_by_id_helper(
);
join_event_stub.insert(
"content".to_owned(),
- to_canonical_value(member::MemberEventContent {
- membership: member::MembershipState::Join,
+ to_canonical_value(RoomMemberEventContent {
+ membership: MembershipState::Join,
displayname: db.users.displayname(sender_user)?,
avatar_url: db.users.avatar_url(sender_user)?,
is_direct: None,
@@ -653,7 +644,7 @@ async fn join_room_by_id_helper(
federation::membership::create_join_event::v2::Request {
room_id,
event_id: &event_id,
- pdu: PduEvent::convert_to_outgoing_federation_event(join_event.clone()),
+ pdu: &PduEvent::convert_to_outgoing_federation_event(join_event.clone()),
},
)
.await?;
@@ -723,7 +714,7 @@ async fn join_room_by_id_helper(
state
.into_iter()
.map(|(k, id)| db.rooms.compress_state_event(k, &id, &db.globals))
- .collect::>>()?,
+ .collect::>()?,
db,
)?;
@@ -756,8 +747,8 @@ async fn join_room_by_id_helper(
// where events in the current room state do not exist
db.rooms.set_room_state(room_id, statehashid)?;
} else {
- let event = member::MemberEventContent {
- membership: member::MembershipState::Join,
+ let event = RoomMemberEventContent {
+ membership: MembershipState::Join,
displayname: db.users.displayname(sender_user)?,
avatar_url: db.users.avatar_url(sender_user)?,
is_direct: None,
@@ -769,7 +760,7 @@ async fn join_room_by_id_helper(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomMember,
- content: serde_json::to_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,
state_key: Some(sender_user.to_string()),
redacts: None,
@@ -789,12 +780,12 @@ async fn join_room_by_id_helper(
}
fn validate_and_add_event_id(
- pdu: &Raw,
+ pdu: &RawJsonValue,
room_version: &RoomVersionId,
pub_key_map: &RwLock>>,
db: &Database,
) -> Result<(EventId, CanonicalJsonObject)> {
- let mut value = serde_json::from_str::(pdu.json().get()).map_err(|e| {
+ let mut value: CanonicalJsonObject = serde_json::from_str(pdu.get()).map_err(|e| {
error!("Invalid PDU in server response: {:?}: {:?}", pdu, e);
Error::BadServerResponse("Invalid PDU in server response")
})?;
@@ -870,27 +861,24 @@ pub(crate) async fn invite_helper<'a>(
);
let state_lock = mutex_state.lock().await;
- let prev_events = db
+ let prev_events: Vec<_> = db
.rooms
.get_pdu_leaves(room_id)?
.into_iter()
.take(20)
- .collect::>();
+ .collect();
let create_event = db
.rooms
.room_state_get(room_id, &EventType::RoomCreate, "")?;
- let create_event_content = create_event
+ let create_event_content: Option = create_event
.as_ref()
.map(|create_event| {
- serde_json::from_value::>(create_event.content.clone())
- .expect("Raw::from_value always works.")
- .deserialize()
- .map_err(|e| {
- warn!("Invalid create event: {}", e);
- Error::bad_database("Invalid create event in db.")
- })
+ serde_json::from_str(create_event.content.get()).map_err(|e| {
+ warn!("Invalid create event: {}", e);
+ Error::bad_database("Invalid create event in db.")
+ })
})
.transpose()?;
@@ -910,7 +898,7 @@ pub(crate) async fn invite_helper<'a>(
let room_version =
RoomVersion::new(&room_version_id).expect("room version is supported");
- let content = serde_json::to_value(MemberEventContent {
+ let content = to_raw_value(&RoomMemberEventContent {
avatar_url: None,
displayname: None,
is_direct: Some(is_direct),
@@ -946,7 +934,7 @@ pub(crate) async fn invite_helper<'a>(
unsigned.insert("prev_content".to_owned(), prev_pdu.content.clone());
unsigned.insert(
"prev_sender".to_owned(),
- serde_json::to_value(&prev_pdu.sender).expect("UserId::to_value always works"),
+ serde_json::from_str(prev_pdu.sender.as_str()).expect("UserId is valid string"),
);
}
@@ -967,11 +955,15 @@ pub(crate) async fn invite_helper<'a>(
.map(|(_, pdu)| pdu.event_id.clone())
.collect(),
redacts: None,
- unsigned,
- hashes: ruma::events::pdu::EventHash {
+ unsigned: if unsigned.is_empty() {
+ None
+ } else {
+ Some(to_raw_value(&unsigned).expect("to_raw_value always works"))
+ },
+ hashes: EventHash {
sha256: "aaa".to_owned(),
},
- signatures: BTreeMap::new(),
+ signatures: None,
};
let auth_check = state_res::auth_check(
@@ -1035,11 +1027,11 @@ pub(crate) async fn invite_helper<'a>(
&db.globals,
user_id.server_name(),
create_invite::v2::Request {
- room_id: room_id.clone(),
- event_id: expected_event_id.clone(),
- room_version: room_version_id,
- event: PduEvent::convert_to_outgoing_federation_event(pdu_json.clone()),
- invite_room_state,
+ room_id,
+ event_id: &expected_event_id,
+ room_version: &room_version_id,
+ event: &PduEvent::convert_to_outgoing_federation_event(pdu_json.clone()),
+ invite_room_state: &invite_room_state,
},
)
.await?;
@@ -1062,7 +1054,7 @@ pub(crate) async fn invite_helper<'a>(
warn!("Server {} changed invite event, that's not allowed in the spec: ours: {:?}, theirs: {:?}", user_id.server_name(), pdu_json, value);
}
- let origin = serde_json::from_value::>(
+ let origin: Box = serde_json::from_value(
serde_json::to_value(value.get("origin").ok_or(Error::BadRequest(
ErrorKind::InvalidParam,
"Event needs an origin field.",
@@ -1116,8 +1108,8 @@ pub(crate) async fn invite_helper<'a>(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomMember,
- content: serde_json::to_value(member::MemberEventContent {
- membership: member::MembershipState::Invite,
+ content: to_raw_value(&RoomMemberEventContent {
+ membership: MembershipState::Invite,
displayname: db.users.displayname(user_id)?,
avatar_url: db.users.avatar_url(user_id)?,
is_direct: Some(is_direct),
diff --git a/src/client_server/message.rs b/src/client_server/message.rs
index 25964cc2..abbbe8ea 100644
--- a/src/client_server/message.rs
+++ b/src/client_server/message.rs
@@ -140,14 +140,11 @@ pub async fn get_message_events_route(
let to = body.to.as_ref().map(|t| t.parse());
// Use limit or else 10
- let limit = body
- .limit
- .try_into()
- .map_or(Ok::<_, Error>(10_usize), |l: u32| Ok(l as usize))?;
+ let limit = body.limit.try_into().map_or(10_usize, |l: u32| l as usize);
match body.dir {
get_message_events::Direction::Forward => {
- let events_after = db
+ let events_after: Vec<_> = db
.rooms
.pdus_after(sender_user, &body.room_id, from)?
.take(limit)
@@ -159,14 +156,14 @@ pub async fn get_message_events_route(
.ok()
})
.take_while(|&(k, _)| Some(Ok(k)) != to) // Stop at `to`
- .collect::>();
+ .collect();
let end_token = events_after.last().map(|(count, _)| count.to_string());
- let events_after = events_after
+ let events_after: Vec<_> = events_after
.into_iter()
.map(|(_, pdu)| pdu.to_room_event())
- .collect::>();
+ .collect();
let mut resp = get_message_events::Response::new();
resp.start = Some(body.from.to_owned());
@@ -177,7 +174,7 @@ pub async fn get_message_events_route(
Ok(resp.into())
}
get_message_events::Direction::Backward => {
- let events_before = db
+ let events_before: Vec<_> = db
.rooms
.pdus_until(sender_user, &body.room_id, from)?
.take(limit)
@@ -189,14 +186,14 @@ pub async fn get_message_events_route(
.ok()
})
.take_while(|&(k, _)| Some(Ok(k)) != to) // Stop at `to`
- .collect::>();
+ .collect();
let start_token = events_before.last().map(|(count, _)| count.to_string());
- let events_before = events_before
+ let events_before: Vec<_> = events_before
.into_iter()
.map(|(_, pdu)| pdu.to_room_event())
- .collect::>();
+ .collect();
let mut resp = get_message_events::Response::new();
resp.start = Some(body.from.to_owned());
diff --git a/src/client_server/profile.rs b/src/client_server/profile.rs
index ab7fb024..29b1ae87 100644
--- a/src/client_server/profile.rs
+++ b/src/client_server/profile.rs
@@ -9,9 +9,9 @@ use ruma::{
},
federation::{self, query::get_profile_information::v1::ProfileField},
},
- events::EventType,
- serde::Raw,
+ events::{room::member::RoomMemberEventContent, EventType},
};
+use serde_json::value::to_raw_value;
use std::{convert::TryInto, sync::Arc};
#[cfg(feature = "conduit_bin")]
@@ -45,9 +45,9 @@ pub async fn set_displayname_route(
Ok::<_, Error>((
PduBuilder {
event_type: EventType::RoomMember,
- content: serde_json::to_value(ruma::events::room::member::MemberEventContent {
+ content: to_raw_value(&RoomMemberEventContent {
displayname: body.displayname.clone(),
- ..serde_json::from_value::>(
+ ..serde_json::from_str(
db.rooms
.room_state_get(
&room_id,
@@ -61,10 +61,8 @@ pub async fn set_displayname_route(
)
})?
.content
- .clone(),
+ .get(),
)
- .expect("from_value::> can never fail")
- .deserialize()
.map_err(|_| Error::bad_database("Database contains invalid PDU."))?
})
.expect("event is valid, we just created it"),
@@ -190,9 +188,9 @@ pub async fn set_avatar_url_route(
Ok::<_, Error>((
PduBuilder {
event_type: EventType::RoomMember,
- content: serde_json::to_value(ruma::events::room::member::MemberEventContent {
+ content: to_raw_value(&RoomMemberEventContent {
avatar_url: body.avatar_url.clone(),
- ..serde_json::from_value::>(
+ ..serde_json::from_str(
db.rooms
.room_state_get(
&room_id,
@@ -206,10 +204,8 @@ pub async fn set_avatar_url_route(
)
})?
.content
- .clone(),
+ .get(),
)
- .expect("from_value::> can never fail")
- .deserialize()
.map_err(|_| Error::bad_database("Database contains invalid PDU."))?
})
.expect("event is valid, we just created it"),
diff --git a/src/client_server/push.rs b/src/client_server/push.rs
index 98555d09..64f27f1c 100644
--- a/src/client_server/push.rs
+++ b/src/client_server/push.rs
@@ -8,7 +8,7 @@ use ruma::{
set_pushrule_enabled, RuleKind,
},
},
- events::{push_rules, EventType},
+ events::{push_rules::PushRulesEvent, EventType},
push::{ConditionalPushRuleInit, PatternedPushRuleInit, SimplePushRuleInit},
};
@@ -29,9 +29,9 @@ pub async fn get_pushrules_all_route(
) -> ConduitResult {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
- let event = db
+ let event: PushRulesEvent = db
.account_data
- .get::(None, sender_user, EventType::PushRules)?
+ .get(None, sender_user, EventType::PushRules)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"PushRules event not found.",
@@ -57,9 +57,9 @@ pub async fn get_pushrule_route(
) -> ConduitResult {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
- let event = db
+ let event: PushRulesEvent = db
.account_data
- .get::(None, sender_user, EventType::PushRules)?
+ .get(None, sender_user, EventType::PushRules)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"PushRules event not found.",
@@ -122,9 +122,9 @@ pub async fn set_pushrule_route(
));
}
- let mut event = db
+ let mut event: PushRulesEvent = db
.account_data
- .get::(None, sender_user, EventType::PushRules)?
+ .get(None, sender_user, EventType::PushRules)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"PushRules event not found.",
@@ -222,9 +222,9 @@ pub async fn get_pushrule_actions_route(
));
}
- let mut event = db
+ let mut event: PushRulesEvent = db
.account_data
- .get::(None, sender_user, EventType::PushRules)?
+ .get(None, sender_user, EventType::PushRules)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"PushRules event not found.",
@@ -284,9 +284,9 @@ pub async fn set_pushrule_actions_route(
));
}
- let mut event = db
+ let mut event: PushRulesEvent = db
.account_data
- .get::(None, sender_user, EventType::PushRules)?
+ .get(None, sender_user, EventType::PushRules)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"PushRules event not found.",
@@ -356,9 +356,9 @@ pub async fn get_pushrule_enabled_route(
));
}
- let mut event = db
+ let mut event: PushRulesEvent = db
.account_data
- .get::(None, sender_user, EventType::PushRules)?
+ .get(None, sender_user, EventType::PushRules)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"PushRules event not found.",
@@ -420,9 +420,9 @@ pub async fn set_pushrule_enabled_route(
));
}
- let mut event = db
+ let mut event: PushRulesEvent = db
.account_data
- .get::(None, sender_user, EventType::PushRules)?
+ .get(None, sender_user, EventType::PushRules)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"PushRules event not found.",
@@ -497,9 +497,9 @@ pub async fn delete_pushrule_route(
));
}
- let mut event = db
+ let mut event: PushRulesEvent = db
.account_data
- .get::(None, sender_user, EventType::PushRules)?
+ .get(None, sender_user, EventType::PushRules)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"PushRules event not found.",
diff --git a/src/client_server/redact.rs b/src/client_server/redact.rs
index 4b5219b2..7435c5c5 100644
--- a/src/client_server/redact.rs
+++ b/src/client_server/redact.rs
@@ -3,11 +3,12 @@ use std::sync::Arc;
use crate::{database::DatabaseGuard, pdu::PduBuilder, ConduitResult, Ruma};
use ruma::{
api::client::r0::redact::redact_event,
- events::{room::redaction, EventType},
+ events::{room::redaction::RoomRedactionEventContent, EventType},
};
#[cfg(feature = "conduit_bin")]
use rocket::put;
+use serde_json::value::to_raw_value;
/// # `PUT /_matrix/client/r0/rooms/{roomId}/redact/{eventId}/{txnId}`
///
@@ -38,7 +39,7 @@ pub async fn redact_event_route(
let event_id = db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomRedaction,
- content: serde_json::to_value(redaction::RedactionEventContent {
+ content: to_raw_value(&RoomRedactionEventContent {
reason: body.reason.clone(),
})
.expect("event is valid, we just created it"),
diff --git a/src/client_server/room.rs b/src/client_server/room.rs
index f6c3a50e..2d1fe237 100644
--- a/src/client_server/room.rs
+++ b/src/client_server/room.rs
@@ -8,12 +8,24 @@ use ruma::{
r0::room::{self, aliases, create_room, get_room_event, upgrade_room},
},
events::{
- room::{guest_access, history_visibility, join_rules, member, name, topic},
+ room::{
+ canonical_alias::RoomCanonicalAliasEventContent,
+ create::RoomCreateEventContent,
+ guest_access::{GuestAccess, RoomGuestAccessEventContent},
+ history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent},
+ join_rules::{JoinRule, RoomJoinRulesEventContent},
+ member::{MembershipState, RoomMemberEventContent},
+ name::RoomNameEventContent,
+ power_levels::RoomPowerLevelsEventContent,
+ tombstone::RoomTombstoneEventContent,
+ topic::RoomTopicEventContent,
+ },
EventType,
},
- serde::Raw,
+ serde::JsonObject,
RoomAliasId, RoomId, RoomVersionId,
};
+use serde_json::value::to_raw_value;
use std::{cmp::max, collections::BTreeMap, convert::TryFrom, sync::Arc};
use tracing::{info, warn};
@@ -90,7 +102,7 @@ pub async fn create_room_route(
}
})?;
- let mut content = ruma::events::room::create::CreateEventContent::new(sender_user.clone());
+ let mut content = RoomCreateEventContent::new(sender_user.clone());
content.federate = body.creation_content.federate;
content.predecessor = body.creation_content.predecessor.clone();
content.room_version = match body.room_version.clone() {
@@ -111,7 +123,7 @@ pub async fn create_room_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomCreate,
- content: serde_json::to_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,
state_key: Some("".to_owned()),
redacts: None,
@@ -126,8 +138,8 @@ pub async fn create_room_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomMember,
- content: serde_json::to_value(member::MemberEventContent {
- membership: member::MembershipState::Join,
+ content: to_raw_value(&RoomMemberEventContent {
+ membership: MembershipState::Join,
displayname: db.users.displayname(sender_user)?,
avatar_url: db.users.avatar_url(sender_user)?,
is_direct: Some(body.is_direct),
@@ -167,20 +179,17 @@ pub async fn create_room_route(
}
}
- let mut power_levels_content =
- serde_json::to_value(ruma::events::room::power_levels::PowerLevelsEventContent {
- users,
- ..Default::default()
- })
- .expect("event is valid, we just created it");
+ let mut power_levels_content = serde_json::to_value(RoomPowerLevelsEventContent {
+ users,
+ ..Default::default()
+ })
+ .expect("event is valid, we just created it");
if let Some(power_level_content_override) = &body.power_level_content_override {
- let json = serde_json::from_str::>(
- power_level_content_override.json().get(),
- )
- .map_err(|_| {
- Error::BadRequest(ErrorKind::BadJson, "Invalid power_level_content_override.")
- })?;
+ let json: JsonObject = serde_json::from_str(power_level_content_override.json().get())
+ .map_err(|_| {
+ Error::BadRequest(ErrorKind::BadJson, "Invalid power_level_content_override.")
+ })?;
for (key, value) in json {
power_levels_content[key] = value;
@@ -190,7 +199,8 @@ pub async fn create_room_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomPowerLevels,
- content: power_levels_content,
+ content: to_raw_value(&power_levels_content)
+ .expect("to_raw_value always works on serde_json::Value"),
unsigned: None,
state_key: Some("".to_owned()),
redacts: None,
@@ -206,12 +216,10 @@ pub async fn create_room_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomCanonicalAlias,
- content: serde_json::to_value(
- ruma::events::room::canonical_alias::CanonicalAliasEventContent {
- alias: Some(room_alias_id.clone()),
- alt_aliases: vec![],
- },
- )
+ content: to_raw_value(&RoomCanonicalAliasEventContent {
+ alias: Some(room_alias_id.clone()),
+ alt_aliases: vec![],
+ })
.expect("We checked that alias earlier, it must be fine"),
unsigned: None,
state_key: Some("".to_owned()),
@@ -230,17 +238,12 @@ pub async fn create_room_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomJoinRules,
- content: match preset {
- create_room::RoomPreset::PublicChat => serde_json::to_value(
- join_rules::JoinRulesEventContent::new(join_rules::JoinRule::Public),
- )
- .expect("event is valid, we just created it"),
+ content: to_raw_value(&RoomJoinRulesEventContent::new(match preset {
+ create_room::RoomPreset::PublicChat => JoinRule::Public,
// according to spec "invite" is the default
- _ => serde_json::to_value(join_rules::JoinRulesEventContent::new(
- join_rules::JoinRule::Invite,
- ))
- .expect("event is valid, we just created it"),
- },
+ _ => JoinRule::Invite,
+ }))
+ .expect("event is valid, we just created it"),
unsigned: None,
state_key: Some("".to_owned()),
redacts: None,
@@ -255,8 +258,8 @@ pub async fn create_room_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomHistoryVisibility,
- content: serde_json::to_value(history_visibility::HistoryVisibilityEventContent::new(
- history_visibility::HistoryVisibility::Shared,
+ content: to_raw_value(&RoomHistoryVisibilityEventContent::new(
+ HistoryVisibility::Shared,
))
.expect("event is valid, we just created it"),
unsigned: None,
@@ -273,18 +276,11 @@ pub async fn create_room_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomGuestAccess,
- content: match preset {
- create_room::RoomPreset::PublicChat => {
- serde_json::to_value(guest_access::GuestAccessEventContent::new(
- guest_access::GuestAccess::Forbidden,
- ))
- .expect("event is valid, we just created it")
- }
- _ => serde_json::to_value(guest_access::GuestAccessEventContent::new(
- guest_access::GuestAccess::CanJoin,
- ))
- .expect("event is valid, we just created it"),
- },
+ content: to_raw_value(&RoomGuestAccessEventContent::new(match preset {
+ create_room::RoomPreset::PublicChat => GuestAccess::Forbidden,
+ _ => GuestAccess::CanJoin,
+ }))
+ .expect("event is valid, we just created it"),
unsigned: None,
state_key: Some("".to_owned()),
redacts: None,
@@ -316,7 +312,7 @@ pub async fn create_room_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomName,
- content: serde_json::to_value(name::NameEventContent::new(Some(name.clone())))
+ content: to_raw_value(&RoomNameEventContent::new(Some(name.clone())))
.expect("event is valid, we just created it"),
unsigned: None,
state_key: Some("".to_owned()),
@@ -333,7 +329,7 @@ pub async fn create_room_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomTopic,
- content: serde_json::to_value(topic::TopicEventContent {
+ content: to_raw_value(&RoomTopicEventContent {
topic: topic.clone(),
})
.expect("event is valid, we just created it"),
@@ -487,8 +483,8 @@ pub async fn upgrade_room_route(
let tombstone_event_id = db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomTombstone,
- content: serde_json::to_value(ruma::events::room::tombstone::TombstoneEventContent {
- body: "This room has been replaced".to_string(),
+ content: to_raw_value(&RoomTombstoneEventContent {
+ body: "This room has been replaced".to_owned(),
replacement_room: replacement_room.clone(),
})
.expect("event is valid, we just created it"),
@@ -515,15 +511,13 @@ pub async fn upgrade_room_route(
let state_lock = mutex_state.lock().await;
// Get the old room federations status
- let federate = serde_json::from_value::>(
+ let federate = serde_json::from_str::(
db.rooms
.room_state_get(&body.room_id, &EventType::RoomCreate, "")?
.ok_or_else(|| Error::bad_database("Found room without m.room.create event."))?
.content
- .clone(),
+ .get(),
)
- .expect("Raw::from_value always works")
- .deserialize()
.map_err(|_| Error::bad_database("Invalid room event in database."))?
.federate;
@@ -534,8 +528,7 @@ pub async fn upgrade_room_route(
));
// Send a m.room.create event containing a predecessor field and the applicable room_version
- let mut create_event_content =
- ruma::events::room::create::CreateEventContent::new(sender_user.clone());
+ let mut create_event_content = RoomCreateEventContent::new(sender_user.clone());
create_event_content.federate = federate;
create_event_content.room_version = body.new_version.clone();
create_event_content.predecessor = predecessor;
@@ -543,7 +536,7 @@ pub async fn upgrade_room_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomCreate,
- content: serde_json::to_value(create_event_content)
+ content: to_raw_value(&create_event_content)
.expect("event is valid, we just created it"),
unsigned: None,
state_key: Some("".to_owned()),
@@ -559,8 +552,8 @@ pub async fn upgrade_room_route(
db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomMember,
- content: serde_json::to_value(member::MemberEventContent {
- membership: member::MembershipState::Join,
+ content: to_raw_value(&RoomMemberEventContent {
+ membership: MembershipState::Join,
displayname: db.users.displayname(sender_user)?,
avatar_url: db.users.avatar_url(sender_user)?,
is_direct: None,
@@ -621,17 +614,14 @@ pub async fn upgrade_room_route(
}
// Get the old room power levels
- let mut power_levels_event_content =
- serde_json::from_value::>(
- db.rooms
- .room_state_get(&body.room_id, &EventType::RoomPowerLevels, "")?
- .ok_or_else(|| Error::bad_database("Found room without m.room.create event."))?
- .content
- .clone(),
- )
- .expect("database contains invalid PDU")
- .deserialize()
- .map_err(|_| Error::bad_database("Invalid room event in database."))?;
+ let mut power_levels_event_content: RoomPowerLevelsEventContent = serde_json::from_str(
+ db.rooms
+ .room_state_get(&body.room_id, &EventType::RoomPowerLevels, "")?
+ .ok_or_else(|| Error::bad_database("Found room without m.room.create event."))?
+ .content
+ .get(),
+ )
+ .map_err(|_| Error::bad_database("Invalid room event in database."))?;
// Setting events_default and invite to the greater of 50 and users_default + 1
let new_level = max(
@@ -645,7 +635,7 @@ pub async fn upgrade_room_route(
let _ = db.rooms.build_and_append_pdu(
PduBuilder {
event_type: EventType::RoomPowerLevels,
- content: serde_json::to_value(power_levels_event_content)
+ content: to_raw_value(&power_levels_event_content)
.expect("event is valid, we just created it"),
unsigned: None,
state_key: Some("".to_owned()),
diff --git a/src/client_server/search.rs b/src/client_server/search.rs
index 9ff1a1bd..59c9480a 100644
--- a/src/client_server/search.rs
+++ b/src/client_server/search.rs
@@ -74,7 +74,7 @@ pub async fn search_events_route(
}
}
- let results = results
+ let results: Vec<_> = results
.iter()
.map(|result| {
Ok::<_, Error>(SearchResult {
@@ -95,7 +95,7 @@ pub async fn search_events_route(
.filter_map(|r| r.ok())
.skip(skip)
.take(limit)
- .collect::>();
+ .collect();
let next_batch = if results.len() < limit as usize {
None
@@ -114,7 +114,7 @@ pub async fn search_events_route(
.search_term
.split_terminator(|c: char| !c.is_alphanumeric())
.map(str::to_lowercase)
- .collect::>(),
+ .collect(),
},
})
.into())
diff --git a/src/client_server/session.rs b/src/client_server/session.rs
index b42689d2..61e5519a 100644
--- a/src/client_server/session.rs
+++ b/src/client_server/session.rs
@@ -60,10 +60,10 @@ pub async fn login_route(
// Validate login method
// TODO: Other login methods
let user_id = match &body.login_info {
- login::IncomingLoginInfo::Password {
+ login::IncomingLoginInfo::Password(login::IncomingPassword {
identifier,
password,
- } => {
+ }) => {
let username = if let IncomingUserIdentifier::MatrixId(matrix_id) = identifier {
matrix_id
} else {
@@ -97,7 +97,7 @@ pub async fn login_route(
user_id
}
- login::IncomingLoginInfo::Token { token } => {
+ login::IncomingLoginInfo::Token(login::IncomingToken { token }) => {
if let Some(jwt_decoding_key) = db.globals.jwt_decoding_key() {
let token = jsonwebtoken::decode::(
token,
@@ -116,6 +116,12 @@ pub async fn login_route(
));
}
}
+ _ => {
+ return Err(Error::BadRequest(
+ ErrorKind::Unknown,
+ "Unsupported login type.",
+ ));
+ }
};
// Generate new device id if the user didn't specify one
diff --git a/src/client_server/state.rs b/src/client_server/state.rs
index 7618dcc4..307bccab 100644
--- a/src/client_server/state.rs
+++ b/src/client_server/state.rs
@@ -10,8 +10,8 @@ use ruma::{
},
events::{
room::{
- canonical_alias::CanonicalAliasEventContent,
- history_visibility::{HistoryVisibility, HistoryVisibilityEventContent},
+ canonical_alias::RoomCanonicalAliasEventContent,
+ history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent},
},
AnyStateEventContent, EventType,
},
@@ -120,13 +120,13 @@ pub async fn get_state_events_route(
db.rooms
.room_state_get(&body.room_id, &EventType::RoomHistoryVisibility, "")?
.map(|event| {
- serde_json::from_value::(event.content.clone())
+ serde_json::from_str(event.content.get())
+ .map(|e: RoomHistoryVisibilityEventContent| e.history_visibility)
.map_err(|_| {
Error::bad_database(
"Invalid room history visibility event in database.",
)
})
- .map(|e| e.history_visibility)
}),
Some(Ok(HistoryVisibility::WorldReadable))
)
@@ -172,13 +172,13 @@ pub async fn get_state_events_for_key_route(
db.rooms
.room_state_get(&body.room_id, &EventType::RoomHistoryVisibility, "")?
.map(|event| {
- serde_json::from_value::(event.content.clone())
+ serde_json::from_str(event.content.get())
+ .map(|e: RoomHistoryVisibilityEventContent| e.history_visibility)
.map_err(|_| {
Error::bad_database(
"Invalid room history visibility event in database.",
)
})
- .map(|e| e.history_visibility)
}),
Some(Ok(HistoryVisibility::WorldReadable))
)
@@ -198,7 +198,7 @@ pub async fn get_state_events_for_key_route(
))?;
Ok(get_state_events_for_key::Response {
- content: serde_json::from_value(event.content.clone())
+ content: serde_json::from_str(event.content.get())
.map_err(|_| Error::bad_database("Invalid event content in database"))?,
}
.into())
@@ -228,13 +228,13 @@ pub async fn get_state_events_for_empty_key_route(
db.rooms
.room_state_get(&body.room_id, &EventType::RoomHistoryVisibility, "")?
.map(|event| {
- serde_json::from_value::(event.content.clone())
+ serde_json::from_str(event.content.get())
+ .map(|e: RoomHistoryVisibilityEventContent| e.history_visibility)
.map_err(|_| {
Error::bad_database(
"Invalid room history visibility event in database.",
)
})
- .map(|e| e.history_visibility)
}),
Some(Ok(HistoryVisibility::WorldReadable))
)
@@ -254,7 +254,7 @@ pub async fn get_state_events_for_empty_key_route(
))?;
Ok(get_state_events_for_key::Response {
- content: serde_json::from_value(event.content.clone())
+ content: serde_json::from_str(event.content.get())
.map_err(|_| Error::bad_database("Invalid event content in database"))?,
}
.into())
@@ -273,7 +273,7 @@ async fn send_state_event_for_key_helper(
// TODO: Review this check, error if event is unparsable, use event type, allow alias if it
// previously existed
if let Ok(canonical_alias) =
- serde_json::from_str::(json.json().get())
+ serde_json::from_str::(json.json().get())
{
let mut aliases = canonical_alias.alt_aliases.clone();
diff --git a/src/client_server/sync.rs b/src/client_server/sync.rs
index 2d5ad27d..d98d759f 100644
--- a/src/client_server/sync.rs
+++ b/src/client_server/sync.rs
@@ -1,7 +1,10 @@
use crate::{database::DatabaseGuard, ConduitResult, Database, Error, Result, Ruma, RumaResponse};
use ruma::{
api::client::r0::{sync::sync_events, uiaa::UiaaResponse},
- events::{room::member::MembershipState, AnySyncEphemeralRoomEvent, EventType},
+ events::{
+ room::member::{MembershipState, RoomMemberEventContent},
+ AnySyncEphemeralRoomEvent, EventType,
+ },
serde::Raw,
DeviceId, RoomId, UserId,
};
@@ -57,7 +60,7 @@ use rocket::{get, tokio};
pub async fn sync_events_route(
db: DatabaseGuard,
body: Ruma>,
-) -> std::result::Result, RumaResponse> {
+) -> Result, RumaResponse> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
@@ -179,7 +182,7 @@ async fn sync_helper(
full_state: bool,
timeout: Option,
// bool = caching allowed
-) -> std::result::Result<(sync_events::Response, bool), Error> {
+) -> Result<(sync_events::Response, bool), Error> {
// TODO: match body.set_presence {
db.rooms.edus.ping_presence(&sender_user)?;
@@ -241,13 +244,13 @@ async fn sync_helper(
});
// Take the last 10 events for the timeline
- let timeline_pdus = non_timeline_pdus
+ let timeline_pdus: Vec<_> = non_timeline_pdus
.by_ref()
.take(10)
.collect::>()
.into_iter()
.rev()
- .collect::>();
+ .collect();
let send_notification_counts = !timeline_pdus.is_empty()
|| db
@@ -287,10 +290,10 @@ async fn sync_helper(
.filter_map(|pdu| pdu.ok()) // Ignore all broken pdus
.filter(|(_, pdu)| pdu.kind == EventType::RoomMember)
.map(|(_, pdu)| {
- let content = serde_json::from_value::<
- ruma::events::room::member::MemberEventContent,
- >(pdu.content.clone())
- .map_err(|_| Error::bad_database("Invalid member event in database."))?;
+ let content: RoomMemberEventContent =
+ serde_json::from_str(pdu.content.get()).map_err(|_| {
+ Error::bad_database("Invalid member event in database.")
+ })?;
if let Some(state_key) = &pdu.state_key {
let user_id = UserId::try_from(state_key.clone()).map_err(|_| {
@@ -343,11 +346,11 @@ async fn sync_helper(
let (joined_member_count, invited_member_count, heroes) = calculate_counts()?;
let current_state_ids = db.rooms.state_full_ids(current_shortstatehash)?;
- let state_events = current_state_ids
+ let state_events: Vec<_> = current_state_ids
.iter()
.map(|(_, id)| db.rooms.get_pdu(id))
.filter_map(|r| r.ok().flatten())
- .collect::>();
+ .collect();
(
heroes,
@@ -363,7 +366,7 @@ async fn sync_helper(
// Incremental /sync
let since_shortstatehash = since_shortstatehash.unwrap();
- let since_sender_member = db
+ let since_sender_member: Option = db
.rooms
.state_get(
since_shortstatehash,
@@ -371,13 +374,9 @@ async fn sync_helper(
sender_user.as_str(),
)?
.and_then(|pdu| {
- serde_json::from_value::>(
- pdu.content.clone(),
- )
- .expect("Raw::from_value always works")
- .deserialize()
- .map_err(|_| Error::bad_database("Invalid PDU in database."))
- .ok()
+ serde_json::from_str(pdu.content.get())
+ .map_err(|_| Error::bad_database("Invalid PDU in database."))
+ .ok()
});
let joined_since_last_sync = since_sender_member
@@ -432,11 +431,9 @@ async fn sync_helper(
continue;
}
- let new_membership = serde_json::from_value::<
- Raw,
- >(state_event.content.clone())
- .expect("Raw::from_value always works")
- .deserialize()
+ let new_membership = serde_json::from_str::(
+ state_event.content.get(),
+ )
.map_err(|_| Error::bad_database("Invalid PDU in database."))?
.membership;
@@ -525,18 +522,18 @@ async fn sync_helper(
Ok(Some(db.rooms.pdu_count(pdu_id)?.to_string()))
})?;
- let room_events = timeline_pdus
+ let room_events: Vec<_> = timeline_pdus
.iter()
.map(|(_, pdu)| pdu.to_sync_room_event())
- .collect::>();
+ .collect();
- let mut edus = db
+ let mut edus: Vec<_> = db
.rooms
.edus
.readreceipts_since(&room_id, since)
.filter_map(|r| r.ok()) // Filter out buggy events
.map(|(_, _, v)| v)
- .collect::>();
+ .collect();
if db.rooms.edus.last_typing_update(&room_id, &db.globals)? > since {
edus.push(
@@ -565,7 +562,7 @@ async fn sync_helper(
.map_err(|_| Error::bad_database("Invalid account event in database."))
.ok()
})
- .collect::>(),
+ .collect(),
},
summary: sync_events::RoomSummary {
heroes,
@@ -630,7 +627,7 @@ async fn sync_helper(
}
let mut left_rooms = BTreeMap::new();
- let all_left_rooms = db.rooms.rooms_left(&sender_user).collect::>();
+ let all_left_rooms: Vec<_> = db.rooms.rooms_left(&sender_user).collect();
for result in all_left_rooms {
let (room_id, left_state_events) = result?;
@@ -670,7 +667,7 @@ async fn sync_helper(
}
let mut invited_rooms = BTreeMap::new();
- let all_invited_rooms = db.rooms.rooms_invited(&sender_user).collect::>();
+ let all_invited_rooms: Vec<_> = db.rooms.rooms_invited(&sender_user).collect();
for result in all_invited_rooms {
let (room_id, invite_state_events) = result?;
@@ -739,7 +736,7 @@ async fn sync_helper(
presence: sync_events::Presence {
events: presence_updates
.into_iter()
- .map(|(_, v)| Raw::from(v))
+ .map(|(_, v)| Raw::new(&v).expect("PresenceEvent always serializes successfully"))
.collect(),
},
account_data: sync_events::GlobalAccountData {
@@ -752,19 +749,13 @@ async fn sync_helper(
.map_err(|_| Error::bad_database("Invalid account event in database."))
.ok()
})
- .collect::>(),
+ .collect(),
},
device_lists: sync_events::DeviceLists {
changed: device_list_updates.into_iter().collect(),
left: device_list_left.into_iter().collect(),
},
- device_one_time_keys_count: if db.users.last_one_time_keys_update(&sender_user)? > since
- || since == 0
- {
- db.users.count_one_time_keys(&sender_user, &sender_device)?
- } else {
- BTreeMap::new()
- },
+ device_one_time_keys_count: db.users.count_one_time_keys(&sender_user, &sender_device)?,
to_device: sync_events::ToDevice {
events: db
.users
diff --git a/src/client_server/tag.rs b/src/client_server/tag.rs
index 1eb508c7..42bad4cf 100644
--- a/src/client_server/tag.rs
+++ b/src/client_server/tag.rs
@@ -1,7 +1,10 @@
use crate::{database::DatabaseGuard, ConduitResult, Ruma};
use ruma::{
api::client::r0::tag::{create_tag, delete_tag, get_tags},
- events::EventType,
+ events::{
+ tag::{TagEvent, TagEventContent},
+ EventType,
+ },
};
use std::collections::BTreeMap;
@@ -26,9 +29,9 @@ pub async fn update_tag_route(
let mut tags_event = db
.account_data
- .get::(Some(&body.room_id), sender_user, EventType::Tag)?
- .unwrap_or_else(|| ruma::events::tag::TagEvent {
- content: ruma::events::tag::TagEventContent {
+ .get(Some(&body.room_id), sender_user, EventType::Tag)?
+ .unwrap_or_else(|| TagEvent {
+ content: TagEventContent {
tags: BTreeMap::new(),
},
});
@@ -68,9 +71,9 @@ pub async fn delete_tag_route(
let mut tags_event = db
.account_data
- .get::(Some(&body.room_id), sender_user, EventType::Tag)?
- .unwrap_or_else(|| ruma::events::tag::TagEvent {
- content: ruma::events::tag::TagEventContent {
+ .get(Some(&body.room_id), sender_user, EventType::Tag)?
+ .unwrap_or_else(|| TagEvent {
+ content: TagEventContent {
tags: BTreeMap::new(),
},
});
@@ -108,9 +111,9 @@ pub async fn get_tags_route(
Ok(get_tags::Response {
tags: db
.account_data
- .get::(Some(&body.room_id), sender_user, EventType::Tag)?
- .unwrap_or_else(|| ruma::events::tag::TagEvent {
- content: ruma::events::tag::TagEventContent {
+ .get(Some(&body.room_id), sender_user, EventType::Tag)?
+ .unwrap_or_else(|| TagEvent {
+ content: TagEventContent {
tags: BTreeMap::new(),
},
})
diff --git a/src/database.rs b/src/database.rs
index 8a589299..8cf4f640 100644
--- a/src/database.rs
+++ b/src/database.rs
@@ -501,13 +501,13 @@ impl Database {
if let Some(parent_stateinfo) = states_parents.last() {
let statediffnew = current_state
.difference(&parent_stateinfo.1)
- .cloned()
+ .copied()
.collect::>();
let statediffremoved = parent_stateinfo
.1
.difference(¤t_state)
- .cloned()
+ .copied()
.collect::>();
(statediffnew, statediffremoved)
@@ -701,7 +701,7 @@ impl Database {
println!("Deleting starts");
- let batch2 = db
+ let batch2: Vec<_> = db
.rooms
.tokenids
.iter()
@@ -713,7 +713,7 @@ impl Database {
None
}
})
- .collect::>();
+ .collect();
for key in batch2 {
println!("del");
diff --git a/src/database/abstraction.rs b/src/database/abstraction.rs
index 5b941fbe..11bbc3b1 100644
--- a/src/database/abstraction.rs
+++ b/src/database/abstraction.rs
@@ -22,7 +22,7 @@ pub trait Tree: Send + Sync {
fn get(&self, key: &[u8]) -> Result