matrix-sdk: Allow any event content to be sent out with room_send().

master
Damir Jelić 2020-08-26 15:41:27 +02:00
parent 54391040a4
commit 39628a308b
5 changed files with 64 additions and 47 deletions

View File

@ -4,7 +4,7 @@ use matrix_sdk::{
self, self,
events::{ events::{
room::message::{MessageEventContent, TextMessageEventContent}, room::message::{MessageEventContent, TextMessageEventContent},
SyncMessageEvent, AnyMessageEventContent, SyncMessageEvent,
}, },
Client, ClientConfig, EventEmitter, JsonStore, SyncRoom, SyncSettings, Client, ClientConfig, EventEmitter, JsonStore, SyncRoom, SyncSettings,
}; };
@ -38,11 +38,13 @@ impl EventEmitter for CommandBot {
}; };
if msg_body.contains("!party") { if msg_body.contains("!party") {
let content = MessageEventContent::Text(TextMessageEventContent { let content = AnyMessageEventContent::RoomMessage(MessageEventContent::Text(
body: "🎉🎊🥳 let's PARTY!! 🥳🎊🎉".to_string(), TextMessageEventContent {
formatted: None, body: "🎉🎊🥳 let's PARTY!! 🥳🎊🎉".to_string(),
relates_to: None, formatted: None,
}); relates_to: None,
},
));
// we clone here to hold the lock for as little time as possible. // we clone here to hold the lock for as little time as possible.
let room_id = room.read().await.room_id.clone(); let room_id = room.read().await.room_id.clone();

View File

@ -80,7 +80,7 @@ use matrix_sdk_common::{
}; };
use crate::{ use crate::{
events::{room::message::MessageEventContent, AnyMessageEventContent}, events::AnyMessageEventContent,
http_client::{client_with_config, HttpClient, HttpSend}, http_client::{client_with_config, HttpClient, HttpSend},
identifiers::{EventId, RoomId, RoomIdOrAliasId, UserId}, identifiers::{EventId, RoomId, RoomIdOrAliasId, UserId},
Error, EventEmitter, OutgoingRequest, Result, Error, EventEmitter, OutgoingRequest, Result,
@ -995,14 +995,20 @@ impl Client {
/// # use futures::executor::block_on; /// # use futures::executor::block_on;
/// # use matrix_sdk::identifiers::room_id; /// # use matrix_sdk::identifiers::room_id;
/// # use std::convert::TryFrom; /// # use std::convert::TryFrom;
/// use matrix_sdk::events::room::message::{MessageEventContent, TextMessageEventContent}; /// use matrix_sdk::events::{
/// AnyMessageEventContent,
/// room::message::{MessageEventContent, TextMessageEventContent},
/// };
/// # block_on(async { /// # block_on(async {
/// # let homeserver = Url::parse("http://localhost:8080").unwrap(); /// # let homeserver = Url::parse("http://localhost:8080").unwrap();
/// # let mut client = Client::new(homeserver).unwrap(); /// # let mut client = Client::new(homeserver).unwrap();
/// # let room_id = room_id!("!test:localhost"); /// # let room_id = room_id!("!test:localhost");
/// use matrix_sdk_common::uuid::Uuid; /// use matrix_sdk_common::uuid::Uuid;
/// ///
/// let content = MessageEventContent::Text(TextMessageEventContent::plain("Hello world")); /// let content = AnyMessageEventContent::RoomMessage(
/// MessageEventContent::Text(TextMessageEventContent::plain("Hello world"))
/// );
///
/// let txn_id = Uuid::new_v4(); /// let txn_id = Uuid::new_v4();
/// client.room_send(&room_id, content, Some(txn_id)).await.unwrap(); /// client.room_send(&room_id, content, Some(txn_id)).await.unwrap();
/// # }) /// # })
@ -1010,11 +1016,11 @@ impl Client {
pub async fn room_send( pub async fn room_send(
&self, &self,
room_id: &RoomId, room_id: &RoomId,
content: MessageEventContent, content: impl Into<AnyMessageEventContent>,
txn_id: Option<Uuid>, txn_id: Option<Uuid>,
) -> Result<send_message_event::Response> { ) -> Result<send_message_event::Response> {
#[cfg(not(feature = "encryption"))] #[cfg(not(feature = "encryption"))]
let content = AnyMessageEventContent::RoomMessage(content); let content: AnyMessageEventContent = content.into();
#[cfg(feature = "encryption")] #[cfg(feature = "encryption")]
let content = { let content = {
@ -1029,11 +1035,12 @@ impl Client {
if encrypted { if encrypted {
self.preshare_group_session(room_id).await?; self.preshare_group_session(room_id).await?;
AnyMessageEventContent::RoomEncrypted( AnyMessageEventContent::RoomEncrypted(
self.base_client.encrypt(room_id, content).await?, self.base_client.encrypt(room_id, content).await?,
) )
} else { } else {
AnyMessageEventContent::RoomMessage(content) content.into()
} }
}; };
@ -1482,7 +1489,7 @@ impl Client {
mod test { mod test {
use super::{ use super::{
get_public_rooms, get_public_rooms_filtered, register::RegistrationKind, Client, get_public_rooms, get_public_rooms_filtered, register::RegistrationKind, Client,
ClientConfig, Invite3pid, MessageEventContent, Session, SyncSettings, Url, ClientConfig, Invite3pid, Session, SyncSettings, Url,
}; };
use matrix_sdk_base::JsonStore; use matrix_sdk_base::JsonStore;
use matrix_sdk_common::{ use matrix_sdk_common::{
@ -1493,7 +1500,10 @@ mod test {
}, },
assign, assign,
directory::Filter, directory::Filter,
events::room::message::TextMessageEventContent, events::{
room::message::{MessageEventContent, TextMessageEventContent},
AnyMessageEventContent,
},
identifiers::{event_id, room_id, user_id}, identifiers::{event_id, room_id, user_id},
thirdparty, thirdparty,
}; };
@ -2020,11 +2030,13 @@ mod test {
let room_id = room_id!("!testroom:example.org"); let room_id = room_id!("!testroom:example.org");
let content = MessageEventContent::Text(TextMessageEventContent { let content = AnyMessageEventContent::RoomMessage(MessageEventContent::Text(
body: "Hello world".to_owned(), TextMessageEventContent {
relates_to: None, body: "Hello world".to_owned(),
formatted: None, relates_to: None,
}); formatted: None,
},
));
let txn_id = Uuid::new_v4(); let txn_id = Uuid::new_v4();
let response = client let response = client
.room_send(&room_id, content, Some(txn_id)) .room_send(&room_id, content, Some(txn_id))

View File

@ -28,8 +28,9 @@ use matrix_sdk_common::{
api::r0 as api, api::r0 as api,
events::{ events::{
ignored_user_list::IgnoredUserListEvent, push_rules::PushRulesEvent, ignored_user_list::IgnoredUserListEvent, push_rules::PushRulesEvent,
room::member::MemberEventContent, AnyBasicEvent, AnyStrippedStateEvent, room::member::MemberEventContent, AnyBasicEvent, AnyMessageEventContent,
AnySyncEphemeralRoomEvent, AnySyncMessageEvent, AnySyncRoomEvent, AnySyncStateEvent, AnyStrippedStateEvent, AnySyncEphemeralRoomEvent, AnySyncMessageEvent, AnySyncRoomEvent,
AnySyncStateEvent,
}, },
identifiers::{RoomId, UserId}, identifiers::{RoomId, UserId},
locks::RwLock, locks::RwLock,
@ -41,10 +42,7 @@ use matrix_sdk_common::{
use matrix_sdk_common::{ use matrix_sdk_common::{
api::r0::keys::claim_keys::Request as KeysClaimRequest, api::r0::keys::claim_keys::Request as KeysClaimRequest,
api::r0::to_device::send_event_to_device::IncomingRequest as OwnedToDeviceRequest, api::r0::to_device::send_event_to_device::IncomingRequest as OwnedToDeviceRequest,
events::room::{ events::room::encrypted::EncryptedEventContent, identifiers::DeviceId,
encrypted::EncryptedEventContent, message::MessageEventContent as MsgEventContent,
},
identifiers::DeviceId,
}; };
#[cfg(feature = "encryption")] #[cfg(feature = "encryption")]
use matrix_sdk_crypto::{ use matrix_sdk_crypto::{
@ -1336,12 +1334,12 @@ impl BaseClient {
pub async fn encrypt( pub async fn encrypt(
&self, &self,
room_id: &RoomId, room_id: &RoomId,
content: MsgEventContent, content: impl Into<AnyMessageEventContent>,
) -> Result<EncryptedEventContent> { ) -> Result<EncryptedEventContent> {
let olm = self.olm.lock().await; let olm = self.olm.lock().await;
match &*olm { match &*olm {
Some(o) => Ok(o.encrypt(room_id, content).await?), Some(o) => Ok(o.encrypt(room_id, content.into()).await?),
None => panic!("Olm machine wasn't started"), None => panic!("Olm machine wasn't started"),
} }
} }

View File

@ -40,11 +40,10 @@ use matrix_sdk_common::{
}, },
encryption::DeviceKeys, encryption::DeviceKeys,
events::{ events::{
forwarded_room_key::ForwardedRoomKeyEventContent, forwarded_room_key::ForwardedRoomKeyEventContent, room::encrypted::EncryptedEventContent,
room::{encrypted::EncryptedEventContent, message::MessageEventContent}, room_key::RoomKeyEventContent, room_key_request::RoomKeyRequestEventContent,
room_key::RoomKeyEventContent, AnyMessageEventContent, AnySyncRoomEvent, AnyToDeviceEvent, EventType, SyncMessageEvent,
room_key_request::RoomKeyRequestEventContent, ToDeviceEvent,
AnySyncRoomEvent, AnyToDeviceEvent, EventType, SyncMessageEvent, ToDeviceEvent,
}, },
identifiers::{DeviceId, DeviceKeyAlgorithm, EventEncryptionAlgorithm, RoomId, UserId}, identifiers::{DeviceId, DeviceKeyAlgorithm, EventEncryptionAlgorithm, RoomId, UserId},
uuid::Uuid, uuid::Uuid,
@ -1074,7 +1073,7 @@ impl OlmMachine {
pub async fn encrypt( pub async fn encrypt(
&self, &self,
room_id: &RoomId, room_id: &RoomId,
content: MessageEventContent, content: AnyMessageEventContent,
) -> MegolmResult<EncryptedEventContent> { ) -> MegolmResult<EncryptedEventContent> {
let session = if let Some(s) = self.get_outbound_group_session(room_id) { let session = if let Some(s) = self.get_outbound_group_session(room_id) {
s s
@ -1569,8 +1568,8 @@ pub(crate) mod test {
encrypted::EncryptedEventContent, encrypted::EncryptedEventContent,
message::{MessageEventContent, TextMessageEventContent}, message::{MessageEventContent, TextMessageEventContent},
}, },
AnySyncMessageEvent, AnySyncRoomEvent, AnyToDeviceEvent, EventType, SyncMessageEvent, AnyMessageEventContent, AnySyncMessageEvent, AnySyncRoomEvent, AnyToDeviceEvent,
ToDeviceEvent, Unsigned, EventType, SyncMessageEvent, ToDeviceEvent, Unsigned,
}, },
identifiers::{ identifiers::{
event_id, room_id, user_id, DeviceId, DeviceKeyAlgorithm, DeviceKeyId, UserId, event_id, room_id, user_id, DeviceId, DeviceKeyAlgorithm, DeviceKeyId, UserId,
@ -2081,7 +2080,13 @@ pub(crate) mod test {
let content = MessageEventContent::Text(TextMessageEventContent::plain(plaintext)); let content = MessageEventContent::Text(TextMessageEventContent::plain(plaintext));
let encrypted_content = alice.encrypt(&room_id, content.clone()).await.unwrap(); let encrypted_content = alice
.encrypt(
&room_id,
AnyMessageEventContent::RoomMessage(content.clone()),
)
.await
.unwrap();
let event = SyncMessageEvent { let event = SyncMessageEvent {
event_id: event_id!("$xxxxx:example.org"), event_id: event_id!("$xxxxx:example.org"),

View File

@ -25,11 +25,8 @@ use std::{
use matrix_sdk_common::{ use matrix_sdk_common::{
events::{ events::{
room::{ room::{encrypted::EncryptedEventContent, encryption::EncryptionEventContent},
encrypted::EncryptedEventContent, encryption::EncryptionEventContent, AnyMessageEventContent, AnySyncRoomEvent, EventContent, SyncMessageEvent,
message::MessageEventContent,
},
AnySyncRoomEvent, EventType, SyncMessageEvent,
}, },
identifiers::{DeviceId, EventEncryptionAlgorithm, RoomId}, identifiers::{DeviceId, EventEncryptionAlgorithm, RoomId},
instant::Instant, instant::Instant,
@ -372,11 +369,11 @@ impl OutboundGroupSession {
/// # Panics /// # Panics
/// ///
/// Panics if the content can't be serialized. /// Panics if the content can't be serialized.
pub async fn encrypt(&self, content: MessageEventContent) -> EncryptedEventContent { pub async fn encrypt(&self, content: AnyMessageEventContent) -> EncryptedEventContent {
let json_content = json!({ let json_content = json!({
"content": content, "content": content,
"room_id": &*self.room_id, "room_id": &*self.room_id,
"type": EventType::RoomMessage, "type": content.event_type(),
}); });
let plaintext = cjson::to_string(&json_content).unwrap_or_else(|_| { let plaintext = cjson::to_string(&json_content).unwrap_or_else(|_| {
@ -482,7 +479,10 @@ mod test {
}; };
use matrix_sdk_common::{ use matrix_sdk_common::{
events::room::message::{MessageEventContent, TextMessageEventContent}, events::{
room::message::{MessageEventContent, TextMessageEventContent},
AnyMessageEventContent,
},
identifiers::{room_id, user_id}, identifiers::{room_id, user_id},
}; };
@ -505,9 +505,9 @@ mod test {
assert!(!session.expired()); assert!(!session.expired());
let _ = session let _ = session
.encrypt(MessageEventContent::Text(TextMessageEventContent::plain( .encrypt(AnyMessageEventContent::RoomMessage(
"Test message", MessageEventContent::Text(TextMessageEventContent::plain("Test message")),
))) ))
.await; .await;
assert!(session.expired()); assert!(session.expired());