repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/serde/base64.rs | crates/core/src/serde/base64.rs | //! Transparent base64 encoding / decoding as part of (de)serialization.
use std::{fmt, marker::PhantomData};
use base64::{
Engine,
engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig, general_purpose},
};
use salvo::oapi::{Components, RefOr, Schema, ToSchema};
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
/// A wrapper around `B` (usually `Vec<u8>`) that (de)serializes from / to a
/// base64 string.
///
/// The base64 character set (and miscellaneous other encoding / decoding
/// options) can be customized through the generic parameter `C`.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Base64<C = Standard, B = Vec<u8>> {
bytes: B,
// Invariant PhantomData, Send + Sync
_phantom_conf: PhantomData<fn(C) -> C>,
}
impl<C, B> ToSchema for Base64<C, B> {
fn to_schema(components: &mut Components) -> RefOr<Schema> {
<String>::to_schema(components)
}
}
/// Config used for the [`Base64`] type.
pub trait Base64Config {
/// The config as a constant.
///
/// Opaque so our interface is not tied to the base64 crate version.
#[doc(hidden)]
const CONF: Conf;
}
#[doc(hidden)]
pub struct Conf(base64::alphabet::Alphabet);
/// Standard base64 character set without padding.
///
/// Allows trailing bits in decoding for maximum compatibility.
#[non_exhaustive]
// Easier than implementing these all for Base64 manually to avoid the `C: Trait` bounds.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Standard;
impl Base64Config for Standard {
const CONF: Conf = Conf(base64::alphabet::STANDARD);
}
/// Url-safe base64 character set without padding.
///
/// Allows trailing bits in decoding for maximum compatibility.
#[non_exhaustive]
// Easier than implementing these all for Base64 manually to avoid the `C: Trait` bounds.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct UrlSafe;
impl Base64Config for UrlSafe {
const CONF: Conf = Conf(base64::alphabet::URL_SAFE);
}
impl<C: Base64Config, B> Base64<C, B> {
const CONFIG: GeneralPurposeConfig = general_purpose::NO_PAD
// See https://github.com/matrix-org/matrix-spec/issues/838
.with_decode_allow_trailing_bits(true)
.with_decode_padding_mode(DecodePaddingMode::Indifferent);
const ENGINE: GeneralPurpose = GeneralPurpose::new(&C::CONF.0, Self::CONFIG);
}
impl<C: Base64Config, B: AsRef<[u8]>> Base64<C, B> {
/// Create a `Base64` instance from raw bytes, to be base64-encoded in
/// serialization.
pub fn new(bytes: B) -> Self {
Self {
bytes,
_phantom_conf: PhantomData,
}
}
/// Get a reference to the raw bytes held by this `Base64` instance.
pub fn as_bytes(&self) -> &[u8] {
self.bytes.as_ref()
}
/// Encode the bytes contained in this `Base64` instance to unpadded base64.
pub fn encode(&self) -> String {
Self::ENGINE.encode(self.as_bytes())
}
}
impl<C, B> Base64<C, B> {
/// Get the raw bytes held by this `Base64` instance.
pub fn into_inner(self) -> B {
self.bytes
}
}
impl<C: Base64Config> Base64<C> {
/// Create a `Base64` instance containing an empty `Vec<u8>`.
pub fn empty() -> Self {
Self::new(Vec::new())
}
/// Parse some base64-encoded data to create a `Base64` instance.
pub fn parse(encoded: impl AsRef<[u8]>) -> Result<Self, Base64DecodeError> {
Self::ENGINE
.decode(encoded)
.map(Self::new)
.map_err(Base64DecodeError)
}
}
impl<C: Base64Config, B: AsRef<[u8]>> fmt::Debug for Base64<C, B> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.encode().fmt(f)
}
}
impl<C: Base64Config, B: AsRef<[u8]>> fmt::Display for Base64<C, B> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.encode().fmt(f)
}
}
impl<'de, C: Base64Config> Deserialize<'de> for Base64<C> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let encoded = super::deserialize_cow_str(deserializer)?;
Self::parse(&*encoded).map_err(de::Error::custom)
}
}
impl<C: Base64Config, B: AsRef<[u8]>> Serialize for Base64<C, B> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.encode())
}
}
/// An error that occurred while decoding a base64 string.
#[derive(Clone)]
pub struct Base64DecodeError(base64::DecodeError);
impl fmt::Debug for Base64DecodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl fmt::Display for Base64DecodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl std::error::Error for Base64DecodeError {}
#[cfg(test)]
mod tests {
use super::{Base64, Standard};
#[test]
fn slightly_malformed_base64() {
const INPUT: &str = "3UmJnEIzUr2xWyaUnJg5fXwRybwG5FVC6Gq\
MHverEUn0ztuIsvVxX89JXX2pvdTsOBbLQx+4TVL02l4Cp5wPCm";
const INPUT_WITH_PADDING: &str = "im9+knCkMNQNh9o6sbdcZw==";
Base64::<Standard>::parse(INPUT).unwrap();
Base64::<Standard>::parse(INPUT_WITH_PADDING)
.expect("We should be able to decode padded Base64");
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/serde/pdu_process_response.rs | crates/core/src/serde/pdu_process_response.rs | use std::{collections::BTreeMap, fmt};
use serde::{
Deserialize, Serialize,
de::{Deserializer, MapAccess, Visitor},
ser::{SerializeMap, Serializer},
};
use crate::OwnedEventId;
#[derive(Deserialize, Serialize)]
struct WrappedError {
#[serde(skip_serializing_if = "Option::is_none")]
error: Option<String>,
}
pub(crate) fn serialize<S>(
response: &BTreeMap<OwnedEventId, Result<(), String>>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut map = serializer.serialize_map(Some(response.len()))?;
for (key, value) in response {
let wrapped_error = WrappedError {
error: value.clone().err(),
};
map.serialize_entry(&key, &wrapped_error)?;
}
map.end()
}
#[allow(clippy::type_complexity)]
pub(crate) fn deserialize<'de, D>(
deserializer: D,
) -> Result<BTreeMap<OwnedEventId, Result<(), String>>, D::Error>
where
D: Deserializer<'de>,
{
struct PduProcessResponseVisitor;
impl<'de> Visitor<'de> for PduProcessResponseVisitor {
type Value = BTreeMap<OwnedEventId, Result<(), String>>;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("A map of EventIds to a map of optional errors")
}
fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
where
M: MapAccess<'de>,
{
let mut map = BTreeMap::new();
while let Some((key, value)) = access.next_entry::<OwnedEventId, WrappedError>()? {
let v = match value.error {
None => Ok(()),
Some(error) => Err(error),
};
map.insert(key, v);
}
Ok(map)
}
}
deserializer.deserialize_map(PduProcessResponseVisitor)
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use serde_json::{json, value::Serializer as JsonSerializer};
use super::{deserialize, serialize};
use crate::{OwnedEventId, event_id, owned_event_id};
#[test]
fn serialize_error() {
let mut response: BTreeMap<OwnedEventId, Result<(), String>> = BTreeMap::new();
response.insert(
owned_event_id!("$someevent:matrix.org"),
Err("Some processing error.".into()),
);
let serialized = serialize(&response, JsonSerializer).unwrap();
let json = json!({
"$someevent:matrix.org": { "error": "Some processing error." }
});
assert_eq!(serialized, json);
}
#[test]
fn serialize_ok() {
let mut response: BTreeMap<OwnedEventId, Result<(), String>> = BTreeMap::new();
response.insert(owned_event_id!("$someevent:matrix.org"), Ok(()));
let serialized = serialize(&response, serde_json::value::Serializer).unwrap();
let json = json!({
"$someevent:matrix.org": {}
});
assert_eq!(serialized, json);
}
#[test]
fn deserialize_error() {
let json = json!({
"$someevent:matrix.org": { "error": "Some processing error." }
});
let response = deserialize(json).unwrap();
let event_id = event_id!("$someevent:matrix.org");
let event_response = response.get(event_id).unwrap().clone().unwrap_err();
assert_eq!(event_response, "Some processing error.");
}
#[test]
fn deserialize_null_error_is_ok() {
let json = json!({
"$someevent:matrix.org": { "error": null }
});
let response = deserialize(json).unwrap();
let event_id = event_id!("$someevent:matrix.org");
response.get(event_id).unwrap().as_ref().unwrap();
}
#[test]
fn deserialize_empty_error_is_err() {
let json = json!({
"$someevent:matrix.org": { "error": "" }
});
let response = deserialize(json).unwrap();
let event_id = event_id!("$someevent:matrix.org");
let event_response = response.get(event_id).unwrap().clone().unwrap_err();
assert_eq!(event_response, "");
}
#[test]
fn deserialize_ok() {
let json = json!({
"$someevent:matrix.org": {}
});
let response = deserialize(json).unwrap();
response
.get(event_id!("$someevent:matrix.org"))
.unwrap()
.as_ref()
.unwrap();
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/serde/cow.rs | crates/core/src/serde/cow.rs | use std::{borrow::Cow, str};
use serde::de::{self, Deserializer, Unexpected, Visitor};
/// Deserialize a `Cow<'de, str>`.
///
/// Different from serde's implementation of `Deserialize` for `Cow` since it
/// borrows from the input when possible.
///
/// This will become unnecessary if Rust gains lifetime specialization at some
/// point; see <https://github.com/serde-rs/serde/issues/1497#issuecomment-716246686>.
pub fn deserialize_cow_str<'de, D>(deserializer: D) -> Result<Cow<'de, str>, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_string(CowStrVisitor)
}
struct CowStrVisitor;
impl<'de> Visitor<'de> for CowStrVisitor {
type Value = Cow<'de, str>;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("a string")
}
fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(Cow::Borrowed(v))
}
fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E>
where
E: de::Error,
{
match str::from_utf8(v) {
Ok(s) => Ok(Cow::Borrowed(s)),
Err(_) => Err(de::Error::invalid_value(Unexpected::Bytes(v), &self)),
}
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(Cow::Owned(v.to_owned()))
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(Cow::Owned(v))
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: de::Error,
{
match str::from_utf8(v) {
Ok(s) => Ok(Cow::Owned(s.to_owned())),
Err(_) => Err(de::Error::invalid_value(Unexpected::Bytes(v), &self)),
}
}
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
where
E: de::Error,
{
match String::from_utf8(v) {
Ok(s) => Ok(Cow::Owned(s)),
Err(e) => Err(de::Error::invalid_value(
Unexpected::Bytes(&e.into_bytes()),
&self,
)),
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/serde/strings.rs | crates/core/src/serde/strings.rs | use std::{collections::BTreeMap, fmt, marker::PhantomData};
use serde::{
Deserialize, Serialize,
de::{self, Deserializer, IntoDeserializer as _, MapAccess, Visitor},
ser::Serializer,
};
/// Serde deserialization decorator to map empty Strings to None,
/// and forward non-empty Strings to the Deserialize implementation for T.
/// Useful for the typical
/// "A room with an X event with an absent, null, or empty Y field
/// should be treated the same as a room with no such event."
/// formulation in the spec.
///
/// To be used like this:
/// `#[serde(default, deserialize_with = "empty_string_as_none")]`
/// Relevant serde issue: <https://github.com/serde-rs/serde/issues/1425>
pub fn empty_string_as_none<'de, D, T>(de: D) -> Result<Option<T>, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de>,
{
let opt = Option::<String>::deserialize(de)?;
match opt.as_deref() {
None | Some("") => Ok(None),
// If T = String, like in m.room.name, the second deserialize is actually superfluous.
// TODO: optimize that somehow?
Some(s) => T::deserialize(s.into_deserializer()).map(Some),
}
}
/// Serde serializiation decorator to map `None` to an empty `String`,
/// and forward `Some`s to the `Serialize` implementation for `T`.
///
/// To be used like this:
/// `#[serde(serialize_with = "empty_string_as_none")]`
pub fn none_as_empty_string<T: Serialize, S>(
value: &Option<T>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match value {
Some(x) => x.serialize(serializer),
None => serializer.serialize_str(""),
}
}
/// Take either a floating point number or a string and deserialize to an
/// floating-point number.
///
/// To be used like this:
/// `#[serde(deserialize_with = "deserialize_as_f64_or_string")]`
pub fn deserialize_as_f64_or_string<'de, D>(de: D) -> Result<f64, D::Error>
where
D: Deserializer<'de>,
{
struct F64OrStringVisitor;
impl<'de> Visitor<'de> for F64OrStringVisitor {
type Value = f64;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a double or a string")
}
fn visit_f32<E>(self, v: f32) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(v.into())
}
fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(v)
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
v.parse().map_err(E::custom)
}
}
de.deserialize_any(F64OrStringVisitor)
}
#[derive(Deserialize)]
struct F64OrStringWrapper(#[serde(deserialize_with = "deserialize_as_f64_or_string")] f64);
/// Deserializes an `Option<f64>` as encoded as a f64 or a string.
pub fn deserialize_as_optional_f64_or_string<'de, D>(
deserializer: D,
) -> Result<Option<f64>, D::Error>
where
D: Deserializer<'de>,
{
Ok(Option::<F64OrStringWrapper>::deserialize(deserializer)?.map(|w| w.0))
}
/// Take either an integer number or a string and deserialize to an integer
/// number.
///
/// To be used like this:
/// `#[serde(deserialize_with = "deserialize_v1_power_level")]`
pub fn deserialize_v1_power_level<'de, D>(de: D) -> Result<i64, D::Error>
where
D: Deserializer<'de>,
{
struct IntOrStringVisitor;
impl<'de> Visitor<'de> for IntOrStringVisitor {
type Value = i64;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("an integer or a string")
}
fn visit_i8<E: de::Error>(self, v: i8) -> Result<Self::Value, E> {
Ok(v.into())
}
fn visit_i16<E: de::Error>(self, v: i16) -> Result<Self::Value, E> {
Ok(v.into())
}
fn visit_i32<E: de::Error>(self, v: i32) -> Result<Self::Value, E> {
Ok(v.into())
}
fn visit_i64<E: de::Error>(self, v: i64) -> Result<Self::Value, E> {
Ok(v)
}
fn visit_i128<E: de::Error>(self, v: i128) -> Result<Self::Value, E> {
v.try_into().map_err(E::custom)
}
fn visit_u8<E: de::Error>(self, v: u8) -> Result<Self::Value, E> {
Ok(v.into())
}
fn visit_u16<E: de::Error>(self, v: u16) -> Result<Self::Value, E> {
Ok(v.into())
}
fn visit_u32<E: de::Error>(self, v: u32) -> Result<Self::Value, E> {
Ok(v.into())
}
fn visit_u64<E: de::Error>(self, v: u64) -> Result<Self::Value, E> {
v.try_into().map_err(E::custom)
}
fn visit_u128<E: de::Error>(self, v: u128) -> Result<Self::Value, E> {
v.try_into().map_err(E::custom)
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
let trimmed = v.trim();
match trimmed.strip_prefix('+') {
Some(without) => without.parse::<u64>().map(|u| u as i64).map_err(E::custom),
None => trimmed.parse().map_err(E::custom),
}
}
}
de.deserialize_any(IntOrStringVisitor)
}
/// Take a BTreeMap with values of either an integer number or a string and
/// deserialize those to integer numbers.
///
/// To be used like this:
/// `#[serde(deserialize_with = "btreemap_deserialize_v1_power_level_values")]`
pub fn btreemap_deserialize_v1_power_level_values<'de, D, T>(
de: D,
) -> Result<BTreeMap<T, i64>, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de> + Ord,
{
#[repr(transparent)]
struct IntWrap(i64);
impl<'de> Deserialize<'de> for IntWrap {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserialize_v1_power_level(deserializer).map(IntWrap)
}
}
struct IntMapVisitor<T> {
_phantom: PhantomData<T>,
}
impl<T> IntMapVisitor<T> {
fn new() -> Self {
Self {
_phantom: PhantomData,
}
}
}
impl<'de, T> Visitor<'de> for IntMapVisitor<T>
where
T: Deserialize<'de> + Ord,
{
type Value = BTreeMap<T, i64>;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a map with integers or strings as values")
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
let mut res = BTreeMap::new();
while let Some((k, IntWrap(v))) = map.next_entry()? {
res.insert(k, v);
}
Ok(res)
}
}
de.deserialize_map(IntMapVisitor::new())
}
/// Take a Map with values of either an integer number or a string and
/// deserialize those to integer numbers in a Vec of sorted pairs.
///
/// To be used like this:
/// `#[serde(deserialize_with = "vec_deserialize_v1_power_level_values")]`
pub fn vec_deserialize_v1_power_level_values<'de, D, T>(de: D) -> Result<Vec<(T, i64)>, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de> + Ord,
{
#[repr(transparent)]
struct IntWrap(i64);
impl<'de> Deserialize<'de> for IntWrap {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserialize_v1_power_level(deserializer).map(IntWrap)
}
}
struct IntMapVisitor<T> {
_phantom: PhantomData<T>,
}
impl<T> IntMapVisitor<T> {
fn new() -> Self {
Self {
_phantom: PhantomData,
}
}
}
impl<'de, T> Visitor<'de> for IntMapVisitor<T>
where
T: Deserialize<'de> + Ord,
{
type Value = Vec<(T, i64)>;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a map with integers or strings as values")
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
let mut res = Vec::new();
if let Some(hint) = map.size_hint() {
res.reserve(hint);
}
while let Some((k, IntWrap(v))) = map.next_entry()? {
res.push((k, v));
}
res.sort_unstable();
res.dedup_by(|a, b| a.0 == b.0);
Ok(res)
}
}
de.deserialize_map(IntMapVisitor::new())
}
/// Take a Map with integer values and deserialize those to a Vec of sorted
/// pairs
///
/// To be used like this:
/// `#[serde(deserialize_with = "vec_deserialize_int_power_level_values")]`
pub fn vec_deserialize_int_power_level_values<'de, D, T>(de: D) -> Result<Vec<(T, i64)>, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de> + Ord,
{
struct IntMapVisitor<T> {
_phantom: PhantomData<T>,
}
impl<T> IntMapVisitor<T> {
fn new() -> Self {
Self {
_phantom: PhantomData,
}
}
}
impl<'de, T> Visitor<'de> for IntMapVisitor<T>
where
T: Deserialize<'de> + Ord,
{
type Value = Vec<(T, i64)>;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a map with integers as values")
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
let mut res = Vec::new();
if let Some(hint) = map.size_hint() {
res.reserve(hint);
}
while let Some(item) = map.next_entry()? {
res.push(item);
}
res.sort_unstable();
res.dedup_by(|a, b| a.0 == b.0);
Ok(res)
}
}
de.deserialize_map(IntMapVisitor::new())
}
#[cfg(test)]
mod tests {
use serde::Deserialize;
use super::deserialize_v1_power_level;
#[derive(Debug, Deserialize)]
struct Test {
#[serde(deserialize_with = "deserialize_v1_power_level")]
num: i64,
}
#[test]
fn int_or_string() {
let test = serde_json::from_value::<Test>(serde_json::json!({ "num": "0" })).unwrap();
assert_eq!(test.num, 0);
}
#[test]
fn weird_plus_string() {
let test =
serde_json::from_value::<Test>(serde_json::json!({ "num": " +0000000001000 " }))
.unwrap();
assert_eq!(test.num, 1000);
}
#[test]
fn weird_minus_string() {
let test = serde_json::from_value::<Test>(
serde_json::json!({ "num": " \n\n-0000000000000001000 " }),
)
.unwrap();
assert_eq!(test.num, -1000);
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/serde/can_be_empty.rs | crates/core/src/serde/can_be_empty.rs | //! Helpers for emptiness checks in `#[serde(skip_serializing_if)]`.
/// Trait for types that have an "empty" state.
///
/// If `Default` is implemented for `Self`, `Self::default().is_empty()` should
/// always be `true`.
pub trait CanBeEmpty {
/// Check whether `self` is empty.
fn is_empty(&self) -> bool;
}
/// Check whether a value is empty.
pub fn is_empty<T: CanBeEmpty>(val: &T) -> bool {
val.is_empty()
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/serde/buf.rs | crates/core/src/serde/buf.rs | use bytes::BufMut;
use serde::Serialize;
/// Converts a byte slice to a buffer by copying.
pub fn slice_to_buf<B: Default + BufMut>(s: &[u8]) -> B {
let mut buf = B::default();
buf.put_slice(s);
buf
}
/// Creates a buffer and writes a serializable value to it.
pub fn json_to_buf<B: Default + BufMut, T: Serialize>(val: &T) -> serde_json::Result<B> {
let mut buf = B::default().writer();
serde_json::to_writer(&mut buf, val)?;
Ok(buf.into_inner())
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/serde/canonical_json.rs | crates/core/src/serde/canonical_json.rs | //! Canonical JSON types and related functions.
use std::{fmt, mem};
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value as JsonValue;
mod value;
pub use self::value::{CanonicalJsonObject, CanonicalJsonValue};
use crate::{room_version_rules::RedactionRules, serde::RawJson};
const CANONICALJSON_MAX_INT: i64 = (2i64.pow(53)) - 1;
const CANONICALJSON_MIN_INT: i64 = -CANONICALJSON_MAX_INT;
/// The set of possible errors when serializing to canonical JSON.
#[derive(Debug)]
#[allow(clippy::exhaustive_enums)]
pub enum CanonicalJsonError {
IntConvert,
InvalidIntRange,
/// An error occurred while serializing/deserializing.
SerDe(serde_json::Error),
}
impl fmt::Display for CanonicalJsonError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CanonicalJsonError::IntConvert => f.write_str("number found is not a valid `int`"),
CanonicalJsonError::InvalidIntRange => {
write!(f, "integer is out of range for canonical JSON")
}
CanonicalJsonError::SerDe(err) => write!(f, "serde Error: {err}"),
}
}
}
impl std::error::Error for CanonicalJsonError {}
impl From<serde_json::Error> for CanonicalJsonError {
fn from(value: serde_json::Error) -> Self {
Self::SerDe(value)
}
}
/// Errors that can happen in redaction.
#[derive(Debug)]
pub enum RedactionError {
/// The field `field` is not of the correct type `of_type` ([`JsonType`]).
NotOfType {
/// The field name.
field: String,
/// The expected JSON type.
of_type: JsonType,
},
/// The given required field is missing from a JSON object.
JsonFieldMissingFromObject(String),
}
impl fmt::Display for RedactionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RedactionError::NotOfType { field, of_type } => {
write!(f, "Value in {field:?} must be a JSON {of_type:?}")
}
RedactionError::JsonFieldMissingFromObject(field) => {
write!(f, "JSON object must contain the field {field:?}")
}
}
}
}
impl std::error::Error for RedactionError {}
impl RedactionError {
fn not_of_type(target: &str, of_type: JsonType) -> Self {
Self::NotOfType {
field: target.to_owned(),
of_type,
}
}
fn field_missing_from_object(target: &str) -> Self {
Self::JsonFieldMissingFromObject(target.to_owned())
}
}
/// A JSON type enum for [`RedactionError`] variants.
#[derive(Debug)]
#[allow(clippy::exhaustive_enums)]
pub enum JsonType {
/// A JSON Object.
Object,
/// A JSON String.
String,
/// A JSON Integer.
Integer,
/// A JSON Array.
Array,
/// A JSON Boolean.
Boolean,
/// JSON Null.
Null,
}
/// Fallible conversion from a `serde_json::Map` to a `CanonicalJsonObject`.
pub fn try_from_json_map(
json: serde_json::Map<String, JsonValue>,
) -> Result<CanonicalJsonObject, CanonicalJsonError> {
json.into_iter()
.map(|(k, v)| Ok((k, v.try_into()?)))
.collect()
}
/// Fallible conversion from any value that implements `Serialize` to a `CanonicalJsonObject`.
///
/// `value` must serialize to an `serde_json::Value::Object`.
pub fn to_canonical_object<T: serde::Serialize>(
value: T,
) -> Result<CanonicalJsonObject, CanonicalJsonError> {
use serde::ser::Error;
match serde_json::to_value(value).map_err(CanonicalJsonError::SerDe)? {
serde_json::Value::Object(map) => try_from_json_map(map),
_ => Err(CanonicalJsonError::SerDe(serde_json::Error::custom(
"Value must be an object",
))),
}
}
/// Fallible conversion from any value that impl's `Serialize` to a
/// `CanonicalJsonValue`.
pub fn to_canonical_value<T: Serialize>(
value: T,
) -> Result<CanonicalJsonValue, CanonicalJsonError> {
serde_json::to_value(value)
.map_err(CanonicalJsonError::SerDe)?
.try_into()
}
pub fn from_canonical_value<T>(value: CanonicalJsonObject) -> Result<T, CanonicalJsonError>
where
T: DeserializeOwned,
{
serde_json::from_value(serde_json::to_value(value)?).map_err(CanonicalJsonError::SerDe)
}
pub fn validate_canonical_json(json: &CanonicalJsonObject) -> Result<(), CanonicalJsonError> {
for value in json.values() {
match value {
CanonicalJsonValue::Object(obj) => validate_canonical_json(obj)?,
CanonicalJsonValue::Array(arr) => {
for item in arr {
if let CanonicalJsonValue::Object(obj) = item {
validate_canonical_json(obj)?
}
}
}
CanonicalJsonValue::Integer(value) => {
if *value < CANONICALJSON_MIN_INT || *value > CANONICALJSON_MAX_INT {
return Err(CanonicalJsonError::InvalidIntRange);
}
}
_ => {}
}
}
Ok(())
}
/// The value to put in `unsigned.redacted_because`.
#[derive(Clone, Debug)]
pub struct RedactedBecause(CanonicalJsonObject);
impl RedactedBecause {
/// Create a `RedactedBecause` from an arbitrary JSON object.
pub fn from_json(obj: CanonicalJsonObject) -> Self {
Self(obj)
}
/// Create a `RedactedBecause` from a redaction event.
///
/// Fails if the raw event is not valid canonical JSON.
pub fn from_raw_event(ev: &RawJson<impl RedactionEvent>) -> serde_json::Result<Self> {
ev.deserialize_as().map(Self)
}
}
/// Marker trait for redaction events.
pub trait RedactionEvent {}
/// Redacts an event using the rules specified in the Matrix client-server
/// specification.
///
/// This is part of the process of signing an event.
///
/// Redaction is also suggested when verifying an event with `verify_event`
/// returns `Verified::Signatures`. See the documentation for `Verified` for
/// details.
///
/// Returns a new JSON object with all applicable fields redacted.
///
/// # Parameters
///
/// * `object`: A JSON object to redact.
/// * `version`: The room version, determines which keys to keep for a few event
/// types.
/// * `redacted_because`: If this is set, an `unsigned` object with a
/// `redacted_because` field set to the given value is added to the event
/// after redaction.
///
/// # Errors
///
/// Returns an error if:
///
/// * `object` contains a field called `content` that is not a JSON object.
/// * `object` contains a field called `hashes` that is not a JSON object.
/// * `object` contains a field called `signatures` that is not a JSON object.
/// * `object` is missing the `type` field or the field is not a JSON string.
pub fn redact(
mut object: CanonicalJsonObject,
rules: &RedactionRules,
redacted_because: Option<RedactedBecause>,
) -> Result<CanonicalJsonObject, RedactionError> {
redact_in_place(&mut object, rules, redacted_because)?;
Ok(object)
}
/// Redacts an event using the rules specified in the Matrix client-server
/// specification.
///
/// Functionally equivalent to `redact`, only this'll redact the event in-place.
pub fn redact_in_place(
event: &mut CanonicalJsonObject,
rules: &RedactionRules,
redacted_because: Option<RedactedBecause>,
) -> Result<(), RedactionError> {
// Get the content keys here even if they're only needed inside the branch below, because we
// can't teach rust that this is a disjoint borrow with `get_mut("content")`.
let retained_event_content_keys = match event.get("type") {
Some(CanonicalJsonValue::String(event_type)) => {
retained_event_content_keys(event_type.as_ref(), rules)
}
Some(_) => return Err(RedactionError::not_of_type("type", JsonType::String)),
None => return Err(RedactionError::field_missing_from_object("type")),
};
if let Some(content_value) = event.get_mut("content") {
let CanonicalJsonValue::Object(content) = content_value else {
return Err(RedactionError::not_of_type("content", JsonType::Object));
};
retained_event_content_keys.apply(rules, content)?;
}
let retained_event_keys =
RetainedKeys::some(|rules, key, _value| Ok(is_event_key_retained(rules, key)));
retained_event_keys.apply(rules, event)?;
if let Some(redacted_because) = redacted_because {
let unsigned = CanonicalJsonObject::from_iter([(
"redacted_because".to_owned(),
redacted_because.0.into(),
)]);
event.insert("unsigned".to_owned(), unsigned.into());
}
Ok(())
}
/// Redacts event content using the rules specified in the Matrix client-server
/// specification.
///
/// Edits the `object` in-place.
pub fn redact_content_in_place(
content: &mut CanonicalJsonObject,
rules: &RedactionRules,
event_type: impl AsRef<str>,
) -> Result<(), RedactionError> {
retained_event_content_keys(event_type.as_ref(), rules).apply(rules, content)
}
/// A function that takes redaction rules, a key and its value, and returns whether the field
/// should be retained.
type RetainKeyFn =
dyn Fn(&RedactionRules, &str, &mut CanonicalJsonValue) -> Result<bool, RedactionError>;
/// Keys to retain on an object.
enum RetainedKeys {
/// All keys are retained.
All,
/// Some keys are retained, they are determined by the inner function.
Some(Box<RetainKeyFn>),
/// No keys are retained.
None,
}
impl RetainedKeys {
/// Construct a `RetainedKeys::Some(_)` with the given function.
fn some<F>(retain_key_fn: F) -> Self
where
F: Fn(&RedactionRules, &str, &mut CanonicalJsonValue) -> Result<bool, RedactionError>
+ 'static,
{
Self::Some(Box::new(retain_key_fn))
}
/// Apply this `RetainedKeys` on the given object.
fn apply(
&self,
rules: &RedactionRules,
object: &mut CanonicalJsonObject,
) -> Result<(), RedactionError> {
match self {
Self::All => {}
Self::Some(allow_field_fn) => {
let old_object = mem::take(object);
for (key, mut value) in old_object {
if allow_field_fn(rules, &key, &mut value)? {
object.insert(key, value);
}
}
}
Self::None => object.clear(),
}
Ok(())
}
}
/// Get the given keys should be retained at the top level of an event.
fn is_event_key_retained(rules: &RedactionRules, key: &str) -> bool {
match key {
"event_id" | "type" | "room_id" | "sender" | "state_key" | "content" | "hashes"
| "signatures" | "depth" | "prev_events" | "auth_events" | "origin_server_ts" => true,
"origin" | "membership" | "prev_state" => rules.keep_origin_membership_prev_state,
_ => false,
}
}
/// Get the keys that should be retained in the `content` of an event with the given type.
fn retained_event_content_keys(event_type: &str, rules: &RedactionRules) -> RetainedKeys {
match event_type {
"m.room.member" => RetainedKeys::some(is_room_member_content_key_retained),
"m.room.create" => room_create_content_retained_keys(rules),
"m.room.join_rules" => RetainedKeys::some(|rules, key, _value| {
is_room_join_rules_content_key_retained(rules, key)
}),
"m.room.power_levels" => RetainedKeys::some(|rules, key, _value| {
is_room_power_levels_content_key_retained(rules, key)
}),
"m.room.history_visibility" => RetainedKeys::some(|_rules, key, _value| {
is_room_history_visibility_content_key_retained(key)
}),
"m.room.redaction" => room_redaction_content_retained_keys(rules),
"m.room.aliases" => room_aliases_content_retained_keys(rules),
#[cfg(feature = "unstable-msc2870")]
"m.room.server_acl" => RetainedKeys::some(|rules, key, _value| {
is_room_server_acl_content_key_retained(rules, key)
}),
_ => RetainedKeys::None,
}
}
/// Whether the given key in the `content` of an `m.room.member` event is retained after redaction.
fn is_room_member_content_key_retained(
rules: &RedactionRules,
key: &str,
value: &mut CanonicalJsonValue,
) -> Result<bool, RedactionError> {
Ok(match key {
"membership" => true,
"join_authorised_via_users_server" => {
rules.keep_room_member_join_authorised_via_users_server
}
"third_party_invite" if rules.keep_room_member_third_party_invite_signed => {
let Some(third_party_invite) = value.as_object_mut() else {
return Err(RedactionError::not_of_type(
"third_party_invite",
JsonType::Object,
));
};
third_party_invite.retain(|key, _| key == "signed");
// Keep the field only if it's not empty.
!third_party_invite.is_empty()
}
_ => false,
})
}
/// Get the retained keys in the `content` of an `m.room.create` event.
fn room_create_content_retained_keys(rules: &RedactionRules) -> RetainedKeys {
if rules.keep_room_create_content {
RetainedKeys::All
} else {
RetainedKeys::some(|_rules, field, _value| Ok(field == "creator"))
}
}
/// Whether the given key in the `content` of an `m.room.join_rules` event is retained after
/// redaction.
fn is_room_join_rules_content_key_retained(
rules: &RedactionRules,
key: &str,
) -> Result<bool, RedactionError> {
Ok(match key {
"join_rule" => true,
"allow" => rules.keep_room_join_rules_allow,
_ => false,
})
}
/// Whether the given key in the `content` of an `m.room.power_levels` event is retained after
/// redaction.
fn is_room_power_levels_content_key_retained(
rules: &RedactionRules,
key: &str,
) -> Result<bool, RedactionError> {
Ok(match key {
"ban" | "events" | "events_default" | "kick" | "redact" | "state_default" | "users"
| "users_default" => true,
"invite" => rules.keep_room_power_levels_invite,
_ => false,
})
}
/// Whether the given key in the `content` of an `m.room.history_visibility` event is retained after
/// redaction.
fn is_room_history_visibility_content_key_retained(key: &str) -> Result<bool, RedactionError> {
Ok(key == "history_visibility")
}
/// Get the retained keys in the `content` of an `m.room.redaction` event.
fn room_redaction_content_retained_keys(rules: &RedactionRules) -> RetainedKeys {
if rules.keep_room_redaction_redacts {
RetainedKeys::some(|_rules, field, _value| Ok(field == "redacts"))
} else {
RetainedKeys::None
}
}
/// Get the retained keys in the `content` of an `m.room.aliases` event.
fn room_aliases_content_retained_keys(rules: &RedactionRules) -> RetainedKeys {
if rules.keep_room_aliases_aliases {
RetainedKeys::some(|_rules, field, _value| Ok(field == "aliases"))
} else {
RetainedKeys::None
}
}
/// Whether the given key in the `content` of an `m.room.server_acl` event is retained after
/// redaction.
#[cfg(feature = "unstable-msc2870")]
fn is_room_server_acl_content_key_retained(
rules: &RedactionRules,
key: &str,
) -> Result<bool, RedactionError> {
Ok(match key {
"allow" | "deny" | "allow_ip_literals" => {
rules.keep_room_server_acl_allow_deny_allow_ip_literals
}
_ => false,
})
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use assert_matches2::assert_matches;
use serde_json::{
from_str as from_json_str, json, to_string as to_json_string, to_value as to_json_value,
};
use super::{
redact_in_place, to_canonical_value, try_from_json_map, value::CanonicalJsonValue,
};
use crate::room_version_rules::RedactionRules;
#[test]
fn serialize_canon() {
let json: CanonicalJsonValue = json!({
"a": [1, 2, 3],
"other": { "stuff": "hello" },
"string": "Thing"
})
.try_into()
.unwrap();
let ser = to_json_string(&json).unwrap();
let back = from_json_str::<CanonicalJsonValue>(&ser).unwrap();
assert_eq!(json, back);
}
#[test]
fn check_canonical_sorts_keys() {
let json: CanonicalJsonValue = json!({
"auth": {
"success": true,
"mxid": "@john.doe:example.com",
"profile": {
"display_name": "John Doe",
"three_pids": [
{
"medium": "email",
"address": "john.doe@example.org"
},
{
"medium": "msisdn",
"address": "123456789"
}
]
}
}
})
.try_into()
.unwrap();
assert_eq!(
to_json_string(&json).unwrap(),
r#"{"auth":{"mxid":"@john.doe:example.com","profile":{"display_name":"John Doe","three_pids":[{"address":"john.doe@example.org","medium":"email"},{"address":"123456789","medium":"msisdn"}]},"success":true}}"#
);
}
#[test]
fn serialize_map_to_canonical() {
let mut expected = BTreeMap::new();
expected.insert("foo".into(), CanonicalJsonValue::String("string".into()));
expected.insert(
"bar".into(),
CanonicalJsonValue::Array(vec![
CanonicalJsonValue::Integer(0),
CanonicalJsonValue::Integer(1),
CanonicalJsonValue::Integer(2),
]),
);
let mut map = serde_json::Map::new();
map.insert("foo".into(), json!("string"));
map.insert("bar".into(), json!(vec![0, 1, 2,]));
assert_eq!(try_from_json_map(map).unwrap(), expected);
}
#[test]
fn to_canonical() {
#[derive(Debug, serde::Serialize)]
struct Thing {
foo: String,
bar: Vec<u8>,
}
let t = Thing {
foo: "string".into(),
bar: vec![0, 1, 2],
};
let mut expected = BTreeMap::new();
expected.insert("foo".into(), CanonicalJsonValue::String("string".into()));
expected.insert(
"bar".into(),
CanonicalJsonValue::Array(vec![
CanonicalJsonValue::Integer(0),
CanonicalJsonValue::Integer(1),
CanonicalJsonValue::Integer(2),
]),
);
assert_eq!(
to_canonical_value(t).unwrap(),
CanonicalJsonValue::Object(expected)
);
}
#[test]
fn redact_allowed_keys_some() {
let original_event = json!({
"content": {
"ban": 50,
"events": {
"m.room.avatar": 50,
"m.room.canonical_alias": 50,
"m.room.history_visibility": 100,
"m.room.name": 50,
"m.room.power_levels": 100
},
"events_default": 0,
"invite": 0,
"kick": 50,
"redact": 50,
"state_default": 50,
"users": {
"@example:localhost": 100
},
"users_default": 0
},
"event_id": "$15139375512JaHAW:localhost",
"origin_server_ts": 45,
"sender": "@example:localhost",
"room_id": "!room:localhost",
"state_key": "",
"type": "m.room.power_levels",
"unsigned": {
"age": 45
}
});
assert_matches!(
CanonicalJsonValue::try_from(original_event),
Ok(CanonicalJsonValue::Object(mut object))
);
redact_in_place(&mut object, &RedactionRules::V1, None).unwrap();
let redacted_event = to_json_value(&object).unwrap();
assert_eq!(
redacted_event,
json!({
"content": {
"ban": 50,
"events": {
"m.room.avatar": 50,
"m.room.canonical_alias": 50,
"m.room.history_visibility": 100,
"m.room.name": 50,
"m.room.power_levels": 100
},
"events_default": 0,
"kick": 50,
"redact": 50,
"state_default": 50,
"users": {
"@example:localhost": 100
},
"users_default": 0
},
"event_id": "$15139375512JaHAW:localhost",
"origin_server_ts": 45,
"sender": "@example:localhost",
"room_id": "!room:localhost",
"state_key": "",
"type": "m.room.power_levels",
})
);
}
#[test]
fn redact_allowed_keys_none() {
let original_event = json!({
"content": {
"aliases": ["#somewhere:localhost"]
},
"event_id": "$152037280074GZeOm:localhost",
"origin_server_ts": 1,
"sender": "@example:localhost",
"state_key": "room.com",
"room_id": "!room:room.com",
"type": "m.room.aliases",
"unsigned": {
"age": 1
}
});
assert_matches!(
CanonicalJsonValue::try_from(original_event),
Ok(CanonicalJsonValue::Object(mut object))
);
redact_in_place(&mut object, &RedactionRules::V9, None).unwrap();
let redacted_event = to_json_value(&object).unwrap();
assert_eq!(
redacted_event,
json!({
"content": {},
"event_id": "$152037280074GZeOm:localhost",
"origin_server_ts": 1,
"sender": "@example:localhost",
"state_key": "room.com",
"room_id": "!room:room.com",
"type": "m.room.aliases",
})
);
}
#[test]
fn redact_allowed_keys_all() {
let original_event = json!({
"content": {
"m.federate": true,
"predecessor": {
"event_id": "$something",
"room_id": "!oldroom:example.org"
},
"room_version": "11",
},
"event_id": "$143273582443PhrSn",
"origin_server_ts": 1_432_735,
"room_id": "!jEsUZKDJdhlrceRyVU:example.org",
"sender": "@example:example.org",
"state_key": "",
"type": "m.room.create",
"unsigned": {
"age": 1234,
},
});
assert_matches!(
CanonicalJsonValue::try_from(original_event),
Ok(CanonicalJsonValue::Object(mut object))
);
redact_in_place(&mut object, &RedactionRules::V11, None).unwrap();
let redacted_event = to_json_value(&object).unwrap();
assert_eq!(
redacted_event,
json!({
"content": {
"m.federate": true,
"predecessor": {
"event_id": "$something",
"room_id": "!oldroom:example.org"
},
"room_version": "11",
},
"event_id": "$143273582443PhrSn",
"origin_server_ts": 1_432_735,
"room_id": "!jEsUZKDJdhlrceRyVU:example.org",
"sender": "@example:example.org",
"state_key": "",
"type": "m.room.create",
})
);
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/serde/duration.rs | crates/core/src/serde/duration.rs | //! De-/serialization functions for `std::time::Duration` objects
pub mod ms;
pub mod opt_ms;
pub mod opt_secs;
pub mod secs;
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/serde/duration/opt_ms.rs | crates/core/src/serde/duration/opt_ms.rs | //! De-/serialization functions for `Option<std::time::Duration>` objects
//! represented as milliseconds.
use std::time::Duration;
use serde::{
de::{Deserialize, Deserializer},
ser::{Error, Serialize, Serializer},
};
/// Serialize an `Option<Duration>`.
///
/// Will fail if integer is greater than the maximum integer that can be
/// unambiguously represented by an f64.
pub fn serialize<S>(opt_duration: &Option<Duration>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match opt_duration {
Some(duration) => match u64::try_from(duration.as_millis()) {
Ok(uint) => uint.serialize(serializer),
Err(err) => Err(S::Error::custom(err)),
},
None => serializer.serialize_none(),
}
}
/// Deserializes an `Option<Duration>`.
///
/// Will fail if integer is greater than the maximum integer that can be
/// unambiguously represented by an f64.
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Duration>, D::Error>
where
D: Deserializer<'de>,
{
Ok(Option::<u64>::deserialize(deserializer)?.map(Duration::from_millis))
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use serde::{Deserialize, Serialize};
use serde_json::json;
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
struct DurationTest {
#[serde(with = "super", default, skip_serializing_if = "Option::is_none")]
timeout: Option<Duration>,
}
#[test]
fn deserialize_some() {
let json = json!({ "timeout": 3000 });
assert_eq!(
serde_json::from_value::<DurationTest>(json).unwrap(),
DurationTest {
timeout: Some(Duration::from_millis(3000))
},
);
}
#[test]
fn deserialize_none_by_absence() {
let json = json!({});
assert_eq!(
serde_json::from_value::<DurationTest>(json).unwrap(),
DurationTest { timeout: None },
);
}
#[test]
fn deserialize_none_by_null() {
let json = json!({ "timeout": null });
assert_eq!(
serde_json::from_value::<DurationTest>(json).unwrap(),
DurationTest { timeout: None },
);
}
#[test]
fn serialize_some() {
let request = DurationTest {
timeout: Some(Duration::new(2, 0)),
};
assert_eq!(
serde_json::to_value(request).unwrap(),
json!({ "timeout": 2000 })
);
}
#[test]
fn serialize_none() {
let request = DurationTest { timeout: None };
assert_eq!(serde_json::to_value(request).unwrap(), json!({}));
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/serde/duration/secs.rs | crates/core/src/serde/duration/secs.rs | //! De-/serialization functions for `Option<std::time::Duration>` objects
//! represented as milliseconds.
use std::time::Duration;
use serde::{
de::{Deserialize, Deserializer},
ser::{Serialize, Serializer},
};
/// Serializes a Duration to an integer representing seconds.
///
/// Will fail if integer is greater than the maximum integer that can be
/// unambiguously represented by an f64.
pub fn serialize<S>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
duration.as_secs().serialize(serializer)
}
/// Deserializes an integer representing seconds into a Duration.
///
/// Will fail if integer is greater than the maximum integer that can be
/// unambiguously represented by an f64.
pub fn deserialize<'de, D>(deserializer: D) -> Result<Duration, D::Error>
where
D: Deserializer<'de>,
{
u64::deserialize(deserializer).map(Duration::from_secs)
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use serde::{Deserialize, Serialize};
use serde_json::json;
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
struct DurationTest {
#[serde(with = "super")]
timeout: Duration,
}
#[test]
fn deserialize() {
let json = json!({ "timeout": 3 });
assert_eq!(
serde_json::from_value::<DurationTest>(json).unwrap(),
DurationTest {
timeout: Duration::from_secs(3)
},
);
}
#[test]
fn serialize() {
let test = DurationTest {
timeout: Duration::from_millis(7000),
};
assert_eq!(serde_json::to_value(test).unwrap(), json!({ "timeout": 7 }));
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/serde/duration/ms.rs | crates/core/src/serde/duration/ms.rs | //! De-/serialization functions for `Option<std::time::Duration>` objects
//! represented as milliseconds.
use std::time::Duration;
use serde::{
de::{Deserialize, Deserializer},
ser::{Error, Serialize, Serializer},
};
/// Serializes a Duration to an integer representing seconds.
///
/// Will fail if integer is greater than the maximum integer that can be
/// unambiguously represented by an f64.
pub fn serialize<S>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match u64::try_from(duration.as_millis()) {
Ok(uint) => uint.serialize(serializer),
Err(err) => Err(S::Error::custom(err)),
}
}
/// Deserializes an integer representing seconds into a Duration.
///
/// Will fail if integer is greater than the maximum integer that can be
/// unambiguously represented by an f64.
pub fn deserialize<'de, D>(deserializer: D) -> Result<Duration, D::Error>
where
D: Deserializer<'de>,
{
u64::deserialize(deserializer).map(Duration::from_millis)
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use serde::{Deserialize, Serialize};
use serde_json::json;
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
struct DurationTest {
#[serde(with = "super")]
timeout: Duration,
}
#[test]
fn deserialize() {
let json = json!({ "timeout": 3000 });
assert_eq!(
serde_json::from_value::<DurationTest>(json).unwrap(),
DurationTest {
timeout: Duration::from_secs(3)
},
);
}
#[test]
fn serialize() {
let test = DurationTest {
timeout: Duration::from_millis(7000),
};
assert_eq!(
serde_json::to_value(test).unwrap(),
json!({ "timeout": 7000 })
);
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/serde/duration/opt_secs.rs | crates/core/src/serde/duration/opt_secs.rs | //! De-/serialization functions for `Option<std::time::Duration>` objects
//! represented as milliseconds.
use std::time::Duration;
use serde::{
de::{Deserialize, Deserializer},
ser::{Serialize, Serializer},
};
/// Serialize an `Option<Duration>`.
///
/// Will fail if integer is greater than the maximum integer that can be
/// unambiguously represented by an f64.
pub fn serialize<S>(opt_duration: &Option<Duration>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match opt_duration {
Some(duration) => duration.as_secs().serialize(serializer),
None => serializer.serialize_none(),
}
}
/// Deserializes an `Option<Duration>`.
///
/// Will fail if integer is greater than the maximum integer that can be
/// unambiguously represented by an f64.
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Duration>, D::Error>
where
D: Deserializer<'de>,
{
Ok(Option::<u64>::deserialize(deserializer)?.map(Duration::from_secs))
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use serde::{Deserialize, Serialize};
use serde_json::json;
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
struct DurationTest {
#[serde(with = "super", default, skip_serializing_if = "Option::is_none")]
timeout: Option<Duration>,
}
#[test]
fn deserialize_some() {
let json = json!({ "timeout": 300 });
assert_eq!(
serde_json::from_value::<DurationTest>(json).unwrap(),
DurationTest {
timeout: Some(Duration::from_secs(300))
},
);
}
#[test]
fn deserialize_none_by_absence() {
let json = json!({});
assert_eq!(
serde_json::from_value::<DurationTest>(json).unwrap(),
DurationTest { timeout: None },
);
}
#[test]
fn deserialize_none_by_null() {
let json = json!({ "timeout": null });
assert_eq!(
serde_json::from_value::<DurationTest>(json).unwrap(),
DurationTest { timeout: None },
);
}
#[test]
fn serialize_some() {
let request = DurationTest {
timeout: Some(Duration::new(2, 0)),
};
assert_eq!(
serde_json::to_value(request).unwrap(),
json!({ "timeout": 2 })
);
}
#[test]
fn serialize_none() {
let request = DurationTest { timeout: None };
assert_eq!(serde_json::to_value(request).unwrap(), json!({}));
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/serde/canonical_json/value.rs | crates/core/src/serde/canonical_json/value.rs | use std::{collections::BTreeMap, fmt};
use as_variant::as_variant;
use serde::{Deserialize, Serialize, de::Deserializer, ser::Serializer};
use serde_json::{Value as JsonValue, to_string as to_json_string};
use super::CanonicalJsonError;
/// The inner type of `CanonicalJsonValue::Object`.
pub type CanonicalJsonObject = BTreeMap<String, CanonicalJsonValue>;
/// Represents a canonical JSON value as per the Matrix specification.
#[derive(Clone, Default, Eq, PartialEq)]
#[allow(clippy::exhaustive_enums)]
pub enum CanonicalJsonValue {
/// Represents a JSON null value.
///
/// ```
/// # use serde_json::json;
/// # use palpo_core::serde::CanonicalJsonValue;
/// let v: CanonicalJsonValue = json!(null).try_into().unwrap();
/// ```
#[default]
Null,
/// Represents a JSON boolean.
///
/// ```
/// # use serde_json::json;
/// # use palpo_core::serde::CanonicalJsonValue;
/// let v: CanonicalJsonValue = json!(true).try_into().unwrap();
/// ```
Bool(bool),
/// Represents a JSON integer.
///
/// ```
/// # use serde_json::json;
/// # use palpo_core::serde::CanonicalJsonValue;
/// let v: CanonicalJsonValue = json!(12).try_into().unwrap();
/// ```
Integer(i64),
/// Represents a JSON string.
///
/// ```
/// # use serde_json::json;
/// # use palpo_core::serde::CanonicalJsonValue;
/// let v: CanonicalJsonValue = json!("a string").try_into().unwrap();
/// ```
String(String),
/// Represents a JSON array.
///
/// ```
/// # use serde_json::json;
/// # use palpo_core::serde::CanonicalJsonValue;
/// let v: CanonicalJsonValue = json!(["an", "array"]).try_into().unwrap();
/// ```
Array(Vec<CanonicalJsonValue>),
/// Represents a JSON object.
///
/// The map is backed by a BTreeMap to guarantee the sorting of keys.
///
/// ```
/// # use serde_json::json;
/// # use palpo_core::serde::CanonicalJsonValue;
/// let v: CanonicalJsonValue = json!({ "an": "object" }).try_into().unwrap();
/// ```
Object(CanonicalJsonObject),
}
impl CanonicalJsonValue {
/// If the `CanonicalJsonValue` is a `Bool`, return the inner value.
pub fn as_bool(&self) -> Option<bool> {
as_variant!(self, Self::Bool).copied()
}
/// If the `CanonicalJsonValue` is an `Integer`, return the inner value.
pub fn as_integer(&self) -> Option<i64> {
as_variant!(self, Self::Integer).copied()
}
/// If the `CanonicalJsonValue` is a `String`, return a reference to the
/// inner value.
pub fn as_str(&self) -> Option<&str> {
as_variant!(self, Self::String)
}
/// If the `CanonicalJsonValue` is an `Array`, return a reference to the
/// inner value.
pub fn as_array(&self) -> Option<&[CanonicalJsonValue]> {
as_variant!(self, Self::Array)
}
/// If the `CanonicalJsonValue` is an `Object`, return a reference to the
/// inner value.
pub fn as_object(&self) -> Option<&CanonicalJsonObject> {
as_variant!(self, Self::Object)
}
/// If the `CanonicalJsonValue` is an `Array`, return a mutable reference to
/// the inner value.
pub fn as_array_mut(&mut self) -> Option<&mut Vec<CanonicalJsonValue>> {
as_variant!(self, Self::Array)
}
/// If the `CanonicalJsonValue` is an `Object`, return a mutable reference
/// to the inner value.
pub fn as_object_mut(&mut self) -> Option<&mut CanonicalJsonObject> {
as_variant!(self, Self::Object)
}
/// Returns `true` if the `CanonicalJsonValue` is a `Bool`.
pub fn is_bool(&self) -> bool {
matches!(self, Self::Bool(_))
}
/// Returns `true` if the `CanonicalJsonValue` is an `Integer`.
pub fn is_integer(&self) -> bool {
matches!(self, Self::Integer(_))
}
/// Returns `true` if the `CanonicalJsonValue` is a `String`.
pub fn is_string(&self) -> bool {
matches!(self, Self::String(_))
}
/// Returns `true` if the `CanonicalJsonValue` is an `Array`.
pub fn is_array(&self) -> bool {
matches!(self, Self::Array(_))
}
/// Returns `true` if the `CanonicalJsonValue` is an `Object`.
pub fn is_object(&self) -> bool {
matches!(self, Self::Object(_))
}
}
impl fmt::Debug for CanonicalJsonValue {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::Null => formatter.debug_tuple("Null").finish(),
Self::Bool(v) => formatter.debug_tuple("Bool").field(&v).finish(),
Self::Integer(ref v) => fmt::Debug::fmt(v, formatter),
Self::String(ref v) => formatter.debug_tuple("String").field(v).finish(),
Self::Array(ref v) => {
formatter.write_str("Array(")?;
fmt::Debug::fmt(v, formatter)?;
formatter.write_str(")")
}
Self::Object(ref v) => {
formatter.write_str("Object(")?;
fmt::Debug::fmt(v, formatter)?;
formatter.write_str(")")
}
}
}
}
impl fmt::Display for CanonicalJsonValue {
/// Display this value as a string.
///
/// This `Display` implementation is intentionally unaffected by any
/// formatting parameters, because adding extra whitespace or otherwise
/// pretty-printing it would make it not the canonical form anymore.
///
/// If you want to pretty-print a `CanonicalJsonValue` for debugging
/// purposes, use one of `serde_json::{to_string_pretty, to_vec_pretty,
/// to_writer_pretty}`.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", to_json_string(&self).map_err(|_| fmt::Error)?)
}
}
impl TryFrom<JsonValue> for CanonicalJsonValue {
type Error = CanonicalJsonError;
fn try_from(val: JsonValue) -> Result<Self, Self::Error> {
Ok(match val {
JsonValue::Bool(b) => Self::Bool(b),
JsonValue::Number(num) => {
Self::Integer(num.as_i64().ok_or(CanonicalJsonError::IntConvert)?)
}
JsonValue::Array(vec) => Self::Array(
vec.into_iter()
.map(TryInto::try_into)
.collect::<Result<Vec<_>, _>>()?,
),
JsonValue::String(string) => Self::String(string),
JsonValue::Object(obj) => Self::Object(
obj.into_iter()
.map(|(k, v)| Ok((k, v.try_into()?)))
.collect::<Result<CanonicalJsonObject, CanonicalJsonError>>()?,
),
JsonValue::Null => Self::Null,
})
}
}
impl From<CanonicalJsonValue> for JsonValue {
fn from(val: CanonicalJsonValue) -> Self {
match val {
CanonicalJsonValue::Bool(b) => Self::Bool(b),
CanonicalJsonValue::Integer(int) => Self::Number(int.into()),
CanonicalJsonValue::String(string) => Self::String(string),
CanonicalJsonValue::Array(vec) => {
Self::Array(vec.into_iter().map(Into::into).collect())
}
CanonicalJsonValue::Object(obj) => {
Self::Object(obj.into_iter().map(|(k, v)| (k, v.into())).collect())
}
CanonicalJsonValue::Null => Self::Null,
}
}
}
macro_rules! variant_impls {
($variant:ident($ty:ty)) => {
impl From<$ty> for CanonicalJsonValue {
fn from(val: $ty) -> Self {
Self::$variant(val.into())
}
}
impl PartialEq<$ty> for CanonicalJsonValue {
fn eq(&self, other: &$ty) -> bool {
match self {
Self::$variant(val) => val == other,
_ => false,
}
}
}
impl PartialEq<CanonicalJsonValue> for $ty {
fn eq(&self, other: &CanonicalJsonValue) -> bool {
match other {
CanonicalJsonValue::$variant(val) => self == val,
_ => false,
}
}
}
};
}
variant_impls!(Bool(bool));
variant_impls!(Integer(i64));
variant_impls!(String(String));
variant_impls!(String(&str));
variant_impls!(Array(Vec<CanonicalJsonValue>));
variant_impls!(Object(CanonicalJsonObject));
impl From<u64> for CanonicalJsonValue {
fn from(value: u64) -> Self {
Self::Integer(value as i64)
}
}
impl Serialize for CanonicalJsonValue {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::Null => serializer.serialize_unit(),
Self::Bool(b) => serializer.serialize_bool(*b),
Self::Integer(n) => n.serialize(serializer),
Self::String(s) => serializer.serialize_str(s),
Self::Array(v) => v.serialize(serializer),
Self::Object(m) => {
use serde::ser::SerializeMap;
let mut map = serializer.serialize_map(Some(m.len()))?;
for (k, v) in m {
map.serialize_entry(k, v)?;
}
map.end()
}
}
}
}
impl<'de> Deserialize<'de> for CanonicalJsonValue {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<CanonicalJsonValue, D::Error>
where
D: Deserializer<'de>,
{
let val = JsonValue::deserialize(deserializer)?;
val.try_into().map_err(serde::de::Error::custom)
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::CanonicalJsonValue;
#[test]
fn to_string() {
const CANONICAL_STR: &str = r#"{"city":"London","street":"10 Downing Street"}"#;
let json: CanonicalJsonValue = json!({ "city": "London", "street": "10 Downing Street" })
.try_into()
.unwrap();
assert_eq!(format!("{json}"), CANONICAL_STR);
assert_eq!(format!("{json:#}"), CANONICAL_STR);
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/video.rs | crates/core/src/events/video.rs | //! Types for extensible video message events ([MSC3553]).
//!
//! [MSC3553]: https://github.com/matrix-org/matrix-spec-proposals/pull/3553
use std::time::Duration;
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use super::{
file::{CaptionContentBlock, FileContentBlock},
image::ThumbnailContentBlock,
message::TextContentBlock,
room::message::Relation,
};
/// The payload for an extensible video message.
///
/// This is the new primary type introduced in [MSC3553] and should only be sent
/// in rooms with a version that supports it. See the documentation of the
/// [`message`] module for more information.
///
/// [MSC3553]: https://github.com/matrix-org/matrix-spec-proposals/pull/3553
/// [`message`]: super::message
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize, EventContent)]
#[palpo_event(type = "org.matrix.msc1767.video", kind = MessageLike, without_relation)]
pub struct VideoEventContent {
/// The text representation of the message.
#[serde(rename = "org.matrix.msc1767.text")]
pub text: TextContentBlock,
/// The file content of the message.
#[serde(rename = "org.matrix.msc1767.file")]
pub file: FileContentBlock,
/// The video details of the message, if any.
#[serde(
rename = "org.matrix.msc1767.video_details",
skip_serializing_if = "Option::is_none"
)]
pub video_details: Option<VideoDetailsContentBlock>,
/// The thumbnails of the message, if any.
///
/// This is optional and defaults to an empty array.
#[serde(
rename = "org.matrix.msc1767.thumbnail",
default,
skip_serializing_if = "ThumbnailContentBlock::is_empty"
)]
pub thumbnail: ThumbnailContentBlock,
/// The caption of the message, if any.
#[serde(
rename = "org.matrix.msc1767.caption",
skip_serializing_if = "Option::is_none"
)]
pub caption: Option<CaptionContentBlock>,
/// Whether this message is automated.
#[serde(
default,
skip_serializing_if = "palpo_core::serde::is_default",
rename = "org.matrix.msc1767.automated"
)]
pub automated: bool,
/// Information about related messages.
#[serde(
flatten,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::events::room::message::relation_serde::deserialize_relation"
)]
pub relates_to: Option<Relation<VideoEventContentWithoutRelation>>,
}
impl VideoEventContent {
/// Creates a new `VideoEventContent` with the given fallback representation
/// and file.
pub fn new(text: TextContentBlock, file: FileContentBlock) -> Self {
Self {
text,
file,
video_details: None,
thumbnail: Default::default(),
caption: None,
automated: false,
relates_to: None,
}
}
/// Creates a new `VideoEventContent` with the given plain text fallback
/// representation and file.
pub fn with_plain_text(plain_text: impl Into<String>, file: FileContentBlock) -> Self {
Self {
text: TextContentBlock::plain(plain_text),
file,
video_details: None,
thumbnail: Default::default(),
caption: None,
automated: false,
relates_to: None,
}
}
}
/// A block for details of video content.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct VideoDetailsContentBlock {
/// The width of the video in pixels.
pub width: u32,
/// The height of the video in pixels.
pub height: u32,
/// The duration of the video in seconds.
#[serde(
with = "palpo_core::serde::duration::opt_secs",
default,
skip_serializing_if = "Option::is_none"
)]
pub duration: Option<Duration>,
}
impl VideoDetailsContentBlock {
/// Creates a new `VideoDetailsContentBlock` with the given height and
/// width.
pub fn new(width: u32, height: u32) -> Self {
Self {
width,
height,
duration: None,
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/rtc.rs | crates/core/src/events/rtc.rs | //! Modules for events in the `m.rtc` namespace.
#[cfg(feature = "unstable-msc4310")]
pub mod decline;
#[cfg(feature = "unstable-msc4075")]
pub mod notification;
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/direct.rs | crates/core/src/events/direct.rs | //! Types for the [`m.direct`] event.
//!
//! [`m.direct`]: https://spec.matrix.org/latest/client-server-api/#mdirect
use std::{
collections::{BTreeMap, btree_map},
ops::{Deref, DerefMut},
};
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{OwnedRoomId, OwnedUserId};
/// The content of an `m.direct` event.
///
/// A mapping of `UserId`s to a list of `RoomId`s which are considered *direct*
/// for that particular user.
///
/// Informs the client about the rooms that are considered direct by a user.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize, EventContent)]
#[allow(clippy::exhaustive_structs)]
#[palpo_event(type = "m.direct", kind = GlobalAccountData)]
pub struct DirectEventContent(pub BTreeMap<OwnedUserId, Vec<OwnedRoomId>>);
impl Deref for DirectEventContent {
type Target = BTreeMap<OwnedUserId, Vec<OwnedRoomId>>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for DirectEventContent {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl IntoIterator for DirectEventContent {
type Item = (OwnedUserId, Vec<OwnedRoomId>);
type IntoIter = btree_map::IntoIter<OwnedUserId, Vec<OwnedRoomId>>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl FromIterator<(OwnedUserId, Vec<OwnedRoomId>)> for DirectEventContent {
fn from_iter<T>(iter: T) -> Self
where
T: IntoIterator<Item = (OwnedUserId, Vec<OwnedRoomId>)>,
{
Self(BTreeMap::from_iter(iter))
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::{DirectEvent, DirectEventContent};
use crate::{owned_room_id, owned_user_id};
#[test]
fn serialization() {
let mut content = DirectEventContent(BTreeMap::new());
let alice = owned_user_id!("@alice:palpo.io");
let rooms = vec![owned_room_id!("!1:palpo.io")];
content.insert(alice.clone(), rooms.clone());
let json_data = json!({
alice: rooms,
});
assert_eq!(to_json_value(&content).unwrap(), json_data);
}
#[test]
fn deserialization() {
let alice = owned_user_id!("@alice:palpo.io");
let rooms = vec![owned_room_id!("!1:palpo.io"), owned_room_id!("!2:palpo.io")];
let json_data = json!({
"content": {
alice.to_string(): rooms,
},
"type": "m.direct"
});
let event: DirectEvent = from_json_value(json_data).unwrap();
let direct_rooms = event.content.get(&alice).unwrap();
assert!(direct_rooms.contains(&rooms[0]));
assert!(direct_rooms.contains(&rooms[1]));
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/beacon.rs | crates/core/src/events/beacon.rs | //! Types for the `org.matrix.msc3489.beacon` event, the unstable version of
//! `m.beacon` ([MSC3489]).
//!
//! [MSC3489]: https://github.com/matrix-org/matrix-spec-proposals/pull/3489
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{
OwnedEventId, UnixMillis,
events::{location::LocationContent, relation::Reference},
};
/// The content of a beacon.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize, EventContent)]
#[palpo_event(type = "org.matrix.msc3672.beacon", alias = "m.beacon", kind = MessageLike)]
pub struct BeaconEventContent {
/// The beacon_info event id this relates to.
#[serde(rename = "m.relates_to")]
pub relates_to: Reference,
/// The location of the beacon.
#[serde(rename = "org.matrix.msc3488.location")]
pub location: LocationContent,
/// The timestamp of the event.
#[serde(rename = "org.matrix.msc3488.ts")]
pub ts: UnixMillis,
}
impl BeaconEventContent {
/// Creates a new `BeaconEventContent` with the given beacon_info event id,
/// geo uri and optional ts. If ts is None, the current time will be
/// used.
pub fn new(
beacon_info_event_id: OwnedEventId,
geo_uri: String,
ts: Option<UnixMillis>,
) -> Self {
Self {
relates_to: Reference::new(beacon_info_event_id),
location: LocationContent::new(geo_uri),
ts: ts.unwrap_or_else(UnixMillis::now),
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/_custom.rs | crates/core/src/events/_custom.rs | use salvo::oapi::ToSchema;
use serde::Serialize;
use crate::{
events::{
EphemeralRoomEventContent, EphemeralRoomEventType, EventContentFromType,
GlobalAccountDataEventContent, GlobalAccountDataEventType, MessageLikeEventContent,
MessageLikeEventType, MessageLikeUnsigned, PossiblyRedactedStateEventContent,
RedactContent, RedactedMessageLikeEventContent, RedactedStateEventContent,
RoomAccountDataEventContent, RoomAccountDataEventType, StateEventContent, StateEventType,
StaticStateEventContent, ToDeviceEventContent, ToDeviceEventType,
},
room_version_rules::RedactionRules,
serde::RawJsonValue,
};
macro_rules! custom_event_content {
($i:ident, $evt:ident) => {
/// A custom event's type. Used for event enum `_Custom` variants.
// FIXME: Serialize shouldn't be required here, but it's currently a supertrait of
// EventContent
#[derive(ToSchema, Clone, Debug, Serialize)]
#[allow(clippy::exhaustive_structs)]
pub struct $i {
#[serde(skip)]
event_type: Box<str>,
}
impl EventContentFromType for $i {
fn from_parts(event_type: &str, _content: &RawJsonValue) -> serde_json::Result<Self> {
Ok(Self {
event_type: event_type.into(),
})
}
}
};
}
macro_rules! custom_room_event_content {
($i:ident, $evt:ident) => {
custom_event_content!($i, $evt);
impl RedactContent for $i {
type Redacted = Self;
fn redact(self, _: &RedactionRules) -> Self {
self
}
}
};
}
custom_event_content!(
CustomGlobalAccountDataEventContent,
GlobalAccountDataEventType
);
impl GlobalAccountDataEventContent for CustomGlobalAccountDataEventContent {
fn event_type(&self) -> GlobalAccountDataEventType {
self.event_type[..].into()
}
}
custom_event_content!(CustomRoomAccountDataEventContent, RoomAccountDataEventType);
impl RoomAccountDataEventContent for CustomRoomAccountDataEventContent {
fn event_type(&self) -> RoomAccountDataEventType {
self.event_type[..].into()
}
}
custom_event_content!(CustomEphemeralRoomEventContent, EphemeralRoomEventType);
impl EphemeralRoomEventContent for CustomEphemeralRoomEventContent {
fn event_type(&self) -> EphemeralRoomEventType {
self.event_type[..].into()
}
}
custom_room_event_content!(CustomMessageLikeEventContent, MessageLikeEventType);
impl MessageLikeEventContent for CustomMessageLikeEventContent {
fn event_type(&self) -> MessageLikeEventType {
self.event_type[..].into()
}
}
impl RedactedMessageLikeEventContent for CustomMessageLikeEventContent {
fn event_type(&self) -> MessageLikeEventType {
self.event_type[..].into()
}
}
custom_room_event_content!(CustomStateEventContent, StateEventType);
impl StateEventContent for CustomStateEventContent {
type StateKey = String;
fn event_type(&self) -> StateEventType {
self.event_type[..].into()
}
}
impl StaticStateEventContent for CustomStateEventContent {
// Like `StateUnsigned`, but without `prev_content`.
// We don't care about `prev_content` since we'd only store the event type that
// is the same as in the content.
type Unsigned = MessageLikeUnsigned<CustomMessageLikeEventContent>;
type PossiblyRedacted = Self;
}
impl PossiblyRedactedStateEventContent for CustomStateEventContent {
type StateKey = String;
fn event_type(&self) -> StateEventType {
self.event_type[..].into()
}
}
impl RedactedStateEventContent for CustomStateEventContent {
type StateKey = String;
fn event_type(&self) -> StateEventType {
self.event_type[..].into()
}
}
custom_event_content!(CustomToDeviceEventContent, ToDeviceEventType);
impl ToDeviceEventContent for CustomToDeviceEventContent {
fn event_type(&self) -> ToDeviceEventType {
self.event_type[..].into()
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/beacon_info.rs | crates/core/src/events/beacon_info.rs | //! Types for the `org.matrix.msc3489.beacon_info` state event, the unstable
//! version of `m.beacon_info` ([MSC3489]).
//!
//! [MSC3489]: https://github.com/matrix-org/matrix-spec-proposals/pull/3489
use std::time::{Duration, SystemTime};
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{OwnedUserId, UnixMillis, events::location::AssetContent};
/// The content of a beacon_info state.
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize, EventContent)]
#[palpo_event(
type = "org.matrix.msc3672.beacon_info", alias = "m.beacon_info", kind = State, state_key_type = OwnedUserId
)]
pub struct BeaconInfoEventContent {
/// The description of the location.
///
/// It should be used to label the location on a map.
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// Whether the user starts sharing their location.
pub live: bool,
/// The time when location sharing started.
#[serde(rename = "org.matrix.msc3488.ts")]
pub ts: UnixMillis,
/// The duration that the location sharing will be live.
///
/// Meaning that the location will stop being shared at `ts + timeout`.
#[serde(default, with = "crate::serde::duration::ms")]
pub timeout: Duration,
/// The asset that this message refers to.
#[serde(default, rename = "org.matrix.msc3488.asset")]
pub asset: AssetContent,
}
impl BeaconInfoEventContent {
/// Creates a new `BeaconInfoEventContent` with the given description, live,
/// timeout and optional ts. If ts is None, the current time will be
/// used.
pub fn new(
description: Option<String>,
timeout: Duration,
live: bool,
ts: Option<UnixMillis>,
) -> Self {
Self {
description,
live,
ts: ts.unwrap_or_else(UnixMillis::now),
timeout,
asset: Default::default(),
}
}
/// Starts the beacon_info being live.
pub fn start(&mut self) {
self.live = true;
}
/// Stops the beacon_info from being live.
pub fn stop(&mut self) {
self.live = false;
}
/// Start time plus its timeout, it returns `false`, indicating that the
/// beacon is not live. Otherwise, it returns `true`.
pub fn is_live(&self) -> bool {
self.live
&& self
.ts
.to_system_time()
.and_then(|t| t.checked_add(self.timeout))
.is_some_and(|t| t > SystemTime::now())
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/key.rs | crates/core/src/events/key.rs | //! Modules for events in the `m.key` namespace.
pub mod verification;
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/identity_server.rs | crates/core/src/events/identity_server.rs | //! Types for the [`m.identity_server`] event.
//!
//! [`m.identity_server`]: https://spec.matrix.org/latest/client-server-api/#mdirect
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
/// The content of an `m.identity_server` event.
///
/// Persists the user's preferred identity server, or preference to not use an
/// identity server at all.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.identity_server", kind = GlobalAccountData)]
pub struct IdentityServerEventContent {
/// The URL of the identity server the user prefers to use, or `Null` if the
/// user does not want to use an identity server.
///
/// If this is `Undefined`, that means the user has not expressed a
/// preference or has revoked their preference, and any applicable
/// default should be used.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub base_url: Option<String>,
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/state_key.rs | crates/core/src/events/state_key.rs | use salvo::oapi::ToSchema;
use serde::{
Serialize, Serializer,
de::{
Deserialize, Deserializer, Unexpected, {self},
},
};
/// A type that can be used as the `state_key` for event types where that field
/// is always empty.
#[derive(ToSchema, Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
#[allow(clippy::exhaustive_structs)]
pub struct EmptyStateKey;
impl AsRef<str> for EmptyStateKey {
fn as_ref(&self) -> &str {
""
}
}
impl<'de> Deserialize<'de> for EmptyStateKey {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = palpo_core::serde::deserialize_cow_str(deserializer)?;
if s.is_empty() {
Ok(EmptyStateKey)
} else {
Err(de::Error::invalid_value(
Unexpected::Str(&s),
&"an empty string",
))
}
}
}
impl Serialize for EmptyStateKey {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str("")
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/call.rs | crates/core/src/events/call.rs | //! Modules for events in the `m.call` namespace.
//!
//! This module also contains types shared by events in its child namespaces.
pub mod answer;
pub mod candidates;
pub mod hangup;
pub mod invite;
#[cfg(feature = "unstable-msc3401")]
pub mod member;
pub mod negotiate;
#[cfg(feature = "unstable-msc4075")]
pub mod notify;
pub mod reject;
pub mod sdp_stream_metadata_changed;
pub mod select_answer;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{PrivOwnedStr, serde::StringEnum};
/// A VoIP session description.
///
/// This is the same type as WebRTC's [`RTCSessionDescriptionInit`].
///
/// [`RTCSessionDescriptionInit`]: (https://www.w3.org/TR/webrtc/#dom-rtcsessiondescriptioninit):
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct SessionDescription {
/// The type of session description.
///
/// This is the `type` field of `RTCSessionDescriptionInit`.
#[serde(rename = "type")]
pub session_type: String,
/// The SDP text of the session description.
///
/// Defaults to an empty string.
#[serde(default)]
pub sdp: String,
}
impl SessionDescription {
/// Creates a new `SessionDescription` with the given session type and SDP
/// text.
pub fn new(session_type: String, sdp: String) -> Self {
Self { session_type, sdp }
}
}
/// Metadata about a VoIP stream.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StreamMetadata {
/// The purpose of the stream.
pub purpose: StreamPurpose,
/// Whether the audio track of the stream is muted.
///
/// Defaults to `false`.
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub audio_muted: bool,
/// Whether the video track of the stream is muted.
///
/// Defaults to `false`.
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub video_muted: bool,
}
impl StreamMetadata {
/// Creates a new `StreamMetadata` with the given purpose.
pub fn new(purpose: StreamPurpose) -> Self {
Self {
purpose,
audio_muted: false,
video_muted: false,
}
}
}
/// The purpose of a VoIP stream.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(Clone, StringEnum)]
#[palpo_enum(rename_all(prefix = "m.", rule = "lowercase"))]
#[non_exhaustive]
pub enum StreamPurpose {
/// `m.usermedia`.
///
/// A stream that contains the webcam and/or microphone tracks.
UserMedia,
/// `m.screenshare`.
///
/// A stream with the screen-sharing tracks.
ScreenShare,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
/// The capabilities of a client in a VoIP call.
#[cfg(feature = "unstable-msc2747")]
#[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)]
pub struct CallCapabilities {
/// Whether this client supports [DTMF].
///0
/// Defaults to `false`.
///
/// [DTMF]: https://w3c.github.io/webrtc-pc/#peer-to-peer-dtmf
#[serde(rename = "m.call.dtmf", default)]
pub dtmf: bool,
}
#[cfg(feature = "unstable-msc2747")]
impl CallCapabilities {
/// Creates a default `CallCapabilities`.
pub fn new() -> Self {
Self::default()
}
/// Whether this `CallCapabilities` only contains default values.
pub fn is_default(&self) -> bool {
!self.dtmf
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room_key.rs | crates/core/src/events/room_key.rs | //! Types for the [`m.room_key`] event.
//!
//! [`m.room_key`]: https://spec.matrix.org/latest/client-server-api/#mroom_key
pub mod withheld;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::macros::EventContent;
use crate::{EventEncryptionAlgorithm, OwnedRoomId};
/// The content of an `m.room_key` event.
///
/// Typically encrypted as an `m.room.encrypted` event, then sent as a to-device
/// event.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.room_key", kind = ToDevice)]
pub struct ToDeviceRoomKeyEventContent {
/// The encryption algorithm the key in this event is to be used with.
///
/// Must be `m.megolm.v1.aes-sha2`.
pub algorithm: EventEncryptionAlgorithm,
/// The room where the key is used.
pub room_id: OwnedRoomId,
/// The ID of the session that the key is for.
pub session_id: String,
/// The key to be exchanged.
pub session_key: String,
/// Used to mark key if allowed for shared history.
///
/// Defaults to `false`.
#[cfg(feature = "unstable-msc3061")]
#[serde(
default,
rename = "org.matrix.msc3061.shared_history",
skip_serializing_if = "palpo_core::serde::is_default"
)]
pub shared_history: bool,
}
impl ToDeviceRoomKeyEventContent {
/// Creates a new `ToDeviceRoomKeyEventContent` with the given algorithm,
/// room ID, session ID and session key.
pub fn new(
algorithm: EventEncryptionAlgorithm,
room_id: OwnedRoomId,
session_id: String,
session_key: String,
) -> Self {
Self {
algorithm,
room_id,
session_id,
session_key,
#[cfg(feature = "unstable-msc3061")]
shared_history: false,
}
}
}
#[cfg(test)]
mod tests {
use serde_json::{json, to_value as to_json_value};
use super::ToDeviceRoomKeyEventContent;
use crate::{EventEncryptionAlgorithm, owned_room_id};
#[test]
fn serialization() {
let content = ToDeviceRoomKeyEventContent {
algorithm: EventEncryptionAlgorithm::MegolmV1AesSha2,
room_id: owned_room_id!("!testroomid:example.org"),
session_id: "SessId".into(),
session_key: "SessKey".into(),
#[cfg(feature = "unstable-msc3061")]
shared_history: true,
};
#[cfg(not(feature = "unstable-msc3061"))]
assert_eq!(
to_json_value(content).unwrap(),
json!({
"algorithm": "m.megolm.v1.aes-sha2",
"room_id": "!testroomid:example.org",
"session_id": "SessId",
"session_key": "SessKey",
})
);
#[cfg(feature = "unstable-msc3061")]
assert_eq!(
to_json_value(content).unwrap(),
json!({
"algorithm": "m.megolm.v1.aes-sha2",
"room_id": "!testroomid:example.org",
"session_id": "SessId",
"session_key": "SessKey",
"org.matrix.msc3061.shared_history": true,
})
);
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/image.rs | crates/core/src/events/image.rs | //! Types for extensible image message events ([MSC3552]).
//!
//! [MSC3552]: https://github.com/matrix-org/matrix-spec-proposals/pull/3552
use std::ops::Deref;
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use super::{
file::{CaptionContentBlock, EncryptedContent, FileContentBlock},
message::TextContentBlock,
room::message::Relation,
};
use crate::OwnedMxcUri;
/// The payload for an extensible image message.
///
/// This is the new primary type introduced in [MSC3552] and should only be sent
/// in rooms with a version that supports it. This type replaces both the
/// `m.room.message` type with `msgtype: "m.image"` and the `m.sticker` type. To
/// replace the latter, `sticker` must be set to `true` in `image_details`. See
/// the documentation of the [`message`] module for more information.
///
/// [MSC3552]: https://github.com/matrix-org/matrix-spec-proposals/pull/3552
/// [`message`]: super::message
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize, EventContent)]
#[palpo_event(type = "org.matrix.msc1767.image", kind = MessageLike, without_relation)]
pub struct ImageEventContent {
/// The text representation of the message.
#[serde(rename = "org.matrix.msc1767.text")]
pub text: TextContentBlock,
/// The file content of the message.
#[serde(rename = "org.matrix.msc1767.file")]
pub file: FileContentBlock,
/// The image details of the message, if any.
#[serde(
rename = "org.matrix.msc1767.image_details",
skip_serializing_if = "Option::is_none"
)]
pub image_details: Option<ImageDetailsContentBlock>,
/// The thumbnails of the message, if any.
///
/// This is optional and defaults to an empty array.
#[serde(
rename = "org.matrix.msc1767.thumbnail",
default,
skip_serializing_if = "ThumbnailContentBlock::is_empty"
)]
pub thumbnail: ThumbnailContentBlock,
/// The caption of the message, if any.
#[serde(
rename = "org.matrix.msc1767.caption",
skip_serializing_if = "Option::is_none"
)]
pub caption: Option<CaptionContentBlock>,
/// The alternative text of the image, for accessibility considerations, if
/// any.
#[serde(
rename = "org.matrix.msc1767.alt_text",
skip_serializing_if = "Option::is_none"
)]
pub alt_text: Option<AltTextContentBlock>,
/// Whether this message is automated.
#[cfg(feature = "unstable-msc3955")]
#[serde(
default,
skip_serializing_if = "palpo_core::serde::is_default",
rename = "org.matrix.msc1767.automated"
)]
pub automated: bool,
/// Information about related messages.
#[serde(
flatten,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::events::room::message::relation_serde::deserialize_relation"
)]
pub relates_to: Option<Relation<ImageEventContentWithoutRelation>>,
}
impl ImageEventContent {
/// Creates a new `ImageEventContent` with the given fallback representation
/// and file.
pub fn new(text: TextContentBlock, file: FileContentBlock) -> Self {
Self {
text,
file,
image_details: None,
thumbnail: Default::default(),
caption: None,
alt_text: None,
#[cfg(feature = "unstable-msc3955")]
automated: false,
relates_to: None,
}
}
/// Creates a new `ImageEventContent` with the given plain text fallback
/// representation and file.
pub fn with_plain_text(plain_text: impl Into<String>, file: FileContentBlock) -> Self {
Self {
text: TextContentBlock::plain(plain_text),
file,
image_details: None,
thumbnail: Default::default(),
caption: None,
alt_text: None,
#[cfg(feature = "unstable-msc3955")]
automated: false,
relates_to: None,
}
}
}
/// A block for details of image content.
#[derive(ToSchema, Default, Clone, Debug, Serialize, Deserialize)]
pub struct ImageDetailsContentBlock {
/// The height of the image in pixels.
pub height: u64,
/// The width of the image in pixels.
pub width: u64,
/// Whether the image should be presented as sticker.
#[serde(
rename = "org.matrix.msc1767.sticker",
default,
skip_serializing_if = "palpo_core::serde::is_default"
)]
pub sticker: bool,
}
impl ImageDetailsContentBlock {
/// Creates a new `ImageDetailsContentBlock` with the given width and
/// height.
pub fn new(width: u64, height: u64) -> Self {
Self {
height,
width,
sticker: Default::default(),
}
}
}
/// A block for thumbnail content.
///
/// This is an array of [`Thumbnail`].
///
/// To construct a `ThumbnailContentBlock` convert a `Vec<Thumbnail>` with
/// `ThumbnailContentBlock::from()` / `.into()`.
#[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)]
#[allow(clippy::exhaustive_structs)]
pub struct ThumbnailContentBlock(Vec<Thumbnail>);
impl ThumbnailContentBlock {
/// Whether this content block is empty.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl From<Vec<Thumbnail>> for ThumbnailContentBlock {
fn from(thumbnails: Vec<Thumbnail>) -> Self {
Self(thumbnails)
}
}
impl FromIterator<Thumbnail> for ThumbnailContentBlock {
fn from_iter<T: IntoIterator<Item = Thumbnail>>(iter: T) -> Self {
Self(iter.into_iter().collect())
}
}
impl Deref for ThumbnailContentBlock {
type Target = [Thumbnail];
fn deref(&self) -> &Self::Target {
&self.0
}
}
/// Thumbnail content.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct Thumbnail {
/// The file info of the thumbnail.
#[serde(rename = "org.matrix.msc1767.file")]
pub file: ThumbnailFileContentBlock,
/// The image info of the thumbnail.
#[serde(rename = "org.matrix.msc1767.image_details")]
pub image_details: ThumbnailImageDetailsContentBlock,
}
impl Thumbnail {
/// Creates a `Thumbnail` with the given file and image details.
pub fn new(
file: ThumbnailFileContentBlock,
image_details: ThumbnailImageDetailsContentBlock,
) -> Self {
Self {
file,
image_details,
}
}
}
/// A block for thumbnail file content.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct ThumbnailFileContentBlock {
/// The URL to the thumbnail.
pub url: OwnedMxcUri,
/// The mimetype of the file, e.g. "image/png".
pub mimetype: String,
/// The original filename of the uploaded file.
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// The size of the file in bytes.
#[serde(skip_serializing_if = "Option::is_none")]
pub size: Option<i64>,
/// Information on the encrypted thumbnail.
///
/// Required if the thumbnail is encrypted.
#[serde(flatten, skip_serializing_if = "Option::is_none")]
pub encryption_info: Option<Box<EncryptedContent>>,
}
impl ThumbnailFileContentBlock {
/// Creates a new non-encrypted `ThumbnailFileContentBlock` with the given
/// url and mimetype.
pub fn plain(url: OwnedMxcUri, mimetype: String) -> Self {
Self {
url,
mimetype,
name: None,
size: None,
encryption_info: None,
}
}
/// Creates a new encrypted `ThumbnailFileContentBlock` with the given url,
/// mimetype and encryption info.
pub fn encrypted(
url: OwnedMxcUri,
mimetype: String,
encryption_info: EncryptedContent,
) -> Self {
Self {
url,
mimetype,
name: None,
size: None,
encryption_info: Some(Box::new(encryption_info)),
}
}
/// Whether the thumbnail file is encrypted.
pub fn is_encrypted(&self) -> bool {
self.encryption_info.is_some()
}
}
/// A block for details of thumbnail image content.
#[derive(ToSchema, Default, Clone, Debug, Serialize, Deserialize)]
pub struct ThumbnailImageDetailsContentBlock {
/// The height of the image in pixels.
pub height: i64,
/// The width of the image in pixels.
pub width: i64,
}
impl ThumbnailImageDetailsContentBlock {
/// Creates a new `ThumbnailImageDetailsContentBlock` with the given width
/// and height.
pub fn new(width: i64, height: i64) -> Self {
Self { height, width }
}
}
/// A block for alternative text content.
///
/// The content should only contain plain text messages. Non-plain text messages
/// should be ignored.
///
/// To construct an `AltTextContentBlock` with a custom [`TextContentBlock`],
/// convert it with `AltTextContentBlock::from()` / `.into()`.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct AltTextContentBlock {
/// The alternative text.
#[serde(rename = "org.matrix.msc1767.text")]
pub text: TextContentBlock,
}
impl AltTextContentBlock {
/// A convenience constructor to create a plain text alternative text
/// content block.
pub fn plain(body: impl Into<String>) -> Self {
Self {
text: TextContentBlock::plain(body),
}
}
}
impl From<TextContentBlock> for AltTextContentBlock {
fn from(text: TextContentBlock) -> Self {
Self { text }
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/presence.rs | crates/core/src/events/presence.rs | //! A presence event is represented by a struct with a set content field.
//!
//! The only content valid for this event is `PresenceEventContent`.
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{OwnedMxcUri, OwnedUserId, presence::PresenceState};
/// Presence event.
#[derive(ToSchema, Serialize, Deserialize, Clone, Debug)]
#[allow(clippy::exhaustive_structs)]
#[serde(tag = "type", rename = "m.presence")]
pub struct PresenceEvent {
/// Data specific to the event type.
pub content: PresenceEventContent,
/// Contains the fully-qualified ID of the user who sent this event.
pub sender: OwnedUserId,
}
/// Informs the room of members presence.
///
/// This is the only type a `PresenceEvent` can contain as its `content` field.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct PresenceEventContent {
/// The current avatar URL for this user.
#[serde(
skip_serializing_if = "Option::is_none",
default,
deserialize_with = "palpo_core::serde::empty_string_as_none"
)]
pub avatar_url: Option<OwnedMxcUri>,
/// Whether or not the user is currently active.
#[serde(skip_serializing_if = "Option::is_none")]
pub currently_active: Option<bool>,
/// The current display name for this user.
#[serde(skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
/// The last time since this user performed some action, in milliseconds.
#[serde(skip_serializing_if = "Option::is_none")]
pub last_active_ago: Option<u64>,
/// The presence state for this user.
pub presence: PresenceState,
/// An optional description to accompany the presence.
#[serde(skip_serializing_if = "Option::is_none")]
pub status_msg: Option<String>,
}
impl PresenceEventContent {
/// Creates a new `PresenceEventContent` with the given state.
pub fn new(presence: PresenceState) -> Self {
Self {
avatar_url: None,
currently_active: None,
display_name: None,
last_active_ago: None,
presence,
status_msg: None,
}
}
}
// #[cfg(test)]
// mod tests {
// use crate::{mxc_uri, presence::PresenceState};
// use serde_json::{from_value as from_json_value, json, to_value as
// to_json_value};
// use super::{PresenceEvent, PresenceEventContent};
// #[test]
// fn serialization() {
// let content = PresenceEventContent {
// avatar_url:
// Some(mxc_uri!("mxc://localhost/wefuiwegh8742w").to_owned()),
// currently_active: Some(false), display_name: None,
// last_active_ago: Some(uint!(2_478_593)),
// presence: PresenceState::Online,
// status_msg: Some("Making cupcakes".into()),
// };
// let json = json!({
// "avatar_url": "mxc://localhost/wefuiwegh8742w",
// "currently_active": false,
// "last_active_ago": 2_478_593,
// "presence": "online",
// "status_msg": "Making cupcakes"
// });
// assert_eq!(to_json_value(&content).unwrap(), json);
// }
// #[test]
// fn deserialization() {
// let json = json!({
// "content": {
// "avatar_url": "mxc://localhost/wefuiwegh8742w",
// "currently_active": false,
// "last_active_ago": 2_478_593,
// "presence": "online",
// "status_msg": "Making cupcakes"
// },
// "sender": "@example:localhost",
// "type": "m.presence"
// });
// let ev = from_json_value::<PresenceEvent>(json).unwrap();
// assert_eq!(
// ev.content.avatar_url.as_deref(),
// Some(mxc_uri!("mxc://localhost/wefuiwegh8742w"))
// );
// assert_eq!(ev.content.currently_active, Some(false));
// assert_eq!(ev.content.display_name, None);
// assert_eq!(ev.content.last_active_ago, Some(uint!(2_478_593)));
// assert_eq!(ev.content.presence, PresenceState::Online);
// assert_eq!(ev.content.status_msg.as_deref(), Some("Making
// cupcakes")); assert_eq!(ev.sender, "@example:localhost");
// let json = json!({
// "content": {
// "avatar_url": "",
// "currently_active": false,
// "last_active_ago": 2_478_593,
// "presence": "online",
// "status_msg": "Making cupcakes"
// },
// "sender": "@example:localhost",
// "type": "m.presence"
// });
// let ev = from_json_value::<PresenceEvent>(json).unwrap();
// assert_eq!(ev.content.avatar_url, None);
// assert_eq!(ev.content.currently_active, Some(false));
// assert_eq!(ev.content.display_name, None);
// assert_eq!(ev.content.last_active_ago, Some(uint!(2_478_593)));
// assert_eq!(ev.content.presence, PresenceState::Online);
// assert_eq!(ev.content.status_msg.as_deref(), Some("Making
// cupcakes")); assert_eq!(ev.sender, "@example:localhost");
// }
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/content.rs | crates/core/src/events/content.rs | use std::fmt;
use serde::{Serialize, de::DeserializeOwned};
use crate::{
events::{
EphemeralRoomEventType, GlobalAccountDataEventType, MessageLikeEventType,
RoomAccountDataEventType, StateEventType, ToDeviceEventType,
},
serde::{CanBeEmpty, RawJson, RawJsonValue},
};
/// Extension trait for [`RawJson<T>`].
pub trait RawJsonExt<T: EventContentFromType> {
/// Try to deserialize the JSON as an event's content with the given event
/// type.
fn deserialize_with_type(&self, event_type: &str) -> serde_json::Result<T>;
}
impl<T> RawJsonExt<T> for RawJson<T>
where
T: EventContentFromType,
{
fn deserialize_with_type(&self, event_type: &str) -> serde_json::Result<T> {
T::from_parts(event_type, self.inner())
}
}
/// An event content type with a statically-known event `type` value.
///
/// Note that the `TYPE` might not be the full event type. If `IsPrefix` is set to `True`, it only
/// contains the statically-known prefix of the event type.
///
/// To only support full event types, the bound `StaticEventContent<IsPrefix = False>` can be used.
pub trait StaticEventContent: Sized {
/// The statically-known part of the event type.
///
/// If this is only the prefix of the event type, it should end with `.`, which is usually used
/// a separator in Matrix event types.
const TYPE: &'static str;
/// Whether the statically-known part of the event type is the prefix.
///
/// Should be set to the [`True`] or [`False`] types.
///
/// Ideally this should be a boolean associated constant, but [associated constant equality is
/// unstable], so this field could not be used as a bound. Instead we use an associated type so
/// we can rely on associated type equality.
///
/// If this is set to [`False`], the `TYPE` is the full event type.
///
/// [associated constant equality is unstable]: https://github.com/rust-lang/rust/issues/92827
type IsPrefix: BooleanType;
}
/// A trait for types representing a boolean value.
pub trait BooleanType {
/// The boolean representation of this type.
fn as_bool() -> bool;
}
/// The equivalent of the `true` boolean.
#[non_exhaustive]
pub struct True;
impl BooleanType for True {
fn as_bool() -> bool {
true
}
}
/// The equivalent of the `false` boolean.
#[non_exhaustive]
pub struct False;
impl BooleanType for False {
fn as_bool() -> bool {
false
}
}
/// Content of a global account-data event.
pub trait GlobalAccountDataEventContent: Sized + Serialize {
/// Get the event's type, like `m.push_rules`.
fn event_type(&self) -> GlobalAccountDataEventType;
}
/// Content of a room-specific account-data event.
pub trait RoomAccountDataEventContent: Sized + Serialize {
/// Get the event's type, like `m.receipt`.
fn event_type(&self) -> RoomAccountDataEventType;
}
/// Content of an ephemeral room event.
pub trait EphemeralRoomEventContent: Sized + Serialize {
/// Get the event's type, like `m.receipt`.
fn event_type(&self) -> EphemeralRoomEventType;
}
/// Content of a non-redacted message-like event.
pub trait MessageLikeEventContent: Sized + Serialize {
/// Get the event's type, like `m.room.message`.
fn event_type(&self) -> MessageLikeEventType;
}
/// Content of a redacted message-like event.
pub trait RedactedMessageLikeEventContent: Sized + Serialize {
/// Get the event's type, like `m.room.message`.
fn event_type(&self) -> MessageLikeEventType;
}
/// Content of a non-redacted state event.
pub trait StateEventContent: Sized + Serialize {
/// The type of the event's `state_key` field.
type StateKey: AsRef<str> + Clone + fmt::Debug + DeserializeOwned + Serialize;
/// Get the event's type, like `m.room.name`.
fn event_type(&self) -> StateEventType;
}
/// Content of a non-redacted state event with a corresponding possibly-redacted
/// type.
pub trait StaticStateEventContent: StateEventContent {
/// The possibly redacted form of the event's content.
type PossiblyRedacted: PossiblyRedactedStateEventContent;
/// The type of the event's `unsigned` field.
type Unsigned: Clone + fmt::Debug + Default + CanBeEmpty + DeserializeOwned;
}
/// Content of a redacted state event.
pub trait RedactedStateEventContent: Sized + Serialize {
/// The type of the event's `state_key` field.
type StateKey: AsRef<str> + Clone + fmt::Debug + DeserializeOwned + Serialize;
/// Get the event's type, like `m.room.name`.
fn event_type(&self) -> StateEventType;
}
/// Content of a state event.
pub trait PossiblyRedactedStateEventContent: Sized + Serialize {
/// The type of the event's `state_key` field.
type StateKey: AsRef<str> + Clone + fmt::Debug + DeserializeOwned + Serialize;
/// Get the event's type, like `m.room.name`.
fn event_type(&self) -> StateEventType;
}
/// Content of a to-device event.
pub trait ToDeviceEventContent: Sized + Serialize {
/// Get the event's type, like `m.room_key`.
fn event_type(&self) -> ToDeviceEventType;
}
/// Event content that can be deserialized with its event type.
pub trait EventContentFromType: Sized {
/// Constructs this event content from the given event type and JSON.
#[doc(hidden)]
fn from_parts(event_type: &str, content: &RawJsonValue) -> serde_json::Result<Self>;
}
impl<T> EventContentFromType for T
where
T: StaticEventContent + DeserializeOwned,
{
fn from_parts(_event_type: &str, content: &RawJsonValue) -> serde_json::Result<Self> {
serde_json::from_str(content.get())
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/poll.rs | crates/core/src/events/poll.rs | //! Modules for events in the `m.poll` namespace ([MSC3381]).
//!
//! This module also contains types shared by events in its child namespaces.
//!
//! [MSC3381]: https://github.com/matrix-org/matrix-spec-proposals/pull/3381
use std::{
collections::{BTreeMap, BTreeSet},
ops::Deref,
};
use indexmap::IndexMap;
use self::start::PollContentBlock;
#[cfg(feature = "unstable-msc3381")]
use self::unstable_start::UnstablePollStartContentBlock;
use crate::{UnixMillis, UserId};
pub mod end;
pub mod response;
pub mod start;
pub mod unstable_end;
#[cfg(feature = "unstable-msc3381")]
pub mod unstable_response;
#[cfg(feature = "unstable-msc3381")]
pub mod unstable_start;
/// The data from a poll response necessary to compile poll results.
#[derive(Debug, Clone, Copy)]
#[allow(clippy::exhaustive_structs)]
pub struct PollResponseData<'a> {
/// The sender of the response.
pub sender: &'a UserId,
/// The time of creation of the response on the originating server.
pub origin_server_ts: UnixMillis,
/// The selections/answers of the response.
pub selections: &'a [String],
}
/// Generate the current results with the given poll and responses.
///
/// If the `end_timestamp` is provided, any response with an `origin_server_ts`
/// after that timestamp is ignored. If it is not provided, `UnixMillis::now()`
/// will be used instead.
///
/// This method will handle invalid responses, or several response from the same
/// user so all responses to the poll should be provided.
///
/// Returns a map of answer ID to a set of user IDs that voted for them. When
/// using `.iter()` or `.into_iter()` on the map, the results are sorted from
/// the highest number of votes to the lowest.
pub fn compile_poll_results<'a>(
poll: &'a PollContentBlock,
responses: impl IntoIterator<Item = PollResponseData<'a>>,
end_timestamp: Option<UnixMillis>,
) -> IndexMap<&'a str, BTreeSet<&'a UserId>> {
let answer_ids = poll.answers.iter().map(|a| a.id.as_str()).collect();
let users_selections =
filter_selections(answer_ids, poll.max_selections, responses, end_timestamp);
aggregate_results(poll.answers.iter().map(|a| a.id.as_str()), users_selections)
}
/// Generate the current results with the given unstable poll and responses.
///
/// If the `end_timestamp` is provided, any response with an `origin_server_ts`
/// after that timestamp is ignored. If it is not provided, `UnixMillis::now()`
/// will be used instead.
///
/// This method will handle invalid responses, or several response from the same
/// user so all responses to the poll should be provided.
///
/// Returns a map of answer ID to a set of user IDs that voted for them. When
/// using `.iter()` or `.into_iter()` on the map, the results are sorted from
/// the highest number of votes to the lowest.
#[cfg(feature = "unstable-msc3381")]
pub fn compile_unstable_poll_results<'a>(
poll: &'a UnstablePollStartContentBlock,
responses: impl IntoIterator<Item = PollResponseData<'a>>,
end_timestamp: Option<UnixMillis>,
) -> IndexMap<&'a str, BTreeSet<&'a UserId>> {
let answer_ids = poll.answers.iter().map(|a| a.id.as_str()).collect();
let users_selections =
filter_selections(answer_ids, poll.max_selections, responses, end_timestamp);
aggregate_results(poll.answers.iter().map(|a| a.id.as_str()), users_selections)
}
/// Validate the selections of a response.
fn validate_selections<'a>(
answer_ids: &BTreeSet<&str>,
max_selections: u32,
selections: &'a [String],
) -> Option<impl Iterator<Item = &'a str> + use<'a>> {
// Vote is spoiled if any answer is unknown.
if selections.iter().any(|s| !answer_ids.contains(s.as_str())) {
return None;
}
// Fallback to the maximum value for usize because we can't have more selections
// than that in memory.
let max_selections: usize = max_selections.try_into().unwrap_or(usize::MAX);
Some(selections.iter().take(max_selections).map(Deref::deref))
}
fn filter_selections<'a, R>(
answer_ids: BTreeSet<&str>,
max_selections: u32,
responses: R,
end_timestamp: Option<UnixMillis>,
) -> BTreeMap<
&'a UserId,
(
UnixMillis,
Option<impl Iterator<Item = &'a str> + use<'a, R>>,
),
>
where
R: IntoIterator<Item = PollResponseData<'a>>,
{
let mut filtered_map = BTreeMap::new();
for item in responses.into_iter().filter(|ev| {
// Filter out responses after the end_timestamp.
end_timestamp.is_none_or(|end_ts| ev.origin_server_ts <= end_ts)
}) {
let response = filtered_map
.entry(item.sender)
.or_insert((UnixMillis(0), None));
// Only keep the latest selections for each user.
if response.0 < item.origin_server_ts {
*response = (
item.origin_server_ts,
validate_selections(&answer_ids, max_selections, item.selections),
);
}
}
filtered_map
}
/// Aggregate the given selections by answer.
fn aggregate_results<'a>(
answers: impl Iterator<Item = &'a str>,
users_selections: BTreeMap<&'a UserId, (UnixMillis, Option<impl Iterator<Item = &'a str>>)>,
) -> IndexMap<&'a str, BTreeSet<&'a UserId>> {
let mut results = IndexMap::from_iter(answers.into_iter().map(|a| (a, BTreeSet::new())));
for (user, (_, selections)) in users_selections {
if let Some(selections) = selections {
for selection in selections {
results
.get_mut(selection)
.expect("validated selections should only match possible answers")
.insert(user);
}
}
}
results.sort_by(|_, a, _, b| b.len().cmp(&a.len()));
results
}
/// Generate the fallback text representation of a poll end event.
///
/// This is a sentence that lists the top answers for the given results, in
/// english. It is used to generate a valid poll end event when using
/// `OriginalSync(Unstable)PollStartEvent::compile_results()`.
///
/// `answers` is an iterator of `(answer ID, answer plain text representation)`
/// and `results` is an iterator of `(answer ID, count)` ordered in descending
/// order.
fn generate_poll_end_fallback_text<'a>(
answers: &[(&'a str, &'a str)],
results: impl Iterator<Item = (&'a str, usize)>,
) -> String {
let mut top_answers = Vec::new();
let mut top_count = 0;
for (id, count) in results {
if count >= top_count {
top_answers.push(id);
top_count = count;
} else {
break;
}
}
let top_answers_text = top_answers
.into_iter()
.map(|id| {
answers
.iter()
.find(|(a_id, _)| *a_id == id)
.expect("top answer ID should be a valid answer ID")
.1
})
.collect::<Vec<_>>();
// Construct the plain text representation.
match top_answers_text.len() {
0 => "The poll has closed with no top answer".to_owned(),
1 => {
format!("The poll has closed. Top answer: {}", top_answers_text[0])
}
_ => {
let answers = top_answers_text.join(", ");
format!("The poll has closed. Top answers: {answers}")
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room_key_bundle.rs | crates/core/src/events/room_key_bundle.rs | //! Types for the `m.room_key_bundle` event defined in [MSC4268].
//!
//! [MSC4268]: https://github.com/matrix-org/matrix-spec-proposals/pull/4268
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::OwnedRoomId;
use crate::events::room::EncryptedFile;
use crate::macros::EventContent;
/// The content of an `m.room_key_bundle` event.
///
/// Typically encrypted as an `m.room.encrypted` event, then sent as a to-device event.
///
/// This event is defined in [MSC4268](https://github.com/matrix-org/matrix-spec-proposals/pull/4268)
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize, EventContent)]
#[palpo_event(type = "io.element.msc4268.room_key_bundle", alias = "m.room_key_bundle", kind = ToDevice)]
pub struct ToDeviceRoomKeyBundleEventContent {
/// The room that these keys are for.
pub room_id: OwnedRoomId,
/// The location and encryption info of the key bundle.
pub file: EncryptedFile,
}
impl ToDeviceRoomKeyBundleEventContent {
/// Creates a new `ToDeviceRoomKeyBundleEventContent` with the given room ID, and
/// [`EncryptedFile`] which contains the room keys from the bundle.
pub fn new(room_id: OwnedRoomId, file: EncryptedFile) -> Self {
Self { room_id, file }
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use crate::{owned_mxc_uri, owned_room_id, serde::Base64};
use serde_json::json;
use super::ToDeviceRoomKeyBundleEventContent;
use crate::events::room::{EncryptedFile, JsonWebKey};
#[test]
fn serialization() {
let content = ToDeviceRoomKeyBundleEventContent {
room_id: owned_room_id!("!testroomid:example.org"),
file: EncryptedFile {
url: owned_mxc_uri!("mxc://example.org/FHyPlCeYUSFFxlgbQYZmoEoe"),
key: JsonWebKey {
kty: "A256CTR".to_owned(),
key_ops: vec!["encrypt".to_owned(), "decrypt".to_owned()],
alg: "A256CTR".to_owned(),
k: Base64::parse("aWF6-32KGYaC3A_FEUCk1Bt0JA37zP0wrStgmdCaW-0").unwrap(),
ext: true,
},
iv: Base64::parse("w+sE15fzSc0AAAAAAAAAAA").unwrap(),
hashes: BTreeMap::from([(
"sha256".to_owned(),
Base64::parse("fdSLu/YkRx3Wyh3KQabP3rd6+SFiKg5lsJZQHtkSAYA").unwrap(),
)]),
v: "v2".to_owned(),
},
};
let serialized = serde_json::to_value(content).unwrap();
assert_eq!(
serialized,
json!({
"room_id": "!testroomid:example.org",
"file": {
"v": "v2",
"url": "mxc://example.org/FHyPlCeYUSFFxlgbQYZmoEoe",
"key": {
"alg": "A256CTR",
"ext": true,
"k": "aWF6-32KGYaC3A_FEUCk1Bt0JA37zP0wrStgmdCaW-0",
"key_ops": ["encrypt","decrypt"],
"kty": "A256CTR"
},
"iv": "w+sE15fzSc0AAAAAAAAAAA",
"hashes": {
"sha256": "fdSLu/YkRx3Wyh3KQabP3rd6+SFiKg5lsJZQHtkSAYA"
}
}
}),
"The serialized value should match the declared JSON Value"
);
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/relation.rs | crates/core/src/events/relation.rs | //! Types describing [relationships between events].
//!
//! [relationships between events]: https://spec.matrix.org/latest/client-server-api/#forming-relationships-between-events
use std::fmt::Debug;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Deserializer, Serialize, de::DeserializeOwned};
use super::AnyMessageLikeEvent;
use crate::{
OwnedEventId, PrivOwnedStr,
serde::{JsonObject, RawJson, StringEnum},
};
/// Information about the event a [rich reply] is replying to.
///
/// [rich reply]: https://spec.matrix.org/latest/client-server-api/#rich-replies
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct InReplyTo {
/// The event being replied to.
pub event_id: OwnedEventId,
}
impl InReplyTo {
/// Creates a new `InReplyTo` with the given event ID.
pub fn new(event_id: OwnedEventId) -> Self {
Self { event_id }
}
}
/// An [annotation] for an event.
///
/// [annotation]: https://spec.matrix.org/latest/client-server-api/#event-annotations-and-reactions
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[serde(tag = "rel_type", rename = "m.annotation")]
pub struct Annotation {
/// The event that is being annotated.
pub event_id: OwnedEventId,
/// A string that indicates the annotation being applied.
///
/// When sending emoji reactions, this field should include the colourful
/// variation-16 when applicable.
///
/// Clients should render reactions that have a long `key` field in a
/// sensible manner.
pub key: String,
}
impl Annotation {
/// Creates a new `Annotation` with the given event ID and key.
pub fn new(event_id: OwnedEventId, key: String) -> Self {
Self { event_id, key }
}
}
/// The content of a [replacement] relation.
///
/// [replacement]: https://spec.matrix.org/latest/client-server-api/#event-replacements
#[derive(ToSchema, Deserialize, Clone, Debug)]
pub struct Replacement<C> {
/// The ID of the event being replaced.
pub event_id: OwnedEventId,
/// New content.
pub new_content: C,
}
impl<C> Replacement<C>
where
C: ToSchema,
{
/// Creates a new `Replacement` with the given event ID and new content.
pub fn new(event_id: OwnedEventId, new_content: C) -> Self {
Self {
event_id,
new_content,
}
}
}
/// The content of a [thread] relation.
///
/// [thread]: https://spec.matrix.org/latest/client-server-api/#threading
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "rel_type", rename = "m.thread")]
pub struct Thread {
/// The ID of the root message in the thread.
pub event_id: OwnedEventId,
/// A reply relation.
///
/// If this event is a reply and belongs to a thread, this points to the
/// message that is being replied to, and `is_falling_back` must be set
/// to `false`.
///
/// If this event is not a reply, this is used as a fallback mechanism for
/// clients that do not support threads. This should point to the latest
/// message-like event in the thread and `is_falling_back` must be set
/// to `true`.
#[serde(rename = "m.in_reply_to", skip_serializing_if = "Option::is_none")]
pub in_reply_to: Option<InReplyTo>,
/// Whether the `m.in_reply_to` field is a fallback for older clients or a
/// genuine reply in a thread.
#[serde(default, skip_serializing_if = "palpo_core::serde::is_default")]
pub is_falling_back: bool,
}
impl Thread {
/// Convenience method to create a regular `Thread` relation with the given
/// root event ID and latest message-like event ID.
pub fn plain(event_id: OwnedEventId, latest_event_id: OwnedEventId) -> Self {
Self {
event_id,
in_reply_to: Some(InReplyTo::new(latest_event_id)),
is_falling_back: true,
}
}
/// Convenience method to create a regular `Thread` relation with the given
/// root event ID and *without* the recommended reply fallback.
pub fn without_fallback(event_id: OwnedEventId) -> Self {
Self {
event_id,
in_reply_to: None,
is_falling_back: false,
}
}
/// Convenience method to create a reply `Thread` relation with the given
/// root event ID and replied-to event ID.
pub fn reply(event_id: OwnedEventId, reply_to_event_id: OwnedEventId) -> Self {
Self {
event_id,
in_reply_to: Some(InReplyTo::new(reply_to_event_id)),
is_falling_back: false,
}
}
}
/// A bundled thread.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct BundledThread {
/// The latest event in the thread.
pub latest_event: RawJson<AnyMessageLikeEvent>,
/// The number of events in the thread.
pub count: u64,
/// Whether the current logged in user has participated in the thread.
pub current_user_participated: bool,
}
impl BundledThread {
/// Creates a new `BundledThread` with the given event, count and user
/// participated flag.
pub fn new(
latest_event: RawJson<AnyMessageLikeEvent>,
count: u64,
current_user_participated: bool,
) -> Self {
Self {
latest_event,
count,
current_user_participated,
}
}
}
/// A [reference] to another event.
///
/// [reference]: https://spec.matrix.org/latest/client-server-api/#reference-relations
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[serde(tag = "rel_type", rename = "m.reference")]
pub struct Reference {
/// The ID of the event being referenced.
pub event_id: OwnedEventId,
}
impl Reference {
/// Creates a new `Reference` with the given event ID.
pub fn new(event_id: OwnedEventId) -> Self {
Self { event_id }
}
}
/// A bundled reference.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct BundledReference {
/// The ID of the event referencing this event.
pub event_id: OwnedEventId,
}
impl BundledReference {
/// Creates a new `BundledThread` with the given event ID.
pub fn new(event_id: OwnedEventId) -> Self {
Self { event_id }
}
}
/// A chunk of references.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct ReferenceChunk {
/// A batch of bundled references.
pub chunk: Vec<BundledReference>,
}
impl ReferenceChunk {
/// Creates a new `ReferenceChunk` with the given chunk.
pub fn new(chunk: Vec<BundledReference>) -> Self {
Self { chunk }
}
}
/// [Bundled aggregations] of related child events of a message-like event.
///
/// [Bundled aggregations]: https://spec.matrix.org/latest/client-server-api/#aggregations-of-child-events
#[derive(ToSchema, Clone, Debug, Serialize)]
pub struct BundledMessageLikeRelations<E> {
/// Replacement relation.
#[serde(rename = "m.replace", skip_serializing_if = "Option::is_none")]
pub replace: Option<Box<E>>,
/// Set when the above fails to deserialize.
///
/// Intentionally *not* public.
#[serde(skip_serializing)]
has_invalid_replacement: bool,
/// Thread relation.
#[serde(rename = "m.thread", skip_serializing_if = "Option::is_none")]
pub thread: Option<Box<BundledThread>>,
/// Reference relations.
#[serde(rename = "m.reference", skip_serializing_if = "Option::is_none")]
pub reference: Option<Box<ReferenceChunk>>,
}
impl<E> BundledMessageLikeRelations<E> {
/// Creates a new empty `BundledMessageLikeRelations`.
pub const fn new() -> Self {
Self {
replace: None,
has_invalid_replacement: false,
thread: None,
reference: None,
}
}
/// Whether this bundle contains a replacement relation.
///
/// This may be `true` even if the `replace` field is `None`, because Matrix
/// versions prior to 1.7 had a different incompatible format for
/// bundled replacements. Use this method to check whether an event was
/// replaced. If this returns `true` but `replace` is `None`, use one of
/// the endpoints from `palpo::api::client::relations` to fetch the relation
/// details.
pub fn has_replacement(&self) -> bool {
self.replace.is_some() || self.has_invalid_replacement
}
/// Returns `true` if all fields are empty.
pub fn is_empty(&self) -> bool {
self.replace.is_none() && self.thread.is_none() && self.reference.is_none()
}
/// Transform `BundledMessageLikeRelations<E>` to
/// `BundledMessageLikeRelations<T>` using the given closure to convert
/// the `replace` field if it is `Some(_)`.
pub(crate) fn map_replace<T>(self, f: impl FnOnce(E) -> T) -> BundledMessageLikeRelations<T> {
let Self {
replace,
has_invalid_replacement,
thread,
reference,
} = self;
let replace = replace.map(|r| Box::new(f(*r)));
BundledMessageLikeRelations {
replace,
has_invalid_replacement,
thread,
reference,
}
}
}
impl<E> Default for BundledMessageLikeRelations<E> {
fn default() -> Self {
Self::new()
}
}
/// [Bundled aggregations] of related child events of a state event.
///
/// [Bundled aggregations]: https://spec.matrix.org/latest/client-server-api/#aggregations-of-child-events
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct BundledStateRelations {
/// Thread relation.
#[serde(rename = "m.thread", skip_serializing_if = "Option::is_none")]
pub thread: Option<Box<BundledThread>>,
/// Reference relations.
#[serde(rename = "m.reference", skip_serializing_if = "Option::is_none")]
pub reference: Option<Box<ReferenceChunk>>,
}
impl BundledStateRelations {
/// Creates a new empty `BundledStateRelations`.
pub const fn new() -> Self {
Self {
thread: None,
reference: None,
}
}
/// Returns `true` if all fields are empty.
pub fn is_empty(&self) -> bool {
self.thread.is_none() && self.reference.is_none()
}
}
/// Relation types as defined in `rel_type` of an `m.relates_to` field.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[palpo_enum(rename_all(prefix = "m.", rule = "snake_case"))]
#[non_exhaustive]
pub enum RelationType {
/// `m.annotation`, an annotation, principally used by reactions.
Annotation,
/// `m.replace`, a replacement.
Replacement,
/// `m.thread`, a participant to a thread.
Thread,
/// `m.reference`, a reference to another event.
Reference,
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(PrivOwnedStr),
}
/// The payload for a custom relation.
#[doc(hidden)]
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
pub struct CustomRelation(pub(super) JsonObject);
impl CustomRelation {
pub(super) fn rel_type(&self) -> Option<RelationType> {
Some(self.0.get("rel_type")?.as_str()?.into())
}
}
#[derive(Deserialize)]
struct BundledMessageLikeRelationsJsonRepr<E> {
#[serde(rename = "m.replace")]
replace: Option<RawJson<Box<E>>>,
#[serde(rename = "m.thread")]
thread: Option<Box<BundledThread>>,
#[serde(rename = "m.reference")]
reference: Option<Box<ReferenceChunk>>,
}
impl<'de, E> Deserialize<'de> for BundledMessageLikeRelations<E>
where
E: DeserializeOwned,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let BundledMessageLikeRelationsJsonRepr {
replace,
thread,
reference,
} = BundledMessageLikeRelationsJsonRepr::deserialize(deserializer)?;
let (replace, has_invalid_replacement) =
match replace.as_ref().map(RawJson::deserialize).transpose() {
Ok(replace) => (replace, false),
Err(_) => (None, true),
};
Ok(BundledMessageLikeRelations {
replace,
has_invalid_replacement,
thread,
reference,
})
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/do_not_disturb.rs | crates/core/src/events/do_not_disturb.rs | //! Types for the [`dm.filament.do_not_disturb`] event.
//!
//! [`dm.filament.do_not_disturb`]: https://github.com/matrix-org/matrix-spec-proposals/pull/4359
use std::collections::BTreeMap;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::OwnedRoomId;
use crate::macros::EventContent;
/// The content of a `dm.filament.do_not_disturb` event.
///
/// A list of rooms in "Do not Disturb" mode.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize, EventContent)]
#[palpo_event(type = "dm.filament.do_not_disturb", kind = GlobalAccountData)]
pub struct DoNotDisturbEventContent {
/// A map of rooms in which to inhibit notifications.
///
/// As [`DoNotDisturbRoom`] is currently empty, only the room IDs are useful and
/// can be accessed with the `.keys()` and `into_keys()` iterators.
pub rooms: BTreeMap<DoNotDisturbRoomKey, DoNotDisturbRoom>,
}
impl DoNotDisturbEventContent {
/// Creates a new `DoNotDisturbEventContent` from the given map of [`DoNotDisturbRoom`]s.
pub fn new(rooms: BTreeMap<DoNotDisturbRoomKey, DoNotDisturbRoom>) -> Self {
Self { rooms }
}
}
impl FromIterator<DoNotDisturbRoomKey> for DoNotDisturbEventContent {
fn from_iter<T: IntoIterator<Item = DoNotDisturbRoomKey>>(iter: T) -> Self {
Self::new(
iter.into_iter()
.map(|key| (key, DoNotDisturbRoom {}))
.collect(),
)
}
}
impl FromIterator<OwnedRoomId> for DoNotDisturbEventContent {
fn from_iter<T: IntoIterator<Item = OwnedRoomId>>(iter: T) -> Self {
iter.into_iter()
.map(DoNotDisturbRoomKey::SingleRoom)
.collect()
}
}
impl Extend<DoNotDisturbRoomKey> for DoNotDisturbEventContent {
fn extend<T: IntoIterator<Item = DoNotDisturbRoomKey>>(&mut self, iter: T) {
self.rooms
.extend(iter.into_iter().map(|key| (key, DoNotDisturbRoom {})));
}
}
impl Extend<OwnedRoomId> for DoNotDisturbEventContent {
fn extend<T: IntoIterator<Item = OwnedRoomId>>(&mut self, iter: T) {
self.extend(iter.into_iter().map(DoNotDisturbRoomKey::SingleRoom));
}
}
/// The key for a "Do not Disturb" setting.
///
/// This either matches a single room or all rooms.
#[derive(ToSchema, Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum DoNotDisturbRoomKey {
/// Match any room.
#[serde(rename = "*")]
AllRooms,
/// Match a single room based on its room ID.
#[serde(untagged)]
SingleRoom(OwnedRoomId),
}
/// Details about a room in "Do not Disturb" mode.
///
/// This is currently empty.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct DoNotDisturbRoom {}
impl DoNotDisturbRoom {
/// Creates an empty `DoNotDisturbRoom`.
pub fn new() -> Self {
Self::default()
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use assert_matches2::assert_matches;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::DoNotDisturbEventContent;
use crate::events::{AnyGlobalAccountDataEvent, do_not_disturb::DoNotDisturbRoomKey};
use crate::owned_room_id;
#[test]
fn serialization_with_single_room() {
let do_not_disturb_room_list: DoNotDisturbEventContent =
vec![owned_room_id!("!foo:bar.baz")].into_iter().collect();
let json = json!({
"rooms": {
"!foo:bar.baz": {}
},
});
assert_eq!(to_json_value(do_not_disturb_room_list).unwrap(), json);
}
#[test]
fn serialization_with_all_rooms() {
let do_not_disturb_room_list = DoNotDisturbEventContent::new(BTreeMap::from([(
DoNotDisturbRoomKey::AllRooms,
Default::default(),
)]));
let json = json!({
"rooms": {
"*": {}
},
});
assert_eq!(to_json_value(do_not_disturb_room_list).unwrap(), json);
}
#[test]
fn deserialization_with_single_room() {
let json = json!({
"content": {
"rooms": {
"!foo:bar.baz": {}
}
},
"type": "dm.filament.do_not_disturb"
});
assert_matches!(
from_json_value::<AnyGlobalAccountDataEvent>(json),
Ok(AnyGlobalAccountDataEvent::DoNotDisturb(ev))
);
assert_eq!(
ev.content.rooms.keys().collect::<Vec<_>>(),
vec![&DoNotDisturbRoomKey::SingleRoom(owned_room_id!(
"!foo:bar.baz"
))]
);
}
#[test]
fn deserialization_with_all_room() {
let json = json!({
"content": {
"rooms": {
"*": {}
}
},
"type": "dm.filament.do_not_disturb"
});
assert_matches!(
from_json_value::<AnyGlobalAccountDataEvent>(json),
Ok(AnyGlobalAccountDataEvent::DoNotDisturb(ev))
);
assert_eq!(
ev.content.rooms.keys().collect::<Vec<_>>(),
vec![&DoNotDisturbRoomKey::AllRooms]
);
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/encrypted.rs | crates/core/src/events/encrypted.rs | //! Types for extensible encrypted events ([MSC3956]).
//!
//! [MSC3956]: https://github.com/matrix-org/matrix-spec-proposals/pull/3956
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use super::room::encrypted::{EncryptedEventScheme, Relation};
/// The payload for an extensible encrypted message.
///
/// This is the new primary type introduced in [MSC3956] and should only be sent
/// in rooms with a version that supports it. See the documentation of the
/// [`message`] module for more information.
///
/// [MSC3956]: https://github.com/matrix-org/matrix-spec-proposals/pull/3956
/// [`message`]: super::message
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize, EventContent)]
#[palpo_event(type = "org.matrix.msc1767.encrypted", kind = MessageLike)]
pub struct EncryptedEventContent {
/// The encrypted content.
#[serde(rename = "org.matrix.msc1767.encrypted")]
pub encrypted: EncryptedContentBlock,
/// Information about related events.
#[serde(rename = "m.relates_to", skip_serializing_if = "Option::is_none")]
pub relates_to: Option<Relation>,
}
impl EncryptedEventContent {
/// Creates a new `EncryptedEventContent` with the given scheme and
/// relation.
pub fn new(scheme: EncryptedEventScheme, relates_to: Option<Relation>) -> Self {
Self {
encrypted: scheme.into(),
relates_to,
}
}
}
impl From<EncryptedEventScheme> for EncryptedEventContent {
fn from(scheme: EncryptedEventScheme) -> Self {
Self {
encrypted: scheme.into(),
relates_to: None,
}
}
}
/// A block for encrypted content.
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize)]
pub struct EncryptedContentBlock {
/// Algorithm-specific fields.
#[serde(flatten)]
pub scheme: EncryptedEventScheme,
}
impl From<EncryptedEventScheme> for EncryptedContentBlock {
fn from(scheme: EncryptedEventScheme) -> Self {
Self { scheme }
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/policy.rs | crates/core/src/events/policy.rs | //! Modules for events in the `m.policy` namespace.
pub mod rule;
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/marked_unread.rs | crates/core/src/events/marked_unread.rs | //! Types for the [`m.marked_unread`] event.
//!
//! [`m.marked_unread`]: https://spec.matrix.org/latest/client-server-api/#unread-markers
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
/// The content of an `m.marked_unread` event.
///
/// Whether the room has been explicitly marked as unread.
///
/// This event appears in the user's room account data for the room the marker
/// is applicable for.
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize, EventContent)]
#[palpo_event(type = "m.marked_unread", kind = RoomAccountData)]
pub struct MarkedUnreadEventContent {
/// The current unread state.
pub unread: bool,
}
impl MarkedUnreadEventContent {
/// Creates a new `MarkedUnreadEventContent` with the given value.
pub fn new(unread: bool) -> Self {
Self { unread }
}
}
/// The content of a [`com.famedly.marked_unread`] event, the unstable version
/// of [MarkedUnreadEventContent].
///
/// Whether the room has been explicitly marked as unread.
///
/// This event appears in the user's room account data for the room the marker
/// is applicable for.
///
/// [`com.famedly.marked_unread`]: https://github.com/matrix-org/matrix-spec-proposals/pull/2867
#[cfg(feature = "unstable-msc2867")]
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize, EventContent)]
#[palpo_event(type = "com.famedly.marked_unread", kind = RoomAccountData)]
#[serde(transparent)]
pub struct UnstableMarkedUnreadEventContent(pub MarkedUnreadEventContent);
#[cfg(feature = "unstable-msc2867")]
impl std::ops::Deref for UnstableMarkedUnreadEventContent {
type Target = MarkedUnreadEventContent;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[cfg(feature = "unstable-msc2867")]
impl From<MarkedUnreadEventContent> for UnstableMarkedUnreadEventContent {
fn from(value: MarkedUnreadEventContent) -> Self {
Self(value)
}
}
#[cfg(feature = "unstable-msc2867")]
impl From<UnstableMarkedUnreadEventContent> for MarkedUnreadEventContent {
fn from(value: UnstableMarkedUnreadEventContent) -> Self {
value.0
}
}
#[cfg(all(test, feature = "unstable-msc2867"))]
mod tests {
use assert_matches2::assert_matches;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::{MarkedUnreadEventContent, UnstableMarkedUnreadEventContent};
use crate::events::{AnyRoomAccountDataEvent, RoomAccountDataEvent};
#[test]
fn deserialize() {
let raw_unstable_marked_unread = json!({
"type": "com.famedly.marked_unread",
"content": {
"unread": true,
},
});
let unstable_marked_unread_account_data =
from_json_value::<AnyRoomAccountDataEvent>(raw_unstable_marked_unread).unwrap();
assert_matches!(
unstable_marked_unread_account_data,
AnyRoomAccountDataEvent::UnstableMarkedUnread(unstable_marked_unread)
);
assert!(unstable_marked_unread.content.unread);
let raw_marked_unread = json!({
"type": "m.marked_unread",
"content": {
"unread": true,
},
});
let marked_unread_account_data =
from_json_value::<AnyRoomAccountDataEvent>(raw_marked_unread).unwrap();
assert_matches!(
marked_unread_account_data,
AnyRoomAccountDataEvent::MarkedUnread(marked_unread)
);
assert!(marked_unread.content.unread);
}
#[test]
fn serialize() {
let marked_unread = MarkedUnreadEventContent::new(true);
let marked_unread_account_data = RoomAccountDataEvent {
content: marked_unread.clone(),
};
assert_eq!(
to_json_value(marked_unread_account_data).unwrap(),
json!({
"type": "m.marked_unread",
"content": {
"unread": true,
},
})
);
let unstable_marked_unread = UnstableMarkedUnreadEventContent::from(marked_unread);
let unstable_marked_unread_account_data = RoomAccountDataEvent {
content: unstable_marked_unread,
};
assert_eq!(
to_json_value(unstable_marked_unread_account_data).unwrap(),
json!({
"type": "com.famedly.marked_unread",
"content": {
"unread": true,
},
})
);
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/push_rules.rs | crates/core/src/events/push_rules.rs | //! Types for the [`m.push_rules`] event.
//!
//! [`m.push_rules`]: https://spec.matrix.org/latest/client-server-api/#mpush_rules
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::push::Ruleset;
/// The content of an `m.push_rules` event.
///
/// Describes all push rules for a user.
#[derive(ToSchema, Deserialize, Serialize, Clone, Default, Debug, EventContent)]
#[palpo_event(type = "m.push_rules", kind = GlobalAccountData)]
pub struct PushRulesEventContent {
/// The global ruleset.
pub global: Ruleset,
}
impl PushRulesEventContent {
/// Creates a new `PushRulesEventContent` with the given global ruleset.
///
/// You can also construct a `PushRulesEventContent` from a global ruleset
/// using `From` / `Into`.
pub fn new(global: Ruleset) -> Self {
Self { global }
}
}
impl From<Ruleset> for PushRulesEventContent {
fn from(global: Ruleset) -> Self {
Self::new(global)
}
}
#[cfg(test)]
mod tests {
use serde_json::{from_value as from_json_value, json};
use super::PushRulesEvent;
#[test]
fn sanity_check() {
// This is a full example of a push rules event from the specification.
let json_data = json!({
"content": {
"global": {
"content": [
{
"actions": [
"notify",
{
"set_tweak": "sound",
"value": "default"
},
{
"set_tweak": "highlight"
}
],
"default": true,
"enabled": true,
"pattern": "alice",
"rule_id": ".m.rule.contains_user_name"
}
],
"override": [
{
"actions": [],
"conditions": [],
"default": true,
"enabled": false,
"rule_id": ".m.rule.master"
},
{
"actions": [],
"conditions": [
{
"key": "content.msgtype",
"kind": "event_match",
"pattern": "m.notice"
}
],
"default": true,
"enabled": true,
"rule_id": ".m.rule.suppress_notices"
}
],
"room": [],
"sender": [],
"underride": [
{
"actions": [
"notify",
{
"set_tweak": "sound",
"value": "ring"
},
{
"set_tweak": "highlight",
"value": false
}
],
"conditions": [
{
"key": "type",
"kind": "event_match",
"pattern": "m.call.invite"
}
],
"default": true,
"enabled": true,
"rule_id": ".m.rule.call"
},
{
"actions": [
"notify",
{
"set_tweak": "sound",
"value": "default"
},
{
"set_tweak": "highlight"
}
],
"conditions": [
{
"kind": "contains_display_name"
}
],
"default": true,
"enabled": true,
"rule_id": ".m.rule.contains_display_name"
},
{
"actions": [
"notify",
{
"set_tweak": "sound",
"value": "default"
},
{
"set_tweak": "highlight",
"value": false
}
],
"conditions": [
{
"is": "2",
"kind": "room_member_count"
}
],
"default": true,
"enabled": true,
"rule_id": ".m.rule.room_one_to_one"
},
{
"actions": [
"notify",
{
"set_tweak": "sound",
"value": "default"
},
{
"set_tweak": "highlight",
"value": false
}
],
"conditions": [
{
"key": "type",
"kind": "event_match",
"pattern": "m.room.member"
},
{
"key": "content.membership",
"kind": "event_match",
"pattern": "invite"
},
{
"key": "state_key",
"kind": "event_match",
"pattern": "@alice:example.com"
}
],
"default": true,
"enabled": true,
"rule_id": ".m.rule.invite_for_me"
},
{
"actions": [
"notify",
{
"set_tweak": "highlight",
"value": false
}
],
"conditions": [
{
"key": "type",
"kind": "event_match",
"pattern": "m.room.member"
}
],
"default": true,
"enabled": true,
"rule_id": ".m.rule.member_event"
},
{
"actions": [
"notify",
{
"set_tweak": "highlight",
"value": false
}
],
"conditions": [
{
"key": "type",
"kind": "event_match",
"pattern": "m.room.message"
}
],
"default": true,
"enabled": true,
"rule_id": ".m.rule.message"
}
]
}
},
"type": "m.push_rules"
});
from_json_value::<PushRulesEvent>(json_data).unwrap();
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/unsigned.rs | crates/core/src/events/unsigned.rs | use salvo::oapi::ToSchema;
use serde::{Deserialize, de::DeserializeOwned};
use super::{
MessageLikeEventContent, OriginalSyncMessageLikeEvent, PossiblyRedactedStateEventContent,
relation::{BundledMessageLikeRelations, BundledStateRelations},
room::redaction::RoomRedactionEventContent,
};
use crate::{OwnedEventId, OwnedTransactionId, OwnedUserId, UnixMillis, serde::CanBeEmpty};
/// Extra information about a message event that is not incorporated into the
/// event's hash.
#[derive(ToSchema, Clone, Debug, Deserialize)]
#[serde(bound = "OriginalSyncMessageLikeEvent<C>: DeserializeOwned")]
pub struct MessageLikeUnsigned<C: MessageLikeEventContent> {
/// The time in milliseconds that has elapsed since the event was sent.
///
/// This field is generated by the local homeserver, and may be incorrect if
/// the local time on at least one of the two servers is out of sync,
/// which can cause the age to either be negative or greater than it
/// actually is.
pub age: Option<i64>,
/// The client-supplied transaction ID, if the client being given the event
/// is the same one which sent it.
pub transaction_id: Option<OwnedTransactionId>,
/// [Bundled aggregations] of related child events.
///
/// [Bundled aggregations]: https://spec.matrix.org/latest/client-server-api/#aggregations-of-child-events
#[serde(rename = "m.relations", default)]
pub relations: BundledMessageLikeRelations<OriginalSyncMessageLikeEvent<C>>,
}
impl<C: MessageLikeEventContent> MessageLikeUnsigned<C> {
/// Create a new `Unsigned` with fields set to `None`.
pub fn new() -> Self {
Self {
age: None,
transaction_id: None,
relations: BundledMessageLikeRelations::default(),
}
}
}
impl<C: MessageLikeEventContent> Default for MessageLikeUnsigned<C> {
fn default() -> Self {
Self::new()
}
}
impl<C: MessageLikeEventContent> CanBeEmpty for MessageLikeUnsigned<C> {
/// Whether this unsigned data is empty (all fields are `None`).
///
/// This method is used to determine whether to skip serializing the
/// `unsigned` field in room events. Do not use it to determine whether
/// an incoming `unsigned` field was present - it could still have been
/// present but contained none of the known fields.
fn is_empty(&self) -> bool {
self.age.is_none() && self.transaction_id.is_none() && self.relations.is_empty()
}
}
/// Extra information about a state event that is not incorporated into the
/// event's hash.
#[derive(ToSchema, Clone, Debug, Deserialize)]
pub struct StateUnsigned<C: PossiblyRedactedStateEventContent> {
/// The time in milliseconds that has elapsed since the event was sent.
///
/// This field is generated by the local homeserver, and may be incorrect if
/// the local time on at least one of the two servers is out of sync,
/// which can cause the age to either be negative or greater than it
/// actually is.
pub age: Option<i64>,
/// The client-supplied transaction ID, if the client being given the event
/// is the same one which sent it.
pub transaction_id: Option<OwnedTransactionId>,
/// Optional previous content of the event.
pub prev_content: Option<C>,
/// [Bundled aggregations] of related child events.
///
/// [Bundled aggregations]: https://spec.matrix.org/latest/client-server-api/#aggregations-of-child-events
#[serde(rename = "m.relations", default)]
pub relations: BundledStateRelations,
}
impl<C: PossiblyRedactedStateEventContent> StateUnsigned<C> {
/// Create a new `Unsigned` with fields set to `None`.
pub fn new() -> Self {
Self {
age: None,
transaction_id: None,
prev_content: None,
relations: Default::default(),
}
}
}
impl<C: PossiblyRedactedStateEventContent> CanBeEmpty for StateUnsigned<C> {
/// Whether this unsigned data is empty (all fields are `None`).
///
/// This method is used to determine whether to skip serializing the
/// `unsigned` field in room events. Do not use it to determine whether
/// an incoming `unsigned` field was present - it could still have been
/// present but contained none of the known fields.
fn is_empty(&self) -> bool {
self.age.is_none()
&& self.transaction_id.is_none()
&& self.prev_content.is_none()
&& self.relations.is_empty()
}
}
impl<C: PossiblyRedactedStateEventContent> Default for StateUnsigned<C> {
fn default() -> Self {
Self::new()
}
}
/// Extra information about a redacted event that is not incorporated into the
/// event's hash.
#[derive(ToSchema, Clone, Debug, Deserialize)]
pub struct RedactedUnsigned {
/// The event that redacted this event, if any.
pub redacted_because: UnsignedRoomRedactionEvent,
}
impl RedactedUnsigned {
/// Create a new `RedactedUnsigned` with the given redaction event.
pub fn new(redacted_because: UnsignedRoomRedactionEvent) -> Self {
Self { redacted_because }
}
}
/// A redaction event as found in `unsigned.redacted_because`.
///
/// While servers usually send this with the `redacts` field (unless nested),
/// the ID of the event being redacted is known from context wherever this type
/// is used, so it's not reflected as a field here.
///
/// It is intentionally not possible to create an instance of this type other
/// than through `Clone` or `Deserialize`.
#[derive(ToSchema, Clone, Debug, Deserialize)]
#[non_exhaustive]
pub struct UnsignedRoomRedactionEvent {
/// Data specific to the event type.
pub content: RoomRedactionEventContent,
/// The globally unique event identifier for the user who sent the event.
pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event.
pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was
/// sent.
pub origin_server_ts: UnixMillis,
/// Additional key-value pairs not signed by the homeserver.
#[serde(default)]
pub unsigned: MessageLikeUnsigned<RoomRedactionEventContent>,
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/pdu.rs | crates/core/src/events/pdu.rs | //! Types for persistent data unit schemas
//!
//! The differences between the `RoomV1Pdu` schema and the `RoomV3Pdu` schema are that the
//! `RoomV1Pdu` takes an `event_id` field (`RoomV3Pdu` does not), and `auth_events` and
//! `prev_events` take `Vec<(OwnedEventId, EventHash)>` rather than `Vec<OwnedEventId>` in
//! `RoomV3Pdu`.
use std::collections::BTreeMap;
use serde::{
Deserialize, Deserializer, Serialize,
de::{Error as _, IgnoredAny},
};
use serde_json::from_str as from_json_str;
use super::TimelineEventType;
use crate::{
OwnedEventId, OwnedRoomId, OwnedServerName, OwnedServerSigningKeyId, OwnedUserId, RawJsonValue, UnixMillis,
};
/// Enum for PDU schemas
#[derive(Clone, Debug, Serialize)]
#[serde(untagged)]
pub enum Pdu {
/// PDU for room versions 1 and 2.
RoomV1Pdu(RoomV1Pdu),
/// PDU for room versions 3 and above.
RoomV3Pdu(RoomV3Pdu),
}
/// A 'persistent data unit' (event) for room versions 1 and 2.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[allow(clippy::exhaustive_structs)]
pub struct RoomV1Pdu {
/// Event ID for the PDU.
pub event_id: OwnedEventId,
/// The room this event belongs to.
pub room_id: OwnedRoomId,
/// The user id of the user who sent this event.
pub sender: OwnedUserId,
/// Timestamp (milliseconds since the UNIX epoch) on originating homeserver
/// of when this event was created.
pub origin_server_ts: UnixMillis,
// TODO: Encode event type as content enum variant, like event enums do
/// The event's type.
#[serde(rename = "type")]
pub kind: TimelineEventType,
/// The event's content.
pub content: Box<RawJsonValue>,
/// A key that determines which piece of room state the event represents.
#[serde(skip_serializing_if = "Option::is_none")]
pub state_key: Option<String>,
/// Event IDs for the most recent events in the room that the homeserver was
/// aware of when it created this event.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub prev_events: Vec<(OwnedEventId, EventHash)>,
/// The maximum depth of the `prev_events`, plus one.
pub depth: u64,
/// Event IDs for the authorization events that would allow this event to be
/// in the room.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub auth_events: Vec<(OwnedEventId, EventHash)>,
/// For redaction events, the ID of the event being redacted.
#[serde(skip_serializing_if = "Option::is_none")]
pub redacts: Option<OwnedEventId>,
/// Additional data added by the origin server but not covered by the
/// signatures.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub unsigned: BTreeMap<String, Box<RawJsonValue>>,
/// Content hashes of the PDU.
pub hashes: EventHash,
/// Signatures for the PDU.
pub signatures: BTreeMap<OwnedServerName, BTreeMap<OwnedServerSigningKeyId, String>>,
}
/// A 'persistent data unit' (event) for room versions 3 and beyond.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[allow(clippy::exhaustive_structs)]
pub struct RoomV3Pdu {
/// The room this event belongs to.
pub room_id: OwnedRoomId,
/// The user id of the user who sent this event.
pub sender: OwnedUserId,
/// Timestamp (milliseconds since the UNIX epoch) on originating homeserver
/// of when this event was created.
pub origin_server_ts: UnixMillis,
// TODO: Encode event type as content enum variant, like event enums do
/// The event's type.
#[serde(rename = "type")]
pub kind: TimelineEventType,
/// The event's content.
pub content: Box<RawJsonValue>,
/// A key that determines which piece of room state the event represents.
#[serde(skip_serializing_if = "Option::is_none")]
pub state_key: Option<String>,
/// Event IDs for the most recent events in the room that the homeserver was
/// aware of when it created this event.
pub prev_events: Vec<OwnedEventId>,
/// The maximum depth of the `prev_events`, plus one.
pub depth: u64,
/// Event IDs for the authorization events that would allow this event to be
/// in the room.
pub auth_events: Vec<OwnedEventId>,
/// For redaction events, the ID of the event being redacted.
#[serde(skip_serializing_if = "Option::is_none")]
pub redacts: Option<OwnedEventId>,
/// Additional data added by the origin server but not covered by the
/// signatures.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub unsigned: BTreeMap<String, Box<RawJsonValue>>,
/// Content hashes of the PDU.
pub hashes: EventHash,
/// Signatures for the PDU.
pub signatures: BTreeMap<OwnedServerName, BTreeMap<OwnedServerSigningKeyId, String>>,
}
/// Content hashes of a PDU.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct EventHash {
/// The SHA-256 hash.
pub sha256: String,
}
impl EventHash {
/// Create a new `EventHash` with the given SHA256 hash.
pub fn new(sha256: String) -> Self {
Self { sha256 }
}
}
impl<'de> Deserialize<'de> for Pdu {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
struct GetEventId {
event_id: Option<IgnoredAny>,
}
let json = Box::<RawJsonValue>::deserialize(deserializer)?;
if from_json_str::<GetEventId>(json.get())
.map_err(D::Error::custom)?
.event_id
.is_some()
{
from_json_str(json.get()).map(Self::RoomV1Pdu).map_err(D::Error::custom)
} else {
from_json_str(json.get()).map(Self::RoomV3Pdu).map_err(D::Error::custom)
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/enums.rs | crates/core/src/events/enums.rs | use crate::macros::{EventEnumFromEvent, event_enum};
use salvo::prelude::*;
use serde::{Deserialize, de};
use super::room::encrypted;
use crate::{
UnixMillis,
identifiers::*,
serde::{RawJsonValue, from_raw_json_value},
};
/// Event types that servers should send as [stripped state] to help clients
/// identify a room when they can't access the full room state.
///
/// [stripped state]: https://spec.matrix.org/latest/client-server-api/#stripped-state
pub const RECOMMENDED_STRIPPED_STATE_EVENT_TYPES: &[StateEventType] = &[
StateEventType::RoomCreate,
StateEventType::RoomName,
StateEventType::RoomAvatar,
StateEventType::RoomTopic,
StateEventType::RoomJoinRules,
StateEventType::RoomCanonicalAlias,
StateEventType::RoomEncryption,
];
/// Event types that servers should transfer upon [room upgrade]. The exact details for what is
/// transferred is left as an implementation detail.
///
/// [room upgrade]: https://spec.matrix.org/v1.17/client-server-api/#server-behaviour-19
pub const RECOMMENDED_TRANSFERABLE_STATE_EVENT_TYPES: &[StateEventType] = &[
StateEventType::RoomServerAcl,
StateEventType::RoomEncryption,
StateEventType::RoomName,
StateEventType::RoomAvatar,
StateEventType::RoomTopic,
StateEventType::RoomGuestAccess,
StateEventType::RoomHistoryVisibility,
StateEventType::RoomJoinRules,
StateEventType::RoomPowerLevels,
];
event_enum! {
/// Any global account data event.
enum GlobalAccountData {
"m.direct" => super::direct,
#[cfg(feature = "unstable-msc4359")]
#[palpo_enum(ident = DoNotDisturb, alias = "m.do_not_disturb")]
"dm.filament.do_not_disturb" => super::do_not_disturb,
"m.identity_server" => super::identity_server,
#[cfg(feature = "unstable-msc4380")]
#[palpo_enum(ident = InvitePermissionConfig, alias = "m.invite_permission_config")]
"org.matrix.msc4380.invite_permission_config" => super::invite_permission_config,
"m.ignored_user_list" => super::ignored_user_list,
"m.push_rules" => super::push_rules,
"m.secret_storage.default_key" => super::secret_storage::default_key,
"m.secret_storage.key.*" => super::secret_storage::key,
#[cfg(feature = "unstable-msc4278")]
"m.media_preview_config" => super::media_preview_config,
#[cfg(feature = "unstable-msc4278")]
#[palpo_enum(ident = UnstableMediaPreviewConfig)]
"io.element.msc4278.media_preview_config" => super::media_preview_config,
#[cfg(feature = "unstable-msc2545")]
#[palpo_enum(ident = AccountImagePack, alias = "m.image_pack")]
"im.ponies.user_emotes" => super::image_pack,
#[cfg(feature = "unstable-msc2545")]
#[palpo_enum(ident = ImagePackRooms, alias = "m.image_pack.rooms")]
"im.ponies.emote_rooms" => super::image_pack,
}
/// Any room account data event.
enum RoomAccountData {
"m.fully_read" => super::fully_read,
"m.tag" => super::tag,
"m.marked_unread" => super::marked_unread,
#[cfg(feature = "unstable-msc2867")]
#[palpo_enum(ident = UnstableMarkedUnread)]
"com.famedly.marked_unread" => super::marked_unread,
#[cfg(feature = "unstable-msc4278")]
"m.media_preview_config" => super::media_preview_config,
#[cfg(feature = "unstable-msc4278")]
#[palpo_enum(ident = UnstableMediaPreviewConfig)]
"io.element.msc4278.media_preview_config" => super::media_preview_config,
#[cfg(feature = "unstable-msc3230")]
#[palpo_enum(alias = "m.space_order")]
"org.matrix.msc3230.space_order" => super::space_order,
}
/// Any ephemeral room event.
enum EphemeralRoom {
"m.receipt" => super::receipt,
"m.typing" => super::typing,
}
/// Any message-like event.
enum MessageLike {
#[cfg(feature = "unstable-msc3927")]
#[palpo_enum(alias = "m.audio")]
"org.matrix.msc1767.audio" => super::audio,
"m.call.answer" => super::call::answer,
"m.call.invite" => super::call::invite,
"m.call.hangup" => super::call::hangup,
"m.call.candidates" => super::call::candidates,
"m.call.negotiate" => super::call::negotiate,
"m.call.reject" => super::call::reject,
#[palpo_enum(alias = "org.matrix.call.sdp_stream_metadata_changed")]
"m.call.sdp_stream_metadata_changed" => super::call::sdp_stream_metadata_changed,
"m.call.select_answer" => super::call::select_answer,
#[cfg(feature = "unstable-msc3954")]
#[palpo_enum(alias = "m.emote")]
"org.matrix.msc1767.emote" => super::emote,
#[cfg(feature = "unstable-msc3956")]
#[palpo_enum(alias = "m.encrypted")]
"org.matrix.msc1767.encrypted" => super::encrypted,
#[cfg(feature = "unstable-msc3551")]
#[palpo_enum(alias = "m.file")]
"org.matrix.msc1767.file" => super::file,
#[cfg(feature = "unstable-msc3552")]
#[palpo_enum(alias = "m.image")]
"org.matrix.msc1767.image" => super::image,
"m.key.verification.ready" => super::key::verification::ready,
"m.key.verification.start" => super::key::verification::start,
"m.key.verification.cancel" => super::key::verification::cancel,
"m.key.verification.accept" => super::key::verification::accept,
"m.key.verification.key" => super::key::verification::key,
"m.key.verification.mac" => super::key::verification::mac,
"m.key.verification.done" => super::key::verification::done,
#[cfg(feature = "unstable-msc3488")]
"m.location" => super::location,
#[cfg(feature = "unstable-msc1767")]
#[palpo_enum(alias = "m.message")]
"org.matrix.msc1767.message" => super::message,
#[cfg(feature = "unstable-msc3381")]
"m.poll.start" => super::poll::start,
#[cfg(feature = "unstable-msc3381")]
#[palpo_enum(ident = UnstablePollStart)]
"org.matrix.msc3381.poll.start" => super::poll::unstable_start,
#[cfg(feature = "unstable-msc3381")]
"m.poll.response" => super::poll::response,
#[cfg(feature = "unstable-msc3381")]
#[palpo_enum(ident = UnstablePollResponse)]
"org.matrix.msc3381.poll.response" => super::poll::unstable_response,
#[cfg(feature = "unstable-msc3381")]
"m.poll.end" => super::poll::end,
#[cfg(feature = "unstable-msc3381")]
#[palpo_enum(ident = UnstablePollEnd)]
"org.matrix.msc3381.poll.end" => super::poll::unstable_end,
#[cfg(feature = "unstable-msc3489")]
#[palpo_enum(alias = "m.beacon")]
"org.matrix.msc3672.beacon" => super::beacon,
"m.reaction" => super::reaction,
"m.room.encrypted" => super::room::encrypted,
"m.room.message" => super::room::message,
"m.room.redaction" => super::room::redaction,
"m.sticker" => super::sticker,
#[cfg(feature = "unstable-msc3553")]
#[palpo_enum(alias = "m.video")]
"org.matrix.msc1767.video" => super::video,
#[cfg(feature = "unstable-msc3245")]
#[palpo_enum(alias = "m.voice")]
"org.matrix.msc3245.voice.v2" => super::voice,
#[cfg(feature = "unstable-msc4075")]
#[palpo_enum(alias = "m.call.notify")]
"org.matrix.msc4075.call.notify" => super::call::notify,
#[cfg(feature = "unstable-msc4075")]
#[palpo_enum(alias = "m.rtc.notification")]
"org.matrix.msc4075.rtc.notification" => super::rtc::notification,
#[cfg(feature = "unstable-msc4310")]
#[palpo_enum(alias = "m.rtc.decline")]
"org.matrix.msc4310.rtc.decline" => super::rtc::decline,
}
/// Any state event.
enum State {
"m.policy.rule.room" => super::policy::rule::room,
"m.policy.rule.server" => super::policy::rule::server,
"m.policy.rule.user" => super::policy::rule::user,
"m.room.aliases" => super::room::aliases,
"m.room.avatar" => super::room::avatar,
"m.room.canonical_alias" => super::room::canonical_alias,
"m.room.create" => super::room::create,
"m.room.encryption" => super::room::encryption,
#[cfg(feature = "unstable-msc4362")]
"m.room.encrypted" => super::room::encrypted::unstable_state,
"m.room.guest_access" => super::room::guest_access,
"m.room.history_visibility" => super::room::history_visibility,
"m.room.join_rules" => super::room::join_rule,
"m.room.member" => super::room::member,
"m.room.name" => super::room::name,
"m.room.pinned_events" => super::room::pinned_events,
"m.room.power_levels" => super::room::power_levels,
"m.room.server_acl" => super::room::server_acl,
"m.room.third_party_invite" => super::room::third_party_invite,
"m.room.tombstone" => super::room::tombstone,
"m.room.topic" => super::room::topic,
"m.space.child" => super::space::child,
"m.space.parent" => super::space::parent,
#[cfg(feature = "unstable-msc2545")]
#[palpo_enum(ident = RoomImagePack, alias = "m.image_pack")]
"im.ponies.room_emotes" => super::image_pack,
#[cfg(feature = "unstable-msc3489")]
#[palpo_enum(alias = "m.beacon_info")]
"org.matrix.msc3672.beacon_info" => super::beacon_info,
#[cfg(feature = "unstable-msc3401")]
#[palpo_enum(alias = "m.call.member")]
"org.matrix.msc3401.call.member" => super::call::member,
#[cfg(feature = "unstable-msc4171")]
#[palpo_enum(alias = "m.member_hints")]
"io.element.functional_members" => super::member_hints,
}
/// Any to-device event.
enum ToDevice {
"m.dummy" => super::dummy,
"m.room_key" => super::room_key,
#[cfg(feature = "unstable-msc4268")]
#[palpo_enum(alias = "m.room_key_bundle")]
"io.element.msc4268.room_key_bundle" => super::room_key_bundle,
"m.room_key_request" => super::room_key_request,
"m.room_key.withheld" => super::room_key::withheld,
"m.forwarded_room_key" => super::forwarded_room_key,
"m.key.verification.request" => super::key::verification::request,
"m.key.verification.ready" => super::key::verification::ready,
"m.key.verification.start" => super::key::verification::start,
"m.key.verification.cancel" => super::key::verification::cancel,
"m.key.verification.accept" => super::key::verification::accept,
"m.key.verification.key" => super::key::verification::key,
"m.key.verification.mac" => super::key::verification::mac,
"m.key.verification.done" => super::key::verification::done,
"m.room.encrypted" => super::room::encrypted,
"m.secret.request"=> super::secret::request,
"m.secret.send" => super::secret::send,
}
}
macro_rules! timeline_event_accessors {
(
$(
#[doc = $docs:literal]
pub fn $field:ident(&self) -> $ty:ty;
)*
) => {
$(
#[doc = $docs]
pub fn $field(&self) -> $ty {
match self {
Self::MessageLike(ev) => ev.$field(),
Self::State(ev) => ev.$field(),
}
}
)*
};
}
/// Any room event.
#[allow(clippy::large_enum_variant, clippy::exhaustive_enums)]
#[derive(ToSchema, Clone, Debug, EventEnumFromEvent)]
pub enum AnyTimelineEvent {
/// Any message-like event.
MessageLike(AnyMessageLikeEvent),
/// Any state event.
State(AnyStateEvent),
}
impl AnyTimelineEvent {
timeline_event_accessors! {
/// Returns this event's `origin_server_ts` field.
pub fn origin_server_ts(&self) -> UnixMillis;
/// Returns this event's `room_id` field.
pub fn room_id(&self) -> &RoomId;
/// Returns this event's `event_id` field.
pub fn event_id(&self) -> &EventId;
/// Returns this event's `sender` field.
pub fn sender(&self) -> &UserId;
/// Returns this event's `transaction_id` from inside `unsigned`, if there is one.
pub fn transaction_id(&self) -> Option<&TransactionId>;
/// Returns whether this event is in its redacted form or not.
pub fn is_redacted(&self) -> bool;
}
/// Returns this event's `type`.
pub fn event_type(&self) -> TimelineEventType {
match self {
Self::MessageLike(e) => e.event_type().into(),
Self::State(e) => e.event_type().into(),
}
}
}
/// Any sync room event.
///
/// Sync room events are room event without a `room_id`, as returned in `/sync`
/// responses.
#[allow(clippy::large_enum_variant, clippy::exhaustive_enums)]
#[derive(ToSchema, Clone, Debug, EventEnumFromEvent)]
pub enum AnySyncTimelineEvent {
/// Any sync message-like event.
MessageLike(AnySyncMessageLikeEvent),
/// Any sync state event.
State(AnySyncStateEvent),
}
impl AnySyncTimelineEvent {
timeline_event_accessors! {
/// Returns this event's `origin_server_ts` field.
pub fn origin_server_ts(&self) -> UnixMillis;
/// Returns this event's `event_id` field.
pub fn event_id(&self) -> &EventId;
/// Returns this event's `sender` field.
pub fn sender(&self) -> &UserId;
/// Returns this event's `transaction_id` from inside `unsigned`, if there is one.
pub fn transaction_id(&self) -> Option<&TransactionId>;
/// Returns whether this event is in its redacted form or not.
pub fn is_redacted(&self) -> bool;
}
/// Returns this event's `type`.
pub fn event_type(&self) -> TimelineEventType {
match self {
Self::MessageLike(e) => e.event_type().into(),
Self::State(e) => e.event_type().into(),
}
}
/// Converts `self` to an `AnyTimelineEvent` by adding the given a room ID.
pub fn into_full_event(self, room_id: OwnedRoomId) -> AnyTimelineEvent {
match self {
Self::MessageLike(ev) => AnyTimelineEvent::MessageLike(ev.into_full_event(room_id)),
Self::State(ev) => AnyTimelineEvent::State(ev.into_full_event(room_id)),
}
}
}
impl From<AnyTimelineEvent> for AnySyncTimelineEvent {
fn from(ev: AnyTimelineEvent) -> Self {
match ev {
AnyTimelineEvent::MessageLike(ev) => Self::MessageLike(ev.into()),
AnyTimelineEvent::State(ev) => Self::State(ev.into()),
}
}
}
#[derive(Deserialize)]
#[allow(clippy::exhaustive_structs)]
struct EventDeHelper {
state_key: Option<de::IgnoredAny>,
}
impl<'de> Deserialize<'de> for AnyTimelineEvent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
let json = Box::<RawJsonValue>::deserialize(deserializer)?;
let EventDeHelper { state_key } = from_raw_json_value(&json)?;
if state_key.is_some() {
Ok(AnyTimelineEvent::State(from_raw_json_value(&json)?))
} else {
Ok(AnyTimelineEvent::MessageLike(from_raw_json_value(&json)?))
}
}
}
impl<'de> Deserialize<'de> for AnySyncTimelineEvent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
let json = Box::<RawJsonValue>::deserialize(deserializer)?;
let EventDeHelper { state_key } = from_raw_json_value(&json)?;
if state_key.is_some() {
Ok(AnySyncTimelineEvent::State(from_raw_json_value(&json)?))
} else {
Ok(AnySyncTimelineEvent::MessageLike(from_raw_json_value(
&json,
)?))
}
}
}
impl AnyMessageLikeEventContent {
/// Get a copy of the event's `m.relates_to` field, if any.
///
/// This is a helper function intended for encryption. There should not be a
/// reason to access `m.relates_to` without first destructuring an
/// `AnyMessageLikeEventContent` otherwise.
pub fn relation(&self) -> Option<encrypted::Relation> {
#[cfg(feature = "unstable-msc3489")]
use super::beacon::BeaconEventContent;
use super::key::verification::{
accept::KeyVerificationAcceptEventContent, cancel::KeyVerificationCancelEventContent,
done::KeyVerificationDoneEventContent, key::KeyVerificationKeyEventContent,
mac::KeyVerificationMacEventContent, ready::KeyVerificationReadyEventContent,
start::KeyVerificationStartEventContent,
};
#[cfg(feature = "unstable-msc3381")]
use super::poll::{
end::PollEndEventContent, response::PollResponseEventContent,
unstable_end::UnstablePollEndEventContent,
unstable_response::UnstablePollResponseEventContent,
};
match self {
#[rustfmt::skip]
Self::KeyVerificationReady(KeyVerificationReadyEventContent { relates_to, .. })
| Self::KeyVerificationStart(KeyVerificationStartEventContent { relates_to, .. })
| Self::KeyVerificationCancel(KeyVerificationCancelEventContent { relates_to, .. })
| Self::KeyVerificationAccept(KeyVerificationAcceptEventContent { relates_to, .. })
| Self::KeyVerificationKey(KeyVerificationKeyEventContent { relates_to, .. })
| Self::KeyVerificationMac(KeyVerificationMacEventContent { relates_to, .. })
| Self::KeyVerificationDone(KeyVerificationDoneEventContent { relates_to, .. }) => {
Some(encrypted::Relation::Reference(relates_to.clone()))
},
Self::Reaction(ev) => Some(encrypted::Relation::Annotation(ev.relates_to.clone())),
Self::RoomEncrypted(ev) => ev.relates_to.clone(),
Self::RoomMessage(ev) => ev.relates_to.clone().map(Into::into),
#[cfg(feature = "unstable-msc1767")]
Self::Message(ev) => ev.relates_to.clone().map(Into::into),
#[cfg(feature = "unstable-msc3954")]
Self::Emote(ev) => ev.relates_to.clone().map(Into::into),
#[cfg(feature = "unstable-msc3956")]
Self::Encrypted(ev) => ev.relates_to.clone(),
#[cfg(feature = "unstable-msc3245")]
Self::Voice(ev) => ev.relates_to.clone().map(Into::into),
#[cfg(feature = "unstable-msc3927")]
Self::Audio(ev) => ev.relates_to.clone().map(Into::into),
#[cfg(feature = "unstable-msc3488")]
Self::Location(ev) => ev.relates_to.clone().map(Into::into),
#[cfg(feature = "unstable-msc3551")]
Self::File(ev) => ev.relates_to.clone().map(Into::into),
#[cfg(feature = "unstable-msc3552")]
Self::Image(ev) => ev.relates_to.clone().map(Into::into),
#[cfg(feature = "unstable-msc3553")]
Self::Video(ev) => ev.relates_to.clone().map(Into::into),
#[cfg(feature = "unstable-msc3381")]
Self::PollResponse(PollResponseEventContent { relates_to, .. })
| Self::UnstablePollResponse(UnstablePollResponseEventContent { relates_to, .. })
| Self::PollEnd(PollEndEventContent { relates_to, .. })
| Self::UnstablePollEnd(UnstablePollEndEventContent { relates_to, .. }) => {
Some(encrypted::Relation::Reference(relates_to.clone()))
}
#[cfg(feature = "unstable-msc3489")]
Self::Beacon(BeaconEventContent { relates_to, .. }) => {
Some(encrypted::Relation::Reference(relates_to.clone()))
}
#[cfg(feature = "unstable-msc3381")]
Self::PollStart(_) | Self::UnstablePollStart(_) => None,
#[cfg(feature = "unstable-msc4075")]
Self::CallNotify(_) => None,
#[cfg(feature = "unstable-msc4075")]
Self::RtcNotification(ev) => ev.relates_to.clone().map(encrypted::Relation::Reference),
#[cfg(feature = "unstable-msc4310")]
Self::RtcDecline(ev) => Some(encrypted::Relation::Reference(ev.relates_to.clone())),
Self::CallSdpStreamMetadataChanged(_)
| Self::CallNegotiate(_)
| Self::CallReject(_)
| Self::CallSelectAnswer(_)
| Self::CallAnswer(_)
| Self::CallInvite(_)
| Self::CallHangup(_)
| Self::CallCandidates(_)
| Self::RoomRedaction(_)
| Self::Sticker(_)
| Self::_Custom { .. } => None,
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/forwarded_room_key.rs | crates/core/src/events/forwarded_room_key.rs | //! Types for the [`m.forwarded_room_key`] event.
//!
//! [`m.forwarded_room_key`]: https://spec.matrix.org/latest/client-server-api/#mforwarded_room_key
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{EventEncryptionAlgorithm, OwnedRoomId};
/// The content of an `m.forwarded_room_key` event.
///
/// To create an instance of this type.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.forwarded_room_key", kind = ToDevice)]
pub struct ToDeviceForwardedRoomKeyEventContent {
/// The encryption algorithm the key in this event is to be used with.
pub algorithm: EventEncryptionAlgorithm,
/// The room where the key is used.
pub room_id: OwnedRoomId,
/// The Curve25519 key of the device which initiated the session originally.
pub sender_key: String,
/// The ID of the session that the key is for.
pub session_id: String,
/// The key to be exchanged.
pub session_key: String,
/// The Ed25519 key of the device which initiated the session originally.
///
/// It is "claimed" because the receiving device has no way to tell that the
/// original room_key actually came from a device which owns the private
/// part of this key unless they have done device verification.
pub sender_claimed_ed25519_key: String,
/// Chain of Curve25519 keys.
///
/// It starts out empty, but each time the key is forwarded to another
/// device, the previous sender in the chain is added to the end of the
/// list. For example, if the key is forwarded from A to B to C, this
/// field is empty between A and B, and contains A's Curve25519 key
/// between B and C.
pub forwarding_curve25519_key_chain: Vec<String>,
/// Used to mark key if allowed for shared history.
///
/// Defaults to `false`.
#[cfg(feature = "unstable-msc3061")]
#[serde(
default,
rename = "org.matrix.msc3061.shared_history",
skip_serializing_if = "palpo_core::serde::is_default"
)]
pub shared_history: bool,
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/receipt.rs | crates/core/src/events/receipt.rs | //! Endpoints for event receipts.
//! `POST /_matrix/client/*/rooms/{room_id}/receipt/{receiptType}/{event_id}`
//!
//! Send a receipt event to a room.
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3roomsroomidreceiptreceipttypeeventid
use std::{
collections::{BTreeMap, btree_map},
ops::{Deref, DerefMut},
};
use salvo::prelude::*;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::macros::EventContent;
use crate::{
EventId, IdParseError, OwnedEventId, OwnedRoomId, OwnedUserId, PrivOwnedStr, UnixMillis,
UserId, serde::StringEnum,
};
/// The content of an `m.receipt` event.
///
/// A mapping of event ID to a collection of receipts for this event ID. The
/// event ID is the ID of the event being acknowledged and *not* an ID for the
/// receipt itself.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[allow(clippy::exhaustive_structs)]
#[palpo_event(type = "m.receipt", kind = EphemeralRoom)]
pub struct ReceiptEventContent(pub BTreeMap<OwnedEventId, Receipts>);
impl ReceiptEventContent {
/// Get the receipt for the given user ID with the given receipt type, if it
/// exists.
pub fn user_receipt(
&self,
user_id: &UserId,
receipt_type: ReceiptType,
) -> Option<(&EventId, &Receipt)> {
self.iter().find_map(|(event_id, receipts)| {
let receipt = receipts.get(&receipt_type)?.get(user_id)?;
Some((event_id.as_ref(), receipt))
})
}
}
impl Deref for ReceiptEventContent {
type Target = BTreeMap<OwnedEventId, Receipts>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for ReceiptEventContent {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl IntoIterator for ReceiptEventContent {
type Item = (OwnedEventId, Receipts);
type IntoIter = btree_map::IntoIter<OwnedEventId, Receipts>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl FromIterator<(OwnedEventId, Receipts)> for ReceiptEventContent {
fn from_iter<T>(iter: T) -> Self
where
T: IntoIterator<Item = (OwnedEventId, Receipts)>,
{
Self(BTreeMap::from_iter(iter))
}
}
/// A collection of receipts.
pub type Receipts = BTreeMap<ReceiptType, UserReceipts>;
/// A mapping of user ID to receipt.
///
/// The user ID is the entity who sent this receipt.
pub type UserReceipts = BTreeMap<OwnedUserId, Receipt>;
/// An acknowledgement of an event.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct Receipt {
/// The time when the receipt was sent.
#[serde(skip_serializing_if = "Option::is_none")]
#[salvo(schema(value_type = Option<u64>))]
pub ts: Option<UnixMillis>,
/// The thread this receipt applies to.
#[serde(
rename = "thread_id",
default,
skip_serializing_if = "crate::serde::is_default"
)]
pub thread: ReceiptThread,
}
impl Receipt {
/// Creates a new `Receipt` with the given timestamp.
///
/// To create an empty receipt instead, use [`Receipt::default`].
pub fn new(ts: UnixMillis) -> Self {
Self {
ts: Some(ts),
thread: ReceiptThread::Unthreaded,
}
}
}
/// The [thread a receipt applies to].
///
/// This type can hold an arbitrary string. To build this with a custom value,
/// convert it from an `Option<String>` with `::from()` / `.into()`.
/// [`ReceiptThread::Unthreaded`] can be constructed from `None`.
///
/// To check for values that are not available as a documented variant here, use
/// its string representation, obtained through [`.as_str()`](Self::as_str()).
///
/// [thread a receipt applies to]: https://spec.matrix.org/latest/client-server-api/#threaded-read-receipts
#[derive(ToSchema, Clone, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ReceiptThread {
/// The receipt applies to the timeline, regardless of threads.
///
/// Used by clients that are not aware of threads.
///
/// This is the default.
#[default]
Unthreaded,
/// The receipt applies to the main timeline.
///
/// Used for events that don't belong to a thread.
Main,
/// The receipt applies to a thread.
///
/// Used for events that belong to a thread with the given thread root.
Thread(OwnedEventId),
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(PrivOwnedStr),
}
impl ReceiptThread {
/// Get the string representation of this `ReceiptThread`.
///
/// [`ReceiptThread::Unthreaded`] returns `None`.
pub fn as_str(&self) -> Option<&str> {
match self {
Self::Unthreaded => None,
Self::Main => Some("main"),
Self::Thread(event_id) => Some(event_id.as_str()),
Self::_Custom(s) => Some(&s.0),
}
}
}
impl<T> TryFrom<Option<T>> for ReceiptThread
where
T: AsRef<str> + Into<Box<str>>,
{
type Error = IdParseError;
fn try_from(s: Option<T>) -> Result<Self, Self::Error> {
let res = match s {
None => Self::Unthreaded,
Some(s) => match s.as_ref() {
"main" => Self::Main,
s_ref if s_ref.starts_with('$') => Self::Thread(EventId::parse(s_ref)?),
_ => Self::_Custom(PrivOwnedStr(s.into())),
},
};
Ok(res)
}
}
impl Serialize for ReceiptThread {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_str().serialize(serializer)
}
}
impl<'de> Deserialize<'de> for ReceiptThread {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = palpo_core::serde::deserialize_cow_str(deserializer)?;
Self::try_from(Some(s)).map_err(serde::de::Error::custom)
}
}
/// The content for "m.receipt" Edu.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[serde(transparent)]
pub struct ReceiptContent(pub BTreeMap<OwnedRoomId, ReceiptMap>);
impl ReceiptContent {
/// Creates a new `ReceiptContent`.
pub fn new(receipts: BTreeMap<OwnedRoomId, ReceiptMap>) -> Self {
Self(receipts)
}
}
impl Deref for ReceiptContent {
type Target = BTreeMap<OwnedRoomId, ReceiptMap>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for ReceiptContent {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl IntoIterator for ReceiptContent {
type Item = (OwnedRoomId, ReceiptMap);
type IntoIter = btree_map::IntoIter<OwnedRoomId, ReceiptMap>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl FromIterator<(OwnedRoomId, ReceiptMap)> for ReceiptContent {
fn from_iter<T>(iter: T) -> Self
where
T: IntoIterator<Item = (OwnedRoomId, ReceiptMap)>,
{
Self(BTreeMap::from_iter(iter))
}
}
/// Mapping between user and `ReceiptData`.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct ReceiptMap {
/// Read receipts for users in the room.
#[serde(rename = "m.read")]
pub read: BTreeMap<OwnedUserId, ReceiptData>,
}
impl ReceiptMap {
/// Creates a new `ReceiptMap`.
pub fn new(read: BTreeMap<OwnedUserId, ReceiptData>) -> Self {
Self { read }
}
}
/// Metadata about the event that was last read and when.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct ReceiptData {
/// Metadata for the read receipt.
pub data: Receipt,
/// The extremity event ID the user has read up to.
pub event_ids: Vec<OwnedEventId>,
}
impl ReceiptData {
/// Creates a new `ReceiptData`.
pub fn new(data: Receipt, event_ids: Vec<OwnedEventId>) -> Self {
Self { data, event_ids }
}
}
// #[cfg(test)]
// mod tests {
// use crate::{owned_event_id, UnixMillis};
// use assert_matches2::assert_matches;
// use serde_json::{from_value as from_json_value, json, to_value as
// to_json_value};
// use super::{Receipt, ReceiptThread};
// #[test]
// fn serialize_receipt() {
// let mut receipt = Receipt::default();
// assert_eq!(to_json_value(receipt.clone()).unwrap(), json!({}));
// receipt.thread = ReceiptThread::Main;
// assert_eq!(to_json_value(receipt.clone()).unwrap(), json!({
// "thread_id": "main" }));
// receipt.thread =
// ReceiptThread::Thread(owned_event_id!("$abcdef76543")); assert_eq!
// (to_json_value(receipt).unwrap(), json!({ "thread_id": "$abcdef76543" }));
// let mut receipt =
// Receipt::new(UnixMillis(1_664_702_144_365_u64.try_into().unwrap()));
// assert_eq!(
// to_json_value(receipt.clone()).unwrap(),
// json!({ "ts": 1_664_702_144_365_u64 })
// );
// receipt.thread =
// ReceiptThread::try_from(Some("io.palpo.unknown")).unwrap();
// assert_eq!(
// to_json_value(receipt).unwrap(),
// json!({ "ts": 1_664_702_144_365_u64, "thread_id":
// "io.palpo.unknown" }) );
// }
// #[test]
// fn deserialize_receipt() {
// let receipt = from_json_value::<Receipt>(json!({})).unwrap();
// assert_eq!(receipt.ts, None);
// assert_eq!(receipt.thread, ReceiptThread::Unthreaded);
// let receipt = from_json_value::<Receipt>(json!({ "thread_id": "main"
// })).unwrap(); assert_eq!(receipt.ts, None);
// assert_eq!(receipt.thread, ReceiptThread::Main);
// let receipt = from_json_value::<Receipt>(json!({ "thread_id":
// "$abcdef76543" })).unwrap(); assert_eq!(receipt.ts, None);
// assert_matches!(receipt.thread, ReceiptThread::Thread(event_id));
// assert_eq!(event_id, "$abcdef76543");
// let receipt = from_json_value::<Receipt>(json!({ "ts":
// 1_664_702_144_365_u64 })).unwrap(); assert_eq!(
// receipt.ts.unwrap(),
// UnixMillis(1_664_702_144_365_u64.try_into().unwrap())
// );
// assert_eq!(receipt.thread, ReceiptThread::Unthreaded);
// let receipt =
// from_json_value::<Receipt>(json!({ "ts": 1_664_702_144_365_u64,
// "thread_id": "io.palpo.unknown" })) .unwrap();
// assert_eq!(
// receipt.ts.unwrap(),
// UnixMillis(1_664_702_144_365_u64.try_into().unwrap())
// );
// assert_matches!(&receipt.thread, ReceiptThread::_Custom(_));
// assert_eq!(receipt.thread.as_str().unwrap(), "io.palpo.unknown");
// }
// }
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// 1.0 =>
// "/_matrix/client/r0/rooms/:room_id/receipt/:receipt_type/:event_id",
// 1.1 =>
// "/_matrix/client/v3/rooms/:room_id/receipt/:receipt_type/:event_id", }
// };
#[derive(ToParameters, Deserialize, Debug)]
pub struct SendReceiptReqArgs {
/// The room in which to send the event.
#[salvo(parameter(parameter_in = Path))]
pub room_id: OwnedRoomId,
/// The type of receipt to send.
#[salvo(parameter(parameter_in = Path))]
pub receipt_type: ReceiptType,
/// The event ID to acknowledge up to.
#[salvo(parameter(parameter_in = Path))]
pub event_id: OwnedEventId,
}
/// Request type for the `create_receipt` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct CreateReceiptReqBody {
/// The thread this receipt applies to.
///
/// *Note* that this must be the default value if used with
/// [`ReceiptType::FullyRead`].
///
/// Defaults to [`ReceiptThread::Unthreaded`].
#[serde(
rename = "thread_id",
default,
skip_serializing_if = "crate::serde::is_default"
)]
pub thread: ReceiptThread,
}
/// The type of receipt.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[non_exhaustive]
pub enum ReceiptType {
/// A [public read receipt].
///
/// Indicates that the given event has been presented to the user.
///
/// This receipt is federated to other users.
///
/// [public read receipt]: https://spec.matrix.org/latest/client-server-api/#receipts
#[palpo_enum(rename = "m.read")]
Read,
/// A [private read receipt].
///
/// Indicates that the given event has been presented to the user.
///
/// This read receipt is not federated so only the user and their homeserver
/// are aware of it.
///
/// [private read receipt]: https://spec.matrix.org/latest/client-server-api/#private-read-receipts
#[palpo_enum(rename = "m.read.private")]
ReadPrivate,
/// A [fully read marker].
///
/// Indicates that the given event has been read by the user.
///
/// This is actually not a receipt, but a piece of room account data. It is
/// provided here for convenience.
///
/// [fully read marker]: https://spec.matrix.org/latest/client-server-api/#fully-read-markers
#[palpo_enum(rename = "m.fully_read")]
FullyRead,
#[doc(hidden)]
#[salvo(schema(value_type = String))]
_Custom(PrivOwnedStr),
}
pub fn combine_receipt_event_contents(receipts: Vec<ReceiptEventContent>) -> ReceiptEventContent {
let mut combined = ReceiptEventContent(BTreeMap::new());
for receipt in receipts {
for (event_id, receipts) in receipt.0 {
let type_map = combined.0.entry(event_id).or_default();
for receipt in receipts {
type_map.entry(receipt.0).or_default().extend(receipt.1);
}
}
}
combined
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/file.rs | crates/core/src/events/file.rs | //! Types for extensible file message events ([MSC3551]).
//!
//! [MSC3551]: https://github.com/matrix-org/matrix-spec-proposals/pull/3551
use std::collections::BTreeMap;
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use super::{
message::TextContentBlock,
room::{EncryptedFile, JsonWebKey, message::Relation},
};
use crate::{OwnedMxcUri, serde::Base64};
/// The payload for an extensible file message.
///
/// This is the new primary type introduced in [MSC3551] and should only be sent
/// in rooms with a version that supports it. See the documentation of the
/// [`message`] module for more information.
///
/// [MSC3551]: https://github.com/matrix-org/matrix-spec-proposals/pull/3551
/// [`message`]: super::message
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize, EventContent)]
#[palpo_event(type = "org.matrix.msc1767.file", kind = MessageLike, without_relation)]
pub struct FileEventContent {
/// The text representation of the message.
#[serde(rename = "org.matrix.msc1767.text")]
pub text: TextContentBlock,
/// The file content of the message.
#[serde(rename = "org.matrix.msc1767.file")]
pub file: FileContentBlock,
/// The caption of the message, if any.
#[serde(
rename = "org.matrix.msc1767.caption",
skip_serializing_if = "Option::is_none"
)]
pub caption: Option<CaptionContentBlock>,
/// Whether this message is automated.
#[cfg(feature = "unstable-msc3955")]
#[serde(
default,
skip_serializing_if = "palpo_core::serde::is_default",
rename = "org.matrix.msc1767.automated"
)]
pub automated: bool,
/// Information about related messages.
#[serde(
flatten,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::events::room::message::relation_serde::deserialize_relation"
)]
pub relates_to: Option<Relation<FileEventContentWithoutRelation>>,
}
impl FileEventContent {
/// Creates a new non-encrypted `FileEventContent` with the given fallback
/// representation, url and file info.
pub fn plain(text: TextContentBlock, url: OwnedMxcUri, name: String) -> Self {
Self {
text,
file: FileContentBlock::plain(url, name),
caption: None,
#[cfg(feature = "unstable-msc3955")]
automated: false,
relates_to: None,
}
}
/// Creates a new non-encrypted `FileEventContent` with the given plain text
/// fallback representation, url and name.
pub fn plain_with_plain_text(
plain_text: impl Into<String>,
url: OwnedMxcUri,
name: String,
) -> Self {
Self {
text: TextContentBlock::plain(plain_text),
file: FileContentBlock::plain(url, name),
caption: None,
#[cfg(feature = "unstable-msc3955")]
automated: false,
relates_to: None,
}
}
/// Creates a new encrypted `FileEventContent` with the given fallback
/// representation, url, name and encryption info.
pub fn encrypted(
text: TextContentBlock,
url: OwnedMxcUri,
name: String,
encryption_info: EncryptedContent,
) -> Self {
Self {
text,
file: FileContentBlock::encrypted(url, name, encryption_info),
caption: None,
#[cfg(feature = "unstable-msc3955")]
automated: false,
relates_to: None,
}
}
/// Creates a new encrypted `FileEventContent` with the given plain text
/// fallback representation, url, name and encryption info.
pub fn encrypted_with_plain_text(
plain_text: impl Into<String>,
url: OwnedMxcUri,
name: String,
encryption_info: EncryptedContent,
) -> Self {
Self {
text: TextContentBlock::plain(plain_text),
file: FileContentBlock::encrypted(url, name, encryption_info),
caption: None,
#[cfg(feature = "unstable-msc3955")]
automated: false,
relates_to: None,
}
}
}
/// A block for file content.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct FileContentBlock {
/// The URL to the file.
pub url: OwnedMxcUri,
/// The original filename of the uploaded file.
pub name: String,
/// The mimetype of the file, e.g. "application/msword".
#[serde(skip_serializing_if = "Option::is_none")]
pub mimetype: Option<String>,
/// The size of the file in bytes.
#[serde(skip_serializing_if = "Option::is_none")]
pub size: Option<u64>,
/// Information on the encrypted file.
///
/// Required if the file is encrypted.
#[serde(flatten, skip_serializing_if = "Option::is_none")]
pub encryption_info: Option<Box<EncryptedContent>>,
}
impl FileContentBlock {
/// Creates a new non-encrypted `FileContentBlock` with the given url and
/// name.
pub fn plain(url: OwnedMxcUri, name: String) -> Self {
Self {
url,
name,
mimetype: None,
size: None,
encryption_info: None,
}
}
/// Creates a new encrypted `FileContentBlock` with the given url, name and
/// encryption info.
pub fn encrypted(url: OwnedMxcUri, name: String, encryption_info: EncryptedContent) -> Self {
Self {
url,
name,
mimetype: None,
size: None,
encryption_info: Some(Box::new(encryption_info)),
}
}
/// Whether the file is encrypted.
pub fn is_encrypted(&self) -> bool {
self.encryption_info.is_some()
}
}
/// The encryption info of a file sent to a room with end-to-end encryption
/// enabled.
///
/// To create an instance of this type.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct EncryptedContent {
/// A [JSON Web Key](https://tools.ietf.org/html/rfc7517#appendix-A.3) object.
pub key: JsonWebKey,
/// The 128-bit unique counter block used by AES-CTR, encoded as unpadded
/// base64.
pub iv: Base64,
/// A map from an algorithm name to a hash of the ciphertext, encoded as
/// unpadded base64.
///
/// Clients should support the SHA-256 hash, which uses the key sha256.
pub hashes: BTreeMap<String, Base64>,
/// Version of the encrypted attachments protocol.
///
/// Must be `v2`.
pub v: String,
}
impl From<&EncryptedFile> for EncryptedContent {
fn from(encrypted: &EncryptedFile) -> Self {
let EncryptedFile {
key, iv, hashes, v, ..
} = encrypted;
Self {
key: key.to_owned(),
iv: iv.to_owned(),
hashes: hashes.to_owned(),
v: v.to_owned(),
}
}
}
/// A block for caption content.
///
/// A caption is usually a text message that should be displayed next to some
/// media content.
///
/// To construct a `CaptionContentBlock` with a custom [`TextContentBlock`],
/// convert it with `CaptionContentBlock::from()` / `.into()`.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct CaptionContentBlock {
/// The text message of the caption.
#[serde(rename = "org.matrix.msc1767.text")]
pub text: TextContentBlock,
}
impl CaptionContentBlock {
/// A convenience constructor to create a plain text caption content block.
pub fn plain(body: impl Into<String>) -> Self {
Self {
text: TextContentBlock::plain(body),
}
}
/// A convenience constructor to create an HTML caption content block.
pub fn html(body: impl Into<String>, html_body: impl Into<String>) -> Self {
Self {
text: TextContentBlock::html(body, html_body),
}
}
/// A convenience constructor to create a caption content block from
/// Markdown.
///
/// The content includes an HTML message if some Markdown formatting was
/// detected, otherwise only a plain text message is included.
#[cfg(feature = "markdown")]
pub fn markdown(body: impl AsRef<str> + Into<String>) -> Self {
Self {
text: TextContentBlock::markdown(body),
}
}
}
impl From<TextContentBlock> for CaptionContentBlock {
fn from(text: TextContentBlock) -> Self {
Self { text }
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room_key_request.rs | crates/core/src/events/room_key_request.rs | //! Types for the [`m.room_key_request`] event.
//!
//! [`m.room_key_request`]: https://spec.matrix.org/latest/client-server-api/#mroom_key_request
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{
EventEncryptionAlgorithm, OwnedDeviceId, OwnedRoomId, OwnedTransactionId, PrivOwnedStr,
serde::StringEnum,
};
/// The content of an `m.room_key_request` event.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.room_key_request", kind = ToDevice)]
pub struct ToDeviceRoomKeyRequestEventContent {
/// Whether this is a new key request or a cancellation of a previous
/// request.
pub action: Action,
/// Information about the requested key.
///
/// Required if action is `request`.
pub body: Option<RequestedKeyInfo>,
/// ID of the device requesting the key.
pub requesting_device_id: OwnedDeviceId,
/// A random string uniquely identifying the request for a key.
///
/// If the key is requested multiple times, it should be reused. It should
/// also reused in order to cancel a request.
pub request_id: OwnedTransactionId,
}
impl ToDeviceRoomKeyRequestEventContent {
/// Creates a new `ToDeviceRoomKeyRequestEventContent` with the given
/// action, boyd, device ID and request ID.
pub fn new(
action: Action,
body: Option<RequestedKeyInfo>,
requesting_device_id: OwnedDeviceId,
request_id: OwnedTransactionId,
) -> Self {
Self {
action,
body,
requesting_device_id,
request_id,
}
}
}
/// A new key request or a cancellation of a previous request.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[palpo_enum(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Action {
/// Request a key.
Request,
/// Cancel a request for a key.
#[palpo_enum(rename = "request_cancellation")]
CancelRequest,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
/// Information about a requested key.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct RequestedKeyInfo {
/// The encryption algorithm the requested key in this event is to be used
/// with.
pub algorithm: EventEncryptionAlgorithm,
/// The room where the key is used.
pub room_id: OwnedRoomId,
/// The ID of the session that the key is for.
pub session_id: String,
}
impl RequestedKeyInfo {
/// Creates a new `RequestedKeyInfo` with the given algorithm, room ID,
/// sender key and session ID.
pub fn new(
algorithm: EventEncryptionAlgorithm,
room_id: OwnedRoomId,
session_id: String,
) -> Self {
Self {
algorithm,
room_id,
session_id,
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/secret.rs | crates/core/src/events/secret.rs | //! Module for events in the `m.secret` namespace.
pub mod request;
pub mod send;
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/ignored_user_list.rs | crates/core/src/events/ignored_user_list.rs | //! Types for the [`m.ignored_user_list`] event.
//!
//! [`m.ignored_user_list`]: https://spec.matrix.org/latest/client-server-api/#mignored_user_list
use std::collections::BTreeMap;
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::OwnedUserId;
/// The content of an `m.ignored_user_list` event.
///
/// A list of users to ignore.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize, EventContent)]
#[palpo_event(type = "m.ignored_user_list", kind = GlobalAccountData)]
pub struct IgnoredUserListEventContent {
/// A map of users to ignore.
///
/// As [`IgnoredUser`] is currently empty, only the user IDs are useful and
/// can be accessed with the `.keys()` and `into_keys()` iterators.
pub ignored_users: BTreeMap<OwnedUserId, IgnoredUser>,
}
impl IgnoredUserListEventContent {
/// Creates a new `IgnoredUserListEventContent` from the given map of
/// ignored user.
pub fn new(ignored_users: BTreeMap<OwnedUserId, IgnoredUser>) -> Self {
Self { ignored_users }
}
/// Creates a new `IgnoredUserListEventContent` from the given list of
/// users.
pub fn users(ignored_users: impl IntoIterator<Item = OwnedUserId>) -> Self {
Self::new(
ignored_users
.into_iter()
.map(|id| (id, IgnoredUser {}))
.collect(),
)
}
}
/// Details about an ignored user.
///
/// This is currently empty.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct IgnoredUser {}
impl IgnoredUser {
/// Creates an empty `IgnoredUser`.
pub fn new() -> Self {
Self::default()
}
}
// #[cfg(test)]
// mod tests {
// use crate::{owned_user_id, user_id};
// use assert_matches2::assert_matches;
// use serde_json::{from_value as from_json_value, json, to_value as
// to_json_value};
// use super::IgnoredUserListEventContent;
// use crate::AnyGlobalAccountDataEvent;
// #[test]
// fn serialization() {
// let ignored_user_list =
// IgnoredUserListEventContent::users(vec![owned_user_id!("@carl:example.com"
// )]);
// let json = json!({
// "ignored_users": {
// "@carl:example.com": {}
// },
// });
// assert_eq!(to_json_value(ignored_user_list).unwrap(), json);
// }
// #[test]
// fn deserialization() {
// let json = json!({
// "content": {
// "ignored_users": {
// "@carl:example.com": {}
// }
// },
// "type": "m.ignored_user_list"
// });
// assert_matches!(
// from_json_value::<AnyGlobalAccountDataEvent>(json),
// Ok(AnyGlobalAccountDataEvent::IgnoredUserList(ev))
// );
// assert_eq!(
// ev.content.ignored_users.keys().collect::<Vec<_>>(),
// vec![user_id!("@carl:example.com")]
// );
// }
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/media_preview_config.rs | crates/core/src/events/media_preview_config.rs | //! Types for the [`m.media_preview_config`] event.
//!
//! [`m.media_preview_config`]: https://github.com/matrix-org/matrix-spec-proposals/pull/4278
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::macros::StringEnum;
use crate::serde::JsonCastable;
use crate::{PrivOwnedStr, macros::EventContent};
/// The content of an `m.media_preview_config` event.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize, EventContent)]
#[palpo_event(type = "m.media_preview_config", kind = GlobalAccountData + RoomAccountData)]
pub struct MediaPreviewConfigEventContent {
/// The media previews configuration.
#[serde(skip_serializing_if = "Option::is_none")]
pub media_previews: Option<MediaPreviews>,
/// The invite avatars configuration.
#[serde(skip_serializing_if = "Option::is_none")]
pub invite_avatars: Option<InviteAvatars>,
}
impl JsonCastable<UnstableMediaPreviewConfigEventContent> for MediaPreviewConfigEventContent {}
/// The content of an `io.element.msc4278.media_preview_config` event,
/// the unstable version of `m.media_preview_config` in global account data.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize, EventContent)]
#[palpo_event(type = "io.element.msc4278.media_preview_config", kind = GlobalAccountData + RoomAccountData)]
#[serde(transparent)]
pub struct UnstableMediaPreviewConfigEventContent(pub MediaPreviewConfigEventContent);
impl JsonCastable<MediaPreviewConfigEventContent> for UnstableMediaPreviewConfigEventContent {}
/// The configuration that handles if media previews should be shown in the timeline.
#[derive(ToSchema, Clone, StringEnum, Default)]
#[palpo_enum(rename_all = "lowercase")]
#[non_exhaustive]
pub enum MediaPreviews {
/// Media previews should be hidden.
Off,
/// Media previews should be only shown in private rooms.
Private,
/// Media previews should always be shown.
#[default]
On,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
/// The configuration to handle if avatars should be shown in invites.
#[derive(ToSchema, StringEnum, Clone, Default)]
#[palpo_enum(rename_all = "lowercase")]
#[non_exhaustive]
pub enum InviteAvatars {
/// Avatars in invites should be hidden.
Off,
/// Avatars in invites should be shown.
#[default]
On,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
impl MediaPreviewConfigEventContent {
/// Create a new empty [`MediaPreviewConfigEventContent`].
pub fn new() -> Self {
Self::default()
}
/// Set the value of the setting for the media previews.
pub fn media_previews(mut self, media_previews: Option<MediaPreviews>) -> Self {
self.media_previews = media_previews;
self
}
/// Set the value of the setting for the media previews.
pub fn invite_avatars(mut self, invite_avatars: Option<InviteAvatars>) -> Self {
self.invite_avatars = invite_avatars;
self
}
/// Merge the config from the global account data with the config from the room account data.
///
/// The values that are set in the room account data take precedence over the values in the
/// global account data.
pub fn merge_global_and_room_config(global_config: Self, room_config: Self) -> Self {
Self {
media_previews: room_config.media_previews.or(global_config.media_previews),
invite_avatars: room_config.invite_avatars.or(global_config.invite_avatars),
}
}
}
impl std::ops::Deref for UnstableMediaPreviewConfigEventContent {
type Target = MediaPreviewConfigEventContent;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<MediaPreviewConfigEventContent> for UnstableMediaPreviewConfigEventContent {
fn from(value: MediaPreviewConfigEventContent) -> Self {
Self(value)
}
}
impl From<UnstableMediaPreviewConfigEventContent> for MediaPreviewConfigEventContent {
fn from(value: UnstableMediaPreviewConfigEventContent) -> Self {
value.0
}
}
#[cfg(all(test, feature = "unstable-msc4278"))]
mod tests {
use assert_matches2::assert_matches;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::{MediaPreviewConfigEventContent, UnstableMediaPreviewConfigEventContent};
use crate::events::{
AnyGlobalAccountDataEvent, GlobalAccountDataEvent,
media_preview_config::{InviteAvatars, MediaPreviews},
};
#[test]
fn deserialize() {
let raw_unstable_media_preview_config = json!({
"type": "io.element.msc4278.media_preview_config",
"content": {
"media_previews": "private",
"invite_avatars": "off",
},
});
let unstable_media_preview_config_data =
from_json_value::<AnyGlobalAccountDataEvent>(raw_unstable_media_preview_config)
.unwrap();
assert_matches!(
unstable_media_preview_config_data,
AnyGlobalAccountDataEvent::UnstableMediaPreviewConfig(unstable_media_preview_config)
);
assert_eq!(
unstable_media_preview_config.content.media_previews,
Some(MediaPreviews::Private)
);
assert_eq!(
unstable_media_preview_config.content.invite_avatars,
Some(InviteAvatars::Off)
);
let raw_media_preview_config = json!({
"type": "m.media_preview_config",
"content": {
"media_previews": "on",
"invite_avatars": "on",
},
});
let media_preview_config_data =
from_json_value::<AnyGlobalAccountDataEvent>(raw_media_preview_config).unwrap();
assert_matches!(
media_preview_config_data,
AnyGlobalAccountDataEvent::MediaPreviewConfig(media_preview_config)
);
assert_eq!(
media_preview_config.content.media_previews,
Some(MediaPreviews::On)
);
assert_eq!(
media_preview_config.content.invite_avatars,
Some(InviteAvatars::On)
);
}
#[test]
fn serialize() {
let unstable_media_preview_config = UnstableMediaPreviewConfigEventContent(
MediaPreviewConfigEventContent::new()
.media_previews(Some(MediaPreviews::Off))
.invite_avatars(Some(InviteAvatars::On)),
);
let unstable_media_preview_config_account_data = GlobalAccountDataEvent {
content: unstable_media_preview_config,
};
assert_eq!(
to_json_value(unstable_media_preview_config_account_data).unwrap(),
json!({
"type": "io.element.msc4278.media_preview_config",
"content": {
"media_previews": "off",
"invite_avatars": "on",
},
})
);
let media_preview_config = MediaPreviewConfigEventContent::new()
.media_previews(Some(MediaPreviews::On))
.invite_avatars(Some(InviteAvatars::Off));
let media_preview_config_account_data = GlobalAccountDataEvent {
content: media_preview_config,
};
assert_eq!(
to_json_value(media_preview_config_account_data).unwrap(),
json!({
"type": "m.media_preview_config",
"content": {
"media_previews": "on",
"invite_avatars": "off",
},
})
);
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/invite_permission_config.rs | crates/core/src/events/invite_permission_config.rs | //! Types for the [`m.invite_permission_config`] account data event.
//!
//! [`m.invite_permission_config`]: https://github.com/matrix-org/matrix-spec-proposals/pull/4380
use serde::{Deserialize, Serialize};
use salvo::oapi::ToSchema;
use crate::macros::EventContent;
/// The content of an `m.invite_permission_config` event.
///
/// A single property: `block_all`.
#[derive(ToSchema,Clone, Debug, Default, Deserialize, Serialize, EventContent)]
#[palpo_event(
kind = GlobalAccountData,
type = "org.matrix.msc4380.invite_permission_config",
alias = "m.invite_permission_config",
)]
pub struct InvitePermissionConfigEventContent {
/// When set to true, indicates that the user does not wish to receive *any* room invites, and
/// they should be blocked.
#[serde(default)]
#[serde(deserialize_with = "crate::serde::default_on_error")]
pub block_all: bool,
}
impl InvitePermissionConfigEventContent {
/// Creates a new `InvitePermissionConfigEventContent` from the desired boolean state.
pub fn new(block_all: bool) -> Self {
Self { block_all }
}
}
// #[cfg(test)]
// mod tests {
// use assert_matches2::assert_matches;
// use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
// use super::InvitePermissionConfigEventContent;
// use crate::AnyGlobalAccountDataEvent;
// #[test]
// fn serialization() {
// let invite_permission_config = InvitePermissionConfigEventContent::new(true);
// let json = json!({
// "block_all": true
// });
// assert_eq!(to_json_value(invite_permission_config).unwrap(), json);
// }
// #[test]
// fn deserialization() {
// let json = json!({
// "content": {
// "block_all": true
// },
// "type": "m.invite_permission_config"
// });
// assert_matches!(
// from_json_value::<AnyGlobalAccountDataEvent>(json),
// Ok(AnyGlobalAccountDataEvent::InvitePermissionConfig(ev))
// );
// assert!(ev.content.block_all);
// }
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/dummy.rs | crates/core/src/events/dummy.rs | //! Types for the [`m.dummy`] event.
//!
//! [`m.dummy`]: https://spec.matrix.org/latest/client-server-api/#mdummy
use std::fmt;
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{
de::{self, Deserialize, Deserializer},
ser::{Serialize, SerializeStruct as _, Serializer},
};
/// The content of an `m.dummy` event.
///
/// This event is used to indicate new Olm sessions for end-to-end encryption.
///
/// Typically it is encrypted as an `m.room.encrypted` event, then sent as a
/// to-device event.
///
/// The event does not have any content associated with it. The sending client
/// is expected to send a key share request shortly after this message, causing
/// the receiving client to process this `m.dummy` event as the most recent
/// event and using the keyshare request to set up the session. The keyshare
/// request and `m.dummy` combination should result in the original sending
/// client receiving keys over the newly established session.
#[derive(ToSchema, Clone, Debug, Default, EventContent)]
#[allow(clippy::exhaustive_structs)]
#[palpo_event(type = "m.dummy", kind = ToDevice)]
pub struct ToDeviceDummyEventContent;
impl ToDeviceDummyEventContent {
/// Create a new `ToDeviceDummyEventContent`.
pub fn new() -> Self {
Self
}
}
impl<'de> Deserialize<'de> for ToDeviceDummyEventContent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct Visitor;
impl<'de> de::Visitor<'de> for Visitor {
type Value = ToDeviceDummyEventContent;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a struct")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: de::MapAccess<'de>,
{
while map
.next_entry::<de::IgnoredAny, de::IgnoredAny>()?
.is_some()
{}
Ok(ToDeviceDummyEventContent)
}
}
deserializer.deserialize_struct("ToDeviceDummyEventContent", &[], Visitor)
}
}
impl Serialize for ToDeviceDummyEventContent {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer
.serialize_struct("ToDeviceDummyEventContent", 0)?
.end()
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/fully_read.rs | crates/core/src/events/fully_read.rs | //! Types for the [`m.fully_read`] event.
//!
//! [`m.fully_read`]: https://spec.matrix.org/latest/client-server-api/#mfully_read
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::OwnedEventId;
/// The content of an `m.fully_read` event.
///
/// The current location of the user's read marker in a room.
///
/// This event appears in the user's room account data for the room the marker
/// is applicable for.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.fully_read", kind = RoomAccountData)]
pub struct FullyReadEventContent {
/// The event the user's read marker is located at in the room.
pub event_id: OwnedEventId,
}
impl FullyReadEventContent {
/// Creates a new `FullyReadEventContent` with the given event ID.
pub fn new(event_id: OwnedEventId) -> Self {
Self { event_id }
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/secret_storage.rs | crates/core/src/events/secret_storage.rs | //! Module for events in the `m.secret_storage` namespace.
pub mod default_key;
pub mod key;
pub mod secret;
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/typing.rs | crates/core/src/events/typing.rs | //! Types for the [`m.typing`] event.
//!
//! [`m.typing`]: https://spec.matrix.org/latest/client-server-api/#mtyping
use crate::macros::EventContent;
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{OwnedRoomId, OwnedUserId};
/// The content of an `m.typing` event.
///
/// Informs the client who is currently typing in a given room.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize, EventContent)]
#[palpo_event(type = "m.typing", kind = EphemeralRoom)]
pub struct TypingEventContent {
/// The list of user IDs typing in this room, if any.
pub user_ids: Vec<OwnedUserId>,
}
impl TypingEventContent {
/// Creates a new `TypingEventContent` with the given user IDs.
pub fn new(user_ids: Vec<OwnedUserId>) -> Self {
Self { user_ids }
}
}
/// The content for "m.typing" Edu.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct TypingContent {
/// The room where the user's typing status has been updated.
pub room_id: OwnedRoomId,
/// The user ID that has had their typing status changed.
pub user_id: OwnedUserId,
/// Whether the user is typing in the room or not.
pub typing: bool,
}
impl TypingContent {
/// Creates a new `TypingContent`.
pub fn new(room_id: OwnedRoomId, user_id: OwnedUserId, typing: bool) -> Self {
Self {
room_id,
user_id,
typing,
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/location.rs | crates/core/src/events/location.rs | //! Types for extensible location message events ([MSC3488]).
//!
//! [MSC3488]: https://github.com/matrix-org/matrix-spec-proposals/pull/3488
use crate::macros::{EventContent, StringEnum};
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use super::{message::TextContentBlock, room::message::Relation};
use crate::{PrivOwnedStr, UnixMillis};
/// The payload for an extensible location message.
///
/// This is the new primary type introduced in [MSC3488] and should only be sent
/// in rooms with a version that supports it. See the documentation of the
/// [`message`] module for more information.
///
/// [MSC3488]: https://github.com/matrix-org/matrix-spec-proposals/pull/3488
/// [`message`]: super::message
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize, EventContent)]
#[palpo_event(type = "m.location", kind = MessageLike, without_relation)]
pub struct LocationEventContent {
/// The text representation of the message.
#[serde(rename = "org.matrix.msc1767.text")]
pub text: TextContentBlock,
/// The location info of the message.
#[serde(rename = "m.location")]
pub location: LocationContent,
/// The asset this message refers to.
#[serde(
default,
rename = "m.asset",
skip_serializing_if = "palpo_core::serde::is_default"
)]
pub asset: AssetContent,
/// The timestamp this message refers to.
#[serde(rename = "m.ts", skip_serializing_if = "Option::is_none")]
pub ts: Option<UnixMillis>,
/// Whether this message is automated.
#[serde(
default,
skip_serializing_if = "palpo_core::serde::is_default",
rename = "org.matrix.msc1767.automated"
)]
#[cfg(feature = "unstable-msc3955")]
pub automated: bool,
/// Information about related messages.
#[serde(
flatten,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::events::room::message::relation_serde::deserialize_relation"
)]
pub relates_to: Option<Relation<LocationEventContentWithoutRelation>>,
}
impl LocationEventContent {
/// Creates a new `LocationEventContent` with the given fallback
/// representation and location.
pub fn new(text: TextContentBlock, location: LocationContent) -> Self {
Self {
text,
location,
asset: Default::default(),
ts: None,
#[cfg(feature = "unstable-msc3955")]
automated: false,
relates_to: None,
}
}
/// Creates a new `LocationEventContent` with the given plain text fallback
/// representation and location.
pub fn with_plain_text(plain_text: impl Into<String>, location: LocationContent) -> Self {
Self {
text: TextContentBlock::plain(plain_text),
location,
asset: Default::default(),
ts: None,
#[cfg(feature = "unstable-msc3955")]
automated: false,
relates_to: None,
}
}
}
/// Location content.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct LocationContent {
/// A `geo:` URI representing the location.
///
/// See [RFC 5870](https://datatracker.ietf.org/doc/html/rfc5870) for more details.
pub uri: String,
/// The description of the location.
///
/// It should be used to label the location on a map.
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// A zoom level to specify the displayed area size.
#[serde(skip_serializing_if = "Option::is_none")]
pub zoom_level: Option<ZoomLevel>,
}
impl LocationContent {
/// Creates a new `LocationContent` with the given geo URI.
pub fn new(uri: String) -> Self {
Self {
uri,
description: None,
zoom_level: None,
}
}
}
/// An error encountered when trying to convert to a `ZoomLevel`.
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum ZoomLevelError {
/// The value is higher than [`ZoomLevel::MAX`].
#[error("value too high")]
TooHigh,
}
/// A zoom level.
///
/// This is an integer between 0 and 20 as defined in the [OpenStreetMap Wiki].
///
/// [OpenStreetMap Wiki]: https://wiki.openstreetmap.org/wiki/Zoom_levels
#[derive(ToSchema, Clone, Debug, Serialize)]
pub struct ZoomLevel(u64);
impl ZoomLevel {
/// The smallest value of a `ZoomLevel`, 0.
pub const MIN: u8 = 0;
/// The largest value of a `ZoomLevel`, 20.
pub const MAX: u8 = 20;
/// Creates a new `ZoomLevel` with the given value.
pub fn new(value: u8) -> Option<Self> {
if value > Self::MAX {
None
} else {
Some(Self(value.into()))
}
}
/// The value of this `ZoomLevel`.
pub fn get(&self) -> u64 {
self.0
}
}
impl TryFrom<u8> for ZoomLevel {
type Error = ZoomLevelError;
fn try_from(value: u8) -> Result<Self, Self::Error> {
Self::new(value).ok_or(ZoomLevelError::TooHigh)
}
}
impl<'de> Deserialize<'de> for ZoomLevel {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let uint = u64::deserialize(deserializer)?;
if uint > Self::MAX as u64 {
Err(serde::de::Error::custom(ZoomLevelError::TooHigh))
} else {
Ok(Self(uint))
}
}
}
/// Asset content.
#[derive(ToSchema, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssetContent {
/// The type of asset being referred to.
#[serde(rename = "type")]
pub type_: AssetType,
}
impl AssetContent {
/// Creates a new default `AssetContent`.
pub fn new() -> Self {
Self::default()
}
}
/// The type of an asset.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, Default, StringEnum)]
#[palpo_enum(rename_all(prefix = "m.", rule = "snake_case"))]
#[non_exhaustive]
pub enum AssetType {
/// The asset is the sender of the event.
#[default]
#[palpo_enum(rename = "m.self")]
Self_,
/// The asset is a location pinned by the sender.
Pin,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/kinds.rs | crates/core/src/events/kinds.rs | #![allow(clippy::exhaustive_structs)]
use crate::macros::Event;
use as_variant::as_variant;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Deserializer, Serialize, ser::SerializeStruct};
use super::{
AnyInitialStateEvent, EmptyStateKey, EphemeralRoomEventContent, EventContentFromType,
GlobalAccountDataEventContent, MessageLikeEventContent, MessageLikeEventType,
MessageLikeUnsigned, PossiblyRedactedStateEventContent, RedactContent,
RedactedMessageLikeEventContent, RedactedStateEventContent, RedactedUnsigned,
RedactionDeHelper, RoomAccountDataEventContent, StateEventContent, StateEventType,
StaticStateEventContent, ToDeviceEventContent,
};
use crate::{
EventId, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId, UnixMillis, UserId,
events::{AnyGlobalAccountDataEvent, AnyRoomAccountDataEvent, receipt::ReceiptEventContent},
room_version_rules::RedactionRules,
serde::{RawJson, RawJsonValue, from_raw_json_value},
};
/// Enum allowing to use the same structures for global and room account data
#[derive(Debug)]
#[allow(clippy::exhaustive_enums)]
pub enum AnyAccountDataEvent {
/// An event for a specific room
Room(AnyRoomAccountDataEvent),
/// An event for the whole account
Global(AnyGlobalAccountDataEvent),
}
/// Enum allowing to use the same structures for global and room account data
#[derive(Debug)]
#[allow(clippy::exhaustive_enums)]
pub enum AnyRawAccountDataEvent {
/// An event for a specific room
Room(RawJson<AnyRoomAccountDataEvent>),
/// An event for the whole account
Global(RawJson<AnyGlobalAccountDataEvent>),
}
/// A global account data event.
#[derive(ToSchema, Clone, Debug, Event)]
pub struct GlobalAccountDataEvent<C: GlobalAccountDataEventContent> {
/// Data specific to the event type.
pub content: C,
}
impl<C: GlobalAccountDataEventContent> Serialize for GlobalAccountDataEvent<C> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut state = serializer.serialize_struct("GlobalAccountDataEvent", 2)?;
state.serialize_field("type", &self.content.event_type())?;
state.serialize_field("content", &self.content)?;
state.end()
}
}
/// A room account data event.
#[derive(ToSchema, Clone, Debug, Event)]
pub struct RoomAccountDataEvent<C: RoomAccountDataEventContent> {
/// Data specific to the event type.
pub content: C,
}
impl<C: RoomAccountDataEventContent> Serialize for RoomAccountDataEvent<C> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut state = serializer.serialize_struct("RoomAccountDataEvent", 2)?;
state.serialize_field("type", &self.content.event_type())?;
state.serialize_field("content", &self.content)?;
state.end()
}
}
/// An ephemeral room event.
#[derive(ToSchema, Clone, Debug, Event)]
pub struct EphemeralRoomEvent<C: EphemeralRoomEventContent> {
/// Data specific to the event type.
pub content: C,
/// The ID of the room associated with this event.
pub room_id: OwnedRoomId,
}
impl<C: EphemeralRoomEventContent> Serialize for EphemeralRoomEvent<C> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut state = serializer.serialize_struct("EphemeralRoomEvent", 2)?;
state.serialize_field("type", &self.content.event_type())?;
state.serialize_field("content", &self.content)?;
state.serialize_field("room_id", &self.room_id)?;
state.end()
}
}
/// An ephemeral room event without a `room_id`.
#[derive(ToSchema, Clone, Debug, Event)]
pub struct SyncEphemeralRoomEvent<C: EphemeralRoomEventContent> {
/// Data specific to the event type.
pub content: C,
}
impl<C: EphemeralRoomEventContent> Serialize for SyncEphemeralRoomEvent<C> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut state = serializer.serialize_struct("SyncEphemeralRoomEvent", 2)?;
state.serialize_field("type", &self.content.event_type())?;
state.serialize_field("content", &self.content)?;
state.end()
}
}
impl SyncEphemeralRoomEvent<ReceiptEventContent> {
pub fn is_empty(&self) -> bool {
self.content.is_empty()
}
}
/// An unredacted message-like event.
///
/// `OriginalMessageLikeEvent` implements the comparison traits using only the
/// `event_id` field, a sorted list would be sorted lexicographically based on
/// the event's `EventId`.
#[derive(ToSchema, Clone, Debug, Event)]
pub struct OriginalMessageLikeEvent<C: MessageLikeEventContent> {
/// Data specific to the event type.
pub content: C,
/// The globally unique event identifier for the user who sent the event.
pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event.
pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was
/// sent.
pub origin_server_ts: UnixMillis,
/// The ID of the room associated with this event.
pub room_id: OwnedRoomId,
/// Additional key-value pairs not signed by the homeserver.
/// TODO???
#[salvo(schema(value_type = Object, additional_properties = true))]
pub unsigned: MessageLikeUnsigned<C>,
}
/// An unredacted message-like event without a `room_id`.
///
/// `OriginalSyncMessageLikeEvent` implements the comparison traits using only
/// the `event_id` field, a sorted list would be sorted lexicographically based
/// on the event's `EventId`.
#[derive(ToSchema, Clone, Debug, Event)]
pub struct OriginalSyncMessageLikeEvent<C: MessageLikeEventContent> {
/// Data specific to the event type.
pub content: C,
/// The globally unique event identifier for the user who sent the event.
pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event.
pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was
/// sent.
pub origin_server_ts: UnixMillis,
/// Additional key-value pairs not signed by the homeserver.
/// TODO???
#[salvo(schema(value_type = Object, additional_properties = true))]
pub unsigned: MessageLikeUnsigned<C>,
}
impl<C: MessageLikeEventContent + RedactContent> OriginalSyncMessageLikeEvent<C>
where
C::Redacted: RedactedMessageLikeEventContent,
{
pub(crate) fn into_maybe_redacted(self) -> SyncMessageLikeEvent<C> {
SyncMessageLikeEvent::Original(self)
}
}
/// A redacted message-like event.
///
/// `RedactedMessageLikeEvent` implements the comparison traits using only the
/// `event_id` field, a sorted list would be sorted lexicographically based on
/// the event's `EventId`.
#[derive(ToSchema, Clone, Debug, Event)]
pub struct RedactedMessageLikeEvent<C: RedactedMessageLikeEventContent> {
/// Data specific to the event type.
pub content: C,
/// The globally unique event identifier for the user who sent the event.
pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event.
pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was
/// sent.
pub origin_server_ts: UnixMillis,
/// The ID of the room associated with this event.
pub room_id: OwnedRoomId,
/// Additional key-value pairs not signed by the homeserver.
/// TODO???
#[salvo(schema(value_type = Object, additional_properties = true))]
pub unsigned: RedactedUnsigned,
}
/// A redacted message-like event without a `room_id`.
///
/// `RedactedSyncMessageLikeEvent` implements the comparison traits using only
/// the `event_id` field, a sorted list would be sorted lexicographically based
/// on the event's `EventId`.
#[derive(ToSchema, Clone, Debug, Event)]
pub struct RedactedSyncMessageLikeEvent<C: RedactedMessageLikeEventContent> {
/// Data specific to the event type.
pub content: C,
/// The globally unique event identifier for the user who sent the event.
pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event.
pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was
/// sent.
pub origin_server_ts: UnixMillis,
/// Additional key-value pairs not signed by the homeserver.
/// TODO???
#[salvo(schema(value_type = Object, additional_properties = true))]
pub unsigned: RedactedUnsigned,
}
/// A possibly-redacted message-like event.
///
/// `MessageLikeEvent` implements the comparison traits using only the
/// `event_id` field, a sorted list would be sorted lexicographically based on
/// the event's `EventId`.
#[allow(clippy::exhaustive_enums)]
#[derive(ToSchema, Clone, Debug)]
#[salvo(schema(bound = "C: ToSchema + 'static, C::Redacted: ToSchema + 'static"))]
pub enum MessageLikeEvent<C: MessageLikeEventContent + RedactContent>
where
C::Redacted: RedactedMessageLikeEventContent,
{
/// Original, unredacted form of the event.
Original(OriginalMessageLikeEvent<C>),
/// Redacted form of the event with minimal fields.
Redacted(RedactedMessageLikeEvent<C::Redacted>),
}
/// A possibly-redacted message-like event without a `room_id`.
///
/// `SyncMessageLikeEvent` implements the comparison traits using only the
/// `event_id` field, a sorted list would be sorted lexicographically based on
/// the event's `EventId`.
#[allow(clippy::exhaustive_enums)]
#[derive(ToSchema, Clone, Debug)]
#[salvo(schema(bound = "C: ToSchema + 'static, C::Redacted: ToSchema + 'static"))]
pub enum SyncMessageLikeEvent<C: MessageLikeEventContent + RedactContent>
where
C::Redacted: RedactedMessageLikeEventContent,
{
/// Original, unredacted form of the event.
Original(OriginalSyncMessageLikeEvent<C>),
/// Redacted form of the event with minimal fields.
Redacted(RedactedSyncMessageLikeEvent<C::Redacted>),
}
/// An unredacted state event.
///
/// `OriginalStateEvent` implements the comparison traits using only the
/// `event_id` field, a sorted list would be sorted lexicographically based on
/// the event's `EventId`.
#[derive(ToSchema, Clone, Debug, Event)]
pub struct OriginalStateEvent<C: StaticStateEventContent> {
/// Data specific to the event type.
pub content: C,
/// The globally unique event identifier for the user who sent the event.
pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event.
pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was
/// sent.
pub origin_server_ts: UnixMillis,
/// The ID of the room associated with this event.
pub room_id: OwnedRoomId,
/// A unique key which defines the overwriting semantics for this piece of
/// room state.
///
/// This is often an empty string, but some events send a `UserId` to show
/// which user the event affects.
pub state_key: C::StateKey,
/// Additional key-value pairs not signed by the homeserver.
#[salvo(schema(value_type = Object, additional_properties = true))]
pub unsigned: C::Unsigned,
}
/// An unredacted state event without a `room_id`.
///
/// `OriginalSyncStateEvent` implements the comparison traits using only the
/// `event_id` field, a sorted list would be sorted lexicographically based on
/// the event's `EventId`.
#[derive(ToSchema, Clone, Debug, Event)]
pub struct OriginalSyncStateEvent<C: StaticStateEventContent> {
/// Data specific to the event type.
pub content: C,
/// The globally unique event identifier for the user who sent the event.
pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event.
pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was
/// sent.
pub origin_server_ts: UnixMillis,
/// A unique key which defines the overwriting semantics for this piece of
/// room state.
///
/// This is often an empty string, but some events send a `UserId` to show
/// which user the event affects.
pub state_key: C::StateKey,
/// Additional key-value pairs not signed by the homeserver.
#[salvo(schema(value_type = Object, additional_properties = true))]
pub unsigned: C::Unsigned,
}
/// A stripped-down state event, used for previews of rooms the user has been
/// invited to.
#[derive(ToSchema, Clone, Debug, Event)]
pub struct StrippedStateEvent<C: PossiblyRedactedStateEventContent> {
/// Data specific to the event type.
pub content: C,
/// The fully-qualified ID of the user who sent this event.
pub sender: OwnedUserId,
/// A unique key which defines the overwriting semantics for this piece of
/// room state.
///
/// This is often an empty string, but some events send a `UserId` to show
/// which user the event affects.
pub state_key: C::StateKey,
/// Timestamp on the originating homeserver when this event was sent.
///
/// This field is usually stripped, but some events might include it.
#[cfg(feature = "unstable-msc4319")]
#[palpo_event(default)]
pub origin_server_ts: Option<UnixMillis>,
/// Additional key-value pairs not signed by the homeserver.
#[cfg(feature = "unstable-msc4319")]
pub unsigned: Option<RawJson<crate::events::StateUnsigned<C>>>,
}
/// A minimal state event, used for creating a new room.
#[derive(ToSchema, Clone, Debug, Event)]
pub struct InitialStateEvent<C: StaticStateEventContent> {
/// Data specific to the event type.
pub content: C,
/// A unique key which defines the overwriting semantics for this piece of
/// room state.
///
/// This is often an empty string, but some events send a `UserId` to show
/// which user the event affects.
///
/// Defaults to the empty string.
pub state_key: C::StateKey,
}
impl<C: StaticStateEventContent> InitialStateEvent<C> {
/// Create a new `InitialStateEvent` for an event type with an empty state
/// key.
///
/// For cases where the state key is not empty, use a struct literal to
/// create the event.
pub fn new(content: C) -> Self
where
C: StaticStateEventContent<StateKey = EmptyStateKey>,
{
Self {
content,
state_key: EmptyStateKey,
}
}
/// Shorthand for `RawJson::new(self).unwrap()`.
///
/// Since none of the content types in Palpo ever return an error in
/// serialization, this will never panic with `C` being a type from
/// Palpo. However, if you use a custom content type with a `Serialize`
/// implementation that can error (for example because it contains an
/// `enum` with one or more variants that use the `#[serde(skip)]`
/// attribute), this method can panic.
pub fn to_raw(&self) -> RawJson<Self> {
RawJson::new(self).unwrap()
}
/// Shorthand for `self.to_raw().cast::<AnyInitialStateEvent>()`.
///
/// Since none of the content types in Palpo ever return an error in
/// serialization, this will never panic with `C` being a type from
/// Palpo. However, if you use a custom content type with a `Serialize`
/// implementation that can error (for example because it contains an
/// `enum` with one or more variants that use the `#[serde(skip)]`
/// attribute), this method can panic.
pub fn to_raw_any(&self) -> RawJson<AnyInitialStateEvent> {
self.to_raw().cast()
}
}
impl<C> Default for InitialStateEvent<C>
where
C: StaticStateEventContent<StateKey = EmptyStateKey> + Default,
{
fn default() -> Self {
Self {
content: Default::default(),
state_key: EmptyStateKey,
}
}
}
impl<C: StaticStateEventContent> Serialize for InitialStateEvent<C> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut state = serializer.serialize_struct("InitialStateEvent", 3)?;
state.serialize_field("type", &self.content.event_type())?;
state.serialize_field("content", &self.content)?;
state.serialize_field("state_key", &self.state_key)?;
state.end()
}
}
/// A redacted state event.
///
/// `RedactedStateEvent` implements the comparison traits using only the
/// `event_id` field, a sorted list would be sorted lexicographically based on
/// the event's `EventId`.
#[derive(ToSchema, Clone, Debug, Event)]
pub struct RedactedStateEvent<C: RedactedStateEventContent> {
/// Data specific to the event type.
pub content: C,
/// The globally unique event identifier for the user who sent the event.
pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event.
pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was
/// sent.
pub origin_server_ts: UnixMillis,
/// The ID of the room associated with this event.
pub room_id: OwnedRoomId,
/// A unique key which defines the overwriting semantics for this piece of
/// room state.
///
/// This is often an empty string, but some events send a `UserId` to show
/// which user the event affects.
pub state_key: C::StateKey,
/// Additional key-value pairs not signed by the homeserver.
#[salvo(schema(value_type = Object, additional_properties = true))]
pub unsigned: RedactedUnsigned,
}
/// A redacted state event without a `room_id`.
///
/// `RedactedSyncStateEvent` implements the comparison traits using only the
/// `event_id` field, a sorted list would be sorted lexicographically based on
/// the event's `EventId`.
#[derive(ToSchema, Clone, Debug, Event)]
pub struct RedactedSyncStateEvent<C: RedactedStateEventContent> {
/// Data specific to the event type.
pub content: C,
/// The globally unique event identifier for the user who sent the event.
pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event.
pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was
/// sent.
pub origin_server_ts: UnixMillis,
/// A unique key which defines the overwriting semantics for this piece of
/// room state.
///
/// This is often an empty string, but some events send a `UserId` to show
/// which user the event affects.
pub state_key: C::StateKey,
/// Additional key-value pairs not signed by the homeserver.
#[salvo(schema(value_type = Object, additional_properties = true))]
pub unsigned: RedactedUnsigned,
}
/// A possibly-redacted state event.
///
/// `StateEvent` implements the comparison traits using only the `event_id`
/// field, a sorted list would be sorted lexicographically based on the event's
/// `EventId`.
#[allow(clippy::exhaustive_enums)]
#[derive(ToSchema, Clone, Debug)]
#[salvo(schema(
bound = "C: ToSchema + 'static, C::Redacted: ToSchema + 'static, <<C as RedactContent>::Redacted as RedactedStateEventContent>::StateKey: ToSchema + 'static, <C as StateEventContent>::StateKey: ToSchema + 'static, C::Unsigned: ToSchema + 'static"
))]
pub enum StateEvent<C: StaticStateEventContent + RedactContent>
where
C::Redacted: RedactedStateEventContent,
{
/// Original, unredacted form of the event.
Original(OriginalStateEvent<C>),
/// Redacted form of the event with minimal fields.
Redacted(RedactedStateEvent<C::Redacted>),
}
/// A possibly-redacted state event without a `room_id`.
///
/// `SyncStateEvent` implements the comparison traits using only the `event_id`
/// field, a sorted list would be sorted lexicographically based on the event's
/// `EventId`.
#[allow(clippy::exhaustive_enums)]
#[derive(ToSchema, Clone, Debug)]
#[salvo(schema(
bound = "C: ToSchema + 'static, C::Redacted: ToSchema + 'static, <C as StateEventContent>::StateKey: ToSchema + 'static,<<C as RedactContent>::Redacted as RedactedStateEventContent>::StateKey: ToSchema + 'static, C::Unsigned: ToSchema + 'static"
))]
pub enum SyncStateEvent<C: StaticStateEventContent + RedactContent>
where
C::Redacted: RedactedStateEventContent,
{
/// Original, unredacted form of the event.
Original(OriginalSyncStateEvent<C>),
/// Redacted form of the event with minimal fields.
Redacted(RedactedSyncStateEvent<C::Redacted>),
}
/// An event sent using send-to-device messaging.
#[derive(ToSchema, Clone, Debug, Event)]
pub struct ToDeviceEvent<C: ToDeviceEventContent> {
/// Data specific to the event type.
pub content: C,
/// The fully-qualified ID of the user who sent this event.
pub sender: OwnedUserId,
}
impl<C: ToDeviceEventContent> Serialize for ToDeviceEvent<C> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut state = serializer.serialize_struct("ToDeviceEvent", 3)?;
state.serialize_field("type", &self.content.event_type())?;
state.serialize_field("content", &self.content)?;
state.serialize_field("sender", &self.sender)?;
state.end()
}
}
/// The decrypted payload of an `m.olm.v1.curve25519-aes-sha2` event.
#[derive(Clone, Debug, Event)]
pub struct DecryptedOlmV1Event<C: MessageLikeEventContent> {
/// Data specific to the event type.
pub content: C,
/// The fully-qualified ID of the user who sent this event.
pub sender: OwnedUserId,
/// The fully-qualified ID of the intended recipient this event.
pub recipient: OwnedUserId,
/// The recipient's ed25519 key.
pub recipient_keys: OlmV1Keys,
/// The sender's ed25519 key.
pub keys: OlmV1Keys,
}
/// Public keys used for an `m.olm.v1.curve25519-aes-sha2` event.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct OlmV1Keys {
/// An ed25519 key.
pub ed25519: String,
}
/// The decrypted payload of an `m.megolm.v1.aes-sha2` event.
#[derive(Clone, Debug, Event)]
pub struct DecryptedMegolmV1Event<C: MessageLikeEventContent> {
/// Data specific to the event type.
pub content: C,
/// The ID of the room associated with the event.
pub room_id: OwnedRoomId,
}
/// A possibly-redacted state event content.
///
/// A non-redacted content also contains the `prev_content` from the unsigned
/// event data.
#[allow(clippy::exhaustive_enums)]
#[derive(ToSchema, Clone, Debug)]
#[salvo(schema(
bound = "C: ToSchema + 'static, C::PossiblyRedacted: ToSchema + 'static, C::Redacted: ToSchema + 'static"
))]
pub enum FullStateEventContent<C: StaticStateEventContent + RedactContent> {
/// Original, unredacted content of the event.
Original {
/// Current content of the room state.
content: C,
/// Previous content of the room state.
prev_content: Option<C::PossiblyRedacted>,
},
/// Redacted content of the event.
Redacted(C::Redacted),
}
impl<C: StaticStateEventContent + RedactContent> FullStateEventContent<C>
where
C::Redacted: RedactedStateEventContent,
{
/// Get the event’s type, like `m.room.create`.
pub fn event_type(&self) -> StateEventType {
match self {
Self::Original { content, .. } => content.event_type(),
Self::Redacted(content) => content.event_type(),
}
}
/// Transform `self` into a redacted form (removing most or all fields)
/// according to the spec.
///
/// If `self` is already [`Redacted`](Self::Redacted), return the inner data
/// unmodified.
///
/// A small number of events have room-version specific redaction behavior,
/// so a version has to be specified.
pub fn redact(self, rules: &RedactionRules) -> C::Redacted {
match self {
FullStateEventContent::Original { content, .. } => content.redact(rules),
FullStateEventContent::Redacted(content) => content,
}
}
}
macro_rules! impl_possibly_redacted_event {
(
$ty:ident ( $content_trait:ident, $redacted_content_trait:ident, $event_type:ident )
$( where C::Redacted: $trait:ident<StateKey = C::StateKey>, )?
{ $($extra:tt)* }
) => {
impl<C> $ty<C>
where
C: $content_trait + RedactContent,
C::Redacted: $redacted_content_trait,
$( C::Redacted: $trait<StateKey = C::StateKey>, )?
{
/// Returns the `type` of this event.
pub fn event_type(&self) -> $event_type {
match self {
Self::Original(ev) => ev.content.event_type(),
Self::Redacted(ev) => ev.content.event_type(),
}
}
/// Returns this event's `event_id` field.
pub fn event_id(&self) -> &EventId {
match self {
Self::Original(ev) => &ev.event_id,
Self::Redacted(ev) => &ev.event_id,
}
}
/// Returns this event's `sender` field.
pub fn sender(&self) -> &UserId {
match self {
Self::Original(ev) => &ev.sender,
Self::Redacted(ev) => &ev.sender,
}
}
/// Returns this event's `origin_server_ts` field.
pub fn origin_server_ts(&self) -> UnixMillis {
match self {
Self::Original(ev) => ev.origin_server_ts,
Self::Redacted(ev) => ev.origin_server_ts,
}
}
// So the room_id method can be in the same impl block, in rustdoc
$($extra)*
}
impl<'de, C> Deserialize<'de> for $ty<C>
where
C: $content_trait + EventContentFromType + RedactContent,
C::Redacted: $redacted_content_trait + EventContentFromType,
$( C::Redacted: $trait<StateKey = C::StateKey>, )?
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let json = Box::<RawJsonValue>::deserialize(deserializer)?;
let RedactionDeHelper { unsigned } = from_raw_json_value(&json)?;
if unsigned.and_then(|u| u.redacted_because).is_some() {
Ok(Self::Redacted(from_raw_json_value(&json)?))
} else {
Ok(Self::Original(from_raw_json_value(&json)?))
}
}
}
}
}
impl_possibly_redacted_event!(
MessageLikeEvent(
MessageLikeEventContent, RedactedMessageLikeEventContent, MessageLikeEventType
) {
/// Returns this event's `room_id` field.
pub fn room_id(&self) -> &RoomId {
match self {
Self::Original(ev) => &ev.room_id,
Self::Redacted(ev) => &ev.room_id,
}
}
/// Get the inner `OriginalMessageLikeEvent` if this is an unredacted event.
pub fn as_original(&self) -> Option<&OriginalMessageLikeEvent<C>> {
as_variant!(self, Self::Original)
}
}
);
impl_possibly_redacted_event!(
SyncMessageLikeEvent(
MessageLikeEventContent, RedactedMessageLikeEventContent, MessageLikeEventType
) {
/// Get the inner `OriginalSyncMessageLikeEvent` if this is an unredacted event.
pub fn as_original(&self) -> Option<&OriginalSyncMessageLikeEvent<C>> {
as_variant!(self, Self::Original)
}
/// Convert this sync event into a full event (one with a `room_id` field).
pub fn into_full_event(self, room_id: OwnedRoomId) -> MessageLikeEvent<C> {
match self {
Self::Original(ev) => MessageLikeEvent::Original(ev.into_full_event(room_id)),
Self::Redacted(ev) => MessageLikeEvent::Redacted(ev.into_full_event(room_id)),
}
}
}
);
impl_possibly_redacted_event!(
StateEvent(StaticStateEventContent, RedactedStateEventContent, StateEventType)
where
C::Redacted: RedactedStateEventContent<StateKey = C::StateKey>,
{
/// Returns this event's `room_id` field.
pub fn room_id(&self) -> &RoomId {
match self {
Self::Original(ev) => &ev.room_id,
Self::Redacted(ev) => &ev.room_id,
}
}
/// Returns this event's `state_key` field.
pub fn state_key(&self) -> &C::StateKey {
match self {
Self::Original(ev) => &ev.state_key,
Self::Redacted(ev) => &ev.state_key,
}
}
/// Get the inner `OriginalStateEvent` if this is an unredacted event.
pub fn as_original(&self) -> Option<&OriginalStateEvent<C>> {
as_variant!(self, Self::Original)
}
}
);
impl_possibly_redacted_event!(
SyncStateEvent(StaticStateEventContent, RedactedStateEventContent, StateEventType)
where
C::Redacted: RedactedStateEventContent<StateKey = C::StateKey>,
{
/// Returns this event's `state_key` field.
pub fn state_key(&self) -> &C::StateKey {
match self {
Self::Original(ev) => &ev.state_key,
Self::Redacted(ev) => &ev.state_key,
}
}
/// Get the inner `OriginalSyncStateEvent` if this is an unredacted event.
pub fn as_original(&self) -> Option<&OriginalSyncStateEvent<C>> {
as_variant!(self, Self::Original)
}
/// Convert this sync event into a full event (one with a `room_id` field).
pub fn into_full_event(self, room_id: OwnedRoomId) -> StateEvent<C> {
match self {
Self::Original(ev) => StateEvent::Original(ev.into_full_event(room_id)),
Self::Redacted(ev) => StateEvent::Redacted(ev.into_full_event(room_id)),
}
}
}
);
macro_rules! impl_sync_from_full {
($ty:ident, $full:ident, $content_trait:ident, $redacted_content_trait: ident) => {
impl<C> From<$full<C>> for $ty<C>
where
C: $content_trait + RedactContent,
C::Redacted: $redacted_content_trait,
{
fn from(full: $full<C>) -> Self {
match full {
$full::Original(ev) => Self::Original(ev.into()),
$full::Redacted(ev) => Self::Redacted(ev.into()),
}
}
}
};
}
impl_sync_from_full!(
SyncMessageLikeEvent,
MessageLikeEvent,
MessageLikeEventContent,
RedactedMessageLikeEventContent
);
impl_sync_from_full!(
SyncStateEvent,
StateEvent,
StaticStateEventContent,
RedactedStateEventContent
);
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/voice.rs | crates/core/src/events/voice.rs | //! Types for voice message events ([MSC3245]).
//!
//! [MSC3245]: https://github.com/matrix-org/matrix-spec-proposals/pull/3245
use std::time::Duration;
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::events::{
audio::Amplitude, file::FileContentBlock, message::TextContentBlock, room::message::Relation,
};
/// The payload for an extensible voice message.
///
/// This is the new primary type introduced in [MSC3245] and can be sent in
/// rooms with a version that doesn't support extensible events. See the
/// documentation of the [`message`] module for more information.
///
/// [MSC3245]: https://github.com/matrix-org/matrix-spec-proposals/pull/3245
/// [`message`]: super::message
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize, EventContent)]
#[palpo_event(type = "org.matrix.msc3245.voice.v2", kind = MessageLike, without_relation)]
pub struct VoiceEventContent {
/// The text representation of the message.
#[serde(rename = "org.matrix.msc1767.text")]
pub text: TextContentBlock,
/// The file content of the message.
#[serde(rename = "org.matrix.msc1767.file")]
pub file: FileContentBlock,
/// The audio content of the message.
#[serde(rename = "org.matrix.msc1767.audio_details")]
pub audio_details: VoiceAudioDetailsContentBlock,
/// Whether this message is automated.
#[serde(
default,
skip_serializing_if = "palpo_core::serde::is_default",
rename = "org.matrix.msc1767.automated"
)]
pub automated: bool,
/// Information about related messages.
#[serde(
flatten,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::events::room::message::relation_serde::deserialize_relation"
)]
pub relates_to: Option<Relation<VoiceEventContentWithoutRelation>>,
}
impl VoiceEventContent {
/// Creates a new `VoiceEventContent` with the given fallback
/// representation, file and audio details.
pub fn new(
text: TextContentBlock,
file: FileContentBlock,
audio_details: VoiceAudioDetailsContentBlock,
) -> Self {
Self {
text,
file,
audio_details,
automated: false,
relates_to: None,
}
}
/// Creates a new `VoiceEventContent` with the given plain text fallback
/// representation, file and audio details.
pub fn with_plain_text(
plain_text: impl Into<String>,
file: FileContentBlock,
audio_details: VoiceAudioDetailsContentBlock,
) -> Self {
Self {
text: TextContentBlock::plain(plain_text),
file,
audio_details,
automated: false,
relates_to: None,
}
}
}
/// A block for details of voice audio content.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct VoiceAudioDetailsContentBlock {
/// The duration of the audio in seconds.
#[serde(with = "palpo_core::serde::duration::secs")]
pub duration: Duration,
/// The waveform representation of the content.
#[serde(rename = "org.matrix.msc3246.waveform")]
pub waveform: Vec<Amplitude>,
}
impl VoiceAudioDetailsContentBlock {
/// Creates a new `AudioDetailsContentBlock` with the given duration and
/// waveform representation.
pub fn new(duration: Duration, waveform: Vec<Amplitude>) -> Self {
Self { duration, waveform }
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/space.rs | crates/core/src/events/space.rs | //! Types for the `m.space` events.
//!
//! See [the specification](https://spec.matrix.org/latest/client-server-api/#spaces).
pub mod child;
pub mod parent;
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/tag.rs | crates/core/src/events/tag.rs | //! Types for the [`m.tag`] event.
//!
//! [`m.tag`]: https://spec.matrix.org/latest/client-server-api/#mtag
use std::{collections::BTreeMap, error::Error, fmt, str::FromStr};
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{PrivOwnedStr, serde::deserialize_cow_str};
/// Map of tag names to tag info.
pub type Tags = BTreeMap<TagName, TagInfo>;
/// The content of an `m.tag` event.
///
/// Informs the client of tags on a room.
#[derive(ToSchema, Default, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.tag", kind = RoomAccountData)]
pub struct TagEventContent {
/// A map of tag names to tag info.
pub tags: Tags,
}
impl TagEventContent {
/// Creates a new `TagEventContent` with the given `Tags`.
pub fn new(tags: Tags) -> Self {
Self { tags }
}
}
impl From<Tags> for TagEventContent {
fn from(tags: Tags) -> Self {
Self::new(tags)
}
}
/// A user-defined tag name.
#[derive(ToSchema, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct UserTagName {
name: String,
}
impl AsRef<str> for UserTagName {
fn as_ref(&self) -> &str {
&self.name
}
}
impl FromStr for UserTagName {
type Err = InvalidUserTagName;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.starts_with("u.") {
Ok(Self { name: s.into() })
} else {
Err(InvalidUserTagName)
}
}
}
/// An error returned when attempting to create a UserTagName with a string that
/// would make it invalid.
#[derive(Debug)]
#[allow(clippy::exhaustive_structs)]
pub struct InvalidUserTagName;
impl fmt::Display for InvalidUserTagName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "missing 'u.' prefix in UserTagName")
}
}
impl Error for InvalidUserTagName {}
/// The name of a tag.
#[derive(ToSchema, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum TagName {
/// `m.favourite`: The user's favorite rooms.
///
/// These should be shown with higher precedence than other rooms.
Favorite,
/// `m.lowpriority`: These should be shown with lower precedence than
/// others.
LowPriority,
/// `m.server_notice`: Used to identify
/// [Server Notice Rooms](https://spec.matrix.org/latest/client-server-api/#server-notices).
ServerNotice,
/// `u.*`: User-defined tag
User(UserTagName),
/// A custom tag
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
impl TagName {
/// Returns the display name of the tag.
///
/// That means the string after `m.` or `u.` for spec- and user-defined tag
/// names, and the string after the last dot for custom tags. If no dot
/// is found, returns the whole string.
pub fn display_name(&self) -> &str {
match self {
Self::_Custom(s) => {
let start = s.0.rfind('.').map(|p| p + 1).unwrap_or(0);
&self.as_ref()[start..]
}
_ => &self.as_ref()[2..],
}
}
}
impl AsRef<str> for TagName {
fn as_ref(&self) -> &str {
match self {
Self::Favorite => "m.favourite",
Self::LowPriority => "m.lowpriority",
Self::ServerNotice => "m.server_notice",
Self::User(tag) => tag.as_ref(),
Self::_Custom(s) => &s.0,
}
}
}
impl<T> From<T> for TagName
where
T: AsRef<str> + Into<String>,
{
fn from(s: T) -> TagName {
match s.as_ref() {
"m.favourite" => Self::Favorite,
"m.lowpriority" => Self::LowPriority,
"m.server_notice" => Self::ServerNotice,
s if s.starts_with("u.") => Self::User(UserTagName { name: s.into() }),
s => Self::_Custom(PrivOwnedStr(s.into())),
}
}
}
impl fmt::Display for TagName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.as_ref().fmt(f)
}
}
impl<'de> Deserialize<'de> for TagName {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let cow = deserialize_cow_str(deserializer)?;
Ok(cow.into())
}
}
impl Serialize for TagName {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(self.as_ref())
}
}
/// Information about a tag.
#[derive(ToSchema, Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
pub struct TagInfo {
/// Value to use for lexicographically ordering rooms with this tag.
///
/// If you activate the `compat-tag-info` feature, this field can be decoded
/// as a stringified floating-point value, instead of a number as it
/// should be according to the specification.
#[serde(skip_serializing_if = "Option::is_none")]
pub order: Option<f64>,
}
impl TagInfo {
/// Creates an empty `TagInfo`.
pub fn new() -> Self {
Default::default()
}
}
#[cfg(test)]
mod tests {
use maplit::btreemap;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::{TagEventContent, TagInfo, TagName};
#[test]
fn serialization() {
let tags = btreemap! {
TagName::Favorite => TagInfo::new(),
TagName::LowPriority => TagInfo::new(),
TagName::ServerNotice => TagInfo::new(),
"u.custom".to_owned().into() => TagInfo { order: Some(0.9) }
};
let content = TagEventContent { tags };
assert_eq!(
to_json_value(content).unwrap(),
json!({
"tags": {
"m.favourite": {},
"m.lowpriority": {},
"m.server_notice": {},
"u.custom": {
"order": 0.9
}
},
})
);
}
#[test]
fn deserialize_tag_info() {
let json = json!({});
assert_eq!(
from_json_value::<TagInfo>(json).unwrap(),
TagInfo::default()
);
let json = json!({ "order": null });
assert_eq!(
from_json_value::<TagInfo>(json).unwrap(),
TagInfo::default()
);
let json = json!({ "order": 0.42 });
assert_eq!(
from_json_value::<TagInfo>(json).unwrap(),
TagInfo { order: Some(0.42) }
);
// #[cfg(feature = "compat-tag-info")]
// {
// let json = json!({ "order": "0.5" });
// assert_eq!(
// from_json_value::<TagInfo>(json).unwrap(),
// TagInfo { order: Some(0.5) }
// );
// let json = json!({ "order": ".5" });
// assert_eq!(
// from_json_value::<TagInfo>(json).unwrap(),
// TagInfo { order: Some(0.5) }
// );
// }
// #[cfg(not(feature = "compat-tag-info"))]
// {
let json = json!({ "order": "0.5" });
assert!(from_json_value::<TagInfo>(json).is_err());
// }
}
#[test]
fn display_name() {
assert_eq!(TagName::Favorite.display_name(), "favourite");
assert_eq!(TagName::LowPriority.display_name(), "lowpriority");
assert_eq!(TagName::ServerNotice.display_name(), "server_notice");
assert_eq!(TagName::from("u.Work").display_name(), "Work");
assert_eq!(TagName::from("rs.palpo.rules").display_name(), "rules");
assert_eq!(TagName::from("Play").display_name(), "Play");
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/audio.rs | crates/core/src/events/audio.rs | //! Types for extensible audio message events ([MSC3927]).
//!
//! [MSC3927]: https://github.com/matrix-org/matrix-spec-proposals/pull/3927
use std::time::Duration;
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
mod amplitude_serde;
use super::{
file::{CaptionContentBlock, FileContentBlock},
message::TextContentBlock,
room::message::Relation,
};
/// The payload for an extensible audio message.
///
/// This is the new primary type introduced in [MSC3927] and should only be sent
/// in rooms with a version that supports it. See the d ocumentation of the
/// [`message`] module for more information.
///
/// [MSC3927]: https://github.com/matrix-org/matrix-spec-proposals/pull/3927
/// [`message`]: super::message
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize, EventContent)]
#[palpo_event(type = "org.matrix.msc1767.audio", kind = MessageLike, without_relation)]
pub struct AudioEventContent {
/// The text representations of the message.
#[serde(rename = "org.matrix.msc1767.text")]
pub text: TextContentBlock,
/// The file content of the message.
#[serde(rename = "org.matrix.msc1767.file")]
pub file: FileContentBlock,
/// The audio details of the message, if any.
#[serde(
rename = "org.matrix.msc1767.audio_details",
skip_serializing_if = "Option::is_none"
)]
pub audio_details: Option<AudioDetailsContentBlock>,
/// The caption of the message, if any.
#[serde(
rename = "org.matrix.msc1767.caption",
skip_serializing_if = "Option::is_none"
)]
pub caption: Option<CaptionContentBlock>,
/// Whether this message is automated.
#[serde(
default,
skip_serializing_if = "palpo_core::serde::is_default",
rename = "org.matrix.msc1767.automated"
)]
pub automated: bool,
/// Information about related messages.
#[serde(
flatten,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::events::room::message::relation_serde::deserialize_relation"
)]
pub relates_to: Option<Relation<AudioEventContentWithoutRelation>>,
}
impl AudioEventContent {
/// Creates a new `AudioEventContent` with the given text fallback and file.
pub fn new(text: TextContentBlock, file: FileContentBlock) -> Self {
Self {
text,
file,
audio_details: None,
caption: None,
automated: false,
relates_to: None,
}
}
/// Creates a new `AudioEventContent` with the given plain text fallback
/// representation and file.
pub fn with_plain_text(plain_text: impl Into<String>, file: FileContentBlock) -> Self {
Self {
text: TextContentBlock::plain(plain_text),
file,
audio_details: None,
caption: None,
automated: false,
relates_to: None,
}
}
}
/// A block for details of audio content.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct AudioDetailsContentBlock {
/// The duration of the audio in seconds.
#[serde(with = "palpo_core::serde::duration::secs")]
pub duration: Duration,
/// The waveform representation of the audio content, if any.
///
/// This is optional and defaults to an empty array.
#[serde(
rename = "org.matrix.msc3246.waveform",
default,
skip_serializing_if = "Vec::is_empty"
)]
pub waveform: Vec<Amplitude>,
}
impl AudioDetailsContentBlock {
/// Creates a new `AudioDetailsContentBlock` with the given duration.
pub fn new(duration: Duration) -> Self {
Self {
duration,
waveform: Default::default(),
}
}
}
/// The amplitude of a waveform sample.
///
/// Must be an integer between 0 and 256.
#[derive(
ToSchema, Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize,
)]
pub struct Amplitude(u64);
impl Amplitude {
/// The smallest value that can be represented by this type, 0.
pub const MIN: u16 = 0;
/// The largest value that can be represented by this type, 256.
pub const MAX: u16 = 256;
/// Creates a new `Amplitude` with the given value.
///
/// It will saturate if it is bigger than [`Amplitude::MAX`].
pub fn new(value: u16) -> Self {
Self(value.min(Self::MAX).into())
}
/// The value of this `Amplitude`.
pub fn get(&self) -> u64 {
self.0
}
}
impl From<u16> for Amplitude {
fn from(value: u16) -> Self {
Self::new(value)
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/message.rs | crates/core/src/events/message.rs | //! Types for extensible text message events ([MSC1767]).
//!
//! # Extensible events
//!
//! [MSC1767] defines a new structure for events that is made of two parts: a
//! type and zero or more reusable content blocks.
//!
//! This allows to construct new event types from a list of known content blocks
//! that allows in turn clients to be able to render unknown event types by
//! using the known content blocks as a fallback. When a new type is defined,
//! all the content blocks it can or must contain are defined too.
//!
//! There are also some content blocks called "mixins" that can apply to any
//! event when they are defined.
//!
//! # MSCs
//!
//! This is a list of MSCs defining the extensible events and deprecating the
//! corresponding legacy types. Note that "primary type" means the `type` field
//! at the root of the event and "message type" means the `msgtype` field in the
//! content of the `m.room.message` primary type.
//!
//! - [MSC1767]: Text messages, where the `m.message` primary type replaces the
//! `m.text` message type.
//! - [MSC3954]: Emotes, where the `m.emote` primary type replaces the `m.emote`
//! message type.
//! - [MSC3955]: Automated events, where the `m.automated` mixin replaces the
//! `m.notice` message type.
//! - [MSC3956]: Encrypted events, where the `m.encrypted` primary type replaces
//! the `m.room.encrypted` primary type.
//! - [MSC3551]: Files, where the `m.file` primary type replaces the `m.file`
//! message type.
//! - [MSC3552]: Images and Stickers, where the `m.image` primary type replaces
//! the `m.image` message type and the `m.sticker` primary type.
//! - [MSC3553]: Videos, where the `m.video` primary type replaces the `m.video`
//! message type.
//! - [MSC3927]: Audio, where the `m.audio` primary type replaces the `m.audio`
//! message type.
//! - [MSC3488]: Location, where the `m.location` primary type replaces the
//! `m.location` message type.
//!
//! There are also the following MSCs that introduce new features with
//! extensible events:
//!
//! - [MSC3245]: Voice Messages.
//! - [MSC3246]: Audio Waveform.
//! - [MSC3381][]: Polls.
//!
//! # How to use them in Matrix
//!
//! The extensible events types are meant to be used separately than the legacy
//! types. As such, their use is reserved for room versions that support it.
//!
//! Currently no stable room version supports extensible events so they can only
//! be sent with unstable room versions that support them.
//!
//! An exception is made for some new extensible events types that don't have a
//! legacy type. They can be used with stable room versions without support for
//! extensible types, but they might be ignored by clients that have no support
//! for extensible events. The types that support this must advertise it in
//! their MSC.
//!
//! Note that if a room version supports extensible events, it doesn't support
//! the legacy types anymore and those should be ignored. There is not yet a
//! definition of the deprecated legacy types in extensible events rooms.
//!
//! # How to use them in Palpo
//!
//! First, you can enable the `unstable-extensible-events` feature from the
//! `palpo` crate, that will enable all the MSCs for the extensible events that
//! correspond to the legacy types. It is also possible to enable only the MSCs
//! you want with the `unstable-mscXXXX` features (where `XXXX` is the number of
//! the MSC). When enabling an MSC, all MSC dependencies are enabled at the same
//! time to avoid issues.
//!
//! Currently the extensible events use the unstable prefixes as defined in the
//! corresponding MSCs.
//!
//! [MSC1767]: https://github.com/matrix-org/matrix-spec-proposals/pull/1767
//! [MSC3954]: https://github.com/matrix-org/matrix-spec-proposals/pull/3954
//! [MSC3955]: https://github.com/matrix-org/matrix-spec-proposals/pull/3955
//! [MSC3956]: https://github.com/matrix-org/matrix-spec-proposals/pull/3956
//! [MSC3551]: https://github.com/matrix-org/matrix-spec-proposals/pull/3551
//! [MSC3552]: https://github.com/matrix-org/matrix-spec-proposals/pull/3552
//! [MSC3553]: https://github.com/matrix-org/matrix-spec-proposals/pull/3553
//! [MSC3927]: https://github.com/matrix-org/matrix-spec-proposals/pull/3927
//! [MSC3488]: https://github.com/matrix-org/matrix-spec-proposals/pull/3488
//! [MSC3245]: https://github.com/matrix-org/matrix-spec-proposals/pull/3245
//! [MSC3246]: https://github.com/matrix-org/matrix-spec-proposals/pull/3246
//! [MSC3381]: https://github.com/matrix-org/matrix-spec-proposals/pull/3381
use std::ops::Deref;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use super::room::message::Relation;
#[cfg(feature = "unstable-msc4095")]
use crate::events::room::message::UrlPreview;
use crate::macros::EventContent;
mod historical_serde;
pub use historical_serde::MessageContentBlock;
/// The payload for an extensible text message.
///
/// This is the new primary type introduced in [MSC1767] and should only be sent
/// in rooms with a version that supports it. See the documentation of the
/// [`message`] module for more information.
///
/// To construct a `MessageEventContent` with a custom [`TextContentBlock`],
/// convert it with `MessageEventContent::from()` / `.into()`.
///
/// [MSC1767]: https://github.com/matrix-org/matrix-spec-proposals/pull/1767
/// [`message`]: super::message
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize, EventContent)]
#[palpo_event(type = "org.matrix.msc1767.message", kind = MessageLike, without_relation)]
pub struct MessageEventContent {
/// The message's text content.
#[serde(rename = "org.matrix.msc1767.text")]
pub text: TextContentBlock,
/// Whether this message is automated.
#[cfg(feature = "unstable-msc3955")]
#[serde(
default,
skip_serializing_if = "palpo_core::serde::is_default",
rename = "org.matrix.msc1767.automated"
)]
pub automated: bool,
/// Information about related messages.
#[serde(
flatten,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::events::room::message::relation_serde::deserialize_relation"
)]
pub relates_to: Option<Relation<MessageEventContentWithoutRelation>>,
/// [MSC4095](https://github.com/matrix-org/matrix-spec-proposals/pull/4095)-style bundled url previews
#[cfg(feature = "unstable-msc4095")]
#[serde(
rename = "com.beeper.linkpreviews",
skip_serializing_if = "Option::is_none",
alias = "m.url_previews"
)]
pub url_previews: Option<Vec<UrlPreview>>,
}
#[cfg(feature = "unstable-msc1767")]
impl MessageEventContent {
/// A convenience constructor to create a plain text message.
pub fn plain(body: impl Into<String>) -> Self {
Self {
text: TextContentBlock::plain(body),
#[cfg(feature = "unstable-msc3955")]
automated: false,
relates_to: None,
#[cfg(feature = "unstable-msc4095")]
url_previews: None,
}
}
/// A convenience constructor to create an HTML message.
pub fn html(body: impl Into<String>, html_body: impl Into<String>) -> Self {
Self {
text: TextContentBlock::html(body, html_body),
#[cfg(feature = "unstable-msc3955")]
automated: false,
relates_to: None,
#[cfg(feature = "unstable-msc4095")]
url_previews: None,
}
}
/// A convenience constructor to create a message from Markdown.
///
/// The content includes an HTML message if some Markdown formatting was
/// detected, otherwise only a plain text message is included.
#[cfg(feature = "markdown")]
pub fn markdown(body: impl AsRef<str> + Into<String>) -> Self {
Self {
text: TextContentBlock::markdown(body),
#[cfg(feature = "unstable-msc3955")]
automated: false,
relates_to: None,
#[cfg(feature = "unstable-msc4095")]
url_previews: None,
}
}
}
impl From<TextContentBlock> for MessageEventContent {
fn from(text: TextContentBlock) -> Self {
Self {
text,
#[cfg(feature = "unstable-msc3955")]
automated: false,
relates_to: None,
#[cfg(feature = "unstable-msc4095")]
url_previews: None,
}
}
}
/// A block for text content with optional markup.
///
/// This is an array of [`TextRepresentation`].
///
/// To construct a `TextContentBlock` with custom MIME types, construct a
/// `Vec<TextRepresentation>` first and use its `::from()` / `.into()`
/// implementation.
#[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)]
pub struct TextContentBlock(Vec<TextRepresentation>);
impl TextContentBlock {
/// A convenience constructor to create a plain text message.
pub fn plain(body: impl Into<String>) -> Self {
Self(vec![TextRepresentation::plain(body)])
}
/// A convenience constructor to create an HTML message with a plain text
/// fallback.
pub fn html(body: impl Into<String>, html_body: impl Into<String>) -> Self {
Self(vec![
TextRepresentation::html(html_body),
TextRepresentation::plain(body),
])
}
/// A convenience constructor to create a message from Markdown.
///
/// The content includes an HTML message if some Markdown formatting was
/// detected, otherwise only a plain text message is included.
#[cfg(feature = "markdown")]
pub fn markdown(body: impl AsRef<str> + Into<String>) -> Self {
let mut message = Vec::with_capacity(2);
if let Some(html_body) = TextRepresentation::markdown(&body) {
message.push(html_body);
}
message.push(TextRepresentation::plain(body));
Self(message)
}
/// Whether this content block is empty.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Get the plain text representation of this message.
pub fn find_plain(&self) -> Option<&str> {
self.iter()
.find(|content| content.mimetype == "text/plain")
.map(|content| content.body.as_ref())
}
/// Get the HTML representation of this message.
pub fn find_html(&self) -> Option<&str> {
self.iter()
.find(|content| content.mimetype == "text/html")
.map(|content| content.body.as_ref())
}
}
impl From<Vec<TextRepresentation>> for TextContentBlock {
fn from(representations: Vec<TextRepresentation>) -> Self {
Self(representations)
}
}
impl FromIterator<TextRepresentation> for TextContentBlock {
fn from_iter<T: IntoIterator<Item = TextRepresentation>>(iter: T) -> Self {
Self(iter.into_iter().collect())
}
}
impl Deref for TextContentBlock {
type Target = [TextRepresentation];
fn deref(&self) -> &Self::Target {
&self.0
}
}
/// Text content with optional markup.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct TextRepresentation {
/// The MIME type of the `body`.
///
/// This must follow the format defined in [RFC6838].
///
/// [RFC6838]: https://datatracker.ietf.org/doc/html/rfc6838
#[serde(
default = "TextRepresentation::default_mimetype",
skip_serializing_if = "TextRepresentation::is_default_mimetype"
)]
pub mimetype: String,
/// The text content.
pub body: String,
/// The language of the text ([MSC3554]).
///
/// This must be a valid language code according to [BCP 47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt).
///
/// This is optional and defaults to `en`.
///
/// [MSC3554]: https://github.com/matrix-org/matrix-spec-proposals/pull/3554
#[cfg(feature = "unstable-msc3554")]
#[serde(
rename = "org.matrix.msc3554.lang",
default = "TextRepresentation::default_lang",
skip_serializing_if = "TextRepresentation::is_default_lang"
)]
pub lang: String,
}
impl TextRepresentation {
/// Creates a new `TextRepresentation` with the given MIME type and body.
pub fn new(mimetype: impl Into<String>, body: impl Into<String>) -> Self {
Self {
mimetype: mimetype.into(),
body: body.into(),
#[cfg(feature = "unstable-msc3554")]
lang: Self::default_lang(),
}
}
/// Creates a new plain text message body.
pub fn plain(body: impl Into<String>) -> Self {
Self::new("text/plain", body)
}
/// Creates a new HTML-formatted message body.
pub fn html(body: impl Into<String>) -> Self {
Self::new("text/html", body)
}
/// Creates a new HTML-formatted message body by parsing the Markdown in
/// `body`.
///
/// Returns `None` if no Markdown formatting was found.
#[cfg(feature = "markdown")]
pub fn markdown(body: impl AsRef<str>) -> Option<Self> {
use super::room::message::parse_markdown;
parse_markdown(body.as_ref()).map(Self::html)
}
fn default_mimetype() -> String {
"text/plain".to_owned()
}
fn is_default_mimetype(mime: &str) -> bool {
mime == "text/plain"
}
#[cfg(feature = "unstable-msc3554")]
fn default_lang() -> String {
"en".to_owned()
}
#[cfg(feature = "unstable-msc3554")]
fn is_default_lang(lang: &str) -> bool {
lang == "en"
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/emote.rs | crates/core/src/events/emote.rs | //! Types for extensible emote message events ([MSC3954]).
//!
//! [MSC3954]: https://github.com/matrix-org/matrix-spec-proposals/pull/3954
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use super::{message::TextContentBlock, room::message::Relation};
use crate::macros::EventContent;
/// The payload for an extensible emote message.
///
/// This is the new primary type introduced in [MSC3954] and should only be sent
/// in rooms with a version that supports it. See the documentation of the
/// [`message`] module for more information.
///
/// To construct an `EmoteEventContent` with a custom [`TextContentBlock`],
/// convert it with `EmoteEventContent::from()` / `.into()`.
///
/// [MSC3954]: https://github.com/matrix-org/matrix-spec-proposals/pull/3954
/// [`message`]: super::message
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize, EventContent)]
#[palpo_event(type = "org.matrix.msc1767.emote", kind = MessageLike, without_relation)]
pub struct EmoteEventContent {
/// The message's text content.
#[serde(rename = "org.matrix.msc1767.text")]
pub text: TextContentBlock,
/// Whether this message is automated.
#[cfg(feature = "unstable-msc3955")]
#[serde(
default,
skip_serializing_if = "palpo_core::serde::is_default",
rename = "org.matrix.msc1767.automated"
)]
pub automated: bool,
/// Information about related messages.
#[serde(
flatten,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::events::room::message::relation_serde::deserialize_relation"
)]
pub relates_to: Option<Relation<EmoteEventContentWithoutRelation>>,
}
impl EmoteEventContent {
/// A convenience constructor to create a plain text emote.
pub fn plain(body: impl Into<String>) -> Self {
Self {
text: TextContentBlock::plain(body),
#[cfg(feature = "unstable-msc3955")]
automated: false,
relates_to: None,
}
}
/// A convenience constructor to create an HTML emote.
pub fn html(body: impl Into<String>, html_body: impl Into<String>) -> Self {
Self {
text: TextContentBlock::html(body, html_body),
#[cfg(feature = "unstable-msc3955")]
automated: false,
relates_to: None,
}
}
/// A convenience constructor to create an emote from Markdown.
///
/// The content includes an HTML message if some Markdown formatting was
/// detected, otherwise only a plain text message is included.
#[cfg(feature = "markdown")]
pub fn markdown(body: impl AsRef<str> + Into<String>) -> Self {
Self {
text: TextContentBlock::markdown(body),
#[cfg(feature = "unstable-msc3955")]
automated: false,
relates_to: None,
}
}
}
impl From<TextContentBlock> for EmoteEventContent {
fn from(text: TextContentBlock) -> Self {
Self {
text,
#[cfg(feature = "unstable-msc3955")]
automated: false,
relates_to: None,
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/image_pack.rs | crates/core/src/events/image_pack.rs | //! Types for image packs in Matrix ([MSC2545]).
//!
//! [MSC2545]: https://github.com/matrix-org/matrix-spec-proposals/pull/2545
use std::collections::{BTreeMap, BTreeSet};
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::events::room::ImageInfo;
use crate::{OwnedMxcUri, OwnedRoomId, PrivOwnedStr, serde::StringEnum};
/// The content of an `im.ponies.room_emotes` event,
/// the unstable version of `m.image_pack` in room state events.
///
/// State key is the identifier for the image pack in
/// [ImagePackRoomsEventContent].
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize, EventContent)]
#[palpo_event(type = "im.ponies.room_emotes", kind = State, state_key_type = String)]
pub struct RoomImagePackEventContent {
/// A list of images available in this image pack.
///
/// Keys in the map are shortcodes for the images.
pub images: BTreeMap<String, PackImage>,
/// Image pack info.
#[serde(skip_serializing_if = "Option::is_none")]
pub pack: Option<PackInfo>,
}
impl RoomImagePackEventContent {
/// Creates a new `RoomImagePackEventContent` with a list of images.
pub fn new(images: BTreeMap<String, PackImage>) -> Self {
Self { images, pack: None }
}
}
/// The content of an `im.ponies.user_emotes` event,
/// the unstable version of `m.image_pack` in account data events.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize, EventContent)]
#[palpo_event(type = "im.ponies.user_emotes", kind = GlobalAccountData)]
pub struct AccountImagePackEventContent {
/// A list of images available in this image pack.
///
/// Keys in the map are shortcodes for the images.
pub images: BTreeMap<String, PackImage>,
/// Image pack info.
#[serde(skip_serializing_if = "Option::is_none")]
pub pack: Option<PackInfo>,
}
impl AccountImagePackEventContent {
/// Creates a new `AccountImagePackEventContent` with a list of images.
pub fn new(images: BTreeMap<String, PackImage>) -> Self {
Self { images, pack: None }
}
}
/// An image object in a image pack.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PackImage {
/// The MXC URI to the media file.
pub url: OwnedMxcUri,
/// An optional text body for this image.
/// Useful for the sticker body text or the emote alt text.
///
/// Defaults to the shortcode.
#[serde(skip_serializing_if = "Option::is_none")]
pub body: Option<String>,
/// The [ImageInfo] object used for the `info` block of `m.sticker` events.
#[serde(skip_serializing_if = "Option::is_none")]
pub info: Option<ImageInfo>,
/// The usages for the image.
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
pub usage: BTreeSet<PackUsage>,
}
impl PackImage {
/// Creates a new `PackImage` with the given MXC URI to the media file.
pub fn new(url: OwnedMxcUri) -> Self {
Self {
url,
body: None,
info: None,
usage: BTreeSet::new(),
}
}
}
/// A description for the pack.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct PackInfo {
/// A display name for the pack.
/// This does not have to be unique from other packs in a room.
///
/// Defaults to the room name, if the image pack event is in the room.
#[serde(skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
/// The MXC URI of an avatar/icon to display for the pack.
///
/// Defaults to the room avatar, if the pack is in the room.
/// Otherwise, the pack does not have an avatar.
#[serde(skip_serializing_if = "Option::is_none")]
pub avatar_url: Option<OwnedMxcUri>,
/// The usages for the pack.
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
pub usage: BTreeSet<PackUsage>,
/// The attribution of this pack.
#[serde(skip_serializing_if = "Option::is_none")]
pub attribution: Option<String>,
}
impl PackInfo {
/// Creates a new empty `PackInfo`.
pub fn new() -> Self {
Self::default()
}
}
/// Usages for either an image pack or an individual image.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[palpo_enum(rename_all = "snake_case")]
#[non_exhaustive]
pub enum PackUsage {
/// Pack or image is usable as a emoticon.
Emoticon,
/// Pack or image is usable as a sticker.
Sticker,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
/// The content of an `im.ponies.emote_rooms` event,
/// the unstable version of `m.image_pack.rooms`.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize, EventContent)]
#[palpo_event(type = "im.ponies.emote_rooms", kind = GlobalAccountData)]
pub struct ImagePackRoomsEventContent {
/// A map of enabled image packs in each room.
pub rooms: BTreeMap<OwnedRoomId, BTreeMap<String, ImagePackRoomContent>>,
}
impl ImagePackRoomsEventContent {
/// Creates a new `ImagePackRoomsEventContent`
/// with a map of enabled image packs in each room.
pub fn new(rooms: BTreeMap<OwnedRoomId, BTreeMap<String, ImagePackRoomContent>>) -> Self {
Self { rooms }
}
}
/// Additional metadatas for a enabled room image pack.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct ImagePackRoomContent {}
impl ImagePackRoomContent {
/// Creates a new empty `ImagePackRoomContent`.
pub fn new() -> Self {
Self {}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room.rs | crates/core/src/events/room.rs | //! Modules for events in the `m.room` namespace.
//!
//! This module also contains types shared by events in its child namespaces.
use std::collections::BTreeMap;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize, de};
use crate::{
OwnedMxcUri,
serde::{Base64, base64::UrlSafe},
};
pub mod aliases;
pub mod avatar;
pub mod canonical_alias;
pub mod create;
pub mod encrypted;
pub mod encryption;
pub mod guest_access;
pub mod history_visibility;
pub mod join_rule;
pub mod member;
pub mod message;
pub mod name;
pub mod pinned_events;
pub mod power_levels;
pub mod redaction;
pub mod server_acl;
pub mod third_party_invite;
mod thumbnail_source_serde;
pub mod tombstone;
pub mod topic;
/// The source of a media file.
#[derive(ToSchema, Clone, Debug, Serialize)]
#[allow(clippy::exhaustive_enums)]
pub enum MediaSource {
/// The MXC URI to the unencrypted media file.
#[serde(rename = "url")]
Plain(OwnedMxcUri),
/// The encryption info of the encrypted media file.
#[serde(rename = "file")]
Encrypted(Box<EncryptedFile>),
}
// Custom implementation of `Deserialize`, because serde doesn't guarantee what
// variant will be deserialized for "externally tagged"¹ enums where multiple
// "tag" fields exist.
//
// ¹ https://serde.rs/enum-representations.html
impl<'de> Deserialize<'de> for MediaSource {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
struct MediaSourceJsonRepr {
url: Option<OwnedMxcUri>,
file: Option<Box<EncryptedFile>>,
}
match MediaSourceJsonRepr::deserialize(deserializer)? {
MediaSourceJsonRepr {
url: None,
file: None,
} => Err(de::Error::missing_field("url")),
// Prefer file if it is set
MediaSourceJsonRepr {
file: Some(file), ..
} => Ok(MediaSource::Encrypted(file)),
MediaSourceJsonRepr { url: Some(url), .. } => Ok(MediaSource::Plain(url)),
}
}
}
/// Metadata about an image.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct ImageInfo {
/// The height of the image in pixels.
#[serde(rename = "h", skip_serializing_if = "Option::is_none")]
pub height: Option<u64>,
/// The width of the image in pixels.
#[serde(rename = "w", skip_serializing_if = "Option::is_none")]
pub width: Option<u64>,
/// The MIME type of the image, e.g. "image/png."
#[serde(skip_serializing_if = "Option::is_none")]
pub mimetype: Option<String>,
/// The file size of the image in bytes.
#[serde(skip_serializing_if = "Option::is_none")]
pub size: Option<u64>,
/// Metadata about the image referred to in `thumbnail_source`.
#[serde(skip_serializing_if = "Option::is_none")]
pub thumbnail_info: Option<Box<ThumbnailInfo>>,
/// The source of the thumbnail of the image.
#[serde(
flatten,
with = "thumbnail_source_serde",
skip_serializing_if = "Option::is_none"
)]
pub thumbnail_source: Option<MediaSource>,
/// The [BlurHash](https://blurha.sh) for this image.
///
/// This uses the unstable prefix in
/// [MSC2448](https://github.com/matrix-org/matrix-spec-proposals/pull/2448).
#[cfg(feature = "unstable-msc2448")]
#[serde(
rename = "xyz.amorgan.blurhash",
skip_serializing_if = "Option::is_none"
)]
pub blurhash: Option<String>,
}
impl ImageInfo {
/// Creates an empty `ImageInfo`.
pub fn new() -> Self {
Self::default()
}
}
/// Metadata about a thumbnail.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct ThumbnailInfo {
/// The height of the thumbnail in pixels.
#[serde(rename = "h", skip_serializing_if = "Option::is_none")]
pub height: Option<u64>,
/// The width of the thumbnail in pixels.
#[serde(rename = "w", skip_serializing_if = "Option::is_none")]
pub width: Option<u64>,
/// The MIME type of the thumbnail, e.g. "image/png."
#[serde(skip_serializing_if = "Option::is_none")]
pub mimetype: Option<String>,
/// The file size of the thumbnail in bytes.
#[serde(skip_serializing_if = "Option::is_none")]
pub size: Option<u64>,
}
impl ThumbnailInfo {
/// Creates an empty `ThumbnailInfo`.
pub fn new() -> Self {
Self::default()
}
}
/// A file sent to a room with end-to-end encryption enabled.
///
/// To create an instance of this type.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct EncryptedFile {
/// The URL to the file.
pub url: OwnedMxcUri,
/// A [JSON Web Key](https://tools.ietf.org/html/rfc7517#appendix-A.3) object.
pub key: JsonWebKey,
/// The 128-bit unique counter block used by AES-CTR, encoded as unpadded
/// base64.
pub iv: Base64,
/// A map from an algorithm name to a hash of the ciphertext, encoded as
/// unpadded base64.
///
/// Clients should support the SHA-256 hash, which uses the key sha256.
pub hashes: BTreeMap<String, Base64>,
/// Version of the encrypted attachments protocol.
///
/// Must be `v2`.
pub v: String,
}
/// A [JSON Web Key](https://tools.ietf.org/html/rfc7517#appendix-A.3) object.
///
/// To create an instance of this type.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct JsonWebKey {
/// Key type.
///
/// Must be `oct`.
pub kty: String,
/// Key operations.
///
/// Must at least contain `encrypt` and `decrypt`.
pub key_ops: Vec<String>,
/// Algorithm.
///
/// Must be `A256CTR`.
pub alg: String,
/// The key, encoded as url-safe unpadded base64.
pub k: Base64<UrlSafe>,
/// Extractable.
///
/// Must be `true`. This is a
/// [W3C extension](https://w3c.github.io/webcrypto/#iana-section-jwk).
pub ext: bool,
}
// #[cfg(test)]
// mod tests {
// use std::collections::BTreeMap;
// use crate::{mxc_uri, serde::Base64};
// use assert_matches2::assert_matches;
// use serde::Deserialize;
// use serde_json::{from_value as from_json_value, json};
// use super::{EncryptedFile, JsonWebKey, MediaSource};
// #[derive(Deserialize)]
// struct MsgWithAttachment {
// #[allow(dead_code)]
// body: String,
// #[serde(flatten)]
// source: MediaSource,
// }
// fn dummy_jwt() -> JsonWebKey {
// JsonWebKey {
// kty: "oct".to_owned(),
// key_ops: vec!["encrypt".to_owned(), "decrypt".to_owned()],
// alg: "A256CTR".to_owned(),
// k: Base64::new(vec![0; 64]),
// ext: true,
// }
// }
// fn encrypted_file() -> EncryptedFile {
// EncryptedFile {
// url: mxc_uri!("mxc://localhost/encryptedfile").to_owned(),
// key: dummy_jwt(),
// iv: Base64::new(vec![0; 64]),
// hashes: BTreeMap::new(),
// v: "v2".to_owned(),
// }
// }
// #[test]
// fn prefer_encrypted_attachment_over_plain() {
// let msg: MsgWithAttachment = from_json_value(json!({
// "body": "",
// "url": "mxc://localhost/file",
// "file": encrypted_file(),
// }))
// .unwrap();
// assert_matches!(msg.source, MediaSource::Encrypted(_));
// // As above, but with the file field before the url field
// let msg: MsgWithAttachment = from_json_value(json!({
// "body": "",
// "file": encrypted_file(),
// "url": "mxc://localhost/file",
// }))
// .unwrap();
// assert_matches!(msg.source, MediaSource::Encrypted(_));
// }
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/sticker.rs | crates/core/src/events/sticker.rs | //! Types for the [`m.sticker`] event.
//!
//! [`m.sticker`]: https://spec.matrix.org/latest/client-server-api/#msticker
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{OwnedMxcUri, events::room::ImageInfo};
/// The content of an `m.sticker` event.
///
/// A sticker message.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.sticker", kind = MessageLike)]
pub struct StickerEventContent {
/// A textual representation or associated description of the sticker image.
///
/// This could be the alt text of the original image, or a message to
/// accompany and further describe the sticker.
pub body: String,
/// Metadata about the image referred to in `url` including a thumbnail
/// representation.
pub info: ImageInfo,
/// The URL to the sticker image.
pub url: OwnedMxcUri,
}
impl StickerEventContent {
/// Creates a new `StickerEventContent` with the given body, image info and
/// URL.
pub fn new(body: String, info: ImageInfo, url: OwnedMxcUri) -> Self {
Self { body, info, url }
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/reaction.rs | crates/core/src/events/reaction.rs | //! Types for the [`m.reaction`] event.
//!
//! [`m.reaction`]: https://spec.matrix.org/latest/client-server-api/#mreaction
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use super::relation::Annotation;
/// The payload for a `m.reaction` event.
///
/// A reaction to another event.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.reaction", kind = MessageLike)]
pub struct ReactionEventContent {
/// Information about the related event.
#[serde(rename = "m.relates_to")]
pub relates_to: Annotation,
}
impl ReactionEventContent {
/// Creates a new `ReactionEventContent` from the given annotation.
///
/// You can also construct a `ReactionEventContent` from an annotation using
/// `From` / `Into`.
pub fn new(relates_to: Annotation) -> Self {
Self { relates_to }
}
}
impl From<Annotation> for ReactionEventContent {
fn from(relates_to: Annotation) -> Self {
Self::new(relates_to)
}
}
// #[cfg(test)]
// mod tests {
// use crate::owned_event_id;
// use assert_matches2::assert_matches;
// use serde_json::{from_value as from_json_value, json, to_value as
// to_json_value};
// use super::ReactionEventContent;
// use crate::events::relation::Annotation;
// #[test]
// fn deserialize() {
// let json = json!({
// "m.relates_to": {
// "rel_type": "m.annotation",
// "event_id": "$1598361704261elfgc:localhost",
// "key": "🦛",
// }
// });
// assert_matches!(
// from_json_value::<ReactionEventContent>(json),
// Ok(ReactionEventContent { relates_to })
// );
// assert_eq!(relates_to.event_id, "$1598361704261elfgc:localhost");
// assert_eq!(relates_to.key, "🦛");
// }
// #[test]
// fn serialize() {
// let content =
// ReactionEventContent::new(Annotation::new(owned_event_id!("$my_reaction"),
// "🏠".to_owned()));
// assert_eq!(
// to_json_value(&content).unwrap(),
// json!({
// "m.relates_to": {
// "rel_type": "m.annotation",
// "event_id": "$my_reaction",
// "key": "🏠"
// }
// })
// );
// }
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/space_order.rs | crates/core/src/events/space_order.rs | //! Types for the [`m.space_order`] event.
//!
//! [`m.space_order`]: https://github.com/matrix-org/matrix-spec-proposals/pull/3230
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::OwnedSpaceChildOrder;
use crate::macros::EventContent;
/// The content of an `m.space_order` event.
///
/// Whether the space has been explicitly ordered.
///
/// This event appears in the user's room account data for the space room in
/// question.
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize, EventContent)]
#[palpo_event(type = "org.matrix.msc3230.space_order", alias = "m.space_order", kind = RoomAccountData)]
pub struct SpaceOrderEventContent {
/// The current space order.
pub order: OwnedSpaceChildOrder,
}
impl SpaceOrderEventContent {
/// Creates a new `SpaceOrderEventContent` with the given order.
pub fn new(order: OwnedSpaceChildOrder) -> Self {
Self { order }
}
}
#[cfg(test)]
mod tests {
use assert_matches2::assert_matches;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::SpaceOrderEventContent;
use crate::SpaceChildOrder;
use crate::events::{AnyRoomAccountDataEvent, RoomAccountDataEvent};
#[test]
fn deserialize() {
let raw_unstable_space_order = json!({
"type": "org.matrix.msc3230.space_order",
"content": {
"order": "a",
},
});
let unstable_space_order_account_data =
from_json_value::<AnyRoomAccountDataEvent>(raw_unstable_space_order).unwrap();
assert_matches!(
unstable_space_order_account_data,
AnyRoomAccountDataEvent::SpaceOrder(unstable_space_order)
);
assert_eq!(
unstable_space_order.content.order,
SpaceChildOrder::parse("a").unwrap()
);
let raw_space_order = json!({
"type": "m.space_order",
"content": {
"order": "b",
},
});
let space_order_account_data =
from_json_value::<AnyRoomAccountDataEvent>(raw_space_order).unwrap();
assert_matches!(
space_order_account_data,
AnyRoomAccountDataEvent::SpaceOrder(space_order)
);
assert_eq!(
space_order.content.order,
SpaceChildOrder::parse("b").unwrap()
);
}
#[test]
fn serialize() {
let space_order = SpaceOrderEventContent::new(SpaceChildOrder::parse("a").unwrap());
let space_order_account_data = RoomAccountDataEvent {
content: space_order,
};
assert_eq!(
to_json_value(space_order_account_data).unwrap(),
json!({
"type": "org.matrix.msc3230.space_order",
"content": {
"order": "a",
},
})
);
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/member_hints.rs | crates/core/src/events/member_hints.rs | //! Types for Matrix member hint state events ([MSC4171]).
//!
//! This implements `m.member_hints` state event described in [MSC4171].
//!
//! [MSC4171]: https://github.com/matrix-org/matrix-spec-proposals/pull/4171
use std::collections::BTreeSet;
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::OwnedUserId;
use crate::events::state_key::EmptyStateKey;
/// The content for an `m.member_hints` state event.
///
/// Any users (service members) listed in the content should not be considered
/// when computing the room name or avatar based on the member list.
#[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize, EventContent, PartialEq)]
#[palpo_event(type = "io.element.functional_members", kind = State, state_key_type = EmptyStateKey)]
pub struct MemberHintsEventContent {
/// The list of user IDs that should be considered a service member of the
/// room.
pub service_members: BTreeSet<OwnedUserId>,
}
impl MemberHintsEventContent {
/// Create a new [`MemberHintsEventContent`] with the given set of service
/// members.
pub fn new(service_members: BTreeSet<OwnedUserId>) -> Self {
Self { service_members }
}
}
#[cfg(test)]
mod test {
use std::collections::BTreeSet;
use assert_matches2::assert_matches;
use serde_json::{from_value as from_json_value, json};
use super::*;
use crate::{events::AnyStateEvent, user_id};
#[test]
fn deserialize() {
let user_id = user_id!("@slackbot:matrix.org");
let data = json!({
"type": "io.element.functional_members",
"state_key": "",
"content": {
"service_members": [
user_id,
]
},
"origin_server_ts": 111,
"event_id": "$3qfxjGYSu4sL25FtR0ep6vePOc",
"room_id": "!1234:example.org",
"sender": "@user:example.org"
});
let event = from_json_value::<AnyStateEvent>(data)
.expect("We should be able to deserialize the member hints event");
assert_matches!(event, AnyStateEvent::MemberHints(event));
assert_matches!(event, crate::events::StateEvent::Original(event));
assert!(event.content.service_members.contains(user_id));
let data = json!({
"type": "m.member_hints",
"state_key": "",
"content": {
"service_members": [
user_id,
]
},
"origin_server_ts": 111,
"event_id": "$3qfxjGYSu4sL25FtR0ep6vePOc",
"room_id": "!1234:example.org",
"sender": "@user:example.org"
});
let event = from_json_value::<AnyStateEvent>(data)
.expect("We should be able to deserialize the member hints event");
assert_matches!(event, AnyStateEvent::MemberHints(event));
assert_matches!(event, crate::events::StateEvent::Original(event));
assert!(event.content.service_members.contains(user_id));
}
#[test]
fn serialize() {
let user_id = user_id!("@slackbot:matrix.org");
let content = MemberHintsEventContent::new(BTreeSet::from([user_id.to_owned()]));
let serialized = serde_json::to_value(content)
.expect("We should be able to serialize the member hints content");
let expected = json!({
"service_members": [
user_id,
]
});
assert_eq!(
expected, serialized,
"The serialized member hints content should match the expected one"
);
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/third_party_invite.rs | crates/core/src/events/room/third_party_invite.rs | //! Types for the [`m.room.third_party_invite`] event.
//!
//! [`m.room.third_party_invite`]: https://spec.matrix.org/latest/client-server-api/#mroomthird_party_invite
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::macros::EventContent;
use crate::serde::Base64;
use crate::third_party_invite::IdentityServerBase64PublicKey;
/// The content of an `m.room.third_party_invite` event.
///
/// An invitation to a room issued to a third party identifier, rather than a
/// matrix user ID.
///
/// Acts as an `m.room.member` invite event, where there isn't a target user_id
/// to invite. This event contains a token and a public key whose private key
/// must be used to sign the token. Any user who can present that signature may
/// use this invitation to join the target room.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.room.third_party_invite", kind = State, state_key_type = String)]
pub struct RoomThirdPartyInviteEventContent {
/// A user-readable string which represents the user who has been invited.
#[serde(default)]
pub display_name: String,
/// A URL which can be fetched to validate whether the key has been revoked.
#[serde(default)]
pub key_validity_url: String,
/// A base64-encoded Ed25519 key with which the token must be signed.
#[serde(default = "empty_identity_server_base64_public_key")]
pub public_key: IdentityServerBase64PublicKey,
/// Keys with which the token may be signed.
#[serde(skip_serializing_if = "Option::is_none")]
pub public_keys: Option<Vec<PublicKey>>,
}
impl RoomThirdPartyInviteEventContent {
/// Creates a new `RoomThirdPartyInviteEventContent` with the given display
/// name, key validity url and public key.
pub fn new(
display_name: String,
key_validity_url: String,
public_key: IdentityServerBase64PublicKey,
) -> Self {
Self {
display_name,
key_validity_url,
public_key,
public_keys: None,
}
}
}
/// A public key for signing a third party invite token.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct PublicKey {
/// An optional URL which can be fetched to validate whether the key has
/// been revoked.
///
/// The URL must return a JSON object containing a boolean property named
/// 'valid'. If this URL is absent, the key must be considered valid
/// indefinitely.
#[serde(skip_serializing_if = "Option::is_none")]
pub key_validity_url: Option<String>,
/// A base64-encoded Ed25519 key with which the token must be signed.
pub public_key: Base64,
}
impl PublicKey {
/// Creates a new `PublicKey` with the given base64-encoded ed25519 key.
pub fn new(public_key: Base64) -> Self {
Self {
key_validity_url: None,
public_key,
}
}
}
/// Generate an empty [`IdentityServerBase64PublicKey`].
fn empty_identity_server_base64_public_key() -> IdentityServerBase64PublicKey {
IdentityServerBase64PublicKey(String::new())
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/avatar.rs | crates/core/src/events/room/avatar.rs | //! Types for the [`m.room.avatar`] event.
//!
//! [`m.room.avatar`]: https://spec.matrix.org/latest/client-server-api/#mroomavatar
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use super::ThumbnailInfo;
use crate::{OwnedMxcUri, events::EmptyStateKey};
/// The content of an `m.room.avatar` event.
///
/// A picture that is associated with the room.
///
/// This can be displayed alongside the room information.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize, EventContent)]
#[palpo_event(type = "m.room.avatar", kind = State, state_key_type = EmptyStateKey)]
pub struct RoomAvatarEventContent {
/// Information about the avatar image.
#[serde(skip_serializing_if = "Option::is_none")]
pub info: Option<Box<ImageInfo>>,
/// URL of the avatar image.
pub url: Option<OwnedMxcUri>,
}
impl RoomAvatarEventContent {
/// Create an empty `RoomAvatarEventContent`.
pub fn new() -> Self {
Self::default()
}
}
/// Metadata about an image (specific to avatars).
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct ImageInfo {
/// The height of the image in pixels.
#[serde(rename = "h", skip_serializing_if = "Option::is_none")]
pub height: Option<u64>,
/// The width of the image in pixels.
#[serde(rename = "w", skip_serializing_if = "Option::is_none")]
pub width: Option<u64>,
/// The MIME type of the image, e.g. "image/png."
#[serde(skip_serializing_if = "Option::is_none")]
pub mimetype: Option<String>,
/// The file size of the image in bytes.
#[serde(skip_serializing_if = "Option::is_none")]
pub size: Option<u64>,
/// Metadata about the image referred to in `thumbnail_url`.
#[serde(skip_serializing_if = "Option::is_none")]
pub thumbnail_info: Option<Box<ThumbnailInfo>>,
/// The URL to the thumbnail of the image.
#[serde(skip_serializing_if = "Option::is_none")]
pub thumbnail_url: Option<OwnedMxcUri>,
/// The [BlurHash](https://blurha.sh) for this image.
///
/// This uses the unstable prefix in
/// [MSC2448](https://github.com/matrix-org/matrix-spec-proposals/pull/2448).
#[cfg(feature = "unstable-msc2448")]
#[serde(
rename = "xyz.amorgan.blurhash",
skip_serializing_if = "Option::is_none"
)]
pub blurhash: Option<String>,
}
impl ImageInfo {
/// Create a new `ImageInfo` with all fields set to `None`.
pub fn new() -> Self {
Self::default()
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/history_visibility.rs | crates/core/src/events/room/history_visibility.rs | //! Types for the [`m.room.history_visibility`] event.
//!
//! [`m.room.history_visibility`]: https://spec.matrix.org/latest/client-server-api/#mroomhistory_visibility
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{PrivOwnedStr, events::EmptyStateKey, serde::StringEnum};
/// The content of an `m.room.history_visibility` event.
///
/// This event controls whether a member of a room can see the events that
/// happened in a room from before they joined.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.room.history_visibility", kind = State, state_key_type = EmptyStateKey)]
pub struct RoomHistoryVisibilityEventContent {
/// Who can see the room history.
#[palpo_event(skip_redaction)]
pub history_visibility: HistoryVisibility,
}
impl RoomHistoryVisibilityEventContent {
/// Creates a new `RoomHistoryVisibilityEventContent` with the given policy.
pub fn new(history_visibility: HistoryVisibility) -> Self {
Self { history_visibility }
}
}
impl RoomHistoryVisibilityEvent {
/// Obtain the history visibility, regardless of whether this event is
/// redacted.
pub fn history_visibility(&self) -> &HistoryVisibility {
match self {
Self::Original(ev) => &ev.content.history_visibility,
Self::Redacted(ev) => &ev.content.history_visibility,
}
}
}
impl SyncRoomHistoryVisibilityEvent {
/// Obtain the history visibility, regardless of whether this event is
/// redacted.
pub fn history_visibility(&self) -> &HistoryVisibility {
match self {
Self::Original(ev) => &ev.content.history_visibility,
Self::Redacted(ev) => &ev.content.history_visibility,
}
}
}
/// Who can see a room's history.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[palpo_enum(rename_all = "snake_case")]
#[non_exhaustive]
pub enum HistoryVisibility {
/// Previous events are accessible to newly joined members from the point
/// they were invited onwards.
///
/// Events stop being accessible when the member's state changes to
/// something other than *invite* or *join*.
Invited,
/// Previous events are accessible to newly joined members from the point
/// they joined the room onwards.
/// Events stop being accessible when the member's state changes to
/// something other than *join*.
Joined,
/// Previous events are always accessible to newly joined members.
///
/// All events in the room are accessible, even those sent when the member
/// was not a part of the room.
Shared,
/// All events while this is the `HistoryVisibility` value may be shared by
/// any participating homeserver with anyone, regardless of whether they
/// have ever joined the room.
WorldReadable,
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(PrivOwnedStr),
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/power_levels.rs | crates/core/src/events/room/power_levels.rs | //! Types for the [`m.room.power_levels`] event.
//!
//! [`m.room.power_levels`]: https://spec.matrix.org/latest/client-server-api/#mroompower_levels
use std::{
cmp::{Ordering, max},
collections::BTreeMap,
};
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::events::{
EmptyStateKey, MessageLikeEventType, RedactContent, RedactedStateEventContent, StateEventType,
StaticEventContent, TimelineEventType,
};
use crate::macros::EventContent;
use crate::{
OwnedUserId, UserId,
power_levels::{NotificationPowerLevels, default_power_level},
push::PushConditionPowerLevelsCtx,
room_version_rules::{AuthorizationRules, RedactionRules, RoomPowerLevelsRules},
};
/// The content of an `m.room.power_levels` event.
///
/// Defines the power levels (privileges) of users in the room.
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize, EventContent)]
#[palpo_event(type = "m.room.power_levels", kind = State, state_key_type = EmptyStateKey, custom_redacted)]
pub struct RoomPowerLevelsEventContent {
/// The level required to ban a user.
#[serde(
default = "default_power_level",
// skip_serializing_if = "is_default_power_level",
deserialize_with = "crate::serde::deserialize_v1_power_level"
)]
pub ban: i64,
/// The level required to send specific event types.
///
/// This is a mapping from event type to power level required.
#[serde(
default,
// skip_serializing_if = "BTreeMap::is_empty",
deserialize_with = "crate::serde::btreemap_deserialize_v1_power_level_values"
)]
pub events: BTreeMap<TimelineEventType, i64>,
/// The default level required to send message events.
#[serde(
default,
// skip_serializing_if = "crate::serde::is_default",
deserialize_with = "crate::serde::deserialize_v1_power_level"
)]
pub events_default: i64,
/// The level required to invite a user.
#[serde(
default = "default_power_level",
// skip_serializing_if = "crate::serde::is_default",
deserialize_with = "crate::serde::deserialize_v1_power_level"
)]
pub invite: i64,
/// The level required to kick a user.
#[serde(
default = "default_power_level",
// skip_serializing_if = "is_default_power_level",
deserialize_with = "crate::serde::deserialize_v1_power_level"
)]
pub kick: i64,
/// The level required to redact an event.
#[serde(
default = "default_power_level",
// skip_serializing_if = "is_default_power_level",
deserialize_with = "crate::serde::deserialize_v1_power_level"
)]
pub redact: i64,
/// The default level required to send state events.
#[serde(
default = "default_power_level",
// skip_serializing_if = "is_default_power_level",
deserialize_with = "crate::serde::deserialize_v1_power_level"
)]
pub state_default: i64,
/// The power levels for specific users.
///
/// This is a mapping from `user_id` to power level for that user.
#[serde(
default,
// skip_serializing_if = "BTreeMap::is_empty",
deserialize_with = "crate::serde::btreemap_deserialize_v1_power_level_values"
)]
pub users: BTreeMap<OwnedUserId, i64>,
/// The default power level for every user in the room.
#[serde(
default,
// skip_serializing_if = "crate::serde::is_default",
deserialize_with = "crate::serde::deserialize_v1_power_level"
)]
pub users_default: i64,
/// The power level requirements for specific notification types.
///
/// This is a mapping from `key` to power level for that notifications key.
// #[serde(default, skip_serializing_if = "NotificationPowerLevels::is_default")]
#[serde(default)]
pub notifications: NotificationPowerLevels,
}
impl RoomPowerLevelsEventContent {
/// Creates a new `RoomPowerLevelsEventContent` with all-default values for the given
/// authorization rules.
pub fn new(rules: &AuthorizationRules) -> Self {
// events_default, users_default and invite having a default of 0 while the others have a
// default of 50 is not an oversight, these defaults are from the Matrix specification.
let mut pl = Self {
ban: default_power_level(),
events: BTreeMap::new(),
events_default: 0,
// matrix spec is 0, but complement test and synapse set to 50.
// https://github.com/matrix-org/synapse/pull/6834
invite: 50,
kick: default_power_level(),
redact: default_power_level(),
state_default: default_power_level(),
users: BTreeMap::new(),
users_default: 0,
notifications: NotificationPowerLevels::default(),
};
if rules.explicitly_privilege_room_creators {
// Since v12, the default power level to send m.room.tombstone events is increased to
// PL150.
pl.events.insert(TimelineEventType::RoomTombstone, 150);
}
pl
}
}
impl RedactContent for RoomPowerLevelsEventContent {
type Redacted = RedactedRoomPowerLevelsEventContent;
fn redact(self, rules: &RedactionRules) -> Self::Redacted {
let Self {
ban,
events,
events_default,
invite,
kick,
redact,
state_default,
users,
users_default,
..
} = self;
let invite = if rules.keep_room_power_levels_invite {
invite
} else {
0
};
RedactedRoomPowerLevelsEventContent {
ban,
events,
events_default,
invite,
kick,
redact,
state_default,
users,
users_default,
}
}
}
/// Used with `#[serde(skip_serializing_if)]` to omit default power levels.
#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_default_power_level(l: &i64) -> bool {
*l == 50
}
impl RoomPowerLevelsEvent {
/// Obtain the effective power levels, regardless of whether this event is redacted.
pub fn power_levels(
&self,
rules: &AuthorizationRules,
creators: Vec<OwnedUserId>,
) -> RoomPowerLevels {
match self {
Self::Original(ev) => RoomPowerLevels::new(ev.content.clone().into(), rules, creators),
Self::Redacted(ev) => RoomPowerLevels::new(ev.content.clone().into(), rules, creators),
}
}
}
impl SyncRoomPowerLevelsEvent {
/// Obtain the effective power levels, regardless of whether this event is redacted.
pub fn power_levels(
&self,
rules: &AuthorizationRules,
creators: Vec<OwnedUserId>,
) -> RoomPowerLevels {
match self {
Self::Original(ev) => RoomPowerLevels::new(ev.content.clone().into(), rules, creators),
Self::Redacted(ev) => RoomPowerLevels::new(ev.content.clone().into(), rules, creators),
}
}
}
impl StrippedRoomPowerLevelsEvent {
/// Obtain the effective power levels from this event.
pub fn power_levels(
&self,
rules: &AuthorizationRules,
creators: Vec<OwnedUserId>,
) -> RoomPowerLevels {
RoomPowerLevels::new(self.content.clone().into(), rules, creators)
}
}
/// Redacted form of [`RoomPowerLevelsEventContent`].
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize)]
pub struct RedactedRoomPowerLevelsEventContent {
/// The level required to ban a user.
#[serde(
default = "default_power_level",
skip_serializing_if = "is_default_power_level",
deserialize_with = "crate::serde::deserialize_v1_power_level"
)]
pub ban: i64,
/// The level required to send specific event types.
///
/// This is a mapping from event type to power level required.
#[serde(
default,
skip_serializing_if = "BTreeMap::is_empty",
deserialize_with = "crate::serde::btreemap_deserialize_v1_power_level_values"
)]
pub events: BTreeMap<TimelineEventType, i64>,
/// The default level required to send message events.
#[serde(
default,
skip_serializing_if = "crate::serde::is_default",
deserialize_with = "crate::serde::deserialize_v1_power_level"
)]
pub events_default: i64,
/// The level required to invite a user.
///
/// This field was redacted in room versions 1 through 10. Starting from room version 11 it is
/// preserved.
#[serde(
default,
skip_serializing_if = "crate::serde::is_default",
deserialize_with = "crate::serde::deserialize_v1_power_level"
)]
pub invite: i64,
/// The level required to kick a user.
#[serde(
default = "default_power_level",
skip_serializing_if = "is_default_power_level",
deserialize_with = "crate::serde::deserialize_v1_power_level"
)]
pub kick: i64,
/// The level required to redact an event.
#[serde(
default = "default_power_level",
skip_serializing_if = "is_default_power_level",
deserialize_with = "crate::serde::deserialize_v1_power_level"
)]
pub redact: i64,
/// The default level required to send state events.
#[serde(
default = "default_power_level",
skip_serializing_if = "is_default_power_level",
deserialize_with = "crate::serde::deserialize_v1_power_level"
)]
pub state_default: i64,
/// The power levels for specific users.
///
/// This is a mapping from `user_id` to power level for that user.
#[serde(
default,
skip_serializing_if = "BTreeMap::is_empty",
deserialize_with = "crate::serde::btreemap_deserialize_v1_power_level_values"
)]
pub users: BTreeMap<OwnedUserId, i64>,
/// The default power level for every user in the room.
#[serde(
default,
skip_serializing_if = "crate::serde::is_default",
deserialize_with = "crate::serde::deserialize_v1_power_level"
)]
pub users_default: i64,
}
impl StaticEventContent for RedactedRoomPowerLevelsEventContent {
const TYPE: &'static str = RoomPowerLevelsEventContent::TYPE;
type IsPrefix = <RoomPowerLevelsEventContent as StaticEventContent>::IsPrefix;
}
impl RedactedStateEventContent for RedactedRoomPowerLevelsEventContent {
type StateKey = EmptyStateKey;
fn event_type(&self) -> StateEventType {
StateEventType::RoomPowerLevels
}
}
/// The power level of a particular user.
///
/// Is either considered "infinite" if that user is a room creator, or an integer if they are not.
#[derive(PartialEq, Copy, Clone, Eq, Debug)]
pub enum UserPowerLevel {
/// The user is considered to have "infinite" power level, due to being a room creator, from
/// room version 12 onwards.
Infinite,
/// The user is either not a creator, or the room version is prior to 12, and hence has an
/// integer power level.
Int(i64),
}
impl Ord for UserPowerLevel {
fn cmp(&self, other: &Self) -> Ordering {
match (self, other) {
(UserPowerLevel::Infinite, UserPowerLevel::Infinite) => Ordering::Equal,
(UserPowerLevel::Infinite, UserPowerLevel::Int(_)) => Ordering::Greater,
(UserPowerLevel::Int(_), UserPowerLevel::Infinite) => Ordering::Less,
(UserPowerLevel::Int(self_int), UserPowerLevel::Int(other_int)) => {
self_int.cmp(other_int)
}
}
}
}
impl PartialOrd for UserPowerLevel {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq<i64> for UserPowerLevel {
fn eq(&self, other: &i64) -> bool {
match self {
UserPowerLevel::Infinite => false,
UserPowerLevel::Int(int) => int.eq(other),
}
}
}
impl PartialEq<UserPowerLevel> for i64 {
fn eq(&self, other: &UserPowerLevel) -> bool {
other.eq(self)
}
}
impl PartialOrd<i64> for UserPowerLevel {
fn partial_cmp(&self, other: &i64) -> Option<Ordering> {
match self {
UserPowerLevel::Infinite => Some(Ordering::Greater),
UserPowerLevel::Int(int) => int.partial_cmp(other),
}
}
}
impl PartialOrd<UserPowerLevel> for i64 {
fn partial_cmp(&self, other: &UserPowerLevel) -> Option<Ordering> {
match other {
UserPowerLevel::Infinite => Some(Ordering::Less),
UserPowerLevel::Int(int) => self.partial_cmp(int),
}
}
}
impl From<i64> for UserPowerLevel {
fn from(value: i64) -> Self {
Self::Int(value)
}
}
/// The effective power levels of a room.
///
/// This struct contains all the power levels settings from the specification and can be constructed
/// from several [`RoomPowerLevelsSource`]s, which means that it can be used when wanting to inspect
/// the power levels of a room, regardless of whether the most recent power levels event is redacted
/// or not, or the room has no power levels event.
///
/// This can also be used to change the power levels of a room by mutating it and then converting it
/// to a [`RoomPowerLevelsEventContent`] using `RoomPowerLevelsEventContent::try_from` /
/// `.try_into()`. This allows to validate the format of the power levels before sending them. Note
/// that the homeserver might still refuse the power levels changes depending on the current power
/// level of the sender.
#[derive(Clone, Debug)]
pub struct RoomPowerLevels {
/// The level required to ban a user.
///
/// When built from [`RoomPowerLevelsSource::None`], defaults to `50`.
pub ban: i64,
/// The level required to send specific event types.
///
/// This is a mapping from event type to power level required.
///
/// When built from [`RoomPowerLevelsSource::None`], defaults to an empty map.
pub events: BTreeMap<TimelineEventType, i64>,
/// The default level required to send message events.
///
/// When built from [`RoomPowerLevelsSource::None`], defaults to `0`.
pub events_default: i64,
/// The level required to invite a user.
///
/// When built from [`RoomPowerLevelsSource::None`], defaults to `0`.
pub invite: i64,
/// The level required to kick a user.
///
/// When built from [`RoomPowerLevelsSource::None`], defaults to `50`.
pub kick: i64,
/// The level required to redact an event.
///
/// When built from [`RoomPowerLevelsSource::None`], defaults to `50`.
pub redact: i64,
/// The default level required to send state events.
///
/// When built from [`RoomPowerLevelsSource::None`], defaults to `50`.
pub state_default: i64,
/// The power levels for specific users.
///
/// This is a mapping from `user_id` to power level for that user.
///
/// Must NOT contain creators of the room in room versions where the
/// `explicitly_privilege_room_creators` field of [`AuthorizationRules`] is set to `true`. This
/// would result in an error when trying to convert this to a [`RoomPowerLevelsEventContent`].
///
/// When built from [`RoomPowerLevelsSource::None`]:
///
/// * If `explicitly_privilege_room_creators` is set to `false` for the room version, defaults
/// to setting the power level to `100` for the creator(s) of the room.
/// * Otherwise, defaults to an empty map.
pub users: BTreeMap<OwnedUserId, i64>,
/// The default power level for every user in the room.
///
/// When built from [`RoomPowerLevelsSource::None`], defaults to `0`.
pub users_default: i64,
/// The power level requirements for specific notification types.
///
/// This is a mapping from `key` to power level for that notifications key.
///
/// When built from [`RoomPowerLevelsSource::None`], uses its `Default` implementation.
pub notifications: NotificationPowerLevels,
/// The tweaks for determining the power level of a user.
pub rules: RoomPowerLevelsRules,
}
impl RoomPowerLevels {
/// Constructs `RoomPowerLevels` from `RoomPowerLevelsSource`, `AuthorizationRules` and the
/// creators of a room.
pub fn new(
power_levels: RoomPowerLevelsSource,
rules: &AuthorizationRules,
creators: impl IntoIterator<Item = OwnedUserId> + Clone,
) -> Self {
match power_levels {
RoomPowerLevelsSource::Original(RoomPowerLevelsEventContent {
ban,
events,
events_default,
invite,
kick,
redact,
state_default,
users,
users_default,
notifications,
}) => Self {
ban,
events,
events_default,
invite,
kick,
redact,
state_default,
users,
users_default,
notifications,
rules: RoomPowerLevelsRules::new(rules, creators),
},
RoomPowerLevelsSource::Redacted(RedactedRoomPowerLevelsEventContent {
ban,
events,
events_default,
invite,
kick,
redact,
state_default,
users,
users_default,
}) => Self {
ban,
events,
events_default,
invite,
kick,
redact,
state_default,
users,
users_default,
notifications: NotificationPowerLevels::new(),
rules: RoomPowerLevelsRules::new(rules, creators),
},
// events_default, users_default and invite having a default of 0 while the others have
// a default of 50 is not an oversight, these defaults are from the Matrix specification.
RoomPowerLevelsSource::None => Self {
ban: default_power_level(),
events: BTreeMap::new(),
events_default: 0,
invite: 0,
kick: default_power_level(),
redact: default_power_level(),
state_default: default_power_level(),
users: if rules.explicitly_privilege_room_creators {
BTreeMap::new()
} else {
// If creators are not explicitly privileged, their power level is 100 if there
// is no power levels state.
BTreeMap::from_iter(creators.clone().into_iter().map(|user| (user, 100)))
},
users_default: 0,
notifications: NotificationPowerLevels::default(),
rules: RoomPowerLevelsRules::new(rules, creators),
},
}
}
/// Whether the given user ID is a privileged creator.
fn is_privileged_creator(&self, user_id: &UserId) -> bool {
self.rules
.privileged_creators
.as_ref()
.is_some_and(|creators| creators.contains(user_id))
}
/// Get the power level of a specific user.
pub fn for_user(&self, user_id: &UserId) -> UserPowerLevel {
if self.is_privileged_creator(user_id) {
return UserPowerLevel::Infinite;
}
self.users
.get(user_id)
.map_or(self.users_default, |pl| *pl)
.into()
}
/// Get the power level required to perform a given action.
pub fn for_action(&self, action: PowerLevelAction) -> i64 {
match action {
PowerLevelAction::Ban => self.ban,
PowerLevelAction::Unban => self.ban.max(self.kick),
PowerLevelAction::Invite => self.invite,
PowerLevelAction::Kick => self.kick,
PowerLevelAction::RedactOwn => self.for_message(MessageLikeEventType::RoomRedaction),
PowerLevelAction::RedactOther => self
.redact
.max(self.for_message(MessageLikeEventType::RoomRedaction)),
PowerLevelAction::SendMessage(msg_type) => self.for_message(msg_type),
PowerLevelAction::SendState(state_type) => self.for_state(state_type),
PowerLevelAction::TriggerNotification(NotificationPowerLevelType::Room) => {
self.notifications.room
}
}
}
/// Get the power level required to send the given message type.
pub fn for_message(&self, msg_type: MessageLikeEventType) -> i64 {
self.events
.get(&msg_type.into())
.copied()
.unwrap_or(self.events_default)
}
/// Get the power level required to send the given state event type.
pub fn for_state(&self, state_type: StateEventType) -> i64 {
self.events
.get(&state_type.into())
.copied()
.unwrap_or(self.state_default)
}
/// Whether the given user can ban other users based on the power levels.
///
/// Shorthand for `power_levels.user_can_do(user_id, PowerLevelAction::Ban)`.
pub fn user_can_ban(&self, user_id: &UserId) -> bool {
self.for_user(user_id) >= self.ban
}
/// Whether the acting user can ban the target user based on the power levels.
///
/// On top of `power_levels.user_can_ban(acting_user_id)`, this performs an extra check
/// to make sure the acting user has at greater power level than the target user.
///
/// Shorthand for `power_levels.user_can_do_to_user(acting_user_id, target_user_id,
/// PowerLevelUserAction::Ban)`.
pub fn user_can_ban_user(&self, acting_user_id: &UserId, target_user_id: &UserId) -> bool {
let acting_pl = self.for_user(acting_user_id);
let target_pl = self.for_user(target_user_id);
acting_pl >= self.ban && target_pl < acting_pl
}
/// Whether the given user can unban other users based on the power levels.
///
/// This action requires to be allowed to ban and to kick.
///
/// Shorthand for `power_levels.user_can_do(user_id, PowerLevelAction::Unban)`.
pub fn user_can_unban(&self, user_id: &UserId) -> bool {
let pl = self.for_user(user_id);
pl >= self.ban && pl >= self.kick
}
/// Whether the acting user can unban the target user based on the power levels.
///
/// This action requires to be allowed to ban and to kick.
///
/// On top of `power_levels.user_can_unban(acting_user_id)`, this performs an extra check
/// to make sure the acting user has at greater power level than the target user.
///
/// Shorthand for `power_levels.user_can_do_to_user(acting_user_id, target_user_id,
/// PowerLevelUserAction::Unban)`.
pub fn user_can_unban_user(&self, acting_user_id: &UserId, target_user_id: &UserId) -> bool {
let acting_pl = self.for_user(acting_user_id);
let target_pl = self.for_user(target_user_id);
acting_pl >= self.ban && acting_pl >= self.kick && target_pl < acting_pl
}
/// Whether the given user can invite other users based on the power levels.
///
/// Shorthand for `power_levels.user_can_do(user_id, PowerLevelAction::Invite)`.
pub fn user_can_invite(&self, user_id: &UserId) -> bool {
self.for_user(user_id) >= self.invite
}
/// Whether the given user can kick other users based on the power levels.
///
/// Shorthand for `power_levels.user_can_do(user_id, PowerLevelAction::Kick)`.
pub fn user_can_kick(&self, user_id: &UserId) -> bool {
self.for_user(user_id) >= self.kick
}
/// Whether the acting user can kick the target user based on the power levels.
///
/// On top of `power_levels.user_can_kick(acting_user_id)`, this performs an extra check
/// to make sure the acting user has at least the same power level as the target user.
///
/// Shorthand for `power_levels.user_can_do_to_user(acting_user_id, target_user_id,
/// PowerLevelUserAction::Kick)`.
pub fn user_can_kick_user(&self, acting_user_id: &UserId, target_user_id: &UserId) -> bool {
let acting_pl = self.for_user(acting_user_id);
let target_pl = self.for_user(target_user_id);
acting_pl >= self.kick && target_pl < acting_pl
}
/// Whether the given user can redact their own events based on the power levels.
///
/// Shorthand for `power_levels.user_can_do(user_id, PowerLevelAction::RedactOwn)`.
pub fn user_can_redact_own_event(&self, user_id: &UserId) -> bool {
self.user_can_send_message(user_id, MessageLikeEventType::RoomRedaction)
}
/// Whether the given user can redact events of other users based on the power levels.
///
/// Shorthand for `power_levels.user_can_do(user_id, PowerLevelAction::RedactOthers)`.
pub fn user_can_redact_event_of_other(&self, user_id: &UserId) -> bool {
self.user_can_redact_own_event(user_id) && self.for_user(user_id) >= self.redact
}
/// Whether the given user can send message events based on the power levels.
///
/// Shorthand for `power_levels.user_can_do(user_id, PowerLevelAction::SendMessage(msg_type))`.
pub fn user_can_send_message(&self, user_id: &UserId, msg_type: MessageLikeEventType) -> bool {
self.for_user(user_id) >= self.for_message(msg_type)
}
/// Whether the given user can send state events based on the power levels.
///
/// Shorthand for `power_levels.user_can_do(user_id, PowerLevelAction::SendState(state_type))`.
pub fn user_can_send_state(&self, user_id: &UserId, state_type: StateEventType) -> bool {
self.for_user(user_id) >= self.for_state(state_type)
}
/// Whether the given user can notify everybody in the room by writing `@room` in a message.
///
/// Shorthand for `power_levels.user_can_do(user_id,
/// PowerLevelAction::TriggerNotification(NotificationPowerLevelType::Room))`.
pub fn user_can_trigger_room_notification(&self, user_id: &UserId) -> bool {
self.for_user(user_id) >= self.notifications.room
}
/// Whether the acting user can change the power level of the target user.
///
/// Shorthand for `power_levels.user_can_do_to_user(acting_user_id, target_user_id,
/// PowerLevelUserAction::ChangePowerLevel`.
pub fn user_can_change_user_power_level(
&self,
acting_user_id: &UserId,
target_user_id: &UserId,
) -> bool {
// Check that the user can change the power levels first.
if !self.user_can_send_state(acting_user_id, StateEventType::RoomPowerLevels) {
return false;
}
// No one can change the power level of a privileged creator.
if self.is_privileged_creator(target_user_id) {
return false;
}
// A user can change their own power level.
if acting_user_id == target_user_id {
return true;
}
// The permission is different whether the target user is added or changed/removed, so
// we need to check that.
if let Some(target_pl) = self.users.get(target_user_id).copied() {
self.for_user(acting_user_id) > target_pl
} else {
true
}
}
/// Whether the given user can do the given action based on the power levels.
pub fn user_can_do(&self, user_id: &UserId, action: PowerLevelAction) -> bool {
match action {
PowerLevelAction::Ban => self.user_can_ban(user_id),
PowerLevelAction::Unban => self.user_can_unban(user_id),
PowerLevelAction::Invite => self.user_can_invite(user_id),
PowerLevelAction::Kick => self.user_can_kick(user_id),
PowerLevelAction::RedactOwn => self.user_can_redact_own_event(user_id),
PowerLevelAction::RedactOther => self.user_can_redact_event_of_other(user_id),
PowerLevelAction::SendMessage(message_type) => {
self.user_can_send_message(user_id, message_type)
}
PowerLevelAction::SendState(state_type) => {
self.user_can_send_state(user_id, state_type)
}
PowerLevelAction::TriggerNotification(NotificationPowerLevelType::Room) => {
self.user_can_trigger_room_notification(user_id)
}
}
}
/// Whether the acting user can do the given action to the target user based on the power
/// levels.
pub fn user_can_do_to_user(
&self,
acting_user_id: &UserId,
target_user_id: &UserId,
action: PowerLevelUserAction,
) -> bool {
match action {
PowerLevelUserAction::Ban => self.user_can_ban_user(acting_user_id, target_user_id),
PowerLevelUserAction::Unban => self.user_can_unban_user(acting_user_id, target_user_id),
PowerLevelUserAction::Invite => self.user_can_invite(acting_user_id),
PowerLevelUserAction::Kick => self.user_can_kick_user(acting_user_id, target_user_id),
PowerLevelUserAction::ChangePowerLevel => {
self.user_can_change_user_power_level(acting_user_id, target_user_id)
}
}
}
/// Get the maximum power level of any user.
pub fn max(&self) -> i64 {
self.users
.values()
.fold(self.users_default, |max_pl, user_pl| max(max_pl, *user_pl))
}
}
/// An error encountered when trying to build a [`RoomPowerLevelsEventContent`] from
/// [`RoomPowerLevels`].
#[derive(Copy, Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum PowerLevelsError {
/// A creator is in the `users` map, and it is not allowed by the current room version.
#[error("a creator is in the `users` map, and it is not allowed by the current room version")]
CreatorInUsersMap,
}
impl TryFrom<RoomPowerLevels> for RoomPowerLevelsEventContent {
type Error = PowerLevelsError;
fn try_from(c: RoomPowerLevels) -> Result<Self, Self::Error> {
if c.rules
.privileged_creators
.as_ref()
.is_some_and(|creators| {
!c.users.is_empty() && creators.iter().any(|user_id| c.users.contains_key(user_id))
})
{
return Err(PowerLevelsError::CreatorInUsersMap);
}
Ok(Self {
ban: c.ban,
events: c.events,
events_default: c.events_default,
invite: c.invite,
kick: c.kick,
redact: c.redact,
state_default: c.state_default,
users: c.users,
users_default: c.users_default,
notifications: c.notifications,
})
}
}
impl From<RoomPowerLevels> for PushConditionPowerLevelsCtx {
fn from(c: RoomPowerLevels) -> Self {
Self::new(c.users, c.users_default, c.notifications, c.rules)
}
}
/// The possible power level sources for [`RoomPowerLevels`].
#[derive(Default)]
pub enum RoomPowerLevelsSource {
/// Construct `RoomPowerLevels` from the non-redacted `m.room.power_levels` event content.
Original(RoomPowerLevelsEventContent),
/// Construct `RoomPowerLevels` from the redacted `m.room.power_levels` event content.
Redacted(RedactedRoomPowerLevelsEventContent),
/// Use the default values defined in the specification.
///
/// Should only be used when there is no power levels state in a room.
#[default]
None,
}
impl From<Option<RoomPowerLevelsEventContent>> for RoomPowerLevelsSource {
fn from(value: Option<RoomPowerLevelsEventContent>) -> Self {
value.map(Self::Original).unwrap_or_default()
}
}
impl From<Option<RedactedRoomPowerLevelsEventContent>> for RoomPowerLevelsSource {
fn from(value: Option<RedactedRoomPowerLevelsEventContent>) -> Self {
value.map(Self::Redacted).unwrap_or_default()
}
}
impl From<RoomPowerLevelsEventContent> for RoomPowerLevelsSource {
fn from(value: RoomPowerLevelsEventContent) -> Self {
Self::Original(value)
}
}
impl From<RedactedRoomPowerLevelsEventContent> for RoomPowerLevelsSource {
fn from(value: RedactedRoomPowerLevelsEventContent) -> Self {
Self::Redacted(value)
}
}
/// The actions that can be limited by power levels.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum PowerLevelAction {
/// Ban a user.
Ban,
/// Unban a user.
Unban,
/// Invite a user.
Invite,
/// Kick a user.
Kick,
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | true |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/join_rule.rs | crates/core/src/events/room/join_rule.rs | //! Types for the [`m.room.join_rules`] event.
//!
//! [`m.room.join_rules`]: https://spec.matrix.org/latest/client-server-api/#mroomjoin_rules
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize, de::Deserializer};
use crate::macros::EventContent;
use crate::{
events::EmptyStateKey,
room::{AllowRule, JoinRule, Restricted},
};
/// The content of an `m.room.join_rules` event.
///
/// Describes how users are allowed to join the room.
#[derive(ToSchema, Clone, Debug, Serialize, EventContent)]
#[palpo_event(type = "m.room.join_rules", kind = State, state_key_type = EmptyStateKey)]
#[serde(transparent)]
pub struct RoomJoinRulesEventContent {
/// The rule used for users wishing to join this room.
#[palpo_event(skip_redaction)]
#[serde(flatten)]
#[salvo(schema(value_type = Object, additional_properties = true))]
pub join_rule: JoinRule,
}
impl RoomJoinRulesEventContent {
/// Creates a new `RoomJoinRulesEventContent` with the given rule.
pub fn new(join_rule: JoinRule) -> Self {
Self { join_rule }
}
/// Creates a new `RoomJoinRulesEventContent` with the restricted rule and
/// the given set of allow rules.
pub fn restricted(allow: Vec<AllowRule>) -> Self {
Self {
join_rule: JoinRule::Restricted(Restricted::new(allow)),
}
}
/// Creates a new `RoomJoinRulesEventContent` with the knock restricted rule
/// and the given set of allow rules.
pub fn knock_restricted(allow: Vec<AllowRule>) -> Self {
Self {
join_rule: JoinRule::KnockRestricted(Restricted::new(allow)),
}
}
}
impl<'de> Deserialize<'de> for RoomJoinRulesEventContent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let join_rule = JoinRule::deserialize(deserializer)?;
Ok(RoomJoinRulesEventContent { join_rule })
}
}
impl RoomJoinRulesEvent {
/// Obtain the join rule, regardless of whether this event is redacted.
pub fn join_rule(&self) -> &JoinRule {
match self {
Self::Original(ev) => &ev.content.join_rule,
Self::Redacted(ev) => &ev.content.join_rule,
}
}
}
impl SyncRoomJoinRulesEvent {
/// Obtain the join rule, regardless of whether this event is redacted.
pub fn join_rule(&self) -> &JoinRule {
match self {
Self::Original(ev) => &ev.content.join_rule,
Self::Redacted(ev) => &ev.content.join_rule,
}
}
}
// #[cfg(test)]
// mod tests {
// use assert_matches2::assert_matches;
// use crate::owned_room_id;
// use serde_json::json;
// use super::{
// AllowRule, JoinRule, OriginalSyncRoomJoinRulesEvent, RedactedRoomJoinRulesEventContent,
// RoomJoinRulesEventContent,
// };
// use crate::room::join_rules::RedactedSyncRoomJoinRulesEvent;
// #[test]
// fn deserialize_content() {
// let json = r#"{"join_rule": "public"}"#;
// let event: RoomJoinRulesEventContent = serde_json::from_str(json).unwrap();
// assert_matches!(
// event,
// RoomJoinRulesEventContent {
// join_rule: JoinRule::Public
// }
// );
// let event: RedactedRoomJoinRulesEventContent = serde_json::from_str(json).unwrap();
// assert_matches!(
// event,
// RedactedRoomJoinRulesEventContent {
// join_rule: JoinRule::Public
// }
// );
// }
// #[test]
// fn deserialize_restricted() {
// let json = r#"{
// "join_rule": "restricted",
// "allow": [
// {
// "type": "m.room_membership",
// "room_id": "!mods:example.org"
// },
// {
// "type": "m.room_membership",
// "room_id": "!users:example.org"
// }
// ]
// }"#;
// let event: RoomJoinRulesEventContent = serde_json::from_str(json).unwrap();
// assert_matches!(event.join_rule, JoinRule::Restricted(restricted));
// assert_eq!(
// restricted.allow,
// &[
// AllowRule::room_membership(owned_room_id!("!mods:example.org")),
// AllowRule::room_membership(owned_room_id!("!users:example.org"))
// ]
// );
// let event: RedactedRoomJoinRulesEventContent = serde_json::from_str(json).unwrap();
// assert_matches!(event.join_rule, JoinRule::Restricted(restricted));
// assert_eq!(
// restricted.allow,
// &[
// AllowRule::room_membership(owned_room_id!("!mods:example.org")),
// AllowRule::room_membership(owned_room_id!("!users:example.org"))
// ]
// );
// }
// #[test]
// fn deserialize_restricted_event() {
// let json = r#"{
// "type": "m.room.join_rules",
// "sender": "@admin:community.rs",
// "content": {
// "join_rule": "restricted",
// "allow": [
// { "type": "m.room_membership","room_id": "!KqeUnzmXPIhHRaWMTs:mccarty.io" }
// ]
// },
// "state_key": "",
// "origin_server_ts":1630508835342,
// "unsigned": {
// "age":4165521871
// },
// "event_id": "$0ACb9KSPlT3al3kikyRYvFhMqXPP9ZcQOBrsdIuh58U"
// }"#;
// assert_matches!(
// serde_json::from_str::<OriginalSyncRoomJoinRulesEvent>(json),
// Ok(_)
// );
// }
// #[test]
// fn deserialize_redacted_restricted_event() {
// let json = r#"{
// "type": "m.room.join_rules",
// "sender": "@admin:community.rs",
// "content": {
// "join_rule": "restricted",
// "allow": [
// { "type": "m.room_membership","room_id": "!KqeUnzmXPIhHRaWMTs:mccarty.io" }
// ]
// },
// "state_key": "",
// "origin_server_ts":1630508835342,
// "unsigned": {
// "age":4165521871,
// "redacted_because": {
// "type": "m.room.redaction",
// "content": {
// "redacts": "$0ACb9KSPlT3al3kikyRYvFhMqXPP9ZcQOBrsdIuh58U"
// },
// "event_id": "$h29iv0s8",
// "origin_server_ts": 1,
// "sender": "@carl:example.com"
// }
// },
// "event_id": "$0ACb9KSPlT3al3kikyRYvFhMqXPP9ZcQOBrsdIuh58U"
// }"#;
// assert_matches!(
// serde_json::from_str::<RedactedSyncRoomJoinRulesEvent>(json),
// Ok(_)
// );
// }
// #[test]
// fn restricted_room_no_allow_field() {
// let json = r#"{"join_rule":"restricted"}"#;
// let join_rules: RoomJoinRulesEventContent = serde_json::from_str(json).unwrap();
// assert_matches!(
// join_rules,
// RoomJoinRulesEventContent {
// join_rule: JoinRule::Restricted(_)
// }
// );
// }
// #[test]
// fn reserialize_unsupported_join_rule() {
// let json = json!({"join_rule": "local.matrix.custom", "foo": "bar"});
// let content = serde_json::from_value::<RoomJoinRulesEventContent>(json.clone()).unwrap();
// assert_eq!(content.join_rule.as_str(), "local.matrix.custom");
// let data = content.join_rule.data();
// assert_eq!(data.get("foo").unwrap().as_str(), Some("bar"));
// assert_eq!(serde_json::to_value(&content).unwrap(), json);
// }
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/pinned_events.rs | crates/core/src/events/room/pinned_events.rs | //! Types for the [`m.room.pinned_events`] event.
//!
//! [`m.room.pinned_events`]: https://spec.matrix.org/latest/client-server-api/#mroompinned_events
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{OwnedEventId, events::EmptyStateKey};
/// The content of an `m.room.pinned_events` event.
///
/// Used to "pin" particular events in a room for other participants to review
/// later.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.room.pinned_events", kind = State, state_key_type = EmptyStateKey)]
pub struct RoomPinnedEventsEventContent {
/// An ordered list of event IDs to pin.
pub pinned: Vec<OwnedEventId>,
}
impl RoomPinnedEventsEventContent {
/// Creates a new `RoomPinnedEventsEventContent` with the given events.
pub fn new(pinned: Vec<OwnedEventId>) -> Self {
Self { pinned }
}
}
#[cfg(test)]
mod tests {
use super::RoomPinnedEventsEventContent;
use crate::owned_event_id;
#[test]
fn serialization_deserialization() {
let mut content: RoomPinnedEventsEventContent =
RoomPinnedEventsEventContent { pinned: Vec::new() };
content.pinned.push(owned_event_id!("$a:example.com"));
content.pinned.push(owned_event_id!("$b:example.com"));
let serialized = serde_json::to_string(&content).unwrap();
let parsed_content: RoomPinnedEventsEventContent =
serde_json::from_str(&serialized).unwrap();
assert_eq!(parsed_content.pinned, content.pinned);
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/thumbnail_source_serde.rs | crates/core/src/events/room/thumbnail_source_serde.rs | //! De-/serialization functions for `Option<MediaSource>` objects representing a
//! thumbnail source.
use serde::{
Deserialize, Deserializer,
ser::{SerializeStruct, Serializer},
};
use super::{EncryptedFile, MediaSource};
use crate::OwnedMxcUri;
/// Serializes a MediaSource to a thumbnail source.
pub(crate) fn serialize<S>(source: &Option<MediaSource>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if let Some(source) = source {
let mut st = serializer.serialize_struct("ThumbnailSource", 1)?;
match source {
MediaSource::Plain(url) => st.serialize_field("thumbnail_url", url)?,
MediaSource::Encrypted(file) => st.serialize_field("thumbnail_file", file)?,
}
st.end()
} else {
serializer.serialize_none()
}
}
/// Deserializes a thumbnail source to a MediaSource.
pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Option<MediaSource>, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
struct ThumbnailSourceJsonRepr {
thumbnail_url: Option<OwnedMxcUri>,
thumbnail_file: Option<Box<EncryptedFile>>,
}
match ThumbnailSourceJsonRepr::deserialize(deserializer)? {
ThumbnailSourceJsonRepr {
thumbnail_url: None,
thumbnail_file: None,
} => Ok(None),
// Prefer file if it is set
ThumbnailSourceJsonRepr {
thumbnail_file: Some(file),
..
} => Ok(Some(MediaSource::Encrypted(file))),
ThumbnailSourceJsonRepr {
thumbnail_url: Some(url),
..
} => Ok(Some(MediaSource::Plain(url))),
}
}
// #[cfg(test)]
// mod tests {
// use crate::{mxc_uri, serde::Base64};
// use assert_matches2::assert_matches;
// use serde::{Deserialize, Serialize};
// use serde_json::json;
// use crate::room::{EncryptedFileInit, JsonWebKeyInit, MediaSource};
// #[derive(Clone, Debug, Deserialize, Serialize)]
// struct ThumbnailSourceTest {
// #[serde(flatten, with = "super", skip_serializing_if =
// "Option::is_none")] source: Option<MediaSource>,
// }
// #[test]
// fn deserialize_plain() {
// let json = json!({ "thumbnail_url": "mxc://notareal.hs/abcdef" });
// assert_matches!(
// serde_json::from_value::<ThumbnailSourceTest>(json),
// Ok(ThumbnailSourceTest {
// source: Some(MediaSource::Plain(url))
// })
// );
// assert_eq!(url, "mxc://notareal.hs/abcdef");
// }
// #[test]
// fn deserialize_encrypted() {
// let json = json!({
// "thumbnail_file": {
// "url": "mxc://notareal.hs/abcdef",
// "key": {
// "kty": "oct",
// "key_ops": ["encrypt", "decrypt"],
// "alg": "A256CTR",
// "k": "TLlG_OpX807zzQuuwv4QZGJ21_u7weemFGYJFszMn9A",
// "ext": true
// },
// "iv": "S22dq3NAX8wAAAAAAAAAAA",
// "hashes": {
// "sha256": "aWOHudBnDkJ9IwaR1Nd8XKoI7DOrqDTwt6xDPfVGN6Q"
// },
// "v": "v2",
// },
// });
// assert_matches!(
// serde_json::from_value::<ThumbnailSourceTest>(json),
// Ok(ThumbnailSourceTest {
// source: Some(MediaSource::Encrypted(file))
// })
// );
// assert_eq!(file.url, "mxc://notareal.hs/abcdef");
// }
// #[test]
// fn deserialize_none_by_absence() {
// let json = json!({});
// assert_matches!(
// serde_json::from_value::<ThumbnailSourceTest>(json).unwrap(),
// ThumbnailSourceTest { source: None }
// );
// }
// #[test]
// fn deserialize_none_by_null_plain() {
// let json = json!({ "thumbnail_url": null });
// assert_matches!(
// serde_json::from_value::<ThumbnailSourceTest>(json).unwrap(),
// ThumbnailSourceTest { source: None }
// );
// }
// #[test]
// fn deserialize_none_by_null_encrypted() {
// let json = json!({ "thumbnail_file": null });
// assert_matches!(
// serde_json::from_value::<ThumbnailSourceTest>(json).unwrap(),
// ThumbnailSourceTest { source: None }
// );
// }
// #[test]
// fn serialize_plain() {
// let request = ThumbnailSourceTest {
// source:
// Some(MediaSource::Plain(mxc_uri!("mxc://notareal.hs/abcdef").into())),
// };
// assert_eq!(
// serde_json::to_value(&request).unwrap(),
// json!({ "thumbnail_url": "mxc://notareal.hs/abcdef" })
// );
// }
// #[test]
// fn serialize_encrypted() {
// let request = ThumbnailSourceTest {
// source: Some(MediaSource::Encrypted(Box::new(
// EncryptedFileInit {
// url: mxc_uri!("mxc://notareal.hs/abcdef").to_owned(),
// key: JsonWebKeyInit {
// kty: "oct".to_owned(),
// key_ops: vec!["encrypt".to_owned(),
// "decrypt".to_owned()], alg: "A256CTR".to_owned(),
// k:
// Base64::parse("TLlG_OpX807zzQuuwv4QZGJ21_u7weemFGYJFszMn9A").unwrap(),
// ext: true,
// }
// .into(),
// iv: Base64::parse("S22dq3NAX8wAAAAAAAAAAA").unwrap(),
// hashes: [(
// "sha256".to_owned(),
//
// Base64::parse("aWOHudBnDkJ9IwaR1Nd8XKoI7DOrqDTwt6xDPfVGN6Q").unwrap(),
// )]
// .into(),
// v: "v2".to_owned(),
// }
// .into(),
// ))),
// };
// assert_eq!(
// serde_json::to_value(&request).unwrap(),
// json!({
// "thumbnail_file": {
// "url": "mxc://notareal.hs/abcdef",
// "key": {
// "kty": "oct",
// "key_ops": ["encrypt", "decrypt"],
// "alg": "A256CTR",
// "k": "TLlG_OpX807zzQuuwv4QZGJ21_u7weemFGYJFszMn9A",
// "ext": true
// },
// "iv": "S22dq3NAX8wAAAAAAAAAAA",
// "hashes": {
// "sha256":
// "aWOHudBnDkJ9IwaR1Nd8XKoI7DOrqDTwt6xDPfVGN6Q" },
// "v": "v2",
// },
// })
// );
// }
// #[test]
// fn serialize_none() {
// let request = ThumbnailSourceTest { source: None };
// assert_eq!(serde_json::to_value(&request).unwrap(), json!({}));
// }
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/encrypted.rs | crates/core/src/events/room/encrypted.rs | //! Types for the [`m.room.encrypted`] event.
//!
//! [`m.room.encrypted`]: https://spec.matrix.org/latest/client-server-api/#mroomencrypted
use std::{borrow::Cow, collections::BTreeMap};
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use super::message;
use crate::{
OwnedEventId,
events::relation::{Annotation, CustomRelation, InReplyTo, Reference, RelationType, Thread},
serde::JsonObject,
};
mod relation_serde;
#[cfg(feature = "unstable-msc4362")]
pub mod unstable_state;
/// The content of an `m.room.encrypted` event.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.room.encrypted", kind = MessageLike)]
pub struct RoomEncryptedEventContent {
/// Algorithm-specific fields.
#[serde(flatten)]
pub scheme: EncryptedEventScheme,
/// Information about related events.
#[serde(rename = "m.relates_to", skip_serializing_if = "Option::is_none")]
pub relates_to: Option<Relation>,
}
impl RoomEncryptedEventContent {
/// Creates a new `RoomEncryptedEventContent` with the given scheme and
/// relation.
pub fn new(scheme: EncryptedEventScheme, relates_to: Option<Relation>) -> Self {
Self { scheme, relates_to }
}
}
impl From<EncryptedEventScheme> for RoomEncryptedEventContent {
fn from(scheme: EncryptedEventScheme) -> Self {
Self {
scheme,
relates_to: None,
}
}
}
/// The to-device content of an `m.room.encrypted` event.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.room.encrypted", kind = ToDevice)]
pub struct ToDeviceRoomEncryptedEventContent {
/// Algorithm-specific fields.
#[serde(flatten)]
pub scheme: EncryptedEventScheme,
}
impl ToDeviceRoomEncryptedEventContent {
/// Creates a new `ToDeviceRoomEncryptedEventContent` with the given scheme.
pub fn new(scheme: EncryptedEventScheme) -> Self {
Self { scheme }
}
}
impl From<EncryptedEventScheme> for ToDeviceRoomEncryptedEventContent {
fn from(scheme: EncryptedEventScheme) -> Self {
Self { scheme }
}
}
/// The encryption scheme for `RoomEncryptedEventContent`.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[serde(tag = "algorithm")]
pub enum EncryptedEventScheme {
/// An event encrypted with `m.olm.v1.curve25519-aes-sha2`.
#[serde(rename = "m.olm.v1.curve25519-aes-sha2")]
OlmV1Curve25519AesSha2(OlmV1Curve25519AesSha2Content),
/// An event encrypted with `m.megolm.v1.aes-sha2`.
#[serde(rename = "m.megolm.v1.aes-sha2")]
MegolmV1AesSha2(MegolmV1AesSha2Content),
}
/// Relationship information about an encrypted event.
///
/// Outside of the encrypted payload to support server aggregation.
#[derive(ToSchema, Clone, Debug)]
#[allow(clippy::manual_non_exhaustive)]
pub enum Relation {
/// An `m.in_reply_to` relation indicating that the event is a reply to
/// another event.
Reply {
/// Information about another message being replied to.
in_reply_to: InReplyTo,
},
/// An event that replaces another event.
Replacement(Replacement),
/// A reference to another event.
Reference(Reference),
/// An annotation to an event.
Annotation(Annotation),
/// An event that belongs to a thread.
Thread(Thread),
#[doc(hidden)]
#[salvo(schema(value_type = Object))]
_Custom(CustomRelation),
}
impl Relation {
/// The type of this `Relation`.
///
/// Returns an `Option` because the `Reply` relation does not have
/// a`rel_type` field.
pub fn rel_type(&self) -> Option<RelationType> {
match self {
Relation::Reply { .. } => None,
Relation::Replacement(_) => Some(RelationType::Replacement),
Relation::Reference(_) => Some(RelationType::Reference),
Relation::Annotation(_) => Some(RelationType::Annotation),
Relation::Thread(_) => Some(RelationType::Thread),
Relation::_Custom(c) => c.rel_type(),
}
}
/// The associated data.
///
/// The returned JSON object holds the contents of `m.relates_to`, including
/// `rel_type` and `event_id` if present, but not things like
/// `m.new_content` for `m.replace` relations that live next to
/// `m.relates_to`.
///
/// Prefer to use the public variants of `Relation` where possible; this
/// method is meant to be used for custom relations only.
pub fn data(&self) -> Cow<'_, JsonObject> {
if let Relation::_Custom(CustomRelation(data)) = self {
Cow::Borrowed(data)
} else {
Cow::Owned(self.serialize_data())
}
}
}
impl<C> From<message::Relation<C>> for Relation
where
C: ToSchema,
{
fn from(rel: message::Relation<C>) -> Self {
match rel {
message::Relation::Reply { in_reply_to } => Self::Reply { in_reply_to },
message::Relation::Replacement(re) => Self::Replacement(Replacement {
event_id: re.event_id,
}),
message::Relation::Thread(t) => Self::Thread(Thread {
event_id: t.event_id,
in_reply_to: t.in_reply_to,
is_falling_back: t.is_falling_back,
}),
message::Relation::_Custom(c) => Self::_Custom(c),
}
}
}
/// The event this relation belongs to [replaces another event].
///
/// In contrast to [`relation::Replacement`](crate::relation::Replacement), this
/// struct doesn't store the new content, since that is part of the encrypted
/// content of an `m.room.encrypted` events.
///
/// [replaces another event]: https://spec.matrix.org/latest/client-server-api/#event-replacements
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct Replacement {
/// The ID of the event being replaced.
pub event_id: OwnedEventId,
}
impl Replacement {
/// Creates a new `Replacement` with the given event ID.
pub fn new(event_id: OwnedEventId) -> Self {
Self { event_id }
}
}
/// The content of an `m.room.encrypted` event using the
/// `m.olm.v1.curve25519-aes-sha2` algorithm.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct OlmV1Curve25519AesSha2Content {
/// A map from the recipient Curve25519 identity key to ciphertext
/// information.
pub ciphertext: BTreeMap<String, CiphertextInfo>,
/// The Curve25519 key of the sender.
pub sender_key: String,
}
impl OlmV1Curve25519AesSha2Content {
/// Creates a new `OlmV1Curve25519AesSha2Content` with the given ciphertext
/// and sender key.
pub fn new(ciphertext: BTreeMap<String, CiphertextInfo>, sender_key: String) -> Self {
Self {
ciphertext,
sender_key,
}
}
}
/// Ciphertext information holding the ciphertext and message type.
///
/// Used for messages encrypted with the `m.olm.v1.curve25519-aes-sha2`
/// algorithm.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct CiphertextInfo {
/// The encrypted payload.
pub body: String,
/// The Olm message type.
#[serde(rename = "type")]
pub message_type: u64,
}
impl CiphertextInfo {
/// Creates a new `CiphertextInfo` with the given body and type.
pub fn new(body: String, message_type: u64) -> Self {
Self { body, message_type }
}
}
/// The content of an `m.room.encrypted` event using the `m.megolm.v1.aes-sha2`
/// algorithm.
///
/// To create an instance of this type.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct MegolmV1AesSha2Content {
/// The encrypted content of the event.
pub ciphertext: String,
/// The ID of the session used to encrypt the message.
pub session_id: String,
}
// #[cfg(test)]
// mod tests {
// use crate::{owned_event_id, serde::RawJson};
// use assert_matches2::assert_matches;
// use serde_json::{from_value as from_json_value, json, to_value as
// to_json_value};
// use super::{EncryptedEventScheme, InReplyTo, MegolmV1AesSha2ContentInit,
// Relation, RoomEncryptedEventContent};
// #[test]
// fn serialization() {
// let key_verification_start_content = RoomEncryptedEventContent {
// scheme: EncryptedEventScheme::MegolmV1AesSha2(
// MegolmV1AesSha2ContentInit {
// ciphertext: "ciphertext".into(),
// _ sender_key: "sender_key".into(),
// _ device_id: "device_id".into(),
// session_id: "session_id".into(),
// }
// .into(),
// ),
// relates_to: Some(Relation::Reply {
// in_reply_to: InReplyTo {
// event_id: owned_event_id!("$h29iv0s8:example.com"),
// },
// }),
// };
// let json_data = json!({
// "algorithm": "m.megolm.v1.aes-sha2",
// "ciphertext": "ciphertext",
// "sender_key": "sender_key",
// "device_id": "device_id",
// "session_id": "session_id",
// "m.relates_to": {
// "m.in_reply_to": {
// "event_id": "$h29iv0s8:example.com"
// }
// },
// });
// assert_eq!(to_json_value(&key_verification_start_content).unwrap(),
// json_data); }
// #[test]
// fn deserialization() {
// let json_data = json!({
// "algorithm": "m.megolm.v1.aes-sha2",
// "ciphertext": "ciphertext",
// "sender_key": "sender_key",
// "device_id": "device_id",
// "session_id": "session_id",
// "m.relates_to": {
// "m.in_reply_to": {
// "event_id": "$h29iv0s8:example.com"
// }
// },
// });
// let content: RoomEncryptedEventContent =
// from_json_value(json_data).unwrap();
// assert_matches!(content.scheme,
// EncryptedEventScheme::MegolmV1AesSha2(scheme)); assert_eq!(scheme.
// ciphertext, "ciphertext"); assert_eq!(scheme.sender_key, "sender_key");
// assert_eq!(scheme.device_id, "device_id");
// assert_eq!(scheme.session_id, "session_id");
// assert_matches!(content.relates_to, Some(Relation::Reply { in_reply_to
// })); assert_eq!(in_reply_to.event_id, "$h29iv0s8:example.com");
// }
// #[test]
// fn deserialization_olm() {
// let json_data = json!({
// "sender_key": "test_key",
// "ciphertext": {
// "test_curve_key": {
// "body": "encrypted_body",
// "type": 1
// }
// },
// "algorithm": "m.olm.v1.curve25519-aes-sha2"
// });
// let content: RoomEncryptedEventContent =
// from_json_value(json_data).unwrap();
// assert_matches!(content.scheme,
// EncryptedEventScheme::OlmV1Curve25519AesSha2(c)); assert_eq!(c.
// sender_key, "test_key"); assert_eq!(c.ciphertext.len(), 1);
// assert_eq!(c.ciphertext["test_curve_key"].body, "encrypted_body");
// assert_eq!(c.ciphertext["test_curve_key"].message_type, 1);
// assert_matches!(content.relates_to, None);
// }
// #[test]
// fn deserialization_failure() {
// from_json_value::<RawJson<RoomEncryptedEventContent>>(json!({
// "algorithm": "m.megolm.v1.aes-sha2" })) .unwrap()
// .deserialize()
// .unwrap_err();
// }
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/encryption.rs | crates/core/src/events/room/encryption.rs | //! Types for the [`m.room.encryption`] event.
//!
//! [`m.room.encryption`]: https://spec.matrix.org/latest/client-server-api/#mroomencryption
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::events::{EmptyStateKey, EventEncryptionAlgorithm};
/// The content of an `m.room.encryption` event.
///
/// Defines how messages sent in this room should be encrypted.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.room.encryption", kind = State, state_key_type = EmptyStateKey)]
pub struct RoomEncryptionEventContent {
/// The encryption algorithm to be used to encrypt messages sent in this
/// room.
///
/// Must be `m.megolm.v1.aes-sha2`.
pub algorithm: EventEncryptionAlgorithm,
/// Whether state events should be encrypted alongside message-like events.
#[cfg(feature = "unstable-msc4362")]
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
#[serde(rename = "io.element.msc4362.encrypt_state_events")]
pub encrypt_state_events: bool,
/// How long the session should be used before changing it.
///
/// `u604800000` (a week) is the recommended default.
#[serde(skip_serializing_if = "Option::is_none")]
pub rotation_period_ms: Option<u64>,
/// How many messages should be sent before changing the session.
///
/// `u100` is the recommended default.
#[serde(skip_serializing_if = "Option::is_none")]
pub rotation_period_msgs: Option<u64>,
}
impl RoomEncryptionEventContent {
/// Creates a new `RoomEncryptionEventContent` with the given algorithm.
pub fn new(algorithm: EventEncryptionAlgorithm) -> Self {
Self {
algorithm,
#[cfg(feature = "unstable-msc4362")]
encrypt_state_events: false,
rotation_period_ms: None,
rotation_period_msgs: None,
}
}
/// Creates a new `RoomEncryptionEventContent` with the mandatory algorithm
/// and the recommended defaults.
///
/// Note that changing the values of the fields is not a breaking change and
/// you shouldn't rely on those specific values.
pub fn with_recommended_defaults() -> Self {
// Defaults defined at <https://spec.matrix.org/latest/client-server-api/#mroomencryption>
Self {
algorithm: EventEncryptionAlgorithm::MegolmV1AesSha2,
#[cfg(feature = "unstable-msc4362")]
encrypt_state_events: false,
rotation_period_ms: Some(604_800_000),
rotation_period_msgs: Some(100),
}
}
/// Enable encrypted state as specified in [MSC4362][msc].
///
/// [msc]: https://github.com/matrix-org/matrix-spec-proposals/pull/4362
#[cfg(feature = "unstable-msc4362")]
pub fn with_encrypted_state(mut self) -> Self {
self.encrypt_state_events = true;
self
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/canonical_alias.rs | crates/core/src/events/room/canonical_alias.rs | //! Types for the [`m.room.canonical_alias`] event.
//!
//! [`m.room.canonical_alias`]: https://spec.matrix.org/latest/client-server-api/#mroomcanonical_alias
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{OwnedRoomAliasId, events::EmptyStateKey};
/// The content of an `m.room.canonical_alias` event.
///
/// Informs the room as to which alias is the canonical one.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize, EventContent)]
#[palpo_event(type = "m.room.canonical_alias", kind = State, state_key_type = EmptyStateKey)]
pub struct RoomCanonicalAliasEventContent {
/// The canonical alias.
///
/// Rooms with `alias: None` should be treated the same as a room
/// with no canonical alias.
#[serde(
default,
deserialize_with = "palpo_core::serde::empty_string_as_none",
skip_serializing_if = "Option::is_none"
)]
pub alias: Option<OwnedRoomAliasId>,
/// List of alternative aliases to the room.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub alt_aliases: Vec<OwnedRoomAliasId>,
}
impl RoomCanonicalAliasEventContent {
/// Creates an empty `RoomCanonicalAliasEventContent`.
pub fn new() -> Self {
Self {
alias: None,
alt_aliases: Vec::new(),
}
}
}
// #[cfg(test)]
// mod tests {
// use crate::owned_room_alias_id;
// use serde_json::{from_value as from_json_value, json, to_value as
// to_json_value};
// use super::RoomCanonicalAliasEventContent;
// use crate::OriginalStateEvent;
// #[test]
// fn serialization_with_optional_fields_as_none() {
// let content = RoomCanonicalAliasEventContent {
// alias: Some(owned_room_alias_id!("#somewhere:localhost")),
// alt_aliases: Vec::new(),
// };
// let actual = to_json_value(&content).unwrap();
// let expected = json!({
// "alias": "#somewhere:localhost",
// });
// assert_eq!(actual, expected);
// }
// #[test]
// fn absent_field_as_none() {
// let json_data = json!({
// "content": {},
// "event_id": "$h29iv0s8:example.com",
// "origin_server_ts": 1,
// "room_id": "!dummy:example.com",
// "sender": "@carl:example.com",
// "state_key": "",
// "type": "m.room.canonical_alias"
// });
// assert_eq!(
//
// from_json_value::<OriginalStateEvent<RoomCanonicalAliasEventContent>>(json_data)
// .unwrap()
// .content
// .alias,
// None
// );
// }
// #[test]
// fn null_field_as_none() {
// let json_data = json!({
// "content": {
// "alias": null
// },
// "event_id": "$h29iv0s8:example.com",
// "origin_server_ts": 1,
// "room_id": "!dummy:example.com",
// "sender": "@carl:example.com",
// "state_key": "",
// "type": "m.room.canonical_alias"
// });
// assert_eq!(
//
// from_json_value::<OriginalStateEvent<RoomCanonicalAliasEventContent>>(json_data)
// .unwrap()
// .content
// .alias,
// None
// );
// }
// #[test]
// fn empty_field_as_none() {
// let json_data = json!({
// "content": {
// "alias": ""
// },
// "event_id": "$h29iv0s8:example.com",
// "origin_server_ts": 1,
// "room_id": "!dummy:example.com",
// "sender": "@carl:example.com",
// "state_key": "",
// "type": "m.room.canonical_alias"
// });
// assert_eq!(
//
// from_json_value::<OriginalStateEvent<RoomCanonicalAliasEventContent>>(json_data)
// .unwrap()
// .content
// .alias,
// None
// );
// }
// #[test]
// fn nonempty_field_as_some() {
// let alias = Some(owned_room_alias_id!("#somewhere:localhost"));
// let json_data = json!({
// "content": {
// "alias": "#somewhere:localhost"
// },
// "event_id": "$h29iv0s8:example.com",
// "origin_server_ts": 1,
// "room_id": "!dummy:example.com",
// "sender": "@carl:example.com",
// "state_key": "",
// "type": "m.room.canonical_alias"
// });
// assert_eq!(
//
// from_json_value::<OriginalStateEvent<RoomCanonicalAliasEventContent>>(json_data)
// .unwrap()
// .content
// .alias,
// alias
// );
// }
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/tombstone.rs | crates/core/src/events/room/tombstone.rs | //! Types for the [`m.room.tombstone`] event.
//!
//! [`m.room.tombstone`]: https://spec.matrix.org/latest/client-server-api/#mroomtombstone
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{
OwnedRoomId,
events::{
EmptyStateKey, PossiblyRedactedStateEventContent, StateEventType, StaticEventContent,
},
};
/// The content of an `m.room.tombstone` event.
///
/// A state event signifying that a room has been upgraded to a different room
/// version, and that clients should go there.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(
type = "m.room.tombstone",
kind = State,
state_key_type = EmptyStateKey,
custom_possibly_redacted,
)]
pub struct RoomTombstoneEventContent {
/// A server-defined message.
#[serde(default)]
pub body: String,
/// The new room the client should be visiting.
pub replacement_room: OwnedRoomId,
}
impl RoomTombstoneEventContent {
/// Creates a new `RoomTombstoneEventContent` with the given body and
/// replacement room ID.
pub fn new(body: String, replacement_room: OwnedRoomId) -> Self {
Self {
body,
replacement_room,
}
}
}
/// The possibly redacted form of [`RoomTombstoneEventContent`].
///
/// This type is used when it's not obvious whether the content is redacted or
/// not.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct PossiblyRedactedRoomTombstoneEventContent {
/// A server-defined message.
pub body: Option<String>,
/// The new room the client should be visiting.
pub replacement_room: Option<OwnedRoomId>,
}
impl PossiblyRedactedStateEventContent for PossiblyRedactedRoomTombstoneEventContent {
type StateKey = EmptyStateKey;
fn event_type(&self) -> StateEventType {
StateEventType::RoomTombstone
}
}
impl StaticEventContent for PossiblyRedactedRoomTombstoneEventContent {
const TYPE: &'static str = RoomTombstoneEventContent::TYPE;
type IsPrefix = <RoomTombstoneEventContent as StaticEventContent>::IsPrefix;
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/name.rs | crates/core/src/events/room/name.rs | //! Types for the [`m.room.name`] event.
//!
//! [`m.room.name`]: https://spec.matrix.org/latest/client-server-api/#mroomname
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::events::EmptyStateKey;
/// The content of an `m.room.name` event.
///
/// The room name is a human-friendly string designed to be displayed to the
/// end-user.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.room.name", kind = State, state_key_type = EmptyStateKey)]
pub struct RoomNameEventContent {
/// The name of the room.
pub name: String,
}
impl RoomNameEventContent {
/// Create a new `RoomNameEventContent` with the given name.
pub fn new(name: String) -> Self {
Self { name }
}
}
// #[cfg(test)]
// mod tests {
// use serde_json::{from_value as from_json_value, json, to_value as
// to_json_value};
// use super::RoomNameEventContent;
// use crate::OriginalStateEvent;
// #[test]
// fn serialization() {
// let content = RoomNameEventContent {
// name: "The room name".to_owned(),
// };
// let actual = to_json_value(content).unwrap();
// let expected = json!({
// "name": "The room name",
// });
// assert_eq!(actual, expected);
// }
// #[test]
// fn deserialization() {
// let json_data = json!({
// "content": {
// "name": "The room name"
// },
// "event_id": "$h29iv0s8:example.com",
// "origin_server_ts": 1,
// "room_id": "!n8f893n9:example.com",
// "sender": "@carl:example.com",
// "state_key": "",
// "type": "m.room.name"
// });
// assert_eq!(
//
// from_json_value::<OriginalStateEvent<RoomNameEventContent>>(json_data)
// .unwrap()
// .content
// .name,
// "The room name"
// );
// }
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/server_acl.rs | crates/core/src/events/room/server_acl.rs | //! Types for the [`m.room.server_acl`] event.
//!
//! [`m.room.server_acl`]: https://spec.matrix.org/latest/client-server-api/#mroomserver_acl
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use wildmatch::WildMatch;
use crate::{ServerName, events::EmptyStateKey};
/// The content of an `m.room.server_acl` event.
///
/// An event to indicate which servers are permitted to participate in the room.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.room.server_acl", kind = State, state_key_type = EmptyStateKey)]
pub struct RoomServerAclEventContent {
/// Whether to allow server names that are IP address literals.
///
/// This is strongly recommended to be set to false as servers running with
/// IP literal names are strongly discouraged in order to require
/// legitimate homeservers to be backed by a valid registered domain
/// name.
#[serde(
default = "palpo_core::serde::default_true",
skip_serializing_if = "palpo_core::serde::is_true"
)]
pub allow_ip_literals: bool,
/// The server names to allow in the room, excluding any port information.
///
/// Wildcards may be used to cover a wider range of hosts, where `*` matches
/// zero or more characters and `?` matches exactly one character.
///
/// **Defaults to an empty list when not provided, effectively disallowing
/// every server.**
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub allow: Vec<String>,
/// The server names to disallow in the room, excluding any port
/// information.
///
/// Wildcards may be used to cover a wider range of hosts, where * matches
/// zero or more characters and `?` matches exactly one character.
///
/// Defaults to an empty list when not provided.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub deny: Vec<String>,
}
impl RoomServerAclEventContent {
/// Creates a new `RoomServerAclEventContent` with the given IP literal
/// allowance flag, allowed and denied servers.
pub fn new(allow_ip_literals: bool, allow: Vec<String>, deny: Vec<String>) -> Self {
Self {
allow_ip_literals,
allow,
deny,
}
}
/// Returns true if and only if the server is allowed by the ACL rules.
pub fn is_allowed(&self, server_name: &ServerName) -> bool {
if !self.allow_ip_literals && server_name.is_ip_literal() {
return false;
}
let host = server_name.host();
self.deny.iter().all(|d| !WildMatch::new(d).matches(host))
&& self.allow.iter().any(|a| WildMatch::new(a).matches(host))
}
}
// #[cfg(test)]
// mod tests {
// use crate::server_name;
// use serde_json::{from_value as from_json_value, json};
// use super::RoomServerAclEventContent;
// use crate::OriginalStateEvent;
// #[test]
// fn default_values() {
// let json_data = json!({
// "content": {},
// "event_id": "$h29iv0s8:example.com",
// "origin_server_ts": 1,
// "room_id": "!n8f893n9:example.com",
// "sender": "@carl:example.com",
// "state_key": "",
// "type": "m.room.server_acl"
// });
// let server_acl_event: OriginalStateEvent<RoomServerAclEventContent> =
// from_json_value(json_data).unwrap();
// assert!(server_acl_event.content.allow_ip_literals);
// assert_eq!(server_acl_event.content.allow.len(), 0);
// assert_eq!(server_acl_event.content.deny.len(), 0);
// }
// #[test]
// fn acl_ignores_port() {
// let acl_event = RoomServerAclEventContent {
// allow_ip_literals: true,
// allow: vec!["*".to_owned()],
// deny: vec!["1.1.1.1".to_owned()],
// };
// assert!(!acl_event.is_allowed(server_name!("1.1.1.1:8000")));
// }
// #[test]
// fn acl_allow_ip_literal() {
// let acl_event = RoomServerAclEventContent {
// allow_ip_literals: true,
// allow: vec!["*".to_owned()],
// deny: Vec::new(),
// };
// assert!(acl_event.is_allowed(server_name!("1.1.1.1")));
// }
// #[test]
// fn acl_deny_ip_literal() {
// let acl_event = RoomServerAclEventContent {
// allow_ip_literals: false,
// allow: vec!["*".to_owned()],
// deny: Vec::new(),
// };
// assert!(!acl_event.is_allowed(server_name!("1.1.1.1")));
// }
// #[test]
// fn acl_deny() {
// let acl_event = RoomServerAclEventContent {
// allow_ip_literals: false,
// allow: vec!["*".to_owned()],
// deny: vec!["matrix.org".to_owned()],
// };
// assert!(!acl_event.is_allowed(server_name!("matrix.org")));
// assert!(acl_event.is_allowed(server_name!("palpo.im")));
// }
// #[test]
// fn acl_explicit_allow() {
// let acl_event = RoomServerAclEventContent {
// allow_ip_literals: false,
// allow: vec!["palpo.im".to_owned()],
// deny: Vec::new(),
// };
// assert!(!acl_event.is_allowed(server_name!("matrix.org")));
// assert!(acl_event.is_allowed(server_name!("palpo.im")));
// }
// #[test]
// fn acl_explicit_glob_1() {
// let acl_event = RoomServerAclEventContent {
// allow_ip_literals: false,
// allow: vec!["*.matrix.org".to_owned()],
// deny: Vec::new(),
// };
// assert!(!acl_event.is_allowed(server_name!("matrix.org")));
// assert!(acl_event.is_allowed(server_name!("server.matrix.org")));
// }
// #[test]
// fn acl_explicit_glob_2() {
// let acl_event = RoomServerAclEventContent {
// allow_ip_literals: false,
// allow: vec!["matrix??.org".to_owned()],
// deny: Vec::new(),
// };
// assert!(!acl_event.is_allowed(server_name!("matrix1.org")));
// assert!(acl_event.is_allowed(server_name!("matrix02.org")));
// }
// #[test]
// fn acl_ipv6_glob() {
// let acl_event = RoomServerAclEventContent {
// allow_ip_literals: true,
// allow: vec!["[2001:db8:1234::1]".to_owned()],
// deny: Vec::new(),
// };
// assert!(!acl_event.is_allowed(server_name!("[2001:db8:1234::2]")));
// assert!(acl_event.is_allowed(server_name!("[2001:db8:1234::1]")));
// }
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/member.rs | crates/core/src/events/room/member.rs | //! Types for the [`m.room.member`] event.
//!
//! [`m.room.member`]: https://spec.matrix.org/latest/client-server-api/#mroommember
use std::collections::BTreeMap;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Deserializer, Serialize};
use crate::macros::EventContent;
use crate::serde::JsonValue;
use crate::{
PrivOwnedStr,
events::{
AnyStrippedStateEvent, BundledStateRelations, PossiblyRedactedStateEventContent,
RedactContent, RedactedStateEventContent, StateEventType, StaticEventContent,
},
identifiers::*,
room_version_rules::RedactionRules,
serde::{CanBeEmpty, RawJson, StringEnum},
};
mod change;
use self::change::membership_change;
pub use self::change::{Change, MembershipChange, MembershipDetails};
/// The content of an `m.room.member` event.
///
/// The current membership state of a user in the room.
///
/// Adjusts the membership state for a user in a room. It is preferable to use
/// the membership APIs (`/rooms/<room id>/invite` etc) when performing
/// membership actions rather than adjusting the state directly as there are a
/// restricted set of valid transformations. For example, user A cannot force
/// user B to join a room, and trying to force this state change directly will
/// fail.
///
/// This event may also include an `invite_room_state` key inside the event's
/// unsigned data, but Palpo doesn't currently expose this; see [#998](https://github.com/palpo/palpo/issues/998).
///
/// The user for which a membership applies is represented by the `state_key`.
/// Under some conditions, the `sender` and `state_key` may not match - this may
/// be interpreted as the `sender` affecting the membership state of the
/// `state_key` user.
///
/// The membership for a given user can change over time. Previous membership
/// can be retrieved from the `prev_content` object on an event. If not present,
/// the user's previous membership must be assumed as leave.
#[derive(ToSchema, Serialize, Clone, Debug, EventContent)]
#[palpo_event(
type = "m.room.member",
kind = State,
state_key_type = OwnedUserId,
unsigned_type = RoomMemberUnsigned,
custom_redacted,
custom_possibly_redacted,
)]
pub struct RoomMemberEventContent {
/// The avatar URL for this user, if any.
#[serde(
skip_serializing_if = "Option::is_none",
default,
deserialize_with = "crate::serde::empty_string_as_none"
)]
pub avatar_url: Option<OwnedMxcUri>,
/// The display name for this user, if any.
///
/// This is added by the homeserver.
#[serde(rename = "displayname", skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
/// Flag indicating whether the room containing this event was created with
/// the intention of being a direct chat.
#[serde(skip_serializing_if = "Option::is_none")]
pub is_direct: Option<bool>,
/// The membership state of this user.
pub membership: MembershipState,
/// If this member event is the successor to a third party invitation, this
/// field will contain information about that invitation.
#[serde(skip_serializing_if = "Option::is_none")]
pub third_party_invite: Option<ThirdPartyInvite>,
/// The [BlurHash](https://blurha.sh) for the avatar pointed to by `avatar_url`.
///
/// This uses the unstable prefix in
/// [MSC2448](https://github.com/matrix-org/matrix-spec-proposals/pull/2448).
#[serde(
rename = "xyz.amorgan.blurhash",
skip_serializing_if = "Option::is_none"
)]
pub blurhash: Option<String>,
/// User-supplied text for why their membership has changed.
///
/// For kicks and bans, this is typically the reason for the kick or ban.
/// For other membership changes, this is a way for the user to
/// communicate their intent without having to send a message to the
/// room, such as in a case where Bob rejects an invite from Alice about an
/// upcoming concert, but can't make it that day.
///
/// Clients are not recommended to show this reason to users when receiving
/// an invite due to the potential for spam and abuse. Hiding the reason
/// behind a button or other component is recommended.
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
/// Arbitrarily chosen `UserId` (MxID) of a local user who can send an invite.
#[serde(rename = "join_authorised_via_users_server")]
#[serde(skip_serializing_if = "Option::is_none")]
pub join_authorized_via_users_server: Option<OwnedUserId>,
#[serde(flatten, skip_serializing_if = "BTreeMap::is_empty")]
#[salvo(schema(value_type = Object, additional_properties = true))]
pub extra_data: BTreeMap<String, JsonValue>,
}
impl<'de> Deserialize<'de> for RoomMemberEventContent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
pub struct RoomMemberEventData {
#[serde(
skip_serializing_if = "Option::is_none",
default,
deserialize_with = "palpo_core::serde::empty_string_as_none"
)]
avatar_url: Option<OwnedMxcUri>,
#[serde(rename = "displayname", skip_serializing_if = "Option::is_none")]
display_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
is_direct: Option<bool>,
membership: MembershipState,
#[serde(skip_serializing_if = "Option::is_none")]
third_party_invite: Option<ThirdPartyInvite>,
#[serde(
rename = "xyz.amorgan.blurhash",
skip_serializing_if = "Option::is_none"
)]
blurhash: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
reason: Option<String>,
#[serde(rename = "join_authorised_via_users_server")]
#[serde(skip_serializing_if = "Option::is_none")]
join_authorized_via_users_server: Option<String>,
#[serde(flatten, skip_serializing_if = "BTreeMap::is_empty")]
extra_data: BTreeMap<String, JsonValue>,
}
let RoomMemberEventData {
avatar_url,
display_name,
is_direct,
membership,
third_party_invite,
blurhash,
reason,
join_authorized_via_users_server,
extra_data,
} = RoomMemberEventData::deserialize(deserializer)?;
let join_authorized_via_users_server =
join_authorized_via_users_server.and_then(|s| OwnedUserId::try_from(s).ok());
Ok(Self {
avatar_url,
display_name,
is_direct,
membership,
third_party_invite,
blurhash,
reason,
join_authorized_via_users_server,
extra_data,
})
}
}
impl RoomMemberEventContent {
/// Creates a new `RoomMemberEventContent` with the given membership state.
pub fn new(membership: MembershipState) -> Self {
Self {
membership,
avatar_url: None,
display_name: None,
is_direct: None,
third_party_invite: None,
blurhash: None,
reason: None,
join_authorized_via_users_server: None,
extra_data: Default::default(),
}
}
/// Obtain the details about this event that are required to calculate a
/// membership change.
///
/// This is required when you want to calculate the change a redacted
/// `m.room.member` event made.
pub fn details(&self) -> MembershipDetails<'_> {
MembershipDetails {
avatar_url: self.avatar_url.as_deref(),
display_name: self.display_name.as_deref(),
membership: &self.membership,
}
}
/// Helper function for membership change.
///
/// This requires data from the full event:
///
/// * The previous details computed from `event.unsigned.prev_content`,
/// * The sender of the event,
/// * The state key of the event.
///
/// Check [the specification][spec] for details.
///
/// [spec]: https://spec.matrix.org/latest/client-server-api/#mroommember
pub fn membership_change<'a>(
&'a self,
prev_details: Option<MembershipDetails<'a>>,
sender: &UserId,
state_key: &UserId,
) -> MembershipChange<'a> {
membership_change(self.details(), prev_details, sender, state_key)
}
}
impl RedactContent for RoomMemberEventContent {
type Redacted = RedactedRoomMemberEventContent;
fn redact(self, rules: &RedactionRules) -> RedactedRoomMemberEventContent {
RedactedRoomMemberEventContent {
membership: self.membership,
third_party_invite: self.third_party_invite.and_then(|i| i.redact(rules)),
join_authorized_via_users_server: self
.join_authorized_via_users_server
.filter(|_| rules.keep_room_member_join_authorised_via_users_server),
}
}
}
/// The possibly redacted form of [`RoomMemberEventContent`].
///
/// This type is used when it's not obvious whether the content is redacted or
/// not.
pub type PossiblyRedactedRoomMemberEventContent = RoomMemberEventContent;
impl PossiblyRedactedStateEventContent for RoomMemberEventContent {
type StateKey = OwnedUserId;
fn event_type(&self) -> StateEventType {
StateEventType::RoomMember
}
}
/// A member event that has been redacted.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct RedactedRoomMemberEventContent {
/// The membership state of this user.
pub membership: MembershipState,
/// If this member event is the successor to a third party invitation, this
/// field will contain information about that invitation.
#[serde(skip_serializing_if = "Option::is_none")]
pub third_party_invite: Option<RedactedThirdPartyInvite>,
/// An arbitrary user who has the power to issue invites.
///
/// This is redacted in room versions 8 and below. It is used for validating
/// joins when the join rule is restricted.
#[serde(
rename = "join_authorised_via_users_server",
skip_serializing_if = "Option::is_none"
)]
pub join_authorized_via_users_server: Option<OwnedUserId>,
}
impl RedactedRoomMemberEventContent {
/// Create a `RedactedRoomMemberEventContent` with the given membership.
pub fn new(membership: MembershipState) -> Self {
Self {
membership,
third_party_invite: None,
join_authorized_via_users_server: None,
}
}
/// Obtain the details about this event that are required to calculate a
/// membership change.
///
/// This is required when you want to calculate the change a redacted
/// `m.room.member` event made.
pub fn details(&self) -> MembershipDetails<'_> {
MembershipDetails {
avatar_url: None,
display_name: None,
membership: &self.membership,
}
}
/// Helper function for membership change.
///
/// Since redacted events don't have `unsigned.prev_content`, you have to
/// pass the `.details()` of the previous `m.room.member` event manually
/// (if there is a previous `m.room.member` event).
///
/// This also requires data from the full event:
///
/// * The sender of the event,
/// * The state key of the event.
///
/// Check [the specification][spec] for details.
///
/// [spec]: https://spec.matrix.org/latest/client-server-api/#mroommember
pub fn membership_change<'a>(
&'a self,
prev_details: Option<MembershipDetails<'a>>,
sender: &UserId,
state_key: &UserId,
) -> MembershipChange<'a> {
membership_change(self.details(), prev_details, sender, state_key)
}
}
impl RedactedStateEventContent for RedactedRoomMemberEventContent {
type StateKey = OwnedUserId;
fn event_type(&self) -> StateEventType {
StateEventType::RoomMember
}
}
impl StaticEventContent for RedactedRoomMemberEventContent {
const TYPE: &'static str = RoomMemberEventContent::TYPE;
type IsPrefix = <RoomMemberEventContent as StaticEventContent>::IsPrefix;
}
impl RoomMemberEvent {
/// Obtain the membership state, regardless of whether this event is
/// redacted.
pub fn membership(&self) -> &MembershipState {
match self {
Self::Original(ev) => &ev.content.membership,
Self::Redacted(ev) => &ev.content.membership,
}
}
}
impl SyncRoomMemberEvent {
/// Obtain the membership state, regardless of whether this event is
/// redacted.
pub fn membership(&self) -> &MembershipState {
match self {
Self::Original(ev) => &ev.content.membership,
Self::Redacted(ev) => &ev.content.membership,
}
}
}
/// The membership state of a user.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[palpo_enum(rename_all = "lowercase")]
#[non_exhaustive]
pub enum MembershipState {
/// The user is banned.
Ban,
/// The user has been invited.
Invite,
/// The user has joined.
Join,
/// The user has requested to join.
Knock,
/// The user has left.
Leave,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
/// Information about a third party invitation.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct ThirdPartyInvite {
/// A name which can be displayed to represent the user instead of their
/// third party identifier.
pub display_name: String,
/// A block of content which has been signed, which servers can use to
/// verify the event.
///
/// Clients should ignore this.
pub signed: SignedContent,
}
impl ThirdPartyInvite {
/// Creates a new `ThirdPartyInvite` with the given display name and signed
/// content.
pub fn new(display_name: String, signed: SignedContent) -> Self {
Self {
display_name,
signed,
}
}
/// Transform `self` into a redacted form (removing most or all fields)
/// according to the spec.
///
/// Returns `None` if the field for this object was redacted in the given
/// room version, otherwise returns the redacted form.
fn redact(self, rules: &RedactionRules) -> Option<RedactedThirdPartyInvite> {
rules
.keep_room_member_third_party_invite_signed
.then_some(RedactedThirdPartyInvite {
signed: self.signed,
})
}
}
/// Redacted information about a third party invitation.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct RedactedThirdPartyInvite {
/// A block of content which has been signed, which servers can use to
/// verify the event.
///
/// Clients should ignore this.
pub signed: SignedContent,
}
/// A block of content which has been signed, which servers can use to verify a
/// third party invitation.
#[derive(ToSchema, Serialize, Deserialize, Clone, Debug)]
pub struct SignedContent {
/// The invited Matrix user ID.
///
/// Must be equal to the user_id property of the event.
pub mxid: OwnedUserId,
/// A single signature from the verifying server, in the format specified by
/// the Signing Events section of the server-server API.
#[salvo(schema(value_type = Object, additional_properties = true))]
pub signatures: ServerSignatures,
/// The token property of the containing `third_party_invite` object.
pub token: String,
}
impl SignedContent {
/// Creates a new `SignedContent` with the given mxid, signature and token.
pub fn new(signatures: ServerSignatures, mxid: OwnedUserId, token: String) -> Self {
Self {
mxid,
signatures,
token,
}
}
}
impl OriginalRoomMemberEvent {
/// Obtain the details about this event that are required to calculate a
/// membership change.
///
/// This is required when you want to calculate the change a redacted
/// `m.room.member` event made.
pub fn details(&self) -> MembershipDetails<'_> {
self.content.details()
}
/// Get a reference to the `prev_content` in unsigned, if it exists.
///
/// Shorthand for `event.unsigned.prev_content.as_ref()`
pub fn prev_content(&self) -> Option<&RoomMemberEventContent> {
self.unsigned.prev_content.as_ref()
}
fn prev_details(&self) -> Option<MembershipDetails<'_>> {
self.prev_content().map(|c| c.details())
}
/// Helper function for membership change.
///
/// Check [the specification][spec] for details.
///
/// [spec]: https://spec.matrix.org/latest/client-server-api/#mroommember
pub fn membership_change(&self) -> MembershipChange<'_> {
membership_change(
self.details(),
self.prev_details(),
&self.sender,
&self.state_key,
)
}
}
impl RedactedRoomMemberEvent {
/// Obtain the details about this event that are required to calculate a
/// membership change.
///
/// This is required when you want to calculate the change a redacted
/// `m.room.member` event made.
pub fn details(&self) -> MembershipDetails<'_> {
self.content.details()
}
/// Helper function for membership change.
///
/// Since redacted events don't have `unsigned.prev_content`, you have to
/// pass the `.details()` of the previous `m.room.member` event manually
/// (if there is a previous `m.room.member` event).
///
/// Check [the specification][spec] for details.
///
/// [spec]: https://spec.matrix.org/latest/client-server-api/#mroommember
pub fn membership_change<'a>(
&'a self,
prev_details: Option<MembershipDetails<'a>>,
) -> MembershipChange<'a> {
membership_change(self.details(), prev_details, &self.sender, &self.state_key)
}
}
impl OriginalSyncRoomMemberEvent {
/// Obtain the details about this event that are required to calculate a
/// membership change.
///
/// This is required when you want to calculate the change a redacted
/// `m.room.member` event made.
pub fn details(&self) -> MembershipDetails<'_> {
self.content.details()
}
/// Get a reference to the `prev_content` in unsigned, if it exists.
///
/// Shorthand for `event.unsigned.prev_content.as_ref()`
pub fn prev_content(&self) -> Option<&RoomMemberEventContent> {
self.unsigned.prev_content.as_ref()
}
fn prev_details(&self) -> Option<MembershipDetails<'_>> {
self.prev_content().map(|c| c.details())
}
/// Helper function for membership change.
///
/// Check [the specification][spec] for details.
///
/// [spec]: https://spec.matrix.org/latest/client-server-api/#mroommember
pub fn membership_change(&self) -> MembershipChange<'_> {
membership_change(
self.details(),
self.prev_details(),
&self.sender,
&self.state_key,
)
}
}
impl RedactedSyncRoomMemberEvent {
/// Obtain the details about this event that are required to calculate a
/// membership change.
///
/// This is required when you want to calculate the change a redacted
/// `m.room.member` event made.
pub fn details(&self) -> MembershipDetails<'_> {
self.content.details()
}
/// Helper function for membership change.
///
/// Since redacted events don't have `unsigned.prev_content`, you have to
/// pass the `.details()` of the previous `m.room.member` event manually
/// (if there is a previous `m.room.member` event).
///
/// Check [the specification][spec] for details.
///
/// [spec]: https://spec.matrix.org/latest/client-server-api/#mroommember
pub fn membership_change<'a>(
&'a self,
prev_details: Option<MembershipDetails<'a>>,
) -> MembershipChange<'a> {
membership_change(self.details(), prev_details, &self.sender, &self.state_key)
}
}
impl StrippedRoomMemberEvent {
/// Obtain the details about this event that are required to calculate a
/// membership change.
///
/// This is required when you want to calculate the change a redacted
/// `m.room.member` event made.
pub fn details(&self) -> MembershipDetails<'_> {
self.content.details()
}
/// Helper function for membership change.
///
/// Since stripped events don't have `unsigned.prev_content`, you have to
/// pass the `.details()` of the previous `m.room.member` event manually
/// (if there is a previous `m.room.member` event).
///
/// Check [the specification][spec] for details.
///
/// [spec]: https://spec.matrix.org/latest/client-server-api/#mroommember
pub fn membership_change<'a>(
&'a self,
prev_details: Option<MembershipDetails<'a>>,
) -> MembershipChange<'a> {
membership_change(self.details(), prev_details, &self.sender, &self.state_key)
}
}
/// Extra information about a message event that is not incorporated into the
/// event's hash.
#[derive(ToSchema, Clone, Debug, Default, Deserialize)]
pub struct RoomMemberUnsigned {
/// The time in milliseconds that has elapsed since the event was sent.
///
/// This field is generated by the local homeserver, and may be incorrect if
/// the local time on at least one of the two servers is out of sync,
/// which can cause the age to either be negative or greater than it
/// actually is.
pub age: Option<i64>,
/// The client-supplied transaction ID, if the client being given the event
/// is the same one which sent it.
pub transaction_id: Option<OwnedTransactionId>,
/// Optional previous content of the event.
pub prev_content: Option<PossiblyRedactedRoomMemberEventContent>,
/// Stripped state events to assist the receiver in identifying the room when receiving an
/// invite.
#[serde(default)]
pub invite_room_state: Vec<RawJson<AnyStrippedStateEvent>>,
/// Stripped state events to assist the receiver in identifying the room after knocking.
#[serde(default)]
pub knock_room_state: Vec<RawJson<AnyStrippedStateEvent>>,
/// [Bundled aggregations] of related child events.
///
/// [Bundled aggregations]: https://spec.matrix.org/latest/client-server-api/#aggregations-of-child-events
#[serde(rename = "m.relations", default)]
pub relations: BundledStateRelations,
}
impl RoomMemberUnsigned {
/// Create a new `Unsigned` with fields set to `None`.
pub fn new() -> Self {
Self::default()
}
}
impl CanBeEmpty for RoomMemberUnsigned {
/// Whether this unsigned data is empty (all fields are `None`).
///
/// This method is used to determine whether to skip serializing the
/// `unsigned` field in room events. Do not use it to determine whether
/// an incoming `unsigned` field was present - it could still have been
/// present but contained none of the known fields.
fn is_empty(&self) -> bool {
self.age.is_none()
&& self.transaction_id.is_none()
&& self.prev_content.is_none()
&& self.invite_room_state.is_empty()
&& self.relations.is_empty()
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/topic.rs | crates/core/src/events/room/topic.rs | //! Types for the [`m.room.topic`] event.
//!
//! [`m.room.topic`]: https://spec.matrix.org/latest/client-server-api/#mroomtopic
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::events::EmptyStateKey;
use crate::events::message::TextContentBlock;
use crate::macros::EventContent;
/// The content of an `m.room.topic` event.
///
/// A topic is a short message detailing what is currently being discussed in
/// the room.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.room.topic", kind = State, state_key_type = EmptyStateKey)]
pub struct RoomTopicEventContent {
/// The topic as plain text.
///
/// This SHOULD duplicate the content of the `text/plain` representation in `topic_block` if
/// any exists.
pub topic: String,
/// Textual representation of the room topic in different mimetypes.
///
/// With the `compat-lax-room-topic-deser` cargo feature, this field is ignored if its
/// deserialization fails.
#[serde(
rename = "m.topic",
default,
skip_serializing_if = "TopicContentBlock::is_empty"
)]
pub topic_block: TopicContentBlock,
}
impl RoomTopicEventContent {
/// Creates a new `RoomTopicEventContent` with the given plain text topic.
pub fn new(topic: String) -> Self {
Self {
topic_block: TopicContentBlock::plain(topic.clone()),
topic,
}
}
/// Convenience constructor to create a new HTML topic with a plain text fallback.
pub fn html(plain: impl Into<String>, html: impl Into<String>) -> Self {
let plain = plain.into();
Self {
topic: plain.clone(),
topic_block: TopicContentBlock::html(plain, html),
}
}
/// Convenience constructor to create a topic from Markdown.
///
/// The content includes an HTML topic if some Markdown formatting was detected, otherwise
/// only a plain text topic is included.
#[cfg(feature = "markdown")]
pub fn markdown(topic: impl AsRef<str> + Into<String>) -> Self {
let plain = topic.as_ref().to_owned();
Self {
topic: plain,
topic_block: TopicContentBlock::markdown(topic),
}
}
}
/// A block for topic content.
///
/// To construct a `TopicContentBlock` with a custom [`TextContentBlock`], convert it with
/// `TopicContentBlock::from()` / `.into()`.
#[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)]
pub struct TopicContentBlock {
/// The text representations of the topic.
#[serde(rename = "m.text")]
pub text: TextContentBlock,
}
impl TopicContentBlock {
/// A convenience constructor to create a plain text `TopicContentBlock`.
pub fn plain(body: impl Into<String>) -> Self {
Self {
text: TextContentBlock::plain(body),
}
}
/// A convenience constructor to create an HTML `TopicContentBlock`.
pub fn html(body: impl Into<String>, html_body: impl Into<String>) -> Self {
Self {
text: TextContentBlock::html(body, html_body),
}
}
/// A convenience constructor to create a `TopicContentBlock` from Markdown.
///
/// The content includes an HTML topic if some Markdown formatting was detected, otherwise
/// only a plain text topic is included.
#[cfg(feature = "markdown")]
pub fn markdown(body: impl AsRef<str> + Into<String>) -> Self {
Self {
text: TextContentBlock::markdown(body),
}
}
/// Whether this content block is empty.
fn is_empty(&self) -> bool {
self.text.is_empty()
}
}
impl From<TextContentBlock> for TopicContentBlock {
fn from(text: TextContentBlock) -> Self {
Self { text }
}
}
#[cfg(test)]
mod tests {
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::RoomTopicEventContent;
use crate::events::message::TextContentBlock;
#[test]
fn serialize_content() {
// Content with plain text block.
let mut content = RoomTopicEventContent::new("Hot Topic".to_owned());
assert_eq!(
to_json_value(&content).unwrap(),
json!({
"topic": "Hot Topic",
"m.topic": {
"m.text": [
{ "body": "Hot Topic" },
],
}
})
);
// Content without block.
content.topic_block.text = TextContentBlock::from(vec![]);
assert_eq!(
to_json_value(&content).unwrap(),
json!({
"topic": "Hot Topic",
})
);
// Content with HTML block.
let content = RoomTopicEventContent::html("Hot Topic", "<strong>Hot</strong> Topic");
assert_eq!(
to_json_value(&content).unwrap(),
json!({
"topic": "Hot Topic",
"m.topic": {
"m.text": [
{ "body": "<strong>Hot</strong> Topic", "mimetype": "text/html" },
{ "body": "Hot Topic" },
],
}
})
);
}
#[test]
fn deserialize_content() {
let json = json!({
"topic": "Hot Topic",
"m.topic": {
"m.text": [
{ "body": "<strong>Hot</strong> Topic", "mimetype": "text/html" },
{ "body": "Hot Topic" },
],
}
});
let content = from_json_value::<RoomTopicEventContent>(json).unwrap();
assert_eq!(content.topic, "Hot Topic");
assert_eq!(
content.topic_block.text.find_html(),
Some("<strong>Hot</strong> Topic")
);
assert_eq!(content.topic_block.text.find_plain(), Some("Hot Topic"));
let content = serde_json::from_str::<RoomTopicEventContent>(
r#"{"topic":"Hot Topic","m.topic":{"m.text":[{"body":"Hot Topic"}]}}"#,
)
.unwrap();
assert_eq!(content.topic, "Hot Topic");
assert_eq!(content.topic_block.text.find_html(), None);
assert_eq!(content.topic_block.text.find_plain(), Some("Hot Topic"));
}
#[test]
fn deserialize_event() {
let json = json!({
"content": {
"topic": "Hot Topic",
"m.topic": {
"m.text": [
{ "body": "<strong>Hot</strong> Topic", "mimetype": "text/html" },
{ "body": "Hot Topic" },
],
},
},
"type": "m.room.topic",
"state_key": "",
"event_id": "$lkioKdioukshnlDDz",
"sender": "@alice:localhost",
"origin_server_ts": 309_998_934,
});
from_json_value::<super::SyncRoomTopicEvent>(json).unwrap();
}
// #[test]
// #[cfg(feature = "compat-lax-room-topic-deser")]
// fn deserialize_invalid_content() {
// let json = json!({
// "topic": "Hot Topic",
// "m.topic": [
// { "body": "<strong>Hot</strong> Topic", "mimetype": "text/html" },
// { "body": "Hot Topic" },
// ],
// });
// let content = from_json_value::<RoomTopicEventContent>(json).unwrap();
// assert_eq!(content.topic, "Hot Topic");
// assert_eq!(content.topic_block.text.find_html(), None);
// assert_eq!(content.topic_block.text.find_plain(), None);
// let content = serde_json::from_str::<RoomTopicEventContent>(
// r#"{"topic":"Hot Topic","m.topic":[{"body":"Hot Topic"}]}"#,
// )
// .unwrap();
// assert_eq!(content.topic, "Hot Topic");
// assert_eq!(content.topic_block.text.find_html(), None);
// assert_eq!(content.topic_block.text.find_plain(), None);
// }
// #[test]
// #[cfg(feature = "compat-lax-room-topic-deser")]
// fn deserialize_invalid_event() {
// let json = json!({
// "content": {
// "topic": "Hot Topic",
// "m.topic": [
// { "body": "<strong>Hot</strong> Topic", "mimetype": "text/html" },
// { "body": "Hot Topic" },
// ],
// },
// "type": "m.room.topic",
// "state_key": "",
// "event_id": "$lkioKdioukshnlDDz",
// "sender": "@alice:localhost",
// "origin_server_ts": 309_998_934,
// });
// from_json_value::<super::SyncRoomTopicEvent>(json).unwrap();
// }
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/message.rs | crates/core/src/events/room/message.rs | //! Types for the [`m.room.message`] event.
//!
//! [`m.room.message`]: https://spec.matrix.org/latest/client-server-api/#mroommessage
use std::borrow::Cow;
use crate::macros::EventContent;
use as_variant::as_variant;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde_json::Value as JsonValue;
#[cfg(feature = "html")]
use self::sanitize::remove_plain_reply_fallback;
use crate::events::Mentions;
use crate::events::relation::{InReplyTo, Replacement, Thread};
#[cfg(feature = "html")]
use crate::html::{HtmlSanitizerMode, RemoveReplyFallback, sanitize_html};
use crate::serde::{JsonObject, StringEnum};
use crate::{EventId, OwnedEventId, PrivOwnedStr, UserId};
mod audio;
mod content_serde;
mod emote;
mod file;
#[cfg(feature = "unstable-msc4274")]
mod gallery;
mod image;
mod key_verification_request;
mod location;
mod notice;
mod relation;
pub(crate) mod relation_serde;
pub mod sanitize;
mod server_notice;
mod text;
#[cfg(feature = "unstable-msc4095")]
mod url_preview;
mod video;
mod without_relation;
#[cfg(feature = "unstable-msc4095")]
pub use self::url_preview::{PreviewImage, PreviewImageSource, UrlPreview};
pub use audio::{
AudioInfo, AudioMessageEventContent, UnstableAmplitude, UnstableAudioDetailsContentBlock,
UnstableVoiceContentBlock,
};
pub use self::{
emote::EmoteMessageEventContent,
file::{FileInfo, FileMessageEventContent},
image::ImageMessageEventContent,
key_verification_request::KeyVerificationRequestEventContent,
location::{LocationInfo, LocationMessageEventContent},
notice::NoticeMessageEventContent,
relation::{Relation, RelationWithoutReplacement},
relation_serde::deserialize_relation,
server_notice::{LimitType, ServerNoticeMessageEventContent, ServerNoticeType},
text::TextMessageEventContent,
video::{VideoInfo, VideoMessageEventContent},
without_relation::RoomMessageEventContentWithoutRelation,
};
/// The content of an `m.room.message` event.
///
/// This event is used when sending messages in a room.
///
/// Messages are not limited to be text.
#[derive(ToSchema, Clone, Debug, Serialize, EventContent)]
#[palpo_event(type = "m.room.message", kind = MessageLike)]
pub struct RoomMessageEventContent {
/// A key which identifies the type of message being sent.
///
/// This also holds the specific content of each message.
#[serde(flatten)]
pub msgtype: MessageType,
/// Information about [related messages].
///
/// [related messages]: https://spec.matrix.org/latest/client-server-api/#forming-relationships-between-events
#[serde(flatten, skip_serializing_if = "Option::is_none")]
pub relates_to: Option<Relation<RoomMessageEventContentWithoutRelation>>,
/// The [mentions] of this event.
///
/// This should always be set to avoid triggering the legacy mention push
/// rules. It is recommended to use [`Self::set_mentions()`] to set this
/// field, that will take care of populating the fields correctly if
/// this is a replacement.
///
/// [mentions]: https://spec.matrix.org/latest/client-server-api/#user-and-room-mentions
#[serde(rename = "m.mentions", skip_serializing_if = "Option::is_none")]
pub mentions: Option<Mentions>,
}
impl RoomMessageEventContent {
/// Create a `RoomMessageEventContent` with the given `MessageType`.
pub fn new(msgtype: MessageType) -> Self {
Self {
msgtype,
relates_to: None,
mentions: None,
}
}
/// A constructor to create a plain text message.
pub fn text_plain(body: impl Into<String>) -> Self {
Self::new(MessageType::text_plain(body))
}
/// A constructor to create an html message.
pub fn text_html(body: impl Into<String>, html_body: impl Into<String>) -> Self {
Self::new(MessageType::text_html(body, html_body))
}
/// A constructor to create a markdown message.
#[cfg(feature = "markdown")]
pub fn text_markdown(body: impl AsRef<str> + Into<String>) -> Self {
Self::new(MessageType::text_markdown(body))
}
/// A constructor to create a plain text notice.
pub fn notice_plain(body: impl Into<String>) -> Self {
Self::new(MessageType::notice_plain(body))
}
/// A constructor to create an html notice.
pub fn notice_html(body: impl Into<String>, html_body: impl Into<String>) -> Self {
Self::new(MessageType::notice_html(body, html_body))
}
/// A constructor to create a markdown notice.
#[cfg(feature = "markdown")]
pub fn notice_markdown(body: impl AsRef<str> + Into<String>) -> Self {
Self::new(MessageType::notice_markdown(body))
}
/// A constructor to create a plain text emote.
pub fn emote_plain(body: impl Into<String>) -> Self {
Self::new(MessageType::emote_plain(body))
}
/// A constructor to create an html emote.
pub fn emote_html(body: impl Into<String>, html_body: impl Into<String>) -> Self {
Self::new(MessageType::emote_html(body, html_body))
}
/// A constructor to create a markdown emote.
#[cfg(feature = "markdown")]
pub fn emote_markdown(body: impl AsRef<str> + Into<String>) -> Self {
Self::new(MessageType::emote_markdown(body))
}
/// Turns `self` into a reply to the given message.
///
/// Takes the `body` / `formatted_body` (if any) in `self` for the main text
/// and prepends a quoted version of `original_message`. Also sets the
/// `in_reply_to` field inside `relates_to`, and optionally the
/// `rel_type` to `m.thread` if the `original_message is in a thread and
/// thread forwarding is enabled.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/rich_reply.md"))]
///
/// # Panics
///
/// Panics if `self` has a `formatted_body` with a format other than HTML.
#[track_caller]
pub fn make_reply_to<'a>(
self,
metadata: impl Into<ReplyMetadata<'a>>,
forward_thread: ForwardThread,
add_mentions: AddMentions,
) -> Self {
self.without_relation()
.make_reply_to(metadata, forward_thread, add_mentions)
}
/// Turns `self` into a new message for a [thread], that is optionally a reply.
///
/// Looks for the `thread` in the given metadata. If it exists, this message will be in the same
/// thread. If it doesn't, a new thread is created with the `event_id` in the metadata as the
/// root.
///
/// It also sets the `in_reply_to` field inside `relates_to` to point the `event_id`
/// in the metadata. If `ReplyWithinThread::Yes` is used, the metadata should be constructed
/// from the event to make a reply to, otherwise it should be constructed from the latest
/// event in the thread.
///
/// If `AddMentions::Yes` is used, the `sender` in the metadata is added as a user mention.
///
/// [thread]: https://spec.matrix.org/latest/client-server-api/#threading
pub fn make_for_thread<'a>(
self,
metadata: impl Into<ReplyMetadata<'a>>,
is_reply: ReplyWithinThread,
add_mentions: AddMentions,
) -> Self {
self.without_relation()
.make_for_thread(metadata, is_reply, add_mentions)
}
/// Turns `self` into a [replacement] (or edit) for a given message.
///
/// The first argument after `self` can be `&OriginalRoomMessageEvent` or
/// `&OriginalSyncRoomMessageEvent` if you don't want to create `ReplacementMetadata` separately
/// before calling this function.
///
/// This takes the content and sets it in `m.new_content`, and modifies the `content` to include
/// a fallback.
///
/// If this message contains [`Mentions`], they are copied into `m.new_content` to keep the same
/// mentions, but the ones in `content` are filtered with the ones in the
/// [`ReplacementMetadata`] so only new mentions will trigger a notification.
///
/// # Panics
///
/// Panics if `self` has a `formatted_body` with a format other than HTML.
///
/// [replacement]: https://spec.matrix.org/latest/client-server-api/#event-replacements
#[track_caller]
pub fn make_replacement(self, metadata: impl Into<ReplacementMetadata>) -> Self {
self.without_relation().make_replacement(metadata)
}
/// Set the [mentions] of this event.
///
/// If this event is a replacement, it will update the mentions both in the
/// `content` and the `m.new_content` so only new mentions will trigger
/// a notification. As such, this needs to be called after
/// [`Self::make_replacement()`].
///
/// It is not recommended to call this method after one that sets mentions
/// automatically, like [`Self::make_reply_to()`] as these will be
/// overwritten. [`Self::add_mentions()`] should be used instead.
///
/// [mentions]: https://spec.matrix.org/latest/client-server-api/#user-and-room-mentions
pub fn set_mentions(mut self, mentions: Mentions) -> Self {
if let Some(Relation::Replacement(replacement)) = &mut self.relates_to {
let old_mentions = &replacement.new_content.mentions;
let new_mentions = if let Some(old_mentions) = old_mentions {
let mut new_mentions = Mentions::new();
new_mentions.user_ids = mentions
.user_ids
.iter()
.filter(|u| !old_mentions.user_ids.contains(*u))
.cloned()
.collect();
new_mentions.room = mentions.room && !old_mentions.room;
new_mentions
} else {
mentions.clone()
};
replacement.new_content.mentions = Some(mentions);
self.mentions = Some(new_mentions);
} else {
self.mentions = Some(mentions);
}
self
}
/// Add the given [mentions] to this event.
///
/// If no [`Mentions`] was set on this events, this sets it. Otherwise, this
/// updates the current mentions by extending the previous `user_ids`
/// with the new ones, and applies a logical OR to the values of `room`.
///
/// This is recommended over [`Self::set_mentions()`] to avoid to overwrite
/// any mentions set automatically by another method, like
/// [`Self::make_reply_to()`]. However, this method has no
/// special support for replacements.
///
/// [mentions]: https://spec.matrix.org/latest/client-server-api/#user-and-room-mentions
pub fn add_mentions(mut self, mentions: Mentions) -> Self {
self.mentions
.get_or_insert_with(Mentions::new)
.add(mentions);
self
}
/// Returns a reference to the `msgtype` string.
///
/// If you want to access the message type-specific data rather than the
/// message type itself, use the `msgtype` *field*, not this method.
pub fn msgtype(&self) -> &str {
self.msgtype.msgtype()
}
/// Return a reference to the message body.
pub fn body(&self) -> &str {
self.msgtype.body()
}
/// Apply the given new content from a [`Replacement`] to this message.
pub fn apply_replacement(&mut self, new_content: RoomMessageEventContentWithoutRelation) {
let RoomMessageEventContentWithoutRelation { msgtype, mentions } = new_content;
self.msgtype = msgtype;
self.mentions = mentions;
}
/// 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.
///
/// 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 = "html")]
pub fn sanitize(
&mut self,
mode: HtmlSanitizerMode,
remove_reply_fallback: RemoveReplyFallback,
) {
let remove_reply_fallback = if matches!(self.relates_to, Some(Relation::Reply { .. })) {
remove_reply_fallback
} else {
RemoveReplyFallback::No
};
self.msgtype.sanitize(mode, remove_reply_fallback);
}
fn without_relation(self) -> RoomMessageEventContentWithoutRelation {
if self.relates_to.is_some() {
warn!("Overwriting existing relates_to value");
}
self.into()
}
/// Get the thread relation from this content, if any.
fn thread(&self) -> Option<&Thread> {
self.relates_to
.as_ref()
.and_then(|relates_to| as_variant!(relates_to, Relation::Thread))
}
}
/// Whether or not to forward a [`Relation::Thread`] when sending a reply.
#[derive(ToSchema, Clone, Copy, Debug, PartialEq, Eq)]
#[allow(clippy::exhaustive_enums)]
pub enum ForwardThread {
/// The thread relation in the original message is forwarded if it exists.
///
/// This should be set if your client doesn't render threads (see the [info
/// box for clients which are acutely aware of threads]).
///
/// [info box for clients which are acutely aware of threads]: https://spec.matrix.org/latest/client-server-api/#fallback-for-unthreaded-clients
Yes,
/// Create a reply in the main conversation even if the original message is
/// in a thread.
///
/// This should be used if you client supports threads and you explicitly
/// want that behavior.
No,
}
/// Whether or not to add intentional [`Mentions`] when sending a reply.
#[derive(ToSchema, Clone, Copy, Debug, PartialEq, Eq)]
#[allow(clippy::exhaustive_enums)]
pub enum AddMentions {
/// Add automatic intentional mentions to the reply.
///
/// Set this if your client supports intentional mentions.
///
/// The sender of the original event will be added to the mentions of this
/// message.
Yes,
/// Do not add intentional mentions to the reply.
///
/// Set this if your client does not support intentional mentions.
No,
}
/// Whether or not the message is a reply inside a thread.
#[derive(ToSchema, Clone, Copy, Debug, PartialEq, Eq)]
#[allow(clippy::exhaustive_enums)]
pub enum ReplyWithinThread {
/// This is a reply.
///
/// Create a [reply within the thread].
///
/// [reply within the thread]: https://spec.matrix.org/latest/client-server-api/#replies-within-threads
Yes,
/// This is not a reply.
///
/// Create a regular message in the thread, with a [fallback for unthreaded
/// clients].
///
/// [fallback for unthreaded clients]: https://spec.matrix.org/latest/client-server-api/#fallback-for-unthreaded-clients
No,
}
/// The content that is specific to each message type variant.
#[derive(ToSchema, Clone, Debug, Serialize)]
#[serde(untagged)]
pub enum MessageType {
/// An audio message.
Audio(AudioMessageEventContent),
/// An emote message.
Emote(EmoteMessageEventContent),
/// A file message.
File(FileMessageEventContent),
/// An image message.
Image(ImageMessageEventContent),
/// A location message.
Location(LocationMessageEventContent),
/// A notice message.
Notice(NoticeMessageEventContent),
/// A server notice message.
ServerNotice(ServerNoticeMessageEventContent),
/// A text message.
Text(TextMessageEventContent),
/// A video message.
Video(VideoMessageEventContent),
/// A request to initiate a key verification.
VerificationRequest(KeyVerificationRequestEventContent),
/// A custom message.
#[doc(hidden)]
_Custom(CustomEventContent),
}
impl MessageType {
/// Creates a new `MessageType`.
///
/// The `msgtype` and `body` are required fields as defined by [the `m.room.message` spec](https://spec.matrix.org/latest/client-server-api/#mroommessage).
/// Additionally it's possible to add arbitrary key/value pairs to the event
/// content for custom events through the `data` map.
///
/// Prefer to use the public variants of `MessageType` where possible; this
/// constructor is meant be used for unsupported message types only and
/// does not allow setting arbitrary data for supported ones.
///
/// # Errors
///
/// Returns an error if the `msgtype` is known and serialization of `data`
/// to the corresponding `MessageType` variant fails.
pub fn new(msgtype: &str, body: String, data: JsonObject) -> serde_json::Result<Self> {
fn deserialize_variant<T: DeserializeOwned>(
body: String,
mut obj: JsonObject,
) -> serde_json::Result<T> {
obj.insert("body".into(), body.into());
serde_json::from_value(JsonValue::Object(obj))
}
Ok(match msgtype {
"m.audio" => Self::Audio(deserialize_variant(body, data)?),
"m.emote" => Self::Emote(deserialize_variant(body, data)?),
"m.file" => Self::File(deserialize_variant(body, data)?),
"m.image" => Self::Image(deserialize_variant(body, data)?),
"m.location" => Self::Location(deserialize_variant(body, data)?),
"m.notice" => Self::Notice(deserialize_variant(body, data)?),
"m.server_notice" => Self::ServerNotice(deserialize_variant(body, data)?),
"m.text" => Self::Text(deserialize_variant(body, data)?),
"m.video" => Self::Video(deserialize_variant(body, data)?),
"m.key.verification.request" => {
Self::VerificationRequest(deserialize_variant(body, data)?)
}
_ => Self::_Custom(CustomEventContent {
msgtype: msgtype.to_owned(),
body,
data,
}),
})
}
/// A constructor to create a plain text message.
pub fn text_plain(body: impl Into<String>) -> Self {
Self::Text(TextMessageEventContent::plain(body))
}
/// A constructor to create an html message.
pub fn text_html(body: impl Into<String>, html_body: impl Into<String>) -> Self {
Self::Text(TextMessageEventContent::html(body, html_body))
}
/// A constructor to create a markdown message.
#[cfg(feature = "markdown")]
pub fn text_markdown(body: impl AsRef<str> + Into<String>) -> Self {
Self::Text(TextMessageEventContent::markdown(body))
}
/// A constructor to create a plain text notice.
pub fn notice_plain(body: impl Into<String>) -> Self {
Self::Notice(NoticeMessageEventContent::plain(body))
}
/// A constructor to create an html notice.
pub fn notice_html(body: impl Into<String>, html_body: impl Into<String>) -> Self {
Self::Notice(NoticeMessageEventContent::html(body, html_body))
}
/// A constructor to create a markdown notice.
#[cfg(feature = "markdown")]
pub fn notice_markdown(body: impl AsRef<str> + Into<String>) -> Self {
Self::Notice(NoticeMessageEventContent::markdown(body))
}
/// A constructor to create a plain text emote.
pub fn emote_plain(body: impl Into<String>) -> Self {
Self::Emote(EmoteMessageEventContent::plain(body))
}
/// A constructor to create an html emote.
pub fn emote_html(body: impl Into<String>, html_body: impl Into<String>) -> Self {
Self::Emote(EmoteMessageEventContent::html(body, html_body))
}
/// A constructor to create a markdown emote.
#[cfg(feature = "markdown")]
pub fn emote_markdown(body: impl AsRef<str> + Into<String>) -> Self {
Self::Emote(EmoteMessageEventContent::markdown(body))
}
/// Returns a reference to the `msgtype` string.
pub fn msgtype(&self) -> &str {
match self {
Self::Audio(_) => "m.audio",
Self::Emote(_) => "m.emote",
Self::File(_) => "m.file",
Self::Image(_) => "m.image",
Self::Location(_) => "m.location",
Self::Notice(_) => "m.notice",
Self::ServerNotice(_) => "m.server_notice",
Self::Text(_) => "m.text",
Self::Video(_) => "m.video",
Self::VerificationRequest(_) => "m.key.verification.request",
Self::_Custom(c) => &c.msgtype,
}
}
/// Return a reference to the message body.
pub fn body(&self) -> &str {
match self {
MessageType::Audio(m) => &m.body,
MessageType::Emote(m) => &m.body,
MessageType::File(m) => &m.body,
MessageType::Image(m) => &m.body,
MessageType::Location(m) => &m.body,
MessageType::Notice(m) => &m.body,
MessageType::ServerNotice(m) => &m.body,
MessageType::Text(m) => &m.body,
MessageType::Video(m) => &m.body,
MessageType::VerificationRequest(m) => &m.body,
MessageType::_Custom(m) => &m.body,
}
}
/// Returns the associated data.
///
/// The returned JSON object won't contain the `msgtype` and `body` fields,
/// use [`.msgtype()`][Self::msgtype] / [`.body()`](Self::body) to
/// access those.
///
/// Prefer to use the public variants of `MessageType` where possible; this
/// method is meant to be used for custom message types only.
pub fn data(&self) -> Cow<'_, JsonObject> {
fn serialize<T: Serialize>(obj: &T) -> JsonObject {
match serde_json::to_value(obj).expect("message type serialization to succeed") {
JsonValue::Object(mut obj) => {
obj.remove("body");
obj
}
_ => panic!("all message types must serialize to objects"),
}
}
match self {
Self::Audio(d) => Cow::Owned(serialize(d)),
Self::Emote(d) => Cow::Owned(serialize(d)),
Self::File(d) => Cow::Owned(serialize(d)),
Self::Image(d) => Cow::Owned(serialize(d)),
Self::Location(d) => Cow::Owned(serialize(d)),
Self::Notice(d) => Cow::Owned(serialize(d)),
Self::ServerNotice(d) => Cow::Owned(serialize(d)),
Self::Text(d) => Cow::Owned(serialize(d)),
Self::Video(d) => Cow::Owned(serialize(d)),
Self::VerificationRequest(d) => Cow::Owned(serialize(d)),
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 = "html")]
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();
}
}
}
fn make_replacement_body(&mut self) {
let empty_formatted_body = || FormattedBody::html(String::new());
let (body, formatted) = {
match self {
MessageType::Emote(m) => (
&mut m.body,
Some(m.formatted.get_or_insert_with(empty_formatted_body)),
),
MessageType::Notice(m) => (
&mut m.body,
Some(m.formatted.get_or_insert_with(empty_formatted_body)),
),
MessageType::Text(m) => (
&mut m.body,
Some(m.formatted.get_or_insert_with(empty_formatted_body)),
),
MessageType::Audio(m) => (&mut m.body, None),
MessageType::File(m) => (&mut m.body, None),
MessageType::Image(m) => (&mut m.body, None),
MessageType::Location(m) => (&mut m.body, None),
MessageType::ServerNotice(m) => (&mut m.body, None),
MessageType::Video(m) => (&mut m.body, None),
MessageType::VerificationRequest(m) => (&mut m.body, None),
MessageType::_Custom(m) => (&mut m.body, None),
}
};
// Add replacement fallback.
*body = format!("* {body}");
if let Some(f) = formatted {
assert_eq!(
f.format,
MessageFormat::Html,
"make_replacement can't handle non-HTML formatted messages"
);
f.body = format!("* {}", f.body);
}
}
}
impl From<MessageType> for RoomMessageEventContent {
fn from(msgtype: MessageType) -> Self {
Self::new(msgtype)
}
}
impl From<RoomMessageEventContent> for MessageType {
fn from(content: RoomMessageEventContent) -> Self {
content.msgtype
}
}
/// Metadata about an event to be replaced.
///
/// To be used with [`RoomMessageEventContent::make_replacement`].
#[derive(Debug)]
pub struct ReplacementMetadata {
event_id: OwnedEventId,
mentions: Option<Mentions>,
}
impl ReplacementMetadata {
/// Creates a new `ReplacementMetadata` with the given event ID and
/// mentions.
pub fn new(event_id: OwnedEventId, mentions: Option<Mentions>) -> Self {
Self { event_id, mentions }
}
}
impl From<&OriginalRoomMessageEvent> for ReplacementMetadata {
fn from(value: &OriginalRoomMessageEvent) -> Self {
ReplacementMetadata::new(value.event_id.to_owned(), value.content.mentions.clone())
}
}
impl From<&OriginalSyncRoomMessageEvent> for ReplacementMetadata {
fn from(value: &OriginalSyncRoomMessageEvent) -> Self {
ReplacementMetadata::new(value.event_id.to_owned(), value.content.mentions.clone())
}
}
/// Metadata about an event to reply to or to add to a thread.
///
/// To be used with [`RoomMessageEventContent::make_reply_to`] or
/// [`RoomMessageEventContent::make_for_thread`].
#[derive(Clone, Copy, Debug)]
pub struct ReplyMetadata<'a> {
/// The event ID of the event to reply to.
event_id: &'a EventId,
/// The sender of the event to reply to.
sender: &'a UserId,
/// The `m.thread` relation of the event to reply to, if any.
thread: Option<&'a Thread>,
}
impl<'a> ReplyMetadata<'a> {
/// Creates a new `ReplyMetadata` with the given event ID, sender and thread relation.
pub fn new(event_id: &'a EventId, sender: &'a UserId, thread: Option<&'a Thread>) -> Self {
Self {
event_id,
sender,
thread,
}
}
}
impl<'a> From<&'a OriginalRoomMessageEvent> for ReplyMetadata<'a> {
fn from(value: &'a OriginalRoomMessageEvent) -> Self {
ReplyMetadata::new(&value.event_id, &value.sender, value.content.thread())
}
}
impl<'a> From<&'a OriginalSyncRoomMessageEvent> for ReplyMetadata<'a> {
fn from(value: &'a OriginalSyncRoomMessageEvent) -> Self {
ReplyMetadata::new(&value.event_id, &value.sender, value.content.thread())
}
}
/// The format for the formatted representation of a message body.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[non_exhaustive]
pub enum MessageFormat {
/// HTML.
#[palpo_enum(rename = "org.matrix.custom.html")]
Html,
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(PrivOwnedStr),
}
/// Common message event content fields for message types that have separate
/// plain-text and formatted representations.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[allow(clippy::exhaustive_structs)]
pub struct FormattedBody {
/// The format used in the `formatted_body`.
pub format: MessageFormat,
/// The formatted version of the `body`.
#[serde(rename = "formatted_body")]
pub body: String,
}
impl FormattedBody {
/// Creates a new HTML-formatted message body.
pub fn html(body: impl Into<String>) -> Self {
Self {
format: MessageFormat::Html,
body: body.into(),
}
}
/// Creates a new HTML-formatted message body by parsing the Markdown in
/// `body`.
///
/// Returns `None` if no Markdown formatting was found.
#[cfg(feature = "markdown")]
pub fn markdown(body: impl AsRef<str>) -> Option<Self> {
parse_markdown(body.as_ref()).map(Self::html)
}
/// Sanitize this `FormattedBody` if its format is `MessageFormat::Html`.
///
/// This removes any [tags and attributes] that are not listed in the Matrix
/// specification.
///
/// It can also optionally remove the [rich reply fallback].
///
/// Returns the sanitized HTML if the format is `MessageFormat::Html`.
///
/// [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 = "html")]
pub fn sanitize_html(
&mut self,
mode: HtmlSanitizerMode,
remove_reply_fallback: RemoveReplyFallback,
) {
if self.format == MessageFormat::Html {
self.body = sanitize_html(&self.body, mode, remove_reply_fallback);
}
}
}
/// The payload for a custom message event.
#[doc(hidden)]
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct CustomEventContent {
/// A custom msgtype.
msgtype: String,
/// The message body.
body: String,
/// Remaining event content.
#[serde(flatten)]
data: JsonObject,
}
#[cfg(feature = "markdown")]
pub(crate) fn parse_markdown(text: &str) -> Option<String> {
use pulldown_cmark::{Event, Options, Parser, Tag, TagEnd};
const OPTIONS: Options = Options::ENABLE_TABLES.union(Options::ENABLE_STRIKETHROUGH);
let parser_events: Vec<_> = Parser::new_ext(text, OPTIONS)
.map(|event| match event {
Event::SoftBreak => Event::HardBreak,
_ => event,
})
.collect();
// Text that does not contain markdown syntax is always inline because when we encounter several
// blocks we convert them to HTML. Inline text is always wrapped by a single paragraph.
let first_event_is_paragraph_start = parser_events
.first()
.is_some_and(|event| matches!(event, Event::Start(Tag::Paragraph)));
let last_event_is_paragraph_end = parser_events
.last()
.is_some_and(|event| matches!(event, Event::End(TagEnd::Paragraph)));
let mut is_inline = first_event_is_paragraph_start && last_event_is_paragraph_end;
let mut has_markdown = !is_inline;
if !has_markdown {
// Check whether the events contain other blocks and whether they contain inline markdown
// syntax.
let mut pos = 0;
for event in parser_events.iter().skip(1) {
match event {
Event::Text(s) => {
// If the string does not contain markdown, the only modification that should
// happen is that newlines are converted to hardbreaks. It means that we should
// find all the other characters from the original string in the text events.
// Let's check that by walking the original string.
if text[pos..].starts_with(s.as_ref()) {
pos += s.len();
continue;
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | true |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/aliases.rs | crates/core/src/events/room/aliases.rs | //! Types for the `m.room.aliases` event.
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{
OwnedRoomAliasId, OwnedServerName,
events::{RedactContent, RedactedStateEventContent, StateEventType, StaticEventContent},
room_version_rules::RedactionRules,
};
/// The content of an `m.room.aliases` event.
///
/// Informs the room about what room aliases it has been given.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.room.aliases", kind = State, state_key_type = OwnedServerName, custom_redacted)]
pub struct RoomAliasesEventContent {
/// A list of room aliases.
pub aliases: Vec<OwnedRoomAliasId>,
}
impl RoomAliasesEventContent {
/// Create an `RoomAliasesEventContent` from the given aliases.
pub fn new(aliases: Vec<OwnedRoomAliasId>) -> Self {
Self { aliases }
}
}
impl RedactContent for RoomAliasesEventContent {
type Redacted = RedactedRoomAliasesEventContent;
fn redact(self, rules: &RedactionRules) -> RedactedRoomAliasesEventContent {
let aliases = rules.keep_room_aliases_aliases.then_some(self.aliases);
RedactedRoomAliasesEventContent { aliases }
}
}
/// An aliases event that has been redacted.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct RedactedRoomAliasesEventContent {
/// A list of room aliases.
///
/// According to the Matrix spec version 1 redaction rules allowed this
/// field to be kept after redaction, this was changed in version 6.
#[serde(skip_serializing_if = "Option::is_none")]
pub aliases: Option<Vec<OwnedRoomAliasId>>,
}
impl RedactedRoomAliasesEventContent {
/// Create a `RedactedAliasesEventContent` with the given aliases.
///
/// This is only valid for room version 5 and below.
pub fn new_v1(aliases: Vec<OwnedRoomAliasId>) -> Self {
Self {
aliases: Some(aliases),
}
}
/// Create a `RedactedAliasesEventContent` with the given aliases.
///
/// This is only valid for room version 6 and above.
pub fn new_v6() -> Self {
Self::default()
}
}
impl RedactedStateEventContent for RedactedRoomAliasesEventContent {
type StateKey = OwnedServerName;
fn event_type(&self) -> StateEventType {
StateEventType::RoomAliases
}
}
impl StaticEventContent for RedactedRoomAliasesEventContent {
const TYPE: &'static str = RoomAliasesEventContent::TYPE;
type IsPrefix = <RoomAliasesEventContent as StaticEventContent>::IsPrefix;
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/redaction.rs | crates/core/src/events/room/redaction.rs | //! Types for the [`m.room.redaction`] event.
//!
//! [`m.room.redaction`]: https://spec.matrix.org/latest/client-server-api/#mroomredaction
use crate::macros::{Event, EventContent};
use as_variant::as_variant;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::room_version_rules::RedactionRules;
use crate::{
EventId, OwnedEventId, OwnedRoomId, OwnedTransactionId, OwnedUserId, RoomId, RoomVersionId,
UnixMillis, UserId,
events::{
BundledMessageLikeRelations, MessageLikeEventContent, MessageLikeEventType, RedactContent,
RedactedMessageLikeEventContent, RedactedUnsigned, StaticEventContent,
},
serde::{CanBeEmpty, canonical_json::RedactionEvent},
};
mod event_serde;
/// A possibly-redacted redaction event.
#[allow(clippy::exhaustive_enums)]
#[derive(ToSchema, Clone, Debug)]
pub enum RoomRedactionEvent {
/// Original, unredacted form of the event.
Original(OriginalRoomRedactionEvent),
/// Redacted form of the event with minimal fields.
Redacted(RedactedRoomRedactionEvent),
}
/// A possibly-redacted redaction event without a `room_id`.
#[allow(clippy::exhaustive_enums)]
#[derive(ToSchema, Clone, Debug)]
pub enum SyncRoomRedactionEvent {
/// Original, unredacted form of the event.
Original(OriginalSyncRoomRedactionEvent),
/// Redacted form of the event with minimal fields.
Redacted(RedactedSyncRoomRedactionEvent),
}
/// Redaction event.
#[derive(ToSchema, Clone, Debug)]
#[allow(clippy::exhaustive_structs)]
pub struct OriginalRoomRedactionEvent {
/// Data specific to the event type.
pub content: RoomRedactionEventContent,
/// The ID of the event that was redacted.
///
/// This field is required in room versions prior to 11.
pub redacts: Option<OwnedEventId>,
/// The globally unique event identifier for the user who sent the event.
pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event.
pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was
/// sent.
pub origin_server_ts: UnixMillis,
/// The ID of the room associated with this event.
pub room_id: OwnedRoomId,
/// Additional key-value pairs not signed by the homeserver.
#[salvo(schema(value_type = Object, additional_properties = true))]
pub unsigned: RoomRedactionUnsigned,
}
impl From<OriginalRoomRedactionEvent> for OriginalSyncRoomRedactionEvent {
fn from(value: OriginalRoomRedactionEvent) -> Self {
let OriginalRoomRedactionEvent {
content,
redacts,
event_id,
sender,
origin_server_ts,
unsigned,
..
} = value;
Self {
content,
redacts,
event_id,
sender,
origin_server_ts,
unsigned,
}
}
}
/// Redacted redaction event.
#[derive(ToSchema, Clone, Debug, Event)]
#[allow(clippy::exhaustive_structs)]
pub struct RedactedRoomRedactionEvent {
/// Data specific to the event type.
pub content: RedactedRoomRedactionEventContent,
/// The globally unique event identifier for the user who sent the event.
pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event.
pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was
/// sent.
pub origin_server_ts: UnixMillis,
/// The ID of the room associated with this event.
pub room_id: OwnedRoomId,
/// Additional key-value pairs not signed by the homeserver.
#[salvo(schema(value_type = Object, additional_properties = true))]
pub unsigned: RedactedUnsigned,
}
/// Redaction event without a `room_id`.
#[derive(ToSchema, Clone, Debug)]
#[allow(clippy::exhaustive_structs)]
pub struct OriginalSyncRoomRedactionEvent {
/// Data specific to the event type.
pub content: RoomRedactionEventContent,
/// The ID of the event that was redacted.
///
/// This field is required in room versions prior to 11.
pub redacts: Option<OwnedEventId>,
/// The globally unique event identifier for the user who sent the event.
pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event.
pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was
/// sent.
pub origin_server_ts: UnixMillis,
/// Additional key-value pairs not signed by the homeserver.
/// TODO???
#[salvo(schema(value_type = Object, additional_properties = true))]
pub unsigned: RoomRedactionUnsigned,
}
impl OriginalSyncRoomRedactionEvent {
/// Convert this sync event into a full event, one with a `room_id` field.
pub fn into_full_event(self, room_id: OwnedRoomId) -> OriginalRoomRedactionEvent {
let Self {
content,
redacts,
event_id,
sender,
origin_server_ts,
unsigned,
} = self;
OriginalRoomRedactionEvent {
content,
redacts,
event_id,
sender,
origin_server_ts,
room_id,
unsigned,
}
}
pub(crate) fn into_maybe_redacted(self) -> SyncRoomRedactionEvent {
SyncRoomRedactionEvent::Original(self)
}
}
/// Redacted redaction event without a `room_id`.
#[derive(ToSchema, Clone, Debug, Event)]
#[allow(clippy::exhaustive_structs)]
pub struct RedactedSyncRoomRedactionEvent {
/// Data specific to the event type.
pub content: RedactedRoomRedactionEventContent,
/// The globally unique event identifier for the user who sent the event.
pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event.
pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was
/// sent.
pub origin_server_ts: UnixMillis,
/// Additional key-value pairs not signed by the homeserver.
#[salvo(schema(value_type = Object, additional_properties = true))]
pub unsigned: RedactedUnsigned,
}
/// A redaction of an event.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize, EventContent)]
#[palpo_event(type = "m.room.redaction", kind = MessageLike, custom_redacted)]
pub struct RoomRedactionEventContent {
/// The ID of the event that was redacted.
///
/// This field is required starting from room version 11.
#[serde(skip_serializing_if = "Option::is_none")]
pub redacts: Option<OwnedEventId>,
/// The reason for the redaction, if any.
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
impl RoomRedactionEventContent {
/// Creates an empty `RoomRedactionEventContent` according to room versions
/// 1 through 10.
pub fn new_v1() -> Self {
Self::default()
}
/// Creates a `RoomRedactionEventContent` with the required `redacts` field
/// introduced in room version 11.
pub fn new_v11(redacts: OwnedEventId) -> Self {
Self {
redacts: Some(redacts),
..Default::default()
}
}
/// Add the given reason to this `RoomRedactionEventContent`.
pub fn with_reason(mut self, reason: String) -> Self {
self.reason = Some(reason);
self
}
}
impl RedactContent for RoomRedactionEventContent {
type Redacted = RedactedRoomRedactionEventContent;
fn redact(self, rules: &RedactionRules) -> Self::Redacted {
let redacts = self.redacts.filter(|_| rules.keep_room_redaction_redacts);
RedactedRoomRedactionEventContent { redacts }
}
}
/// A redacted redaction event.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct RedactedRoomRedactionEventContent {
/// The ID of the event that was redacted.
///
/// This field is required starting from room version 11.
#[serde(skip_serializing_if = "Option::is_none")]
pub redacts: Option<OwnedEventId>,
}
impl StaticEventContent for RedactedRoomRedactionEventContent {
const TYPE: &'static str = RoomRedactionEventContent::TYPE;
type IsPrefix = <RoomRedactionEventContent as StaticEventContent>::IsPrefix;
}
impl RedactedMessageLikeEventContent for RedactedRoomRedactionEventContent {
fn event_type(&self) -> MessageLikeEventType {
MessageLikeEventType::RoomRedaction
}
}
impl RoomRedactionEvent {
/// Returns the `type` of this event.
pub fn event_type(&self) -> MessageLikeEventType {
match self {
Self::Original(ev) => ev.content.event_type(),
Self::Redacted(ev) => ev.content.event_type(),
}
}
/// Returns this event's `event_id` field.
pub fn event_id(&self) -> &EventId {
match self {
Self::Original(ev) => &ev.event_id,
Self::Redacted(ev) => &ev.event_id,
}
}
/// Returns this event's `sender` field.
pub fn sender(&self) -> &UserId {
match self {
Self::Original(ev) => &ev.sender,
Self::Redacted(ev) => &ev.sender,
}
}
/// Returns this event's `origin_server_ts` field.
pub fn origin_server_ts(&self) -> UnixMillis {
match self {
Self::Original(ev) => ev.origin_server_ts,
Self::Redacted(ev) => ev.origin_server_ts,
}
}
/// Returns this event's `room_id` field.
pub fn room_id(&self) -> &RoomId {
match self {
Self::Original(ev) => &ev.room_id,
Self::Redacted(ev) => &ev.room_id,
}
}
/// Returns the ID of the event that this event redacts, according to the
/// given room version.
///
/// # Panics
///
/// Panics if this is a non-redacted event and both `redacts` field are
/// `None`, which is only possible if the event was modified after being
/// deserialized.
pub fn redacts(&self, room_version: &RoomVersionId) -> Option<&EventId> {
match self {
Self::Original(ev) => Some(ev.redacts(room_version)),
Self::Redacted(ev) => ev.content.redacts.as_deref(),
}
}
/// Get the inner `RoomRedactionEvent` if this is an unredacted event.
pub fn as_original(&self) -> Option<&OriginalRoomRedactionEvent> {
as_variant!(self, Self::Original)
}
}
impl SyncRoomRedactionEvent {
/// Returns the `type` of this event.
pub fn event_type(&self) -> MessageLikeEventType {
match self {
Self::Original(ev) => ev.content.event_type(),
Self::Redacted(ev) => ev.content.event_type(),
}
}
/// Returns this event's `event_id` field.
pub fn event_id(&self) -> &EventId {
match self {
Self::Original(ev) => &ev.event_id,
Self::Redacted(ev) => &ev.event_id,
}
}
/// Returns this event's `sender` field.
pub fn sender(&self) -> &UserId {
match self {
Self::Original(ev) => &ev.sender,
Self::Redacted(ev) => &ev.sender,
}
}
/// Returns this event's `origin_server_ts` field.
pub fn origin_server_ts(&self) -> UnixMillis {
match self {
Self::Original(ev) => ev.origin_server_ts,
Self::Redacted(ev) => ev.origin_server_ts,
}
}
/// Returns the ID of the event that this event redacts, according to the
/// given room version.
///
/// # Panics
///
/// Panics if this is a non-redacted event and both `redacts` field are
/// `None`, which is only possible if the event was modified after being
/// deserialized.
pub fn redacts(&self, room_version: &RoomVersionId) -> Option<&EventId> {
match self {
Self::Original(ev) => Some(ev.redacts(room_version)),
Self::Redacted(ev) => ev.content.redacts.as_deref(),
}
}
/// Get the inner `SyncRoomRedactionEvent` if this is an unredacted event.
pub fn as_original(&self) -> Option<&OriginalSyncRoomRedactionEvent> {
as_variant!(self, Self::Original)
}
/// Convert this sync event into a full event (one with a `room_id` field).
pub fn into_full_event(self, room_id: OwnedRoomId) -> RoomRedactionEvent {
match self {
Self::Original(ev) => RoomRedactionEvent::Original(ev.into_full_event(room_id)),
Self::Redacted(ev) => RoomRedactionEvent::Redacted(ev.into_full_event(room_id)),
}
}
}
impl From<RoomRedactionEvent> for SyncRoomRedactionEvent {
fn from(full: RoomRedactionEvent) -> Self {
match full {
RoomRedactionEvent::Original(ev) => Self::Original(ev.into()),
RoomRedactionEvent::Redacted(ev) => Self::Redacted(ev.into()),
}
}
}
impl OriginalRoomRedactionEvent {
/// Returns the ID of the event that this event redacts, according to the
/// proper `redacts` field for the given room version.
///
/// If the `redacts` field is not the proper one for the given room version,
/// this falls back to the one that is available.
///
/// # Panics
///
/// Panics if both `redacts` field are `None`, which is only possible if the
/// event was modified after being deserialized.
pub fn redacts(&self, room_version: &RoomVersionId) -> &EventId {
redacts(
room_version,
self.redacts.as_deref(),
self.content.redacts.as_deref(),
)
}
}
impl OriginalSyncRoomRedactionEvent {
/// Returns the ID of the event that this event redacts, according to the
/// proper `redacts` field for the given room version.
///
/// If the `redacts` field is not the proper one for the given room version,
/// this falls back to the one that is available.
///
/// # Panics
///
/// Panics if both `redacts` field are `None`, which is only possible if the
/// event was modified after being deserialized.
pub fn redacts(&self, room_version: &RoomVersionId) -> &EventId {
redacts(
room_version,
self.redacts.as_deref(),
self.content.redacts.as_deref(),
)
}
}
impl RedactionEvent for OriginalRoomRedactionEvent {}
impl RedactionEvent for OriginalSyncRoomRedactionEvent {}
impl RedactionEvent for RoomRedactionEvent {}
impl RedactionEvent for SyncRoomRedactionEvent {}
/// Extra information about a redaction that is not incorporated into the
/// event's hash.
#[derive(ToSchema, Clone, Debug, Deserialize)]
pub struct RoomRedactionUnsigned {
/// The time in milliseconds that has elapsed since the event was sent.
///
/// This field is generated by the local homeserver, and may be incorrect if
/// the local time on at least one of the two servers is out of sync,
/// which can cause the age to either be negative or greater than it
/// actually is.
pub age: Option<i64>,
/// The client-supplied transaction ID, if the client being given the event
/// is the same one which sent it.
pub transaction_id: Option<OwnedTransactionId>,
/// [Bundled aggregations] of related child events.
///
/// [Bundled aggregations]: https://spec.matrix.org/latest/client-server-api/#aggregations-of-child-events
#[serde(rename = "m.relations", default)]
pub relations: BundledMessageLikeRelations<OriginalSyncRoomRedactionEvent>,
}
impl RoomRedactionUnsigned {
/// Create a new `Unsigned` with fields set to `None`.
pub fn new() -> Self {
Self {
age: None,
transaction_id: None,
relations: BundledMessageLikeRelations::default(),
}
}
}
impl Default for RoomRedactionUnsigned {
fn default() -> Self {
Self::new()
}
}
impl CanBeEmpty for RoomRedactionUnsigned {
/// Whether this unsigned data is empty (all fields are `None`).
///
/// This method is used to determine whether to skip serializing the
/// `unsigned` field in room events. Do not use it to determine whether
/// an incoming `unsigned` field was present - it could still have been
/// present but contained none of the known fields.
fn is_empty(&self) -> bool {
self.age.is_none() && self.transaction_id.is_none() && self.relations.is_empty()
}
}
/// Returns the value of the proper `redacts` field for the given room version.
///
/// If the `redacts` field is not the proper one for the given room version,
/// this falls back to the one that is available.
///
/// # Panics
///
/// Panics if both `redacts` and `content_redacts` are `None`.
fn redacts<'a>(
room_version: &'_ RoomVersionId,
redacts: Option<&'a EventId>,
content_redacts: Option<&'a EventId>,
) -> &'a EventId {
match room_version {
RoomVersionId::V1
| RoomVersionId::V2
| RoomVersionId::V3
| RoomVersionId::V4
| RoomVersionId::V5
| RoomVersionId::V6
| RoomVersionId::V7
| RoomVersionId::V8
| RoomVersionId::V9
| RoomVersionId::V10 => redacts
.or_else(|| {
error!("Redacts field at event level not available, falling back to the one inside content");
content_redacts
})
.expect("At least one redacts field is set"),
_ => content_redacts
.or_else(|| {
error!("Redacts field inside content not available, falling back to the one at the event level");
redacts
})
.expect("At least one redacts field is set"),
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/create.rs | crates/core/src/events/room/create.rs | //! Types for the [`m.room.create`] event.
//!
//! [`m.room.create`]: https://spec.matrix.org/latest/client-server-api/#mroomcreate
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::room_version_rules::RedactionRules;
use crate::{
OwnedRoomId, OwnedUserId, RoomVersionId,
events::{EmptyStateKey, RedactContent, RedactedStateEventContent, StateEventType},
room::RoomType,
};
/// The content of an `m.room.create` event.
///
/// This is the first event in a room and cannot be changed.
///
/// It acts as the root of all other events.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.room.create", kind = State, state_key_type = EmptyStateKey, custom_redacted)]
pub struct RoomCreateEventContent {
/// The `user_id` of the room creator.
///
/// This is set by the homeserver.
///
/// This is required in room versions 1 trough 10, but is removed starting
/// from room version 11.
#[serde(skip_serializing_if = "Option::is_none")]
#[deprecated = "Since Matrix 1.8. This field was removed in Room version 11, clients should use the event's sender instead"]
pub creator: Option<OwnedUserId>,
/// Whether or not this room's data should be transferred to other
/// homeservers.
#[serde(
rename = "m.federate",
default = "crate::serde::default_true",
skip_serializing_if = "crate::serde::is_true"
)]
pub federate: bool,
/// The version of the room.
///
/// Defaults to `RoomVersionId::V1`.
#[serde(default = "default_room_version_id")]
pub room_version: RoomVersionId,
/// A reference to the room this room replaces, if the previous room was
/// upgraded.
#[serde(skip_serializing_if = "Option::is_none")]
pub predecessor: Option<PreviousRoom>,
/// The room type.
///
/// This is currently only used for spaces.
#[serde(skip_serializing_if = "Option::is_none", rename = "type")]
pub room_type: Option<RoomType>,
}
impl RoomCreateEventContent {
/// Creates a new `RoomCreateEventContent` with the given creator, as
/// required for room versions 1 through 10.
pub fn new_v1(creator: OwnedUserId) -> Self {
Self {
creator: Some(creator),
federate: true,
room_version: default_room_version_id(),
predecessor: None,
room_type: None,
}
}
/// Creates a new `RoomCreateEventContent` with the default values and no
/// creator, as introduced in room version 11.
///
/// The room version is set to [`RoomVersionId::V11`].
pub fn new_v11() -> Self {
Self {
creator: None,
federate: true,
room_version: RoomVersionId::V11,
predecessor: None,
room_type: None,
}
}
/// Creates a new `RoomCreateEventContent` with the default values and no
/// creator, as introduced in room version 11.
///
/// The room version is set to [`RoomVersionId::V12`].
pub fn new_v12() -> Self {
Self {
creator: None,
federate: true,
room_version: RoomVersionId::V12,
predecessor: None,
room_type: None,
}
}
}
impl RedactContent for RoomCreateEventContent {
type Redacted = RedactedRoomCreateEventContent;
fn redact(self, rules: &RedactionRules) -> Self::Redacted {
#[allow(deprecated)]
if rules.keep_room_create_content {
self
} else {
Self {
room_version: default_room_version_id(),
creator: self.creator,
..Self::new_v11()
}
}
}
}
/// A reference to an old room replaced during a room version upgrade.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct PreviousRoom {
/// The ID of the old room.
pub room_id: OwnedRoomId,
// /// The event ID of the last known event in the old room.
// #[deprecated = "\
// This field should be sent by servers when possible for backwards compatibility \
// but clients should not rely on it."]
// #[serde(skip_serializing_if = "Option::is_none")]
// pub event_id: Option<OwnedEventId>,
}
impl PreviousRoom {
/// Creates a new `PreviousRoom` from the given room and event IDs.
pub fn new(room_id: OwnedRoomId) -> Self {
Self { room_id }
}
}
/// Used to default the `room_version` field to room version 1.
fn default_room_version_id() -> RoomVersionId {
RoomVersionId::V1
}
/// Redacted form of [`RoomCreateEventContent`].
///
/// The redaction rules of this event changed with room version 11:
///
/// - In room versions 1 through 10, the `creator` field was preserved during
/// redaction, starting from room version 11 the field is removed.
/// - In room versions 1 through 10, all the other fields were redacted,
/// starting from room version 11 all the fields are preserved.
pub type RedactedRoomCreateEventContent = RoomCreateEventContent;
impl RedactedStateEventContent for RedactedRoomCreateEventContent {
type StateKey = EmptyStateKey;
fn event_type(&self) -> StateEventType {
StateEventType::RoomCreate
}
}
// #[cfg(test)]
// mod tests {
// use crate::{owned_user_id, RoomVersionId};
// use assert_matches2::assert_matches;
// use serde_json::{from_value as from_json_value, json, to_value as
// to_json_value};
// use super::{RoomCreateEventContent, RoomType};
// #[test]
// fn serialization() {
// let content = RoomCreateEventContent {
// federate: false,
// room_version: RoomVersionId::V4,
// predecessor: None,
// room_type: None,
// };
// let json = json!({
// "creator": "@carl:example.com",
// "m.federate": false,
// "room_version": "4"
// });
// assert_eq!(to_json_value(&content).unwrap(), json);
// }
// #[test]
// fn space_serialization() {
// let content = RoomCreateEventContent {
// federate: false,
// room_version: RoomVersionId::V4,
// predecessor: None,
// room_type: Some(RoomType::Space),
// };
// let json = json!({
// "creator": "@carl:example.com",
// "m.federate": false,
// "room_version": "4",
// "type": "m.space"
// });
// assert_eq!(to_json_value(&content).unwrap(), json);
// }
// #[test]
// fn deserialization() {
// let json = json!({
// "creator": "@carl:example.com",
// "m.federate": true,
// "room_version": "4"
// });
// let content =
// from_json_value::<RoomCreateEventContent>(json).unwrap(); assert_eq!
// (content.creator.unwrap(), "@carl:example.com"); assert!(content.
// federate); assert_eq!(content.room_version, RoomVersionId::V4);
// assert_matches!(content.predecessor, None);
// assert_eq!(content.room_type, None);
// }
// #[test]
// fn space_deserialization() {
// let json = json!({
// "creator": "@carl:example.com",
// "m.federate": true,
// "room_version": "4",
// "type": "m.space"
// });
// let content =
// from_json_value::<RoomCreateEventContent>(json).unwrap(); assert_eq!
// (content.creator.unwrap(), "@carl:example.com"); assert!(content.
// federate); assert_eq!(content.room_version, RoomVersionId::V4);
// assert_matches!(content.predecessor, None);
// assert_eq!(content.room_type, Some(RoomType::Space));
// }
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/guest_access.rs | crates/core/src/events/room/guest_access.rs | //! Types for the [`m.room.guest_access`] event.
//!
//! [`m.room.guest_access`]: https://spec.matrix.org/latest/client-server-api/#mroomguest_access
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{PrivOwnedStr, events::EmptyStateKey, serde::StringEnum};
/// The content of an `m.room.guest_access` event.
///
/// Controls whether guest users are allowed to join rooms.
///
/// This event controls whether guest users are allowed to join rooms. If this
/// event is absent, servers should act as if it is present and has the value
/// `GuestAccess::Forbidden`.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.room.guest_access", kind = State, state_key_type = EmptyStateKey)]
pub struct RoomGuestAccessEventContent {
/// A policy for guest user access to a room.
pub guest_access: GuestAccess,
}
impl RoomGuestAccessEventContent {
/// Creates a new `RoomGuestAccessEventContent` with the given policy.
pub fn new(guest_access: GuestAccess) -> Self {
Self { guest_access }
}
}
impl RoomGuestAccessEvent {
/// Obtain the guest access policy, regardless of whether this event is
/// redacted.
pub fn guest_access(&self) -> &GuestAccess {
match self {
Self::Original(ev) => &ev.content.guest_access,
Self::Redacted(_) => &GuestAccess::Forbidden,
}
}
}
impl SyncRoomGuestAccessEvent {
/// Obtain the guest access policy, regardless of whether this event is
/// redacted.
pub fn guest_access(&self) -> &GuestAccess {
match self {
Self::Original(ev) => &ev.content.guest_access,
Self::Redacted(_) => &GuestAccess::Forbidden,
}
}
}
/// A policy for guest user access to a room.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[palpo_enum(rename_all = "snake_case")]
#[non_exhaustive]
pub enum GuestAccess {
/// Guests are allowed to join the room.
CanJoin,
/// Guests are not allowed to join the room.
Forbidden,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/encrypted/unstable_state.rs | crates/core/src/events/room/encrypted/unstable_state.rs | //! Types for `m.room.encrypted` state events, as defined in [MSC4362][msc].
//!
//! [msc]: https://github.com/matrix-org/matrix-spec-proposals/pull/4362
use palpo_core_macros::EventContent;
use serde::{Deserialize, Serialize};use salvo::oapi::ToSchema;
use crate::events::{PossiblyRedactedStateEventContent, StateEventType, StaticEventContent};
use crate::events::room::encrypted::EncryptedEventScheme;
/// The content of an `m.room.encrypted` state event.
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize, EventContent)]
#[palpo_event(type = "m.room.encrypted", kind = State, state_key_type = String, custom_possibly_redacted)]
pub struct StateRoomEncryptedEventContent {
/// Algorithm-specific fields.
#[serde(flatten)]
pub scheme: EncryptedEventScheme,
}
/// The possibly redacted form of [`StateRoomEncryptedEventContent`].
#[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)]
pub struct PossiblyRedactedStateRoomEncryptedEventContent {
/// Algorithm-specific fields.
#[serde(flatten, skip_serializing_if = "Option::is_none")]
pub scheme: Option<EncryptedEventScheme>,
}
impl StaticEventContent for PossiblyRedactedStateRoomEncryptedEventContent {
const TYPE: &'static str = StateRoomEncryptedEventContent::TYPE;
type IsPrefix = <StateRoomEncryptedEventContent as StaticEventContent>::IsPrefix;
}
impl PossiblyRedactedStateEventContent for PossiblyRedactedStateRoomEncryptedEventContent {
type StateKey = String;
fn event_type(&self) -> StateEventType {
StateEventType::RoomEncrypted
}
}
// #[cfg(test)]
// mod tests {
// use assert_matches2::assert_matches;
// use crate::{UnixMillis, room_id, user_id};
// use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
// use crate::{
// AnyStateEvent, StateEvent,
// room::encrypted::{
// EncryptedEventScheme, MegolmV1AesSha2ContentInit,
// unstable_state::StateRoomEncryptedEventContent,
// },
// };
// #[test]
// fn serialize_content() {
// let key_verification_start_content = StateRoomEncryptedEventContent {
// scheme: EncryptedEventScheme::MegolmV1AesSha2(
// MegolmV1AesSha2ContentInit {
// ciphertext: "ciphertext".into(),
// sender_key: "sender_key".into(),
// device_id: "device_id".into(),
// session_id: "session_id".into(),
// }
// .into(),
// ),
// };
// let json_data = json!({
// "algorithm": "m.megolm.v1.aes-sha2",
// "ciphertext": "ciphertext",
// "sender_key": "sender_key",
// "device_id": "device_id",
// "session_id": "session_id",
// });
// assert_eq!(
// to_json_value(&key_verification_start_content).unwrap(),
// json_data
// );
// }
// #[test]
// #[allow(deprecated)]
// fn deserialize_content() {
// let json_data = json!({
// "algorithm": "m.megolm.v1.aes-sha2",
// "ciphertext": "ciphertext",
// "session_id": "session_id",
// });
// let content: StateRoomEncryptedEventContent = from_json_value(json_data).unwrap();
// assert_matches!(
// content.scheme,
// EncryptedEventScheme::MegolmV1AesSha2(scheme)
// );
// assert_eq!(scheme.ciphertext, "ciphertext");
// assert_eq!(scheme.sender_key, None);
// assert_eq!(scheme.device_id, None);
// assert_eq!(scheme.session_id, "session_id");
// }
// #[test]
// #[allow(deprecated)]
// fn deserialize_event() {
// let json_data = json!({
// "type": "m.room.encrypted",
// "event_id": "$event_id:example.com",
// "room_id": "!roomid:example.com",
// "sender": "@example:example.com",
// "origin_server_ts": 1_234_567_890,
// "state_key": "",
// "content": {
// "algorithm": "m.megolm.v1.aes-sha2",
// "ciphertext": "ciphertext",
// "session_id": "session_id",
// }
// });
// let event = from_json_value::<AnyStateEvent>(json_data).unwrap();
// assert_matches!(
// event,
// AnyStateEvent::RoomEncrypted(StateEvent::Original(ev))
// );
// assert_matches!(
// ev.content.scheme,
// EncryptedEventScheme::MegolmV1AesSha2(scheme)
// );
// assert_eq!(scheme.ciphertext, "ciphertext");
// assert_eq!(scheme.sender_key, None);
// assert_eq!(scheme.device_id, None);
// assert_eq!(scheme.session_id, "session_id");
// assert_eq!(ev.sender, user_id!("@example:example.com"));
// assert_eq!(ev.room_id, room_id!("!roomid:example.com"));
// assert_eq!(
// ev.origin_server_ts,
// UnixMillis(uint!(1_234_567_890))
// );
// assert_eq!(ev.state_key, "");
// }
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/encrypted/relation_serde.rs | crates/core/src/events/room/encrypted/relation_serde.rs | use serde::{Deserialize, Deserializer, Serialize, ser::SerializeStruct};
use super::{InReplyTo, Relation, Thread};
use crate::{
OwnedEventId,
serde::{JsonObject, JsonValue, RawJsonValue, from_raw_json_value},
};
impl<'de> Deserialize<'de> for Relation {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let json = Box::<RawJsonValue>::deserialize(deserializer)?;
let RelationDeHelper {
in_reply_to,
rel_type,
} = from_raw_json_value(&json)?;
let rel = match (in_reply_to, rel_type.as_deref()) {
(_, Some("m.thread")) => Relation::Thread(from_raw_json_value(&json)?),
(in_reply_to, Some("io.element.thread")) => {
let ThreadUnstableDeHelper {
event_id,
is_falling_back,
} = from_raw_json_value(&json)?;
Relation::Thread(Thread {
event_id,
in_reply_to,
is_falling_back,
})
}
(_, Some("m.annotation")) => Relation::Annotation(from_raw_json_value(&json)?),
(_, Some("m.reference")) => Relation::Reference(from_raw_json_value(&json)?),
(_, Some("m.replace")) => Relation::Replacement(from_raw_json_value(&json)?),
(Some(in_reply_to), _) => Relation::Reply { in_reply_to },
_ => Relation::_Custom(from_raw_json_value(&json)?),
};
Ok(rel)
}
}
#[derive(Default, Deserialize)]
struct RelationDeHelper {
#[serde(rename = "m.in_reply_to")]
in_reply_to: Option<InReplyTo>,
rel_type: Option<String>,
}
/// A thread relation without the reply fallback, with unstable names.
#[derive(Clone, Deserialize)]
struct ThreadUnstableDeHelper {
event_id: OwnedEventId,
#[serde(rename = "io.element.show_reply", default)]
is_falling_back: bool,
}
impl Relation {
pub(super) fn serialize_data(&self) -> JsonObject {
match serde_json::to_value(self).expect("relation serialization to succeed") {
JsonValue::Object(mut obj) => {
obj.remove("rel_type");
obj
}
_ => panic!("all relations must serialize to objects"),
}
}
}
impl Serialize for Relation {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
Relation::Reply { in_reply_to } => {
let mut st = serializer.serialize_struct("Relation", 1)?;
st.serialize_field("m.in_reply_to", in_reply_to)?;
st.end()
}
Relation::Replacement(data) => RelationSerHelper {
rel_type: "m.replace",
data,
}
.serialize(serializer),
Relation::Reference(data) => RelationSerHelper {
rel_type: "m.reference",
data,
}
.serialize(serializer),
Relation::Annotation(data) => RelationSerHelper {
rel_type: "m.annotation",
data,
}
.serialize(serializer),
Relation::Thread(data) => RelationSerHelper {
rel_type: "m.thread",
data,
}
.serialize(serializer),
Relation::_Custom(c) => c.serialize(serializer),
}
}
}
#[derive(Serialize)]
struct RelationSerHelper<'a, T> {
rel_type: &'a str,
#[serde(flatten)]
data: &'a T,
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/member/change.rs | crates/core/src/events/room/member/change.rs | use super::MembershipState;
use crate::{MxcUri, UserId};
/// The details of a member event required to calculate a [`MembershipChange`].
#[derive(Clone, Debug)]
pub struct MembershipDetails<'a> {
pub(crate) avatar_url: Option<&'a MxcUri>,
pub(crate) display_name: Option<&'a str>,
pub(crate) membership: &'a MembershipState,
}
/// Translation of the membership change in `m.room.member` event.
#[derive(Clone, Debug)]
pub enum MembershipChange<'a> {
/// No change.
None,
/// Must never happen.
Error,
/// User joined the room.
Joined,
/// User left the room.
Left,
/// User was banned.
Banned,
/// User was unbanned.
Unbanned,
/// User was kicked.
Kicked,
/// User was invited.
Invited,
/// User was kicked and banned.
KickedAndBanned,
/// User accepted the invite.
InvitationAccepted,
/// User rejected the invite.
InvitationRejected,
/// User had their invite revoked.
InvitationRevoked,
/// User knocked.
Knocked,
/// User had their knock accepted.
KnockAccepted,
/// User retracted their knock.
KnockRetracted,
/// User had their knock denied.
KnockDenied,
/// `display_name` or `avatar_url` changed.
ProfileChanged {
/// The details of the display_name change, if applicable.
display_name_change: Option<Change<Option<&'a str>>>,
/// The details of the avatar url change, if applicable.
avatar_url_change: Option<Change<Option<&'a MxcUri>>>,
},
/// Not implemented.
NotImplemented,
}
/// A simple representation of a change, containing old and new data.
#[derive(Clone, Debug)]
#[allow(clippy::exhaustive_structs)]
pub struct Change<T> {
/// The old data.
pub old: T,
/// The new data.
pub new: T,
}
impl<T: PartialEq> Change<T> {
fn new(old: T, new: T) -> Option<Self> {
if old == new {
None
} else {
Some(Self { old, new })
}
}
}
/// Internal function so all `RoomMemberEventContent` state event kinds can
/// share the same implementation.
///
/// This must match the table for [`m.room.member`] in the spec.
///
/// [`m.room.member`]: https://spec.matrix.org/latest/client-server-api/#mroommember
pub(super) fn membership_change<'a>(
details: MembershipDetails<'a>,
prev_details: Option<MembershipDetails<'a>>,
sender: &UserId,
state_key: &UserId,
) -> MembershipChange<'a> {
use MembershipChange as Ch;
use MembershipState as St;
let prev_details = match prev_details {
Some(prev) => prev,
None => MembershipDetails {
avatar_url: None,
display_name: None,
membership: &St::Leave,
},
};
match (&prev_details.membership, &details.membership) {
(St::Leave, St::Join) => Ch::Joined,
(St::Invite, St::Join) => Ch::InvitationAccepted,
(St::Invite, St::Leave) if sender == state_key => Ch::InvitationRejected,
(St::Invite, St::Leave) => Ch::InvitationRevoked,
(St::Invite, St::Ban) | (St::Leave, St::Ban) | (St::Knock, St::Ban) => Ch::Banned,
(St::Join, St::Invite)
| (St::Ban, St::Invite)
| (St::Ban, St::Join)
| (St::Join, St::Knock)
| (St::Ban, St::Knock)
| (St::Knock, St::Join) => Ch::Error,
(St::Join, St::Join)
if sender == state_key
&& (prev_details.display_name != details.display_name
|| prev_details.avatar_url != details.avatar_url) =>
{
Ch::ProfileChanged {
display_name_change: Change::new(prev_details.display_name, details.display_name),
avatar_url_change: Change::new(prev_details.avatar_url, details.avatar_url),
}
}
(St::Join, St::Leave) if sender == state_key => Ch::Left,
(St::Join, St::Leave) => Ch::Kicked,
(St::Join, St::Ban) => Ch::KickedAndBanned,
(St::Leave, St::Invite) => Ch::Invited,
(St::Ban, St::Leave) => Ch::Unbanned,
(St::Leave, St::Knock) | (St::Invite, St::Knock) => Ch::Knocked,
(St::Knock, St::Invite) => Ch::KnockAccepted,
(St::Knock, St::Leave) if sender == state_key => Ch::KnockRetracted,
(St::Knock, St::Leave) => Ch::KnockDenied,
(a, b) if a == b => Ch::None,
_ => Ch::NotImplemented,
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/redaction/event_serde.rs | crates/core/src/events/room/redaction/event_serde.rs | use serde::{Deserialize, Deserializer, de};
use super::{
OriginalRoomRedactionEvent, OriginalSyncRoomRedactionEvent, RoomRedactionEvent,
RoomRedactionEventContent, RoomRedactionUnsigned, SyncRoomRedactionEvent,
};
use crate::{
OwnedEventId, OwnedRoomId, OwnedUserId, UnixMillis,
events::RedactionDeHelper,
serde::{RawJsonValue, from_raw_json_value},
};
impl<'de> Deserialize<'de> for RoomRedactionEvent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let json = Box::<RawJsonValue>::deserialize(deserializer)?;
let RedactionDeHelper { unsigned } = from_raw_json_value(&json)?;
if unsigned.and_then(|u| u.redacted_because).is_some() {
Ok(Self::Redacted(from_raw_json_value(&json)?))
} else {
Ok(Self::Original(from_raw_json_value(&json)?))
}
}
}
impl<'de> Deserialize<'de> for SyncRoomRedactionEvent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let json = Box::<RawJsonValue>::deserialize(deserializer)?;
let RedactionDeHelper { unsigned } = from_raw_json_value(&json)?;
if unsigned.and_then(|u| u.redacted_because).is_some() {
Ok(Self::Redacted(from_raw_json_value(&json)?))
} else {
Ok(Self::Original(from_raw_json_value(&json)?))
}
}
}
#[derive(Deserialize)]
struct OriginalRoomRedactionEventDeHelper {
content: RoomRedactionEventContent,
redacts: Option<OwnedEventId>,
event_id: OwnedEventId,
sender: OwnedUserId,
origin_server_ts: UnixMillis,
room_id: Option<OwnedRoomId>,
#[serde(default)]
unsigned: RoomRedactionUnsigned,
}
impl<'de> Deserialize<'de> for OriginalRoomRedactionEvent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let json = Box::<RawJsonValue>::deserialize(deserializer)?;
let OriginalRoomRedactionEventDeHelper {
content,
redacts,
event_id,
sender,
origin_server_ts,
room_id,
unsigned,
} = from_raw_json_value(&json)?;
let Some(room_id) = room_id else {
return Err(de::Error::missing_field("room_id"));
};
if redacts.is_none() && content.redacts.is_none() {
return Err(de::Error::missing_field("redacts"));
}
Ok(Self {
content,
redacts,
event_id,
sender,
origin_server_ts,
room_id,
unsigned,
})
}
}
impl<'de> Deserialize<'de> for OriginalSyncRoomRedactionEvent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let json = Box::<RawJsonValue>::deserialize(deserializer)?;
let OriginalRoomRedactionEventDeHelper {
content,
redacts,
event_id,
sender,
origin_server_ts,
unsigned,
..
} = from_raw_json_value(&json)?;
if redacts.is_none() && content.redacts.is_none() {
return Err(de::Error::missing_field("redacts"));
}
Ok(Self {
content,
redacts,
event_id,
sender,
origin_server_ts,
unsigned,
})
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/message/video.rs | crates/core/src/events/room/message/video.rs | use std::time::Duration;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{
OwnedMxcUri,
events::room::{EncryptedFile, MediaSource, ThumbnailInfo},
};
/// The payload for a video message.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[serde(tag = "msgtype", rename = "m.video")]
pub struct VideoMessageEventContent {
/// A description of the video, e.g. "Gangnam Style", or some kind of
/// content description for accessibility, e.g. "video attachment".
pub body: String,
/// The source of the video clip.
#[serde(flatten)]
pub source: MediaSource,
/// Metadata about the video clip referred to in `source`.
#[serde(skip_serializing_if = "Option::is_none")]
pub info: Option<Box<VideoInfo>>,
}
impl VideoMessageEventContent {
/// Creates a new `VideoMessageEventContent` with the given body and source.
pub fn new(body: String, source: MediaSource) -> Self {
Self {
body,
source,
info: None,
}
}
/// Creates a new non-encrypted `VideoMessageEventContent` with the given
/// body and url.
pub fn plain(body: String, url: OwnedMxcUri) -> Self {
Self::new(body, MediaSource::Plain(url))
}
/// Creates a new encrypted `VideoMessageEventContent` with the given body
/// and encrypted file.
pub fn encrypted(body: String, file: EncryptedFile) -> Self {
Self::new(body, MediaSource::Encrypted(Box::new(file)))
}
/// Creates a new `VideoMessageEventContent` from `self` with the `info`
/// field set to the given value.
///
/// Since the field is public, you can also assign to it directly. This
/// method merely acts as a shorthand for that, because it is very
/// common to set this field.
pub fn info(self, info: impl Into<Option<Box<VideoInfo>>>) -> Self {
Self {
info: info.into(),
..self
}
}
}
/// Metadata about a video.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct VideoInfo {
/// The duration of the video in milliseconds.
#[serde(
with = "palpo_core::serde::duration::opt_ms",
default,
skip_serializing_if = "Option::is_none"
)]
pub duration: Option<Duration>,
/// The height of the video in pixels.
#[serde(rename = "h", skip_serializing_if = "Option::is_none")]
pub height: Option<u64>,
/// The width of the video in pixels.
#[serde(rename = "w", skip_serializing_if = "Option::is_none")]
pub width: Option<u64>,
/// The mimetype of the video, e.g. "video/mp4".
#[serde(skip_serializing_if = "Option::is_none")]
pub mimetype: Option<String>,
/// The size of the video in bytes.
#[serde(skip_serializing_if = "Option::is_none")]
pub size: Option<u64>,
/// Metadata about the image referred to in `thumbnail_source`.
#[serde(skip_serializing_if = "Option::is_none")]
pub thumbnail_info: Option<Box<ThumbnailInfo>>,
/// The source of the thumbnail of the video clip.
#[serde(
flatten,
with = "crate::events::room::thumbnail_source_serde",
skip_serializing_if = "Option::is_none"
)]
pub thumbnail_source: Option<MediaSource>,
/// The [BlurHash](https://blurha.sh) for this video.
///
/// This uses the unstable prefix in
/// [MSC2448](https://github.com/matrix-org/matrix-spec-proposals/pull/2448).
#[cfg(feature = "unstable-msc2448")]
#[serde(
rename = "xyz.amorgan.blurhash",
skip_serializing_if = "Option::is_none"
)]
pub blurhash: Option<String>,
}
impl VideoInfo {
/// Creates an empty `VideoInfo`.
pub fn new() -> Self {
Self::default()
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/message/url_preview.rs | crates/core/src/events/room/message/url_preview.rs | use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::events::room::{EncryptedFile, OwnedMxcUri};
/// The Source of the PreviewImage.
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize)]
#[allow(clippy::exhaustive_enums)]
pub enum PreviewImageSource {
/// Source of the PreviewImage as encrypted file data
#[serde(rename = "beeper:image:encryption", alias = "matrix:image:encryption")]
EncryptedImage(EncryptedFile),
/// Source of the PreviewImage as a simple MxcUri
#[serde(rename = "og:image", alias = "og:image:url")]
Url(OwnedMxcUri),
}
/// Metadata and [`PreviewImageSource`] of an [`UrlPreview`] image.
///
/// Modelled after [OpenGraph Image Properties](https://ogp.me/#structured).
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize)]
pub struct PreviewImage {
/// Source information for the image.
#[serde(flatten)]
pub source: PreviewImageSource,
/// The size of the image in bytes.
#[serde(
rename = "matrix:image:size",
alias = "og:image:size",
skip_serializing_if = "Option::is_none"
)]
pub size: Option<u32>,
/// The width of the image in pixels.
#[serde(rename = "og:image:width", skip_serializing_if = "Option::is_none")]
pub width: Option<u32>,
/// The height of the image in pixels.
#[serde(rename = "og:image:height", skip_serializing_if = "Option::is_none")]
pub height: Option<u32>,
/// The mime_type of the image.
#[serde(rename = "og:image:type", skip_serializing_if = "Option::is_none")]
pub mimetype: Option<String>,
}
impl PreviewImage {
/// Construct a PreviewImage with the given [`OwnedMxcUri`] as the source.
pub fn plain(url: OwnedMxcUri) -> Self {
Self::with_image(PreviewImageSource::Url(url))
}
/// Construct the PreviewImage for the given [`EncryptedFile`] as the source.
pub fn encrypted(file: EncryptedFile) -> Self {
Self::with_image(PreviewImageSource::EncryptedImage(file))
}
fn with_image(source: PreviewImageSource) -> Self {
PreviewImage {
source,
size: None,
width: None,
height: None,
mimetype: None,
}
}
}
/// Preview Information for a URL matched in the message's text, according to
/// [MSC 4095](https://github.com/matrix-org/matrix-spec-proposals/pull/4095).
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize)]
pub struct UrlPreview {
/// The url this was matching on.
#[serde(alias = "matrix:matched_url")]
pub matched_url: Option<String>,
/// Canonical URL according to open graph data.
#[serde(rename = "og:url", skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
/// Title to use for the preview.
#[serde(rename = "og:title", skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
/// Description to use for the preview.
#[serde(rename = "og:description", skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// Metadata of a preview image if given.
#[serde(flatten, skip_serializing_if = "Option::is_none")]
pub image: Option<PreviewImage>,
}
impl UrlPreview {
/// Construct an preview for a matched_url.
pub fn matched_url(matched_url: String) -> Self {
UrlPreview {
matched_url: Some(matched_url),
url: None,
image: None,
description: None,
title: None,
}
}
/// Construct an preview for a canonical url.
pub fn canonical_url(url: String) -> Self {
UrlPreview {
matched_url: None,
url: Some(url),
image: None,
description: None,
title: None,
}
}
/// Whether this preview contains an actual preview or the users homeserver
/// should be asked for preview data instead.
pub fn contains_preview(&self) -> bool {
self.url.is_some()
|| self.title.is_some()
|| self.description.is_some()
|| self.image.is_some()
}
}
// #[cfg(test)]
// mod tests {
// use std::collections::BTreeMap;
// use assert_matches2::assert_matches;
// use assign::assign;
// use js_int::uint;
// use palpo_core::{owned_mxc_uri, serde::Base64};
// use crate::events::room::message::{MessageType, RoomMessageEventContent};
// use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
// use super::{super::text::TextMessageEventContent, *};
// use crate::room::{EncryptedFile, JsonWebKey};
// fn dummy_jwt() -> JsonWebKey {
// JsonWebKey {
// kty: "oct".to_owned(),
// key_ops: vec!["encrypt".to_owned(), "decrypt".to_owned()],
// alg: "A256CTR".to_owned(),
// k: Base64::new(vec![0; 64]),
// ext: true,
// }
// }
// fn encrypted_file() -> EncryptedFile {
// let mut hashes: BTreeMap<String, Base64> = BTreeMap::new();
// hashes.insert("sha256".to_owned(), Base64::new(vec![1; 10]));
// EncryptedFile {
// url: owned_mxc_uri!("mxc://localhost/encryptedfile"),
// key: dummy_jwt(),
// iv: Base64::new(vec![1; 12]),
// hashes,
// v: "v2".to_owned(),
// }
// }
// #[test]
// fn serialize_preview_image() {
// let expected_result = json!({
// "og:image": "mxc://maunium.net/zeHhTqqUtUSUTUDxQisPdwZO"
// });
// let preview =
// PreviewImage::plain(owned_mxc_uri!("mxc://maunium.net/zeHhTqqUtUSUTUDxQisPdwZO"));
// assert_eq!(to_json_value(&preview).unwrap(), expected_result);
// let encrypted_result = json!({
// "beeper:image:encryption": {
// "hashes" : {
// "sha256": "AQEBAQEBAQEBAQ",
// },
// "iv": "AQEBAQEBAQEBAQEB",
// "key": {
// "alg": "A256CTR",
// "ext": true,
// "k": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
// "key_ops": [
// "encrypt",
// "decrypt"
// ],
// "kty": "oct",
// },
// "v": "v2",
// "url": "mxc://localhost/encryptedfile",
// },
// });
// let preview = PreviewImage::encrypted(encrypted_file());
// assert_eq!(to_json_value(&preview).unwrap(), encrypted_result);
// }
// #[test]
// fn serialize_room_message_with_url_preview() {
// let expected_result = json!({
// "msgtype": "m.text",
// "body": "Test message",
// "com.beeper.linkpreviews": [
// {
// "matched_url": "https://matrix.org/",
// "og:image": "mxc://maunium.net/zeHhTqqUtUSUTUDxQisPdwZO",
// }
// ]
// });
// let preview_img =
// PreviewImage::plain(owned_mxc_uri!("mxc://maunium.net/zeHhTqqUtUSUTUDxQisPdwZO"));
// let full_preview = assign!(UrlPreview::matched_url("https://matrix.org/".to_owned()), {image: Some(preview_img)});
// let msg = MessageType::Text(assign!(TextMessageEventContent::plain("Test message"), {
// url_previews: Some(vec![full_preview])
// }));
// assert_eq!(to_json_value(RoomMessageEventContent::new(msg)).unwrap(), expected_result);
// }
// #[test]
// fn serialize_room_message_with_url_preview_with_encrypted_image() {
// let expected_result = json!({
// "msgtype": "m.text",
// "body": "Test message",
// "com.beeper.linkpreviews": [
// {
// "matched_url": "https://matrix.org/",
// "beeper:image:encryption": {
// "hashes" : {
// "sha256": "AQEBAQEBAQEBAQ",
// },
// "iv": "AQEBAQEBAQEBAQEB",
// "key": {
// "alg": "A256CTR",
// "ext": true,
// "k": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
// "key_ops": [
// "encrypt",
// "decrypt"
// ],
// "kty": "oct",
// },
// "v": "v2",
// "url": "mxc://localhost/encryptedfile",
// }
// }
// ]
// });
// let preview_img = PreviewImage::encrypted(encrypted_file());
// let full_preview = assign!(UrlPreview::matched_url("https://matrix.org/".to_owned()), {
// image: Some(preview_img),
// });
// let msg = MessageType::Text(assign!(TextMessageEventContent::plain("Test message"), {
// url_previews: Some(vec![full_preview])
// }));
// assert_eq!(to_json_value(RoomMessageEventContent::new(msg)).unwrap(), expected_result);
// }
// #[cfg(feature = "unstable-msc1767")]
// #[test]
// fn serialize_extensible_room_message_with_preview() {
// use crate::message::MessageEventContent;
// let expected_result = json!({
// "org.matrix.msc1767.text": [
// {"body": "matrix.org/support"}
// ],
// "com.beeper.linkpreviews": [
// {
// "matched_url": "matrix.org/support",
// "matrix:image:size": 16588,
// "og:description": "Matrix, the open protocol for secure decentralised communications",
// "og:image":"mxc://maunium.net/zeHhTqqUtUSUTUDxQisPdwZO",
// "og:image:height": 400,
// "og:image:type": "image/jpeg",
// "og:image:width": 800,
// "og:title": "Support Matrix",
// "og:url": "https://matrix.org/support/"
// }
// ],
// });
// let preview_img = assign!(PreviewImage::plain(owned_mxc_uri!("mxc://maunium.net/zeHhTqqUtUSUTUDxQisPdwZO")), {
// height: Some(uint!(400)),
// width: Some(uint!(800)),
// mimetype: Some("image/jpeg".to_owned()),
// size: Some(uint!(16588))
// });
// let full_preview = assign!(UrlPreview::matched_url("matrix.org/support".to_owned()), {
// image: Some(preview_img),
// url: Some("https://matrix.org/support/".to_owned()),
// title: Some("Support Matrix".to_owned()),
// description: Some("Matrix, the open protocol for secure decentralised communications".to_owned()),
// });
// let msg = assign!(MessageEventContent::plain("matrix.org/support"), {
// url_previews: Some(vec![full_preview])
// });
// assert_eq!(to_json_value(&msg).unwrap(), expected_result);
// }
// #[test]
// fn deserialize_regular_example() {
// let normal_preview = json!({
// "msgtype": "m.text",
// "body": "https://matrix.org",
// "m.url_previews": [
// {
// "matrix:matched_url": "https://matrix.org",
// "matrix:image:size": 16588,
// "og:description": "Matrix, the open protocol for secure decentralised communications",
// "og:image": "mxc://maunium.net/zeHhTqqUtUSUTUDxQisPdwZO",
// "og:image:height": 400,
// "og:image:type": "image/jpeg",
// "og:image:width": 800,
// "og:title": "Matrix.org",
// "og:url": "https://matrix.org/"
// }
// ],
// "m.mentions": {}
// });
// let message_with_preview: TextMessageEventContent =
// from_json_value(normal_preview).unwrap();
// let TextMessageEventContent { url_previews, .. } = message_with_preview;
// let previews = url_previews.expect("No url previews found");
// assert_eq!(previews.len(), 1);
// let UrlPreview { image, matched_url, title, url, description } = previews.first().unwrap();
// assert_eq!(matched_url.as_ref().unwrap(), "https://matrix.org");
// assert_eq!(title.as_ref().unwrap(), "Matrix.org");
// assert_eq!(
// description.as_ref().unwrap(),
// "Matrix, the open protocol for secure decentralised communications"
// );
// assert_eq!(url.as_ref().unwrap(), "https://matrix.org/");
// // Check the preview image parsed:
// let PreviewImage { size, height, width, mimetype, source } = image.clone().unwrap();
// assert_eq!(size.unwrap(), uint!(16588));
// assert_matches!(source, PreviewImageSource::Url(url));
// assert_eq!(url.as_str(), "mxc://maunium.net/zeHhTqqUtUSUTUDxQisPdwZO");
// assert_eq!(height.unwrap(), uint!(400));
// assert_eq!(width.unwrap(), uint!(800));
// assert_eq!(mimetype, Some("image/jpeg".to_owned()));
// }
// #[test]
// fn deserialize_under_dev_prefix() {
// let normal_preview = json!({
// "msgtype": "m.text",
// "body": "https://matrix.org",
// "com.beeper.linkpreviews": [
// {
// "matched_url": "https://matrix.org",
// "matrix:image:size": 16588,
// "og:description": "Matrix, the open protocol for secure decentralised communications",
// "og:image": "mxc://maunium.net/zeHhTqqUtUSUTUDxQisPdwZO",
// "og:image:height": 400,
// "og:image:type": "image/jpeg",
// "og:image:width": 800,
// "og:title": "Matrix.org",
// "og:url": "https://matrix.org/"
// }
// ],
// "m.mentions": {}
// });
// let message_with_preview: TextMessageEventContent =
// from_json_value(normal_preview).unwrap();
// let TextMessageEventContent { url_previews, .. } = message_with_preview;
// let previews = url_previews.expect("No url previews found");
// assert_eq!(previews.len(), 1);
// let UrlPreview { image, matched_url, title, url, description } = previews.first().unwrap();
// assert_eq!(matched_url.as_ref().unwrap(), "https://matrix.org");
// assert_eq!(title.as_ref().unwrap(), "Matrix.org");
// assert_eq!(
// description.as_ref().unwrap(),
// "Matrix, the open protocol for secure decentralised communications"
// );
// assert_eq!(url.as_ref().unwrap(), "https://matrix.org/");
// // Check the preview image parsed:
// let PreviewImage { size, height, width, mimetype, source } = image.clone().unwrap();
// assert_eq!(size.unwrap(), uint!(16588));
// assert_matches!(source, PreviewImageSource::Url(url));
// assert_eq!(url.as_str(), "mxc://maunium.net/zeHhTqqUtUSUTUDxQisPdwZO");
// assert_eq!(height.unwrap(), uint!(400));
// assert_eq!(width.unwrap(), uint!(800));
// assert_eq!(mimetype, Some("image/jpeg".to_owned()));
// }
// #[test]
// fn deserialize_example_no_previews() {
// let normal_preview = json!({
// "msgtype": "m.text",
// "body": "https://matrix.org",
// "m.url_previews": [],
// "m.mentions": {}
// });
// let message_with_preview: TextMessageEventContent =
// from_json_value(normal_preview).unwrap();
// let TextMessageEventContent { url_previews, .. } = message_with_preview;
// assert!(url_previews.clone().unwrap().is_empty(), "Unexpectedly found url previews");
// }
// #[test]
// fn deserialize_example_empty_previews() {
// let normal_preview = json!({
// "msgtype": "m.text",
// "body": "https://matrix.org",
// "m.url_previews": [
// { "matrix:matched_url": "https://matrix.org" }
// ],
// "m.mentions": {}
// });
// let message_with_preview: TextMessageEventContent =
// from_json_value(normal_preview).unwrap();
// let TextMessageEventContent { url_previews, .. } = message_with_preview;
// let previews = url_previews.expect("No url previews found");
// assert_eq!(previews.len(), 1);
// let preview = previews.first().unwrap();
// assert_eq!(preview.matched_url.as_ref().unwrap(), "https://matrix.org");
// assert!(!preview.contains_preview());
// }
// #[test]
// fn deserialize_encrypted_image_dev_example() {
// let normal_preview = json!({
// "msgtype": "m.text",
// "body": "https://matrix.org",
// "com.beeper.linkpreviews": [
// {
// "matched_url": "https://matrix.org",
// "og:title": "Matrix.org",
// "og:url": "https://matrix.org/",
// "og:description": "Matrix, the open protocol for secure decentralised communications",
// "matrix:image:size": 16588,
// "og:image:height": 400,
// "og:image:type": "image/jpeg",
// "og:image:width": 800,
// "beeper:image:encryption": {
// "key": {
// "k": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
// "alg": "A256CTR",
// "ext": true,
// "kty": "oct",
// "key_ops": [
// "encrypt",
// "decrypt"
// ]
// },
// "iv": "AQEBAQEBAQEBAQEB",
// "hashes": {
// "sha256": "AQEBAQEBAQEBAQ"
// },
// "v": "v2",
// "url": "mxc://beeper.com/53207ac52ce3e2c722bb638987064bfdc0cc257b"
// }
// }
// ],
// "m.mentions": {}
// });
// let message_with_preview: TextMessageEventContent =
// from_json_value(normal_preview).unwrap();
// let TextMessageEventContent { url_previews, .. } = message_with_preview;
// let previews = url_previews.expect("No url previews found");
// assert_eq!(previews.len(), 1);
// let UrlPreview { image, matched_url, title, url, description } = previews.first().unwrap();
// assert_eq!(matched_url.as_ref().unwrap(), "https://matrix.org");
// assert_eq!(title.as_ref().unwrap(), "Matrix.org");
// assert_eq!(
// description.as_ref().unwrap(),
// "Matrix, the open protocol for secure decentralised communications"
// );
// assert_eq!(url.as_ref().unwrap(), "https://matrix.org/");
// // Check the preview image parsed:
// let PreviewImage { size, height, width, mimetype, source } = image.as_ref().unwrap();
// assert_eq!(size.unwrap(), uint!(16588));
// assert_matches!(source, PreviewImageSource::EncryptedImage(encrypted_image));
// assert_eq!(
// encrypted_image.url.as_str(),
// "mxc://beeper.com/53207ac52ce3e2c722bb638987064bfdc0cc257b"
// );
// assert_eq!(height.unwrap(), uint!(400));
// assert_eq!(width.unwrap(), uint!(800));
// assert_eq!(mimetype.as_ref().unwrap().as_str(), "image/jpeg");
// }
// #[test]
// #[cfg(feature = "unstable-msc1767")]
// fn deserialize_extensible_example() {
// use crate::message::MessageEventContent;
// let normal_preview = json!({
// "m.text": [
// {"body": "matrix.org/support"}
// ],
// "m.url_previews": [
// {
// "matrix:matched_url": "matrix.org/support",
// "matrix:image:size": 16588,
// "og:description": "Matrix, the open protocol for secure decentralised communications",
// "og:image": "mxc://maunium.net/zeHhTqqUtUSUTUDxQisPdwZO",
// "og:image:height": 400,
// "og:image:type": "image/jpeg",
// "og:image:width": 800,
// "og:title": "Support Matrix",
// "og:url": "https://matrix.org/support/"
// }
// ],
// "m.mentions": {}
// });
// let message_with_preview: MessageEventContent = from_json_value(normal_preview).unwrap();
// let MessageEventContent { url_previews, .. } = message_with_preview;
// let previews = url_previews.expect("No url previews found");
// assert_eq!(previews.len(), 1);
// let preview = previews.first().unwrap();
// assert!(preview.contains_preview());
// let UrlPreview { image, matched_url, title, url, description } = preview;
// assert_eq!(matched_url.as_ref().unwrap(), "matrix.org/support");
// assert_eq!(title.as_ref().unwrap(), "Support Matrix");
// assert_eq!(
// description.as_ref().unwrap(),
// "Matrix, the open protocol for secure decentralised communications"
// );
// assert_eq!(url.as_ref().unwrap(), "https://matrix.org/support/");
// // Check the preview image parsed:
// let PreviewImage { size, height, width, mimetype, source } = image.clone().unwrap();
// assert_eq!(size.unwrap(), uint!(16588));
// assert_matches!(source, PreviewImageSource::Url(url));
// assert_eq!(url.as_str(), "mxc://maunium.net/zeHhTqqUtUSUTUDxQisPdwZO");
// assert_eq!(height.unwrap(), uint!(400));
// assert_eq!(width.unwrap(), uint!(800));
// assert_eq!(mimetype, Some("image/jpeg".to_owned()));
// }
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/message/content_serde.rs | crates/core/src/events/room/message/content_serde.rs | //! `Deserialize` implementation for RoomMessageEventContent and MessageType.
use serde::{Deserialize, de};
use super::{
MessageType, RoomMessageEventContent, RoomMessageEventContentWithoutRelation,
relation_serde::deserialize_relation,
};
use crate::{
events::Mentions,
serde::{RawJsonValue, from_raw_json_value},
};
impl<'de> Deserialize<'de> for RoomMessageEventContent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
let json = Box::<RawJsonValue>::deserialize(deserializer)?;
let mut deserializer = serde_json::Deserializer::from_str(json.get());
let relates_to = deserialize_relation(&mut deserializer).map_err(de::Error::custom)?;
let MentionsDeHelper { mentions } = from_raw_json_value(&json)?;
Ok(Self {
msgtype: from_raw_json_value(&json)?,
relates_to,
mentions,
})
}
}
impl<'de> Deserialize<'de> for RoomMessageEventContentWithoutRelation {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
let json = Box::<RawJsonValue>::deserialize(deserializer)?;
let MentionsDeHelper { mentions } = from_raw_json_value(&json)?;
Ok(Self {
msgtype: from_raw_json_value(&json)?,
mentions,
})
}
}
#[derive(Deserialize)]
struct MentionsDeHelper {
#[serde(rename = "m.mentions")]
mentions: Option<Mentions>,
}
/// Helper struct to determine the msgtype from a `serde_json::value::RawValue`
#[derive(Debug, Deserialize)]
struct MessageTypeDeHelper {
/// The message type field
msgtype: String,
}
impl<'de> Deserialize<'de> for MessageType {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
let json = Box::<RawJsonValue>::deserialize(deserializer)?;
let MessageTypeDeHelper { msgtype } = from_raw_json_value(&json)?;
Ok(match msgtype.as_ref() {
"m.audio" => Self::Audio(from_raw_json_value(&json)?),
"m.emote" => Self::Emote(from_raw_json_value(&json)?),
"m.file" => Self::File(from_raw_json_value(&json)?),
"m.image" => Self::Image(from_raw_json_value(&json)?),
"m.location" => Self::Location(from_raw_json_value(&json)?),
"m.notice" => Self::Notice(from_raw_json_value(&json)?),
"m.server_notice" => Self::ServerNotice(from_raw_json_value(&json)?),
"m.text" => Self::Text(from_raw_json_value(&json)?),
"m.video" => Self::Video(from_raw_json_value(&json)?),
"m.key.verification.request" => Self::VerificationRequest(from_raw_json_value(&json)?),
_ => Self::_Custom(from_raw_json_value(&json)?),
})
}
}
#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/112615
#[cfg(feature = "unstable-msc3488")]
pub(in super::super) mod msc3488 {
use serde::{Deserialize, Serialize};
use crate::{
UnixMillis,
events::{
location::{AssetContent, LocationContent},
message::MessageContentBlock,
room::message::{LocationInfo, LocationMessageEventContent},
},
};
/// Deserialize helper type for `LocationMessageEventContent` with unstable
/// fields from msc3488.
#[derive(Serialize, Deserialize)]
#[serde(tag = "msgtype", rename = "m.location")]
pub(in super::super) struct LocationMessageEventContentSerDeHelper {
pub body: String,
pub geo_uri: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub info: Option<Box<LocationInfo>>,
#[serde(flatten)]
pub message: Option<MessageContentBlock>,
#[serde(
rename = "org.matrix.msc3488.location",
skip_serializing_if = "Option::is_none"
)]
pub location: Option<LocationContent>,
#[serde(
rename = "org.matrix.msc3488.asset",
skip_serializing_if = "Option::is_none"
)]
pub asset: Option<AssetContent>,
#[serde(
rename = "org.matrix.msc3488.ts",
skip_serializing_if = "Option::is_none"
)]
pub ts: Option<UnixMillis>,
}
impl From<LocationMessageEventContent> for LocationMessageEventContentSerDeHelper {
fn from(value: LocationMessageEventContent) -> Self {
let LocationMessageEventContent {
body,
geo_uri,
info,
message,
location,
asset,
ts,
} = value;
Self {
body,
geo_uri,
info,
message: message.map(Into::into),
location,
asset,
ts,
}
}
}
impl From<LocationMessageEventContentSerDeHelper> for LocationMessageEventContent {
fn from(value: LocationMessageEventContentSerDeHelper) -> Self {
let LocationMessageEventContentSerDeHelper {
body,
geo_uri,
info,
message,
location,
asset,
ts,
} = value;
LocationMessageEventContent {
body,
geo_uri,
info,
message: message.map(Into::into),
location,
asset,
ts,
}
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/message/image.rs | crates/core/src/events/room/message/image.rs | use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{
OwnedMxcUri,
events::room::{EncryptedFile, ImageInfo, MediaSource},
};
/// The payload for an image message.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[serde(tag = "msgtype", rename = "m.image")]
pub struct ImageMessageEventContent {
/// A textual representation of the image.
///
/// Could be the alt text of the image, the filename of the image, or some
/// kind of content description for accessibility e.g. "image
/// attachment".
pub body: String,
/// The source of the image.
#[serde(flatten)]
pub source: MediaSource,
/// Metadata about the image referred to in `source`.
#[serde(skip_serializing_if = "Option::is_none")]
pub info: Option<Box<ImageInfo>>,
}
impl ImageMessageEventContent {
/// Creates a new `ImageMessageEventContent` with the given body and source.
pub fn new(body: String, source: MediaSource) -> Self {
Self {
body,
source,
info: None,
}
}
/// Creates a new non-encrypted `ImageMessageEventContent` with the given
/// body and url.
pub fn plain(body: String, url: OwnedMxcUri) -> Self {
Self::new(body, MediaSource::Plain(url))
}
/// Creates a new encrypted `ImageMessageEventContent` with the given body
/// and encrypted file.
pub fn encrypted(body: String, file: EncryptedFile) -> Self {
Self::new(body, MediaSource::Encrypted(Box::new(file)))
}
/// Creates a new `ImageMessageEventContent` from `self` with the `info`
/// field set to the given value.
///
/// Since the field is public, you can also assign to it directly. This
/// method merely acts as a shorthand for that, because it is very
/// common to set this field.
pub fn info(self, info: impl Into<Option<Box<ImageInfo>>>) -> Self {
Self {
info: info.into(),
..self
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/message/relation.rs | crates/core/src/events/room/message/relation.rs | use std::borrow::Cow;
use salvo::oapi::ToSchema;
use serde::Deserialize;
use crate::{
events::relation::{CustomRelation, InReplyTo, RelationType, Replacement, Thread},
serde::JsonObject,
};
/// Message event relationship.
#[derive(ToSchema, Deserialize, Clone, Debug)]
#[allow(clippy::manual_non_exhaustive)]
pub enum Relation<C> {
/// An `m.in_reply_to` relation indicating that the event is a reply to
/// another event.
Reply {
/// Information about another message being replied to.
in_reply_to: InReplyTo,
},
/// An event that replaces another event.
Replacement(Replacement<C>),
/// An event that belongs to a thread.
Thread(Thread),
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(CustomRelation),
}
impl<C> Relation<C>
where
C: ToSchema,
{
/// The type of this `Relation`.
///
/// Returns an `Option` because the `Reply` relation does not have
/// a`rel_type` field.
pub fn rel_type(&self) -> Option<RelationType> {
match self {
Relation::Reply { .. } => None,
Relation::Replacement(_) => Some(RelationType::Replacement),
Relation::Thread(_) => Some(RelationType::Thread),
Relation::_Custom(c) => c.rel_type(),
}
}
/// The associated data.
///
/// The returned JSON object holds the contents of `m.relates_to`, including
/// `rel_type` and `event_id` if present, but not things like
/// `m.new_content` for `m.replace` relations that live next to
/// `m.relates_to`.
///
/// Prefer to use the public variants of `Relation` where possible; this
/// method is meant to be used for custom relations only.
pub fn data(&self) -> Cow<'_, JsonObject>
where
C: Clone,
{
if let Relation::_Custom(CustomRelation(data)) = self {
Cow::Borrowed(data)
} else {
Cow::Owned(self.serialize_data())
}
}
}
/// Message event relationship, except a replacement.
#[derive(ToSchema, Clone, Debug)]
#[allow(clippy::manual_non_exhaustive)]
pub enum RelationWithoutReplacement {
/// An `m.in_reply_to` relation indicating that the event is a reply to
/// another event.
Reply {
/// Information about another message being replied to.
in_reply_to: InReplyTo,
},
/// An event that belongs to a thread.
Thread(Thread),
#[doc(hidden)]
_Custom(CustomRelation),
}
impl RelationWithoutReplacement {
/// The type of this `Relation`.
///
/// Returns an `Option` because the `Reply` relation does not have
/// a`rel_type` field.
pub fn rel_type(&self) -> Option<RelationType> {
match self {
Self::Reply { .. } => None,
Self::Thread(_) => Some(RelationType::Thread),
Self::_Custom(c) => c.rel_type(),
}
}
/// The associated data.
///
/// The returned JSON object holds the contents of `m.relates_to`, including
/// `rel_type` and `event_id` if present, but not things like
/// `m.new_content` for `m.replace` relations that live next to
/// `m.relates_to`.
///
/// Prefer to use the public variants of `Relation` where possible; this
/// method is meant to be used for custom relations only.
pub fn data(&self) -> Cow<'_, JsonObject> {
if let Self::_Custom(CustomRelation(data)) = self {
Cow::Borrowed(data)
} else {
Cow::Owned(self.serialize_data())
}
}
}
impl<C> TryFrom<Relation<C>> for RelationWithoutReplacement
where
C: ToSchema,
{
type Error = Replacement<C>;
fn try_from(value: Relation<C>) -> Result<Self, Self::Error> {
let rel = match value {
Relation::Reply { in_reply_to } => Self::Reply { in_reply_to },
Relation::Replacement(r) => return Err(r),
Relation::Thread(t) => Self::Thread(t),
Relation::_Custom(c) => Self::_Custom(c),
};
Ok(rel)
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/message/key_verification_request.rs | crates/core/src/events/room/message/key_verification_request.rs | use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use super::FormattedBody;
use crate::{OwnedDeviceId, OwnedUserId, events::key::verification::VerificationMethod};
/// The payload for a key verification request message.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[serde(tag = "msgtype", rename = "m.key.verification.request")]
pub struct KeyVerificationRequestEventContent {
/// A fallback message to alert users that their client does not support the
/// key verification framework.
///
/// Clients that do support the key verification framework should hide the
/// body and instead present the user with an interface to accept or
/// reject the key verification.
pub body: String,
/// Formatted form of the `body`.
///
/// As with the `body`, clients that do support the key verification
/// framework should hide the formatted body and instead present the
/// user with an interface to accept or reject the key verification.
#[serde(flatten)]
pub formatted: Option<FormattedBody>,
/// The verification methods supported by the sender.
pub methods: Vec<VerificationMethod>,
/// The device ID which is initiating the request.
pub from_device: OwnedDeviceId,
/// The user ID which should receive the request.
///
/// Users should only respond to verification requests if they are named in
/// this field. Users who are not named in this field and who did not
/// send this event should ignore all other events that have a
/// `m.reference` relationship with this event.
pub to: OwnedUserId,
}
impl KeyVerificationRequestEventContent {
/// Creates a new `KeyVerificationRequestEventContent` with the given body,
/// method, device and user ID.
pub fn new(
body: String,
methods: Vec<VerificationMethod>,
from_device: OwnedDeviceId,
to: OwnedUserId,
) -> Self {
Self {
body,
formatted: None,
methods,
from_device,
to,
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/message/sanitize.rs | crates/core/src/events/room/message/sanitize.rs | //! Convenience methods and types to sanitize text messages.
/// Remove the [rich reply fallback] of the given plain text string.
///
/// [rich reply fallback]: https://spec.matrix.org/latest/client-server-api/#fallbacks-for-rich-replies
pub fn remove_plain_reply_fallback(mut s: &str) -> &str {
if !s.starts_with("> ") {
return s;
}
while s.starts_with("> ") {
if let Some((_line, rest)) = s.split_once('\n') {
s = rest;
} else {
return "";
}
}
// Strip the first line after the fallback if it is empty.
if let Some(rest) = s.strip_prefix('\n') {
rest
} else {
s
}
}
#[cfg(test)]
mod tests {
use super::remove_plain_reply_fallback;
#[test]
fn remove_plain_reply() {
assert_eq!(
remove_plain_reply_fallback("No reply here\nJust a simple message"),
"No reply here\nJust a simple message"
);
assert_eq!(
remove_plain_reply_fallback(
"> <@user:notareal.hs> Replied to on\n\
> two lines\n\
\n\
\n\
This is my reply"
),
"\nThis is my reply"
);
assert_eq!(
remove_plain_reply_fallback("\n> Not on first line"),
"\n> Not on first line"
);
assert_eq!(
remove_plain_reply_fallback("> <@user:notareal.hs> Previous message\n\n> New quote"),
"> New quote"
);
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/message/text.rs | crates/core/src/events/room/message/text.rs | use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use super::FormattedBody;
/// The payload for a text message.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[serde(tag = "msgtype", rename = "m.text")]
pub struct TextMessageEventContent {
/// The body of the message.
pub body: String,
/// Formatted form of the message `body`.
#[serde(flatten)]
pub formatted: Option<FormattedBody>,
}
impl TextMessageEventContent {
/// A convenience constructor to create a plain text message.
pub fn plain(body: impl Into<String>) -> Self {
let body = body.into();
Self {
body,
formatted: None,
}
}
/// A convenience constructor to create an HTML message.
pub fn html(body: impl Into<String>, html_body: impl Into<String>) -> Self {
let body = body.into();
Self {
body,
formatted: Some(FormattedBody::html(html_body)),
}
}
/// A convenience constructor to create a Markdown message.
///
/// Returns an HTML message if some Markdown formatting was detected,
/// otherwise returns a plain text message.
#[cfg(feature = "markdown")]
pub fn markdown(body: impl AsRef<str> + Into<String>) -> Self {
if let Some(formatted) = FormattedBody::markdown(&body) {
Self::html(body, formatted.body)
} else {
Self::plain(body)
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/message/file.rs | crates/core/src/events/room/message/file.rs | use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{
OwnedMxcUri,
events::room::{EncryptedFile, MediaSource, ThumbnailInfo},
};
/// The payload for a file message.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[serde(tag = "msgtype", rename = "m.file")]
pub struct FileMessageEventContent {
/// A human-readable description of the file.
///
/// This is recommended to be the filename of the original upload.
pub body: String,
/// The original filename of the uploaded file.
#[serde(skip_serializing_if = "Option::is_none")]
pub filename: Option<String>,
/// The source of the file.
#[serde(flatten)]
pub source: MediaSource,
/// Metadata about the file referred to in `source`.
#[serde(skip_serializing_if = "Option::is_none")]
pub info: Option<Box<FileInfo>>,
}
impl FileMessageEventContent {
/// Creates a new `FileMessageEventContent` with the given body and source.
pub fn new(body: String, source: MediaSource) -> Self {
Self {
body,
filename: None,
source,
info: None,
}
}
/// Creates a new non-encrypted `FileMessageEventContent` with the given
/// body and url.
pub fn plain(body: String, url: OwnedMxcUri) -> Self {
Self::new(body, MediaSource::Plain(url))
}
/// Creates a new encrypted `FileMessageEventContent` with the given body
/// and encrypted file.
pub fn encrypted(body: String, file: EncryptedFile) -> Self {
Self::new(body, MediaSource::Encrypted(Box::new(file)))
}
/// Creates a new `FileMessageEventContent` from `self` with the `filename`
/// field set to the given value.
///
/// Since the field is public, you can also assign to it directly. This
/// method merely acts as a shorthand for that, because it is very
/// common to set this field.
pub fn filename(self, filename: impl Into<Option<String>>) -> Self {
Self {
filename: filename.into(),
..self
}
}
/// Creates a new `FileMessageEventContent` from `self` with the `info`
/// field set to the given value.
///
/// Since the field is public, you can also assign to it directly. This
/// method merely acts as a shorthand for that, because it is very
/// common to set this field.
pub fn info(self, info: impl Into<Option<Box<FileInfo>>>) -> Self {
Self {
info: info.into(),
..self
}
}
}
/// Metadata about a file.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct FileInfo {
/// The mimetype of the file, e.g. "application/msword".
#[serde(skip_serializing_if = "Option::is_none")]
pub mimetype: Option<String>,
/// The size of the file in bytes.
#[serde(skip_serializing_if = "Option::is_none")]
pub size: Option<u64>,
/// Metadata about the image referred to in `thumbnail_source`.
#[serde(skip_serializing_if = "Option::is_none")]
pub thumbnail_info: Option<Box<ThumbnailInfo>>,
/// The source of the thumbnail of the file.
#[serde(
flatten,
with = "crate::events::room::thumbnail_source_serde",
skip_serializing_if = "Option::is_none"
)]
pub thumbnail_source: Option<MediaSource>,
}
impl FileInfo {
/// Creates an empty `FileInfo`.
pub fn new() -> Self {
Self::default()
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/message/server_notice.rs | crates/core/src/events/room/message/server_notice.rs | use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{PrivOwnedStr, serde::StringEnum};
/// The payload for a server notice message.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[serde(tag = "msgtype", rename = "m.server_notice")]
pub struct ServerNoticeMessageEventContent {
/// A human-readable description of the notice.
pub body: String,
/// The type of notice being represented.
pub server_notice_type: ServerNoticeType,
/// A URI giving a contact method for the server administrator.
///
/// Required if the notice type is `m.server_notice.usage_limit_reached`.
#[serde(skip_serializing_if = "Option::is_none")]
pub admin_contact: Option<String>,
/// The kind of usage limit the server has exceeded.
///
/// Required if the notice type is `m.server_notice.usage_limit_reached`.
#[serde(skip_serializing_if = "Option::is_none")]
pub limit_type: Option<LimitType>,
}
impl ServerNoticeMessageEventContent {
/// Creates a new `ServerNoticeMessageEventContent` with the given body and
/// notice type.
pub fn new(body: String, server_notice_type: ServerNoticeType) -> Self {
Self {
body,
server_notice_type,
admin_contact: None,
limit_type: None,
}
}
}
/// Types of server notices.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[non_exhaustive]
pub enum ServerNoticeType {
/// The server has exceeded some limit which requires the server
/// administrator to intervene.
#[palpo_enum(rename = "m.server_notice.usage_limit_reached")]
UsageLimitReached,
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(PrivOwnedStr),
}
/// Types of usage limits.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[palpo_enum(rename_all = "snake_case")]
#[non_exhaustive]
pub enum LimitType {
/// The server's number of active users in the last 30 days has exceeded the
/// maximum.
///
/// New connections are being refused by the server. What defines "active"
/// is left as an implementation detail, however servers are encouraged
/// to treat syncing users as "active".
MonthlyActiveUser,
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(PrivOwnedStr),
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/message/relation_serde.rs | crates/core/src/events/room/message/relation_serde.rs | use serde::{Deserialize, Deserializer, Serialize, de};
use serde_json::Value as JsonValue;
use super::{InReplyTo, Relation, RelationWithoutReplacement, Replacement, Thread};
use crate::{OwnedEventId, events::relation::CustomRelation, serde::JsonObject};
/// Deserialize an event's `relates_to` field.
///
/// Use it like this:
/// ```
/// use serde::{Deserialize, Serialize};
/// use palpo_core::events::room::message::{MessageType, Relation, deserialize_relation};
///
/// #[derive(Deserialize, Serialize)]
/// struct MyEventContent {
/// #[serde(
/// flatten,
/// skip_serializing_if = "Option::is_none",
/// deserialize_with = "deserialize_relation"
/// )]
/// relates_to: Option<Relation<MessageType>>,
/// }
/// ```
pub fn deserialize_relation<'de, D, C>(deserializer: D) -> Result<Option<Relation<C>>, D::Error>
where
D: Deserializer<'de>,
C: Deserialize<'de>,
{
let EventWithRelatesToDeHelper {
relates_to,
new_content,
} = EventWithRelatesToDeHelper::deserialize(deserializer)?;
let Some(relates_to) = relates_to else {
return Ok(None);
};
let RelatesToDeHelper {
in_reply_to,
relation,
} = relates_to;
let rel = match relation {
RelationDeHelper::Known(relation) => match relation {
KnownRelationDeHelper::Replacement(ReplacementJsonRepr { event_id }) => {
match new_content {
Some(new_content) => Relation::Replacement(Replacement {
event_id,
new_content,
}),
None => return Err(de::Error::missing_field("m.new_content")),
}
}
KnownRelationDeHelper::Thread(ThreadDeHelper {
event_id,
is_falling_back,
})
| KnownRelationDeHelper::ThreadUnstable(ThreadUnstableDeHelper {
event_id,
is_falling_back,
}) => Relation::Thread(Thread {
event_id,
in_reply_to,
is_falling_back,
}),
},
RelationDeHelper::Unknown(c) => {
if let Some(in_reply_to) = in_reply_to {
Relation::Reply { in_reply_to }
} else {
Relation::_Custom(c)
}
}
};
Ok(Some(rel))
}
impl<C> Serialize for Relation<C>
where
C: Clone + Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let (relates_to, new_content) = self.clone().into_parts();
EventWithRelatesToSerHelper {
relates_to,
new_content,
}
.serialize(serializer)
}
}
#[derive(Deserialize)]
pub(crate) struct EventWithRelatesToDeHelper<C> {
#[serde(rename = "m.relates_to")]
relates_to: Option<RelatesToDeHelper>,
#[serde(rename = "m.new_content")]
new_content: Option<C>,
}
#[derive(Deserialize)]
pub(crate) struct RelatesToDeHelper {
#[serde(rename = "m.in_reply_to")]
in_reply_to: Option<InReplyTo>,
#[serde(flatten)]
relation: RelationDeHelper,
}
#[derive(Deserialize)]
#[serde(untagged)]
pub(crate) enum RelationDeHelper {
Known(KnownRelationDeHelper),
Unknown(CustomRelation),
}
#[derive(Deserialize)]
#[serde(tag = "rel_type")]
pub(crate) enum KnownRelationDeHelper {
#[serde(rename = "m.replace")]
Replacement(ReplacementJsonRepr),
#[serde(rename = "m.thread")]
Thread(ThreadDeHelper),
#[serde(rename = "io.element.thread")]
ThreadUnstable(ThreadUnstableDeHelper),
}
/// A replacement relation without `m.new_content`.
#[derive(Deserialize, Serialize)]
pub(crate) struct ReplacementJsonRepr {
event_id: OwnedEventId,
}
/// A thread relation without the reply fallback, with stable names.
#[derive(Deserialize)]
pub(crate) struct ThreadDeHelper {
event_id: OwnedEventId,
#[serde(default)]
is_falling_back: bool,
}
/// A thread relation without the reply fallback, with unstable names.
#[derive(Deserialize)]
pub(crate) struct ThreadUnstableDeHelper {
event_id: OwnedEventId,
#[serde(rename = "io.element.show_reply", default)]
is_falling_back: bool,
}
#[derive(Serialize)]
pub(super) struct EventWithRelatesToSerHelper<C> {
#[serde(rename = "m.relates_to")]
relates_to: RelationSerHelper,
#[serde(rename = "m.new_content", skip_serializing_if = "Option::is_none")]
new_content: Option<C>,
}
/// A relation, which associates new information to an existing event.
#[derive(Serialize)]
#[serde(tag = "rel_type")]
pub(super) enum RelationSerHelper {
/// An event that replaces another event.
#[serde(rename = "m.replace")]
Replacement(ReplacementJsonRepr),
/// An event that belongs to a thread, with stable names.
#[serde(rename = "m.thread")]
Thread(Thread),
/// An unknown relation type.
#[serde(untagged)]
Custom(CustomSerHelper),
}
impl<C> Relation<C> {
fn into_parts(self) -> (RelationSerHelper, Option<C>) {
match self {
Relation::Replacement(Replacement {
event_id,
new_content,
}) => (
RelationSerHelper::Replacement(ReplacementJsonRepr { event_id }),
Some(new_content),
),
Relation::Reply { in_reply_to } => {
(RelationSerHelper::Custom(in_reply_to.into()), None)
}
Relation::Thread(t) => (RelationSerHelper::Thread(t), None),
Relation::_Custom(c) => (RelationSerHelper::Custom(c.into()), None),
}
}
pub(super) fn serialize_data(&self) -> JsonObject
where
C: Clone,
{
let (relates_to, _) = self.clone().into_parts();
match serde_json::to_value(relates_to).expect("relation serialization to succeed") {
JsonValue::Object(mut obj) => {
obj.remove("rel_type");
obj
}
_ => panic!("all relations must serialize to objects"),
}
}
}
#[derive(Default, Serialize)]
pub(super) struct CustomSerHelper {
#[serde(rename = "m.in_reply_to", skip_serializing_if = "Option::is_none")]
in_reply_to: Option<InReplyTo>,
#[serde(flatten, skip_serializing_if = "JsonObject::is_empty")]
data: JsonObject,
}
impl From<InReplyTo> for CustomSerHelper {
fn from(value: InReplyTo) -> Self {
Self {
in_reply_to: Some(value),
data: JsonObject::new(),
}
}
}
impl From<CustomRelation> for CustomSerHelper {
fn from(CustomRelation(data): CustomRelation) -> Self {
Self {
in_reply_to: None,
data,
}
}
}
impl From<&RelationWithoutReplacement> for RelationSerHelper {
fn from(value: &RelationWithoutReplacement) -> Self {
match value.clone() {
RelationWithoutReplacement::Reply { in_reply_to } => {
RelationSerHelper::Custom(in_reply_to.into())
}
RelationWithoutReplacement::Thread(t) => RelationSerHelper::Thread(t),
RelationWithoutReplacement::_Custom(c) => RelationSerHelper::Custom(c.into()),
}
}
}
impl Serialize for RelationWithoutReplacement {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
RelationSerHelper::from(self).serialize(serializer)
}
}
impl RelationWithoutReplacement {
pub(super) fn serialize_data(&self) -> JsonObject {
let helper = RelationSerHelper::from(self);
match serde_json::to_value(helper).expect("relation serialization to succeed") {
JsonValue::Object(mut obj) => {
obj.remove("rel_type");
obj
}
_ => panic!("all relations must serialize to objects"),
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events/room/message/location.rs | crates/core/src/events/room/message/location.rs | use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::events::room::{MediaSource, ThumbnailInfo};
#[cfg(feature = "unstable-msc3488")]
use crate::{
UnixMillis,
events::location::{AssetContent, AssetType, LocationContent},
events::message::{TextContentBlock, TextRepresentation},
};
/// The payload for a location message.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[serde(tag = "msgtype", rename = "m.location")]
#[cfg_attr(
feature = "unstable-msc3488",
serde(
from = "super::content_serde::msc3488::LocationMessageEventContentSerDeHelper",
into = "super::content_serde::msc3488::LocationMessageEventContentSerDeHelper"
)
)]
pub struct LocationMessageEventContent {
/// A description of the location e.g. "Big Ben, London, UK", or some kind
/// of content description for accessibility, e.g. "location
/// attachment".
pub body: String,
/// A geo URI representing the location.
pub geo_uri: String,
/// Info about the location being represented.
#[serde(skip_serializing_if = "Option::is_none")]
pub info: Option<Box<LocationInfo>>,
/// Extensible-event text representation of the message.
///
/// If present, this should be preferred over the `body` field.
#[cfg(feature = "unstable-msc3488")]
pub message: Option<TextContentBlock>,
/// Extensible-event location info of the message.
///
/// If present, this should be preferred over the `geo_uri` field.
#[cfg(feature = "unstable-msc3488")]
pub location: Option<LocationContent>,
/// Extensible-event asset this message refers to.
#[cfg(feature = "unstable-msc3488")]
pub asset: Option<AssetContent>,
/// Extensible-event timestamp this message refers to.
#[cfg(feature = "unstable-msc3488")]
pub ts: Option<UnixMillis>,
}
impl LocationMessageEventContent {
/// Creates a new `LocationMessageEventContent` with the given body and geo
/// URI.
pub fn new(body: String, geo_uri: String) -> Self {
Self {
#[cfg(feature = "unstable-msc3488")]
message: Some(vec![TextRepresentation::plain(&body)].into()),
#[cfg(feature = "unstable-msc3488")]
location: Some(LocationContent::new(geo_uri.clone())),
#[cfg(feature = "unstable-msc3488")]
asset: Some(AssetContent::default()),
#[cfg(feature = "unstable-msc3488")]
ts: None,
body,
geo_uri,
info: None,
}
}
/// Set the asset type of this `LocationMessageEventContent`.
#[cfg(feature = "unstable-msc3488")]
pub fn with_asset_type(mut self, asset: AssetType) -> Self {
self.asset = Some(AssetContent { type_: asset });
self
}
/// Set the timestamp of this `LocationMessageEventContent`.
#[cfg(feature = "unstable-msc3488")]
pub fn with_ts(mut self, ts: UnixMillis) -> Self {
self.ts = Some(ts);
self
}
/// Get the `geo:` URI of this `LocationMessageEventContent`.
pub fn geo_uri(&self) -> &str {
#[cfg(feature = "unstable-msc3488")]
if let Some(uri) = self.location.as_ref().map(|l| &l.uri) {
return uri;
}
&self.geo_uri
}
/// Get the plain text representation of this `LocationMessageEventContent`.
pub fn plain_text_representation(&self) -> &str {
#[cfg(feature = "unstable-msc3488")]
if let Some(text) = self.message.as_ref().and_then(|m| m.find_plain()) {
return text;
}
&self.body
}
/// Get the asset type of this `LocationMessageEventContent`.
#[cfg(feature = "unstable-msc3488")]
pub fn asset_type(&self) -> AssetType {
self.asset
.as_ref()
.map(|a| a.type_.clone())
.unwrap_or_default()
}
}
/// Thumbnail info associated with a location.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct LocationInfo {
/// The source of a thumbnail of the location.
#[serde(
flatten,
with = "crate::events::room::thumbnail_source_serde",
skip_serializing_if = "Option::is_none"
)]
pub thumbnail_source: Option<MediaSource>,
/// Metadata about the image referred to in `thumbnail_source.
#[serde(skip_serializing_if = "Option::is_none")]
pub thumbnail_info: Option<Box<ThumbnailInfo>>,
}
impl LocationInfo {
/// Creates an empty `LocationInfo`.
pub fn new() -> Self {
Self::default()
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.