Handle emote messages from Matrix

legacy
Charlotte Som 2021-09-13 00:06:11 +01:00
parent 13dc88f830
commit 33e13eb4b0
1 changed files with 53 additions and 20 deletions

View File

@ -1,10 +1,12 @@
use matrix_sdk::{
async_trait,
room::Room,
room::{Joined, Room},
ruma::{
events::{
room::{
message::{MessageEventContent, MessageFormat, MessageType, Relation},
message::{
FormattedBody, MessageEventContent, MessageFormat, MessageType, Relation,
},
redaction::RedactionEventContent,
},
AnyMessageEventContent, AnySyncRoomEvent, SyncMessageEvent,
@ -20,7 +22,10 @@ use tokio::sync::mpsc;
use url::Url;
use crate::{
message_ast::{convert_matrix, convert_plain, format_discord, format_matrix},
message_ast::{
convert_matrix, convert_plain, format_discord, format_matrix, MessageComponent,
MessageContent,
},
messages::{MessageAuthor, MessageReference, SentMessage},
};
@ -68,6 +73,33 @@ struct MatrixHandler {
current_user_id: UserId,
}
impl MatrixHandler {
async fn get_message_author(&self, room: &Joined, user_id: &UserId) -> Option<MessageAuthor> {
if let Ok(Some(sender)) = room.get_member(user_id).await {
Some(MessageAuthor {
display_name: sender
.display_name()
.unwrap_or_else(|| sender.name())
.to_string(),
})
} else {
None
}
}
fn get_content(&self, body: &str, formatted_body: &Option<FormattedBody>) -> MessageContent {
if let Some(html) = formatted_body
.as_ref()
.filter(|f| f.format == MessageFormat::Html)
.map(|f| &f.body)
{
convert_matrix(html)
} else {
convert_plain(body)
}
}
}
#[async_trait]
impl EventHandler for MatrixHandler {
async fn on_room_message(&self, room: Room, event: &SyncMessageEvent<MessageEventContent>) {
@ -87,27 +119,26 @@ impl EventHandler for MatrixHandler {
match message_type {
MessageType::Text(text) => {
let content = if let Some(html) = text
.formatted
.as_ref()
.filter(|f| f.format == MessageFormat::Html)
.map(|f| &f.body)
{
convert_matrix(html)
} else {
convert_plain(&text.body)
};
let content = self.get_content(&text.body, &text.formatted);
if let Ok(Some(sender)) = room.get_member(&event.sender).await {
if let Some(author) = self.get_message_author(&room, &event.sender).await {
let _ = self.message_tx.send(SentMessage {
source: message_ref,
content,
author: MessageAuthor {
display_name: sender
.display_name()
.unwrap_or_else(|| sender.name())
.to_string(),
},
author,
});
}
}
MessageType::Emote(emote) => {
let mut content = self.get_content(&emote.body, &emote.formatted);
content.insert(0, MessageComponent::Plain("* ".to_string()));
if let Some(author) = self.get_message_author(&room, &event.sender).await {
let _ = self.message_tx.send(SentMessage {
source: message_ref,
content,
author,
});
}
}
@ -115,6 +146,8 @@ impl EventHandler for MatrixHandler {
// TODO: Handle reactions, uploads (audio, video, image, file), and any other types of event
_ => {}
};
let _ = room.read_receipt(&event.event_id).await;
}
}
}