use ruma_common::OwnedMxcUri;
use ruma_macros::EventContent;
use serde::{de, Deserialize, Serialize};
#[cfg(feature = "compat-encrypted-stickers")]
use crate::room::EncryptedFile;
use crate::room::{message::Relation, ImageInfo, MediaSource};
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
pub enum StickerMediaSource {
#[serde(rename = "url")]
Plain(OwnedMxcUri),
#[cfg(feature = "compat-encrypted-stickers")]
#[serde(rename = "file")]
Encrypted(Box<EncryptedFile>),
}
impl<'de> Deserialize<'de> for StickerMediaSource {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
struct StickerMediaSourceJsonRepr {
url: Option<OwnedMxcUri>,
#[cfg(feature = "compat-encrypted-stickers")]
file: Option<Box<EncryptedFile>>,
}
match StickerMediaSourceJsonRepr::deserialize(deserializer)? {
StickerMediaSourceJsonRepr {
url: None,
#[cfg(feature = "compat-encrypted-stickers")]
file: None,
} => Err(de::Error::missing_field("url")),
#[cfg(feature = "compat-encrypted-stickers")]
StickerMediaSourceJsonRepr { file: Some(file), .. } => {
Ok(StickerMediaSource::Encrypted(file))
}
StickerMediaSourceJsonRepr { url: Some(url), .. } => Ok(StickerMediaSource::Plain(url)),
}
}
}
impl From<StickerMediaSource> for MediaSource {
fn from(value: StickerMediaSource) -> Self {
match value {
StickerMediaSource::Plain(url) => MediaSource::Plain(url),
#[cfg(feature = "compat-encrypted-stickers")]
StickerMediaSource::Encrypted(file) => MediaSource::Encrypted(file),
}
}
}
#[cfg(feature = "compat-encrypted-stickers")]
impl From<MediaSource> for StickerMediaSource {
fn from(value: MediaSource) -> Self {
match value {
MediaSource::Plain(url) => StickerMediaSource::Plain(url),
MediaSource::Encrypted(file) => StickerMediaSource::Encrypted(file),
}
}
}
#[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
#[ruma_event(type = "m.sticker", kind = MessageLike, without_relation)]
pub struct StickerEventContent {
pub body: String,
pub info: ImageInfo,
#[serde(flatten)]
pub source: StickerMediaSource,
#[serde(
flatten,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::room::message::relation_serde::deserialize_relation"
)]
pub relates_to: Option<Relation<StickerEventContentWithoutRelation>>,
}
impl StickerEventContent {
pub fn new(body: String, info: ImageInfo, url: OwnedMxcUri) -> Self {
Self { body, info, source: StickerMediaSource::Plain(url.clone()), relates_to: None }
}
pub fn with_source(body: String, info: ImageInfo, source: StickerMediaSource) -> Self {
Self { body, info, source, relates_to: None }
}
}