From 666e1d30a3f591a0609261eaeb66550e1a84ddd4 Mon Sep 17 00:00:00 2001 From: phesch Date: Wed, 21 Jul 2021 10:55:23 +0200 Subject: [PATCH] Implement From on PduBuilder The conversion between the two is now direct and thus shouldn't lose the state_keys. --- src/client_server/room.rs | 7 +++---- src/pdu.rs | 20 +++++++++++++++++--- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/src/client_server/room.rs b/src/client_server/room.rs index 6e27130..f107cc5 100644 --- a/src/client_server/room.rs +++ b/src/client_server/room.rs @@ -233,10 +233,9 @@ pub async fn create_room_route( // 5. Events listed in initial_state for event in &body.initial_state { - let pdu_builder = serde_json::from_str::( - &serde_json::to_string(&event).expect("AnyInitialStateEvent::to_string always works"), - ) - .map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid initial state event."))?; + let pdu_builder = PduBuilder::from(event.deserialize().map_err(|_| { + Error::BadRequest(ErrorKind::InvalidParam, "Invalid initial state event.") + })?); // Silently skip encryption events if they are not allowed if pdu_builder.event_type == EventType::RoomEncryption && !db.globals.allow_encryption() { diff --git a/src/pdu.rs b/src/pdu.rs index a72f04d..2167971 100644 --- a/src/pdu.rs +++ b/src/pdu.rs @@ -2,9 +2,9 @@ use crate::Error; use log::error; use ruma::{ events::{ - pdu::EventHash, room::member::MemberEventContent, AnyEphemeralRoomEvent, AnyRoomEvent, - AnyStateEvent, AnyStrippedStateEvent, AnySyncRoomEvent, AnySyncStateEvent, EventType, - StateEvent, + pdu::EventHash, room::member::MemberEventContent, AnyEphemeralRoomEvent, + AnyInitialStateEvent, AnyRoomEvent, AnyStateEvent, AnyStrippedStateEvent, AnySyncRoomEvent, + AnySyncStateEvent, EventType, StateEvent, }, serde::{CanonicalJsonObject, CanonicalJsonValue, Raw}, state_res, EventId, MilliSecondsSinceUnixEpoch, RoomId, RoomVersionId, ServerName, @@ -346,3 +346,17 @@ pub struct PduBuilder { pub state_key: Option, pub redacts: Option, } + +/// Direct conversion prevents loss of the empty `state_key` that ruma requires. +impl From for PduBuilder { + fn from(event: AnyInitialStateEvent) -> Self { + Self { + event_type: EventType::from(event.event_type()), + content: serde_json::value::to_value(event.content()) + .expect("AnyStateEventContent came from JSON and can thus turn back into JSON."), + unsigned: None, + state_key: Some(event.state_key().to_owned()), + redacts: None, + } + } +}