ruma_events/room/message/
text.rs

1use serde::{Deserialize, Serialize};
2
3#[cfg(feature = "unstable-msc4095")]
4use super::url_preview::UrlPreview;
5use super::FormattedBody;
6
7/// The payload for a text message.
8#[derive(Clone, Debug, Deserialize, Serialize)]
9#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
10#[serde(tag = "msgtype", rename = "m.text")]
11pub struct TextMessageEventContent {
12    /// The body of the message.
13    pub body: String,
14
15    /// Formatted form of the message `body`.
16    #[serde(flatten)]
17    pub formatted: Option<FormattedBody>,
18
19    /// [MSC4095](https://github.com/matrix-org/matrix-spec-proposals/pull/4095)-style bundled url previews
20    #[cfg(feature = "unstable-msc4095")]
21    #[serde(
22        rename = "com.beeper.linkpreviews",
23        skip_serializing_if = "Option::is_none",
24        alias = "m.url_previews"
25    )]
26    pub url_previews: Option<Vec<UrlPreview>>,
27}
28
29impl TextMessageEventContent {
30    /// A convenience constructor to create a plain text message.
31    pub fn plain(body: impl Into<String>) -> Self {
32        let body = body.into();
33        Self {
34            body,
35            formatted: None,
36            #[cfg(feature = "unstable-msc4095")]
37            url_previews: None,
38        }
39    }
40
41    /// A convenience constructor to create an HTML message.
42    pub fn html(body: impl Into<String>, html_body: impl Into<String>) -> Self {
43        let body = body.into();
44        Self {
45            body,
46            formatted: Some(FormattedBody::html(html_body)),
47            #[cfg(feature = "unstable-msc4095")]
48            url_previews: None,
49        }
50    }
51
52    /// A convenience constructor to create a Markdown message.
53    ///
54    /// Returns an HTML message if some Markdown formatting was detected, otherwise returns a plain
55    /// text message.
56    #[cfg(feature = "markdown")]
57    pub fn markdown(body: impl AsRef<str> + Into<String>) -> Self {
58        if let Some(formatted) = FormattedBody::markdown(&body) {
59            Self::html(body, formatted.body)
60        } else {
61            Self::plain(body)
62        }
63    }
64}