events: Implement sanitize on MessageType

This commit is contained in:
Kévin Commaille 2023-04-27 18:53:42 +02:00 committed by Kévin Commaille
parent 44ed922ba2
commit b50037affc
2 changed files with 40 additions and 13 deletions

View File

@ -31,6 +31,7 @@ Improvements:
- `user_can_send_message` - `user_can_send_message`
- `user_can_send_state` - `user_can_send_state`
- `user_can_trigger_room_notification` - `user_can_trigger_room_notification`
- Add `MessageType::sanitize` behind the `unstable-sanitize` feature
# 0.11.3 # 0.11.3

View File

@ -326,19 +326,13 @@ impl RoomMessageEventContent {
mode: HtmlSanitizerMode, mode: HtmlSanitizerMode,
remove_reply_fallback: RemoveReplyFallback, remove_reply_fallback: RemoveReplyFallback,
) { ) {
if let MessageType::Emote(EmoteMessageEventContent { body, formatted, .. }) let remove_reply_fallback = if matches!(self.relates_to, Some(Relation::Reply { .. })) {
| MessageType::Notice(NoticeMessageEventContent { body, formatted, .. }) remove_reply_fallback
| MessageType::Text(TextMessageEventContent { body, formatted, .. }) = &mut self.msgtype } else {
{ RemoveReplyFallback::No
if let Some(formatted) = formatted { };
formatted.sanitize_html(mode, remove_reply_fallback);
} self.msgtype.sanitize(mode, remove_reply_fallback);
if remove_reply_fallback == RemoveReplyFallback::Yes
&& matches!(self.relates_to, Some(Relation::Reply { .. }))
{
*body = remove_plain_reply_fallback(body).to_owned();
}
}
} }
} }
@ -558,6 +552,38 @@ impl MessageType {
Self::_Custom(c) => Cow::Borrowed(&c.data), Self::_Custom(c) => Cow::Borrowed(&c.data),
} }
} }
/// Sanitize this message.
///
/// If this message contains HTML, this removes the [tags and attributes] that are not listed in
/// the Matrix specification.
///
/// It can also optionally remove the [rich reply fallback] from the plain text and HTML
/// message. Note that you should be sure that the message is a reply, as there is no way to
/// differentiate plain text reply fallbacks and markdown quotes.
///
/// This method is only effective on text, notice and emote messages.
///
/// [tags and attributes]: https://spec.matrix.org/latest/client-server-api/#mroommessage-msgtypes
/// [rich reply fallback]: https://spec.matrix.org/latest/client-server-api/#fallbacks-for-rich-replies
#[cfg(feature = "unstable-sanitize")]
pub fn sanitize(
&mut self,
mode: HtmlSanitizerMode,
remove_reply_fallback: RemoveReplyFallback,
) {
if let MessageType::Emote(EmoteMessageEventContent { body, formatted, .. })
| MessageType::Notice(NoticeMessageEventContent { body, formatted, .. })
| MessageType::Text(TextMessageEventContent { body, formatted, .. }) = self
{
if let Some(formatted) = formatted {
formatted.sanitize_html(mode, remove_reply_fallback);
}
if remove_reply_fallback == RemoveReplyFallback::Yes {
*body = remove_plain_reply_fallback(body).to_owned();
}
}
}
} }
impl From<MessageType> for RoomMessageEventContent { impl From<MessageType> for RoomMessageEventContent {