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/events/room/message/gallery.rs | crates/core/src/events/room/message/gallery.rs | use std::borrow::Cow;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde_json::Value as JsonValue;
use super::{
AudioMessageEventContent, FileMessageEventContent, FormattedBody, ImageMessageEventContent,
VideoMessageEventContent,
};
use crate::serde::JsonObject;
/// The payload for a gallery message.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct GalleryMessageEventContent {
/// A human-readable description of the gallery.
pub body: String,
/// Formatted form of the message `body`.
#[serde(flatten)]
pub formatted: Option<FormattedBody>,
/// Item types for the media in the gallery.
pub itemtypes: Vec<GalleryItemType>,
}
impl GalleryMessageEventContent {
/// Creates a new `GalleryMessageEventContent`.
pub fn new(
body: String,
formatted: Option<FormattedBody>,
itemtypes: Vec<GalleryItemType>,
) -> Self {
Self {
body,
formatted,
itemtypes,
}
}
}
/// The content that is specific to each gallery item type variant.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "itemtype")]
pub enum GalleryItemType {
/// An audio item.
#[serde(rename = "m.audio")]
Audio(AudioMessageEventContent),
/// A file item.
#[serde(rename = "m.file")]
File(FileMessageEventContent),
/// An image item.
#[serde(rename = "m.image")]
Image(ImageMessageEventContent),
/// A video item.
#[serde(rename = "m.video")]
Video(VideoMessageEventContent),
/// A custom item.
#[doc(hidden)]
#[serde(untagged)]
_Custom(CustomEventContent),
}
impl GalleryItemType {
/// Creates a new `GalleryItemType`.
///
/// The `itemtype` and `body` are required fields.
/// Additionally it's possible to add arbitrary key/value pairs to the event content for custom
/// item types through the `data` map.
///
/// Prefer to use the public variants of `GalleryItemType` where possible; this constructor is
/// meant be used for unsupported item types only and does not allow setting arbitrary data
/// for supported ones.
///
/// # Errors
///
/// Returns an error if the `itemtype` is known and serialization of `data` to the corresponding
/// `GalleryItemType` variant fails.
pub fn new(itemtype: &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 itemtype {
"m.audio" => Self::Audio(deserialize_variant(body, data)?),
"m.file" => Self::File(deserialize_variant(body, data)?),
"m.image" => Self::Image(deserialize_variant(body, data)?),
"m.video" => Self::Video(deserialize_variant(body, data)?),
_ => Self::_Custom(CustomEventContent {
itemtype: itemtype.to_owned(),
body,
data,
}),
})
}
/// Returns a reference to the `itemtype` string.
pub fn itemtype(&self) -> &str {
match self {
Self::Audio(_) => "m.audio",
Self::File(_) => "m.file",
Self::Image(_) => "m.image",
Self::Video(_) => "m.video",
Self::_Custom(c) => &c.itemtype,
}
}
/// Return a reference to the itemtype body.
pub fn body(&self) -> &str {
match self {
GalleryItemType::Audio(m) => &m.body,
GalleryItemType::File(m) => &m.body,
GalleryItemType::Image(m) => &m.body,
GalleryItemType::Video(m) => &m.body,
GalleryItemType::_Custom(m) => &m.body,
}
}
/// Returns the associated data.
///
/// The returned JSON object won't contain the `itemtype` and `body` fields, use
/// [`.itemtype()`][Self::itemtype] / [`.body()`](Self::body) to access those.
///
/// Prefer to use the public variants of `GalleryItemType` 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("item type serialization to succeed") {
JsonValue::Object(mut obj) => {
obj.remove("body");
obj
}
_ => panic!("all item types must serialize to objects"),
}
}
match self {
Self::Audio(d) => Cow::Owned(serialize(d)),
Self::File(d) => Cow::Owned(serialize(d)),
Self::Image(d) => Cow::Owned(serialize(d)),
Self::Video(d) => Cow::Owned(serialize(d)),
Self::_Custom(c) => Cow::Borrowed(&c.data),
}
}
}
/// The payload for a custom item type.
#[doc(hidden)]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct CustomEventContent {
/// A custom itemtype.
itemtype: String,
/// The message body.
body: String,
/// Remaining event content.
#[serde(flatten)]
data: JsonObject,
}
| 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/notice.rs | crates/core/src/events/room/message/notice.rs | use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use super::FormattedBody;
/// The payload for a notice message.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[serde(tag = "msgtype", rename = "m.notice")]
pub struct NoticeMessageEventContent {
/// The notice text.
pub body: String,
/// Formatted form of the message `body`.
#[serde(flatten)]
pub formatted: Option<FormattedBody>,
}
impl NoticeMessageEventContent {
/// A convenience constructor to create a plain text notice.
pub fn plain(body: impl Into<String>) -> Self {
let body = body.into();
Self {
body,
formatted: None,
}
}
/// A convenience constructor to create an html notice.
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 notice.
///
/// Returns an html notice if some markdown formatting was detected,
/// otherwise returns a plain text notice.
#[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/audio.rs | crates/core/src/events/room/message/audio.rs | use std::time::Duration;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{
OwnedMxcUri,
events::room::{EncryptedFile, MediaSource},
};
/// The payload for an audio message.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[serde(tag = "msgtype", rename = "m.audio")]
pub struct AudioMessageEventContent {
/// The textual representation of this message.
pub body: String,
/// The source of the audio clip.
#[serde(flatten)]
pub source: MediaSource,
/// Metadata for the audio clip referred to in `source`.
#[serde(skip_serializing_if = "Option::is_none")]
pub info: Option<Box<AudioInfo>>,
/// Extensible event fallback data for audio messages, from the
/// [first version of MSC3245][msc].
///
/// [msc]: https://github.com/matrix-org/matrix-spec-proposals/blob/83f6c5b469c1d78f714e335dcaa25354b255ffa5/proposals/3245-voice-messages.md
#[cfg(feature = "unstable-msc3245-v1-compat")]
#[serde(
rename = "org.matrix.msc1767.audio",
skip_serializing_if = "Option::is_none"
)]
pub audio: Option<UnstableAudioDetailsContentBlock>,
/// Extensible event fallback data for voice messages, from the
/// [first version of MSC3245][msc].
///
/// [msc]: https://github.com/matrix-org/matrix-spec-proposals/blob/83f6c5b469c1d78f714e335dcaa25354b255ffa5/proposals/3245-voice-messages.md
#[cfg(feature = "unstable-msc3245-v1-compat")]
#[serde(
rename = "org.matrix.msc3245.voice",
skip_serializing_if = "Option::is_none"
)]
pub voice: Option<UnstableVoiceContentBlock>,
}
impl AudioMessageEventContent {
/// Creates a new `AudioMessageEventContent` with the given body and source.
pub fn new(body: String, source: MediaSource) -> Self {
Self {
body,
source,
info: None,
#[cfg(feature = "unstable-msc3245-v1-compat")]
audio: None,
#[cfg(feature = "unstable-msc3245-v1-compat")]
voice: None,
}
}
/// Creates a new non-encrypted `AudioMessageEventContent` with the given
/// bod and url.
pub fn plain(body: String, url: OwnedMxcUri) -> Self {
Self::new(body, MediaSource::Plain(url))
}
/// Creates a new encrypted `AudioMessageEventContent` 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 `AudioMessageEventContent` 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<AudioInfo>>>) -> Self {
Self {
info: info.into(),
..self
}
}
}
/// Metadata about an audio clip.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct AudioInfo {
/// The duration of the audio in milliseconds.
#[serde(
with = "palpo_core::serde::duration::opt_ms",
default,
skip_serializing_if = "Option::is_none"
)]
pub duration: Option<Duration>,
/// The mimetype of the audio, e.g. "audio/aac".
#[serde(skip_serializing_if = "Option::is_none")]
pub mimetype: Option<String>,
/// The size of the audio clip in bytes.
#[serde(skip_serializing_if = "Option::is_none")]
pub size: Option<u64>,
}
impl AudioInfo {
/// Creates an empty `AudioInfo`.
pub fn new() -> Self {
Self::default()
}
}
/// Extensible event fallback data for audio messages, from the
/// [first version of MSC3245][msc].
///
/// [msc]: https://github.com/matrix-org/matrix-spec-proposals/blob/83f6c5b469c1d78f714e335dcaa25354b255ffa5/proposals/3245-voice-messages.md
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize)]
pub struct UnstableAudioDetailsContentBlock {
/// The duration of the audio in milliseconds.
///
/// Note that the MSC says this should be in seconds but for compatibility
/// with the Element clients, this uses milliseconds.
#[serde(with = "palpo_core::serde::duration::ms")]
pub duration: Duration,
/// The waveform representation of the audio content, if any.
///
/// This is optional and defaults to an empty array.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub waveform: Vec<UnstableAmplitude>,
}
impl UnstableAudioDetailsContentBlock {
/// Creates a new `UnstableAudioDetailsContentBlock ` with the given
/// duration and waveform.
pub fn new(duration: Duration, waveform: Vec<UnstableAmplitude>) -> Self {
Self { duration, waveform }
}
}
/// Extensible event fallback data for voice messages, from the
/// [first version of MSC3245][msc].
///
/// [msc]: https://github.com/matrix-org/matrix-spec-proposals/blob/83f6c5b469c1d78f714e335dcaa25354b255ffa5/proposals/3245-voice-messages.md
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct UnstableVoiceContentBlock {}
impl UnstableVoiceContentBlock {
/// Creates a new `UnstableVoiceContentBlock`.
pub fn new() -> Self {
Self::default()
}
}
/// The unstable version of the amplitude of a waveform sample.
///
/// Must be an integer between 0 and 1024.
#[derive(
ToSchema, Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize,
)]
pub struct UnstableAmplitude(u64);
impl UnstableAmplitude {
/// 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, 1024.
pub const MAX: u16 = 1024;
/// Creates a new `UnstableAmplitude` with the given value.
///
/// It will saturate if it is bigger than [`UnstableAmplitude::MAX`].
pub fn new(value: u16) -> Self {
Self(value.min(Self::MAX).into())
}
/// The value of this `UnstableAmplitude`.
pub fn get(&self) -> u64 {
self.0
}
}
impl From<u16> for UnstableAmplitude {
fn from(value: u16) -> Self {
Self::new(value)
}
}
impl<'de> Deserialize<'de> for UnstableAmplitude {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let uint = u64::deserialize(deserializer)?;
Ok(Self(uint.min(Self::MAX.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/room/message/emote.rs | crates/core/src/events/room/message/emote.rs | use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use super::FormattedBody;
/// The payload for an emote message.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[serde(tag = "msgtype", rename = "m.emote")]
pub struct EmoteMessageEventContent {
/// The emote action to perform.
pub body: String,
/// Formatted form of the message `body`.
#[serde(flatten)]
pub formatted: Option<FormattedBody>,
}
impl EmoteMessageEventContent {
/// A convenience constructor to create a plain-text emote.
pub fn plain(body: impl Into<String>) -> Self {
let body = body.into();
Self {
body,
formatted: None,
}
}
/// A convenience constructor to create an html emote 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 emote.
///
/// Returns an html emote message if some markdown formatting was detected,
/// otherwise returns a plain-text emote.
#[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/without_relation.rs | crates/core/src/events/room/message/without_relation.rs | use salvo::oapi::ToSchema;
use serde::Serialize;
use super::{
AddMentions, ForwardThread, MessageType, Relation, ReplacementMetadata, ReplyMetadata,
ReplyWithinThread, RoomMessageEventContent,
};
use crate::events::Mentions;
use crate::events::relation::{InReplyTo, Replacement, Thread};
/// Form of [`RoomMessageEventContent`] without relation.
#[derive(ToSchema, Clone, Debug, Serialize)]
pub struct RoomMessageEventContentWithoutRelation {
/// A key which identifies the type of message being sent.
///
/// This also holds the specific content of each message.
#[serde(flatten)]
pub msgtype: MessageType,
/// The [mentions] of this event.
///
/// [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 RoomMessageEventContentWithoutRelation {
/// Creates a new `RoomMessageEventContentWithoutRelation` with the given
/// `MessageType`.
pub fn new(msgtype: MessageType) -> Self {
Self {
msgtype,
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))
}
/// Transform `self` into a `RoomMessageEventContent` with the given
/// relation.
pub fn with_relation(
self,
relates_to: Option<Relation<RoomMessageEventContentWithoutRelation>>,
) -> RoomMessageEventContent {
let Self { msgtype, mentions } = self;
RoomMessageEventContent {
msgtype,
relates_to,
mentions,
}
}
/// Turns `self` into a [rich reply] to the message using the given metadata.
///
/// Sets the `in_reply_to` field inside `relates_to`, and optionally the `rel_type` to
/// `m.thread` if the metadata has a `thread` and `ForwardThread::Yes` is used.
///
/// If `AddMentions::Yes` is used, the `sender` in the metadata is added as a user mention.
///
/// [rich reply]: https://spec.matrix.org/latest/client-server-api/#rich-replies
#[track_caller]
pub fn make_reply_to<'a>(
mut self,
metadata: impl Into<ReplyMetadata<'a>>,
forward_thread: ForwardThread,
add_mentions: AddMentions,
) -> RoomMessageEventContent {
let metadata = metadata.into();
let original_event_id = metadata.event_id.to_owned();
let original_thread_id = metadata
.thread
.filter(|_| forward_thread == ForwardThread::Yes)
.map(|thread| thread.event_id.clone());
let relates_to = if let Some(event_id) = original_thread_id {
Relation::Thread(Thread::plain(
event_id.to_owned(),
original_event_id.to_owned(),
))
} else {
Relation::Reply {
in_reply_to: InReplyTo {
event_id: original_event_id.to_owned(),
},
}
};
if add_mentions == AddMentions::Yes {
self.mentions
.get_or_insert_with(Mentions::new)
.user_ids
.insert(metadata.sender.to_owned());
}
self.with_relation(Some(relates_to))
}
/// 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,
) -> RoomMessageEventContent {
let metadata = metadata.into();
let mut content = if is_reply == ReplyWithinThread::Yes {
self.make_reply_to(metadata, ForwardThread::No, add_mentions)
} else {
self.into()
};
let thread_root = if let Some(Thread { event_id, .. }) = &metadata.thread {
event_id.to_owned()
} else {
metadata.event_id.to_owned()
};
content.relates_to = Some(Relation::Thread(Thread {
event_id: thread_root,
in_reply_to: Some(InReplyTo {
event_id: metadata.event_id.to_owned(),
}),
is_falling_back: is_reply == ReplyWithinThread::No,
}));
content
}
/// 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(
mut self,
metadata: impl Into<ReplacementMetadata>,
) -> RoomMessageEventContent {
let metadata = metadata.into();
let mentions = self.mentions.take();
// Only set mentions that were not there before.
if let Some(mentions) = &mentions {
let new_mentions = metadata
.mentions
.map(|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
})
.unwrap_or_else(|| mentions.clone());
self.mentions = Some(new_mentions);
};
// Prepare relates_to with the untouched msgtype.
let relates_to = Relation::Replacement(Replacement {
event_id: metadata.event_id,
new_content: RoomMessageEventContentWithoutRelation {
msgtype: self.msgtype.clone(),
mentions,
},
});
self.msgtype.make_replacement_body();
let mut content = RoomMessageEventContent::from(self);
content.relates_to = Some(relates_to);
content
}
/// 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`.
///
/// [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
}
}
impl From<MessageType> for RoomMessageEventContentWithoutRelation {
fn from(msgtype: MessageType) -> Self {
Self::new(msgtype)
}
}
impl From<RoomMessageEventContent> for RoomMessageEventContentWithoutRelation {
fn from(value: RoomMessageEventContent) -> Self {
let RoomMessageEventContent {
msgtype, mentions, ..
} = value;
Self { msgtype, mentions }
}
}
impl From<RoomMessageEventContentWithoutRelation> for RoomMessageEventContent {
fn from(value: RoomMessageEventContentWithoutRelation) -> Self {
let RoomMessageEventContentWithoutRelation { msgtype, mentions } = value;
Self {
msgtype,
relates_to: None,
mentions,
}
}
}
| 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/key.rs | crates/core/src/events/secret_storage/key.rs | //! Types for the [`m.secret_storage.key.*`] event.
//!
//! [`m.secret_storage.key.*`]: https://spec.matrix.org/latest/client-server-api/#key-storage
use std::borrow::Cow;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize, de};
use serde_json::Value as JsonValue;
use crate::{
KeyDerivationAlgorithm,
macros::EventContent,
serde::{Base64, JsonObject},
};
/// A passphrase from which a key is to be derived.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct PassPhrase {
/// The algorithm to use to generate the key from the passphrase.
///
/// Must be `m.pbkdf2`.
pub algorithm: KeyDerivationAlgorithm,
/// The salt used in PBKDF2.
pub salt: String,
/// The number of iterations to use in PBKDF2.
pub iterations: u64,
/// The number of bits to generate for the key.
///
/// Defaults to 256
#[serde(default = "default_bits", skip_serializing_if = "is_default_bits")]
pub bits: u64,
}
impl PassPhrase {
/// Creates a new `PassPhrase` with a given salt and number of iterations.
pub fn new(salt: String, iterations: u64) -> Self {
Self {
algorithm: KeyDerivationAlgorithm::Pbkfd2,
salt,
iterations,
bits: default_bits(),
}
}
}
fn default_bits() -> u64 {
256
}
fn is_default_bits(val: &u64) -> bool {
*val == default_bits()
}
/// A key description encrypted using a specified algorithm.
///
/// The only algorithm currently specified is `m.secret_storage.v1.aes-hmac-sha2`, so this
/// essentially represents `AesHmacSha2KeyDescription` in the
/// [spec](https://spec.matrix.org/v1.17/client-server-api/#msecret_storagev1aes-hmac-sha2).
#[derive(ToSchema, Clone, Debug, Serialize, EventContent)]
#[palpo_event(type = "m.secret_storage.key.*", kind = GlobalAccountData)]
pub struct SecretStorageKeyEventContent {
/// The ID of the key.
#[palpo_event(type_fragment)]
#[serde(skip)]
pub key_id: String,
/// The name of the key.
pub name: Option<String>,
/// The encryption algorithm used for this key.
///
/// Currently, only `m.secret_storage.v1.aes-hmac-sha2` is supported.
#[serde(flatten)]
pub algorithm: SecretStorageEncryptionAlgorithm,
/// The passphrase from which to generate the key.
#[serde(skip_serializing_if = "Option::is_none")]
pub passphrase: Option<PassPhrase>,
}
impl SecretStorageKeyEventContent {
/// Creates a `KeyDescription` with the given name.
pub fn new(key_id: String, algorithm: SecretStorageEncryptionAlgorithm) -> Self {
Self {
key_id,
name: None,
algorithm,
passphrase: None,
}
}
}
/// An algorithm and its properties, used to encrypt a secret.
#[derive(ToSchema, Debug, Clone)]
pub enum SecretStorageEncryptionAlgorithm {
/// Encrypted using the `m.secret_storage.v1.aes-hmac-sha2` algorithm.
///
/// Secrets using this method are encrypted using AES-CTR-256 and
/// authenticated using HMAC-SHA-256.
V1AesHmacSha2(SecretStorageV1AesHmacSha2Properties),
/// Encrypted using a custom algorithm.
#[doc(hidden)]
_Custom(CustomSecretEncryptionAlgorithm),
}
impl SecretStorageEncryptionAlgorithm {
/// The `algorithm` string.
pub fn algorithm(&self) -> &str {
match self {
Self::V1AesHmacSha2(_) => "m.secret_storage.v1.aes-hmac-sha2",
Self::_Custom(c) => &c.algorithm,
}
}
/// The algorithm-specific properties.
///
/// The returned JSON object won't contain the `algorithm` field, use
/// [`Self::algorithm()`] to access it.
///
/// Prefer to use the public variants of `SecretStorageEncryptionAlgorithm`
/// where possible; this method is meant to be used for custom
/// algorithms only.
pub fn properties(&self) -> Cow<'_, JsonObject> {
fn serialize<T: Serialize>(obj: &T) -> JsonObject {
match serde_json::to_value(obj).expect("secret properties serialization to succeed") {
JsonValue::Object(obj) => obj,
_ => panic!("all secret properties must serialize to objects"),
}
}
match self {
Self::V1AesHmacSha2(p) => Cow::Owned(serialize(p)),
Self::_Custom(c) => Cow::Borrowed(&c.properties),
}
}
}
/// The key properties for the `m.secret_storage.v1.aes-hmac-sha2` algorithm.
#[derive(ToSchema, Debug, Clone, Deserialize, Serialize)]
pub struct SecretStorageV1AesHmacSha2Properties {
/// The 16-byte initialization vector, encoded as base64.
pub iv: Base64,
/// The MAC, encoded as base64.
pub mac: Base64,
}
impl SecretStorageV1AesHmacSha2Properties {
/// Creates a new `SecretStorageV1AesHmacSha2Properties` with the given
/// initialization vector and MAC.
pub fn new(iv: Base64, mac: Base64) -> Self {
Self { iv, mac }
}
}
/// The payload for a custom secret encryption algorithm.
#[doc(hidden)]
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct CustomSecretEncryptionAlgorithm {
/// The encryption algorithm to be used for the key.
algorithm: String,
/// Algorithm-specific properties.
#[serde(flatten)]
properties: JsonObject,
}
#[derive(Deserialize)]
#[serde(untagged)]
enum SecretStorageEncryptionAlgorithmDeHelper {
Known(KnownSecretStorageEncryptionAlgorithmDeHelper),
Unknown(CustomSecretEncryptionAlgorithm),
}
#[derive(Deserialize)]
#[serde(tag = "algorithm")]
enum KnownSecretStorageEncryptionAlgorithmDeHelper {
#[serde(rename = "m.secret_storage.v1.aes-hmac-sha2")]
V1AesHmacSha2(SecretStorageV1AesHmacSha2Properties),
}
impl<'de> Deserialize<'de> for SecretStorageEncryptionAlgorithm {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
let helper = SecretStorageEncryptionAlgorithmDeHelper::deserialize(deserializer)?;
Ok(match helper {
SecretStorageEncryptionAlgorithmDeHelper::Known(k) => match k {
KnownSecretStorageEncryptionAlgorithmDeHelper::V1AesHmacSha2(p) => {
Self::V1AesHmacSha2(p)
}
},
SecretStorageEncryptionAlgorithmDeHelper::Unknown(c) => Self::_Custom(c),
})
}
}
#[derive(Debug, Serialize)]
struct SecretStorageEncryptionAlgorithmSerHelper<'a, T: Serialize> {
algorithm: &'a str,
#[serde(flatten)]
properties: T,
}
impl Serialize for SecretStorageEncryptionAlgorithm {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let algorithm = self.algorithm();
match self {
Self::V1AesHmacSha2(properties) => SecretStorageEncryptionAlgorithmSerHelper {
algorithm,
properties,
}
.serialize(serializer),
Self::_Custom(properties) => SecretStorageEncryptionAlgorithmSerHelper {
algorithm,
properties,
}
.serialize(serializer),
}
}
}
// #[cfg(test)]
// mod tests {
// use crate::{serde::Base64, KeyDerivationAlgorithm};
// use assert_matches2::assert_matches;
// use serde_json::{
// from_value as from_json_value, json, to_value as to_json_value,
// value::to_raw_value as to_raw_json_value, };
// use super::{
// PassPhrase, SecretStorageEncryptionAlgorithm,
// SecretStorageKeyEventContent, SecretStorageV1AesHmacSha2Properties,
// };
// use crate::events::{EventContentFromType, GlobalAccountDataEvent};
// #[test]
// fn key_description_serialization() {
// let mut content = SecretStorageKeyEventContent::new(
// "my_key".into(),
//
// SecretStorageEncryptionAlgorithm::V1AesHmacSha2(SecretStorageV1AesHmacSha2Properties
// { iv: Base64::parse("YWJjZGVmZ2hpamtsbW5vcA").unwrap(),
// mac:
// Base64::parse("aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U").unwrap(),
// }), );
// content.name = Some("my_key".to_owned());
// let json = json!({
// "name": "my_key",
// "algorithm": "m.secret_storage.v1.aes-hmac-sha2",
// "iv": "YWJjZGVmZ2hpamtsbW5vcA",
// "mac": "aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U"
// });
// assert_eq!(to_json_value(&content).unwrap(), json);
// }
// #[test]
// fn key_description_deserialization() {
// let json = to_raw_json_value(&json!({
// "name": "my_key",
// "algorithm": "m.secret_storage.v1.aes-hmac-sha2",
// "iv": "YWJjZGVmZ2hpamtsbW5vcA",
// "mac": "aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U"
// }))
// .unwrap();
// let content =
// SecretStorageKeyEventContent::from_parts("m.secret_storage.key.test",
// &json).unwrap(); assert_eq!(content.name.unwrap(), "my_key");
// assert_matches!(content.passphrase, None);
// assert_matches!(
// content.algorithm,
//
// SecretStorageEncryptionAlgorithm::V1AesHmacSha2(SecretStorageV1AesHmacSha2Properties
// { iv, mac }) );
// assert_eq!(iv.encode(), "YWJjZGVmZ2hpamtsbW5vcA");
// assert_eq!(mac.encode(), "aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U");
// }
// #[test]
// fn key_description_deserialization_without_name() {
// let json = to_raw_json_value(&json!({
// "algorithm": "m.secret_storage.v1.aes-hmac-sha2",
// "iv": "YWJjZGVmZ2hpamtsbW5vcA",
// "mac": "aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U"
// }))
// .unwrap();
// let content =
// SecretStorageKeyEventContent::from_parts("m.secret_storage.key.test",
// &json).unwrap(); assert!(content.name.is_none());
// assert_matches!(content.passphrase, None);
// assert_matches!(
// content.algorithm,
//
// SecretStorageEncryptionAlgorithm::V1AesHmacSha2(SecretStorageV1AesHmacSha2Properties
// { iv, mac }) );
// assert_eq!(iv.encode(), "YWJjZGVmZ2hpamtsbW5vcA");
// assert_eq!(mac.encode(), "aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U");
// }
// #[test]
// fn key_description_with_passphrase_serialization() {
// let mut content = SecretStorageKeyEventContent {
// passphrase: Some(PassPhrase::new("rocksalt".into(), u8)),
// ..SecretStorageKeyEventContent::new(
// "my_key".into(),
//
// SecretStorageEncryptionAlgorithm::V1AesHmacSha2(SecretStorageV1AesHmacSha2Properties
// { iv: Base64::parse("YWJjZGVmZ2hpamtsbW5vcA").unwrap(),
// mac:
// Base64::parse("aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U").unwrap(),
// }), )
// };
// content.name = Some("my_key".to_owned());
// let json = json!({
// "name": "my_key",
// "algorithm": "m.secret_storage.v1.aes-hmac-sha2",
// "iv": "YWJjZGVmZ2hpamtsbW5vcA",
// "mac": "aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U",
// "passphrase": {
// "algorithm": "m.pbkdf2",
// "salt": "rocksalt",
// "iterations": 8
// }
// });
// assert_eq!(to_json_value(&content).unwrap(), json);
// }
// #[test]
// fn key_description_with_passphrase_deserialization() {
// let json = to_raw_json_value(&json!({
// "name": "my_key",
// "algorithm": "m.secret_storage.v1.aes-hmac-sha2",
// "iv": "YWJjZGVmZ2hpamtsbW5vcA",
// "mac": "aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U",
// "passphrase": {
// "algorithm": "m.pbkdf2",
// "salt": "rocksalt",
// "iterations": 8,
// "bits": 256
// }
// }))
// .unwrap();
// let content =
// SecretStorageKeyEventContent::from_parts("m.secret_storage.key.test",
// &json).unwrap(); assert_eq!(content.name.unwrap(), "my_key");
// let passphrase = content.passphrase.unwrap();
// assert_eq!(passphrase.algorithm, KeyDerivationAlgorithm::Pbkfd2);
// assert_eq!(passphrase.salt, "rocksalt");
// assert_eq!(passphrase.iterations, u8);
// assert_eq!(passphrase.bits, u256);
// assert_matches!(
// content.algorithm,
//
// SecretStorageEncryptionAlgorithm::V1AesHmacSha2(SecretStorageV1AesHmacSha2Properties
// { iv, mac }) );
// assert_eq!(iv.encode(), "YWJjZGVmZ2hpamtsbW5vcA");
// assert_eq!(mac.encode(), "aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U");
// }
// #[test]
// fn event_serialization() {
// let mut content = SecretStorageKeyEventContent::new(
// "my_key_id".into(),
//
// SecretStorageEncryptionAlgorithm::V1AesHmacSha2(SecretStorageV1AesHmacSha2Properties
// { iv: Base64::parse("YWJjZGVmZ2hpamtsbW5vcA").unwrap(),
// mac:
// Base64::parse("aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U").unwrap(),
// }), );
// content.name = Some("my_key".to_owned());
// let json = json!({
// "name": "my_key",
// "algorithm": "m.secret_storage.v1.aes-hmac-sha2",
// "iv": "YWJjZGVmZ2hpamtsbW5vcA",
// "mac": "aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U"
// });
// assert_eq!(to_json_value(&content).unwrap(), json);
// }
// #[test]
// fn event_deserialization() {
// let json = json!({
// "type": "m.secret_storage.key.my_key_id",
// "content": {
// "name": "my_key",
// "algorithm": "m.secret_storage.v1.aes-hmac-sha2",
// "iv": "YWJjZGVmZ2hpamtsbW5vcA",
// "mac": "aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U"
// }
// });
// let ev =
// from_json_value::<GlobalAccountDataEvent<SecretStorageKeyEventContent>>(json).
// unwrap(); assert_eq!(ev.content.key_id, "my_key_id");
// assert_eq!(ev.content.name.unwrap(), "my_key");
// assert_matches!(ev.content.passphrase, None);
// assert_matches!(
// ev.content.algorithm,
//
// SecretStorageEncryptionAlgorithm::V1AesHmacSha2(SecretStorageV1AesHmacSha2Properties
// { iv, mac }) );
// assert_eq!(iv.encode(), "YWJjZGVmZ2hpamtsbW5vcA");
// assert_eq!(mac.encode(), "aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U");
// }
// #[test]
// fn custom_algorithm_key_description_deserialization() {
// let json = to_raw_json_value(&json!({
// "name": "my_key",
// "algorithm": "io.palpo.custom_alg",
// "io.palpo.custom_prop1": "YWJjZGVmZ2hpamtsbW5vcA",
// "io.palpo.custom_prop2": "aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U"
// }))
// .unwrap();
// let content =
// SecretStorageKeyEventContent::from_parts("m.secret_storage.key.test",
// &json).unwrap(); assert_eq!(content.name.unwrap(), "my_key");
// assert_matches!(content.passphrase, None);
// let algorithm = content.algorithm;
// assert_eq!(algorithm.algorithm(), "io.palpo.custom_alg");
// let properties = algorithm.properties();
// assert_eq!(properties.len(), 2);
// assert_eq!(
// properties.get("io.palpo.custom_prop1").unwrap().as_str(),
// Some("YWJjZGVmZ2hpamtsbW5vcA")
// );
// assert_eq!(
// properties.get("io.palpo.custom_prop2").unwrap().as_str(),
// Some("aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U")
// );
// }
// }
| 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/default_key.rs | crates/core/src/events/secret_storage/default_key.rs | //! Types for the [`m.secret_storage.default_key`] event.
//!
//! [`m.secret_storage.default_key`]: https://spec.matrix.org/latest/client-server-api/#key-storage
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::macros::EventContent;
/// The payload for `DefaultKeyEvent`.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.secret_storage.default_key", kind = GlobalAccountData)]
pub struct SecretStorageDefaultKeyEventContent {
/// The ID of the default key.
#[serde(rename = "key")]
pub key_id: String,
}
impl SecretStorageDefaultKeyEventContent {
/// Create a new [`SecretStorageDefaultKeyEventContent`] with the given key
/// ID.
///
/// Uploading this to the account data will mark the secret storage key with
/// the given key ID as the default key.
pub fn new(key_id: String) -> Self {
Self { key_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/secret.rs | crates/core/src/events/secret_storage/secret.rs | //! Types for events used for secrets to be stored in the user's account_data.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::serde::Base64;
/// A secret and its encrypted contents.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SecretEventContent {
/// Map from key ID to the encrypted data.
///
/// The exact format for the encrypted data is dependent on the key
/// algorithm.
pub encrypted: BTreeMap<String, SecretEncryptedData>,
}
impl SecretEventContent {
/// Create a new `SecretEventContent` with the given encrypted content.
pub fn new(encrypted: BTreeMap<String, SecretEncryptedData>) -> Self {
Self { encrypted }
}
}
/// Encrypted data for a corresponding secret storage encryption algorithm.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum SecretEncryptedData {
/// Data encrypted using the *m.secret_storage.v1.aes-hmac-sha2* algorithm.
AesHmacSha2EncryptedData {
/// The 16-byte initialization vector, encoded as base64.
iv: Base64,
/// The AES-CTR-encrypted data, encoded as base64.
ciphertext: Base64,
/// The MAC, encoded as base64.
mac: Base64,
},
}
// #[cfg(test)]
// mod tests {
// use std::collections::BTreeMap;
// use crate::serde::Base64;
// use assert_matches2::assert_matches;
// use serde_json::{from_value as from_json_value, json, to_value as
// to_json_value};
// use super::{SecretEncryptedData, SecretEventContent};
// #[test]
// fn test_secret_serialization() {
// let key_one_data = SecretEncryptedData::AesHmacSha2EncryptedData {
// iv: Base64::parse("YWJjZGVmZ2hpamtsbW5vcA").unwrap(),
// ciphertext:
// Base64::parse("dGhpc2lzZGVmaW5pdGVseWNpcGhlcnRleHQ").unwrap(),
// mac: Base64::parse("aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U").unwrap(),
// };
// let mut encrypted = BTreeMap::<String, SecretEncryptedData>::new();
// encrypted.insert("key_one".to_owned(), key_one_data);
// let content = SecretEventContent::new(encrypted);
// let json = json!({
// "encrypted": {
// "key_one" : {
// "iv": "YWJjZGVmZ2hpamtsbW5vcA",
// "ciphertext": "dGhpc2lzZGVmaW5pdGVseWNpcGhlcnRleHQ",
// "mac": "aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U"
// }
// }
// });
// assert_eq!(to_json_value(content).unwrap(), json);
// }
// #[test]
// fn test_secret_deserialization() {
// let json = json!({
// "encrypted": {
// "key_one" : {
// "iv": "YWJjZGVmZ2hpamtsbW5vcA",
// "ciphertext": "dGhpc2lzZGVmaW5pdGVseWNpcGhlcnRleHQ",
// "mac": "aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U"
// }
// }
// });
// let deserialized: SecretEventContent =
// from_json_value(json).unwrap(); let secret_data =
// deserialized.encrypted.get("key_one").unwrap();
// assert_matches!(
// secret_data,
// SecretEncryptedData::AesHmacSha2EncryptedData { iv, ciphertext,
// mac } );
// assert_eq!(iv.encode(), "YWJjZGVmZ2hpamtsbW5vcA");
// assert_eq!(ciphertext.encode(),
// "dGhpc2lzZGVmaW5pdGVseWNpcGhlcnRleHQ"); assert_eq!(mac.encode(),
// "aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U"); }
// }
| 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/verification.rs | crates/core/src/events/key/verification.rs | //! Modules for events in the `m.key.verification` namespace.
//!
//! This module also contains types shared by events in its child namespaces.
//!
//! The MSC for the in-room variants of the `m.key.verification.*` events can be
//! found on [MSC2241].
//!
//! [MSC2241]: https://github.com/matrix-org/matrix-spec-proposals/pull/2241
use std::time::Duration;
use salvo::oapi::ToSchema;
use crate::{PrivOwnedStr, serde::StringEnum};
pub mod accept;
pub mod cancel;
pub mod done;
pub mod key;
pub mod mac;
pub mod ready;
pub mod request;
pub mod start;
// For these two constants, see <https://spec.matrix.org/latest/client-server-api/#key-verification-framework>
/// The amount of time after which a verification request should be ignored,
/// relative to its `origin_server_ts` (for in-room events) or its `timestamp`
/// (for to-device events).
///
/// This is defined as 10 minutes.
pub const REQUEST_TIMESTAMP_TIMEOUT: Duration = Duration::from_secs(10 * 60);
/// The amount of time after which a verification request should be ignored,
/// relative to the time it was received by the client.
///
/// This is defined as 2 minutes.
pub const REQUEST_RECEIVED_TIMEOUT: Duration = Duration::from_secs(2 * 60);
/// A hash algorithm.
#[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 HashAlgorithm {
/// The SHA256 hash algorithm.
Sha256,
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(PrivOwnedStr),
}
/// A key agreement protocol.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[palpo_enum(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum KeyAgreementProtocol {
/// The [Curve25519](https://cr.yp.to/ecdh.html) key agreement protocol.
Curve25519,
/// The Curve25519 key agreement protocol with check for public keys.
Curve25519HkdfSha256,
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(PrivOwnedStr),
}
/// A message authentication code algorithm.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[palpo_enum(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum MessageAuthenticationCode {
/// The second version of the HKDF-HMAC-SHA256 MAC.
#[palpo_enum(rename = "hkdf-hmac-sha256.v2")]
HkdfHmacSha256V2,
/// The HMAC-SHA256 MAC.
HmacSha256,
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(PrivOwnedStr),
}
/// A Short Authentication String method.
#[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 ShortAuthenticationString {
/// The decimal method.
Decimal,
/// The emoji method.
Emoji,
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(PrivOwnedStr),
}
/// A Short Authentication String (SAS) verification method.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[non_exhaustive]
pub enum VerificationMethod {
/// The `m.sas.v1` verification method.
#[palpo_enum(rename = "m.sas.v1")]
SasV1,
/// The `m.qr_code.scan.v1` verification method.
#[palpo_enum(rename = "m.qr_code.scan.v1")]
QrCodeScanV1,
/// The `m.qr_code.show.v1` verification method.
#[palpo_enum(rename = "m.qr_code.show.v1")]
QrCodeShowV1,
/// The `m.reciprocate.v1` verification method.
#[palpo_enum(rename = "m.reciprocate.v1")]
ReciprocateV1,
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(PrivOwnedStr),
}
#[cfg(test)]
mod tests {
use super::{KeyAgreementProtocol, MessageAuthenticationCode};
#[test]
fn serialize_key_agreement() {
let serialized =
serde_json::to_string(&KeyAgreementProtocol::Curve25519HkdfSha256).unwrap();
assert_eq!(serialized, "\"curve25519-hkdf-sha256\"");
let deserialized: KeyAgreementProtocol = serde_json::from_str(&serialized).unwrap();
assert_eq!(deserialized, KeyAgreementProtocol::Curve25519HkdfSha256);
}
#[test]
fn serialize_mac_method_v2() {
let serialized =
serde_json::to_string(&MessageAuthenticationCode::HkdfHmacSha256V2).unwrap();
let deserialized: MessageAuthenticationCode = serde_json::from_str(&serialized).unwrap();
assert_eq!(serialized, "\"hkdf-hmac-sha256.v2\"");
assert_eq!(deserialized, MessageAuthenticationCode::HkdfHmacSha256V2);
}
}
| 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/verification/key.rs | crates/core/src/events/key/verification/key.rs | //! Types for the [`m.key.verification.key`] event.
//!
//! [`m.key.verification.key`]: https://spec.matrix.org/latest/client-server-api/#mkeyverificationkey
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{OwnedTransactionId, events::relation::Reference, serde::Base64};
/// The content of a to-device `m.key.verification.key` event.
///
/// Sends the ephemeral public key for a device to the partner device.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.key.verification.key", kind = ToDevice)]
pub struct ToDeviceKeyVerificationKeyEventContent {
/// An opaque identifier for the verification process.
///
/// Must be the same as the one used for the `m.key.verification.start`
/// message.
pub transaction_id: OwnedTransactionId,
/// The device's ephemeral public key, encoded as unpadded base64.
pub key: Base64,
}
impl ToDeviceKeyVerificationKeyEventContent {
/// Creates a new `ToDeviceKeyVerificationKeyEventContent` with the given
/// transaction ID and key.
pub fn new(transaction_id: OwnedTransactionId, key: Base64) -> Self {
Self {
transaction_id,
key,
}
}
}
/// The content of an in-room `m.key.verification.key` event.
///
/// Sends the ephemeral public key for a device to the partner device.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.key.verification.key", kind = MessageLike)]
pub struct KeyVerificationKeyEventContent {
/// The device's ephemeral public key, encoded as unpadded base64.
pub key: Base64,
/// Information about the related event.
#[serde(rename = "m.relates_to")]
pub relates_to: Reference,
}
impl KeyVerificationKeyEventContent {
/// Creates a new `KeyVerificationKeyEventContent` with the given key and
/// reference.
pub fn new(key: Base64, relates_to: Reference) -> Self {
Self { key, relates_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/key/verification/accept.rs | crates/core/src/events/key/verification/accept.rs | //! Types for the [`m.key.verification.accept`] event.
//!
//! [`m.key.verification.accept`]: https://spec.matrix.org/latest/client-server-api/#mkeyverificationaccept
use std::collections::BTreeMap;
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use super::{
HashAlgorithm, KeyAgreementProtocol, MessageAuthenticationCode, ShortAuthenticationString,
};
use crate::{OwnedTransactionId, events::relation::Reference, serde::Base64};
/// The content of a to-device `m.key.verification.accept` event.
///
/// Accepts a previously sent `m.key.verification.start` message.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.key.verification.accept", kind = ToDevice)]
pub struct ToDeviceKeyVerificationAcceptEventContent {
/// An opaque identifier for the verification process.
///
/// Must be the same as the one used for the `m.key.verification.start`
/// message.
pub transaction_id: OwnedTransactionId,
/// The method specific content.
#[serde(flatten)]
pub method: AcceptMethod,
}
impl ToDeviceKeyVerificationAcceptEventContent {
/// Creates a new `ToDeviceKeyVerificationAcceptEventContent` with the given
/// transaction ID and method-specific content.
pub fn new(transaction_id: OwnedTransactionId, method: AcceptMethod) -> Self {
Self {
transaction_id,
method,
}
}
}
/// The content of a in-room `m.key.verification.accept` event.
///
/// Accepts a previously sent `m.key.verification.start` message.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.key.verification.accept", kind = MessageLike)]
pub struct KeyVerificationAcceptEventContent {
/// The method specific content.
#[serde(flatten)]
pub method: AcceptMethod,
/// Information about the related event.
#[serde(rename = "m.relates_to")]
pub relates_to: Reference,
}
impl KeyVerificationAcceptEventContent {
/// Creates a new `ToDeviceKeyVerificationAcceptEventContent` with the given
/// method-specific content and reference.
pub fn new(method: AcceptMethod, relates_to: Reference) -> Self {
Self { method, relates_to }
}
}
/// An enum representing the different method specific
/// `m.key.verification.accept` content.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[serde(untagged)]
pub enum AcceptMethod {
/// The `m.sas.v1` verification method.
SasV1(SasV1Content),
/// Any unknown accept method.
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(_CustomContent),
}
/// Method specific content of a unknown key verification method.
#[doc(hidden)]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[allow(clippy::exhaustive_structs)]
pub struct _CustomContent {
/// The name of the method.
pub method: String,
/// The additional fields that the method contains.
#[serde(flatten)]
pub data: BTreeMap<String, JsonValue>,
}
/// The payload of an `m.key.verification.accept` event using the `m.sas.v1`
/// method.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[serde(rename = "m.sas.v1", tag = "method")]
pub struct SasV1Content {
/// The key agreement protocol the device is choosing to use, out of the
/// options in the `m.key.verification.start` message.
pub key_agreement_protocol: KeyAgreementProtocol,
/// The hash method the device is choosing to use, out of the options in the
/// `m.key.verification.start` message.
pub hash: HashAlgorithm,
// #[cfg(test)]
// mod tests {
// use std::collections::BTreeMap;
// use crate::{event_id, serde::Base64};
// use assert_matches2::assert_matches;
// use serde_json::{from_value as from_json_value, json, to_value as
// to_json_value, Value as JsonValue};
// use super::{
// AcceptMethod, HashAlgorithm, KeyAgreementProtocol,
// KeyVerificationAcceptEventContent, MessageAuthenticationCode,
// SasV1Content, ShortAuthenticationString,
// ToDeviceKeyVerificationAcceptEventContent, _CustomContent,
// };
// use crate::events::{relation::Reference, ToDeviceEvent};
// #[test]
// fn serialization() {
// let key_verification_accept_content =
// ToDeviceKeyVerificationAcceptEventContent { transaction_id:
// "456".into(), method: AcceptMethod::SasV1(SasV1Content {
// hash: HashAlgorithm::Sha256,
// key_agreement_protocol: KeyAgreementProtocol::Curve25519,
// message_authentication_code:
// MessageAuthenticationCode::HkdfHmacSha256V2,
// short_authentication_string: vec![ShortAuthenticationString::Decimal],
// commitment: Base64::new(b"hello".to_vec()),
/// The message authentication code the device is choosing to use, out of
/// the options in the `m.key.verification.start` message.
pub message_authentication_code: MessageAuthenticationCode,
/// The SAS methods both devices involved in the verification process
/// understand.
///
/// Must be a subset of the options in the `m.key.verification.start`
/// message.
pub short_authentication_string: Vec<ShortAuthenticationString>,
/// The hash (encoded as unpadded base64) of the concatenation of the
/// device's ephemeral public key (encoded as unpadded base64) and the
/// canonical JSON representation of the `m.key.verification.start` message.
pub commitment: Base64,
}
// #[cfg(test)]
// mod tests {
// use std::collections::BTreeMap;
// use crate::{event_id, serde::Base64};
// use assert_matches2::assert_matches;
// use serde_json::{from_value as from_json_value, json, to_value as
// to_json_value, Value as JsonValue};
// use super::{
// AcceptMethod, HashAlgorithm, KeyAgreementProtocol,
// KeyVerificationAcceptEventContent, MessageAuthenticationCode,
// SasV1Content, ShortAuthenticationString,
// ToDeviceKeyVerificationAcceptEventContent, _CustomContent,
// };
// use crate::events::{relation::Reference, ToDeviceEvent};
// #[test]
// fn serialization() {
// let key_verification_accept_content =
// ToDeviceKeyVerificationAcceptEventContent { transaction_id:
// "456".into(), method: AcceptMethod::SasV1(SasV1Content {
// hash: HashAlgorithm::Sha256,
// key_agreement_protocol: KeyAgreementProtocol::Curve25519,
// message_authentication_code:
// MessageAuthenticationCode::HkdfHmacSha256V2,
// short_authentication_string: vec![ShortAuthenticationString::Decimal],
// commitment: Base64::new(b"hello".to_vec()),
// }),
// };
// let json_data = json!({
// "transaction_id": "456",
// "method": "m.sas.v1",
// "commitment": "aGVsbG8",
// "key_agreement_protocol": "curve25519",
// "hash": "sha256",
// "message_authentication_code": "hkdf-hmac-sha256.v2",
// "short_authentication_string": ["decimal"]
// });
// assert_eq!(to_json_value(&key_verification_accept_content).unwrap(),
// json_data);
// let json_data = json!({
// "transaction_id": "456",
// "method": "m.sas.custom",
// "test": "field",
// });
// let key_verification_accept_content =
// ToDeviceKeyVerificationAcceptEventContent { transaction_id:
// "456".into(), method: AcceptMethod::_Custom(_CustomContent {
// method: "m.sas.custom".to_owned(),
// data: vec![("test".to_owned(), JsonValue::from("field"))]
// .into_iter()
// .collect::<BTreeMap<String, JsonValue>>(),
// }),
// };
// assert_eq!(to_json_value(&key_verification_accept_content).unwrap(),
// json_data); }
// #[test]
// fn in_room_serialization() {
// let event_id = event_id!("$1598361704261elfgc:localhost");
// let key_verification_accept_content =
// KeyVerificationAcceptEventContent { relates_to: Reference {
// event_id: event_id.to_owned(),
// },
// method: AcceptMethod::SasV1(SasV1Content {
// hash: HashAlgorithm::Sha256,
// key_agreement_protocol: KeyAgreementProtocol::Curve25519,
// message_authentication_code:
// MessageAuthenticationCode::HkdfHmacSha256V2,
// short_authentication_string: vec![ShortAuthenticationString::Decimal],
// commitment: Base64::new(b"hello".to_vec()),
// }),
// };
// let json_data = json!({
// "method": "m.sas.v1",
// "commitment": "aGVsbG8",
// "key_agreement_protocol": "curve25519",
// "hash": "sha256",
// "message_authentication_code": "hkdf-hmac-sha256.v2",
// "short_authentication_string": ["decimal"],
// "m.relates_to": {
// "rel_type": "m.reference",
// "event_id": event_id,
// }
// });
// assert_eq!(to_json_value(&key_verification_accept_content).unwrap(),
// json_data); }
// #[test]
// fn deserialization() {
// let json = json!({
// "transaction_id": "456",
// "commitment": "aGVsbG8",
// "method": "m.sas.v1",
// "hash": "sha256",
// "key_agreement_protocol": "curve25519",
// "message_authentication_code": "hkdf-hmac-sha256.v2",
// "short_authentication_string": ["decimal"]
// });
// // Deserialize the content struct separately to verify `TryFromRaw`
// is implemented for it. let content =
// from_json_value::<ToDeviceKeyVerificationAcceptEventContent>(json).unwrap();
// assert_eq!(content.transaction_id, "456");
// assert_matches!(content.method, AcceptMethod::SasV1(sas));
// assert_eq!(sas.commitment.encode(), "aGVsbG8");
// assert_eq!(sas.hash, HashAlgorithm::Sha256);
// assert_eq!(sas.key_agreement_protocol,
// KeyAgreementProtocol::Curve25519); assert_eq!(
// sas.message_authentication_code,
// MessageAuthenticationCode::HkdfHmacSha256V2
// );
// assert_eq!(
// sas.short_authentication_string,
// vec![ShortAuthenticationString::Decimal]
// );
// let json = json!({
// "content": {
// "commitment": "aGVsbG8",
// "transaction_id": "456",
// "method": "m.sas.v1",
// "key_agreement_protocol": "curve25519",
// "hash": "sha256",
// "message_authentication_code": "hkdf-hmac-sha256.v2",
// "short_authentication_string": ["decimal"]
// },
// "type": "m.key.verification.accept",
// "sender": "@example:localhost",
// });
// let ev =
// from_json_value::<ToDeviceEvent<ToDeviceKeyVerificationAcceptEventContent>>(json).
// unwrap(); assert_eq!(ev.content.transaction_id, "456");
// assert_eq!(ev.sender, "@example:localhost");
// assert_matches!(ev.content.method, AcceptMethod::SasV1(sas));
// assert_eq!(sas.commitment.encode(), "aGVsbG8");
// assert_eq!(sas.hash, HashAlgorithm::Sha256);
// assert_eq!(sas.key_agreement_protocol,
// KeyAgreementProtocol::Curve25519); assert_eq!(
// sas.message_authentication_code,
// MessageAuthenticationCode::HkdfHmacSha256V2
// );
// assert_eq!(
// sas.short_authentication_string,
// vec![ShortAuthenticationString::Decimal]
// );
// let json = json!({
// "content": {
// "from_device": "123",
// "transaction_id": "456",
// "method": "m.sas.custom",
// "test": "field",
// },
// "type": "m.key.verification.accept",
// "sender": "@example:localhost",
// });
// let ev =
// from_json_value::<ToDeviceEvent<ToDeviceKeyVerificationAcceptEventContent>>(json).
// unwrap(); assert_eq!(ev.content.transaction_id, "456");
// assert_eq!(ev.sender, "@example:localhost");
// assert_matches!(ev.content.method, AcceptMethod::_Custom(custom));
// assert_eq!(custom.method, "m.sas.custom");
// assert_eq!(custom.data.get("test"), Some(&JsonValue::from("field")));
// }
// #[test]
// fn in_room_deserialization() {
// let json = json!({
// "commitment": "aGVsbG8",
// "method": "m.sas.v1",
// "hash": "sha256",
// "key_agreement_protocol": "curve25519",
// "message_authentication_code": "hkdf-hmac-sha256.v2",
// "short_authentication_string": ["decimal"],
// "m.relates_to": {
// "rel_type": "m.reference",
// "event_id": "$1598361704261elfgc:localhost",
// }
// });
// // Deserialize the content struct separately to verify `TryFromRaw`
// is implemented for it. let content =
// from_json_value::<KeyVerificationAcceptEventContent>(json).unwrap();
// assert_eq!(content.relates_to.event_id,
// "$1598361704261elfgc:localhost");
// assert_matches!(content.method, AcceptMethod::SasV1(sas));
// assert_eq!(sas.commitment.encode(), "aGVsbG8");
// assert_eq!(sas.hash, HashAlgorithm::Sha256);
// assert_eq!(sas.key_agreement_protocol,
// KeyAgreementProtocol::Curve25519); assert_eq!(
// sas.message_authentication_code,
// MessageAuthenticationCode::HkdfHmacSha256V2
// );
// assert_eq!(
// sas.short_authentication_string,
// vec![ShortAuthenticationString::Decimal]
// );
// }
// }
| 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/verification/cancel.rs | crates/core/src/events/key/verification/cancel.rs | //! Types for the [`m.key.verification.cancel`] event.
//!
//! [`m.key.verification.cancel`]: https://spec.matrix.org/latest/client-server-api/#mkeyverificationcancel
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{OwnedTransactionId, PrivOwnedStr, events::relation::Reference, serde::StringEnum};
/// The content of a to-device `m.key.verification.cancel` event.
///
/// Cancels a key verification process/request.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.key.verification.cancel", kind = ToDevice)]
pub struct ToDeviceKeyVerificationCancelEventContent {
/// The opaque identifier for the verification process/request.
pub transaction_id: OwnedTransactionId,
/// A human readable description of the `code`.
///
/// The client should only rely on this string if it does not understand the
/// `code`.
pub reason: String,
/// The error code for why the process / request was cancelled by the user.
pub code: CancelCode,
}
impl ToDeviceKeyVerificationCancelEventContent {
/// Creates a new `ToDeviceKeyVerificationCancelEventContent` with the given
/// transaction ID, reason and code.
pub fn new(transaction_id: OwnedTransactionId, reason: String, code: CancelCode) -> Self {
Self {
transaction_id,
reason,
code,
}
}
}
/// The content of an in-room `m.key.verification.cancel` event.
///
/// Cancels a key verification process/request.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.key.verification.cancel", kind = MessageLike)]
pub struct KeyVerificationCancelEventContent {
/// A human readable description of the `code`.
///
/// The client should only rely on this string if it does not understand the
/// `code`.
pub reason: String,
/// The error code for why the process/request was cancelled by the user.
pub code: CancelCode,
/// Information about the related event.
#[serde(rename = "m.relates_to")]
pub relates_to: Reference,
}
impl KeyVerificationCancelEventContent {
/// Creates a new `KeyVerificationCancelEventContent` with the given reason,
/// code and reference.
pub fn new(reason: String, code: CancelCode, relates_to: Reference) -> Self {
Self {
reason,
code,
relates_to,
}
}
}
/// An error code for why the process/request was cancelled by the user.
///
/// Custom error codes should use the Java package naming convention.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
// FIXME: Add `m.foo_bar` as a naming scheme in StringEnum and remove rename attributes.
#[derive(ToSchema, Clone, StringEnum)]
#[palpo_enum(rename_all(prefix = "m.", rule = "snake_case"))]
#[non_exhaustive]
pub enum CancelCode {
/// The user cancelled the verification.
#[palpo_enum(rename = "m.user")]
User,
/// The verification process timed out.
///
/// Verification processes can define their own timeout parameters.
#[palpo_enum(rename = "m.timeout")]
Timeout,
/// The device does not know about the given transaction ID.
#[palpo_enum(rename = "m.unknown_transaction")]
UnknownTransaction,
/// The device does not know how to handle the requested method.
///
/// Should be sent for `m.key.verification.start` messages and messages
/// defined by individual verification processes.
#[palpo_enum(rename = "m.unknown_method")]
UnknownMethod,
/// The device received an unexpected message.
///
/// Typically raised when one of the parties is handling the verification
/// out of order.
#[palpo_enum(rename = "m.unexpected_message")]
UnexpectedMessage,
/// The key was not verified.
#[palpo_enum(rename = "m.key_mismatch")]
KeyMismatch,
/// The expected user did not match the user verified.
#[palpo_enum(rename = "m.user_mismatch")]
UserMismatch,
/// The message received was invalid.
#[palpo_enum(rename = "m.invalid_message")]
InvalidMessage,
/// An `m.key.verification.request` was accepted by a different device.
///
/// The device receiving this error can ignore the verification request.
#[palpo_enum(rename = "m.accepted")]
Accepted,
/// The device receiving this error can ignore the verification request.
#[palpo_enum(rename = "m.mismatched_commitment")]
MismatchedCommitment,
/// The SAS did not match.
#[palpo_enum(rename = "m.mismatched_sas")]
MismatchedSas,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
#[cfg(test)]
mod tests {
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::CancelCode;
#[test]
fn cancel_codes_serialize_to_display_form() {
assert_eq!(to_json_value(&CancelCode::User).unwrap(), json!("m.user"));
}
#[test]
fn custom_cancel_codes_serialize_to_display_form() {
assert_eq!(
to_json_value(CancelCode::from("io.palpo.test")).unwrap(),
json!("io.palpo.test")
);
}
#[test]
fn cancel_codes_deserialize_from_display_form() {
assert_eq!(
from_json_value::<CancelCode>(json!("m.user")).unwrap(),
CancelCode::User
);
}
#[test]
fn custom_cancel_codes_deserialize_from_display_form() {
assert_eq!(
from_json_value::<CancelCode>(json!("io.palpo.test")).unwrap(),
"io.palpo.test".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/key/verification/ready.rs | crates/core/src/events/key/verification/ready.rs | //! Types for the [`m.key.verification.ready`] event.
//!
//! [`m.key.verification.ready`]: https://spec.matrix.org/latest/client-server-api/#mkeyverificationready
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use super::VerificationMethod;
use crate::{OwnedDeviceId, OwnedTransactionId, events::relation::Reference};
/// The content of a to-device `m.m.key.verification.ready` event.
///
/// Response to a previously sent `m.key.verification.request` message.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.key.verification.ready", kind = ToDevice)]
pub struct ToDeviceKeyVerificationReadyEventContent {
/// The device ID which is initiating the request.
pub from_device: OwnedDeviceId,
/// The verification methods supported by the sender.
pub methods: Vec<VerificationMethod>,
/// An opaque identifier for the verification process.
///
/// Must be unique with respect to the devices involved. Must be the same as
/// the `transaction_id` given in the `m.key.verification.request` from
/// a request.
pub transaction_id: OwnedTransactionId,
}
impl ToDeviceKeyVerificationReadyEventContent {
/// Creates a new `ToDeviceKeyVerificationReadyEventContent` with the given
/// device ID, verification methods and transaction ID.
pub fn new(
from_device: OwnedDeviceId,
methods: Vec<VerificationMethod>,
transaction_id: OwnedTransactionId,
) -> Self {
Self {
from_device,
methods,
transaction_id,
}
}
}
/// The content of an in-room `m.m.key.verification.ready` event.
///
/// Response to a previously sent `m.key.verification.request` message.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.key.verification.ready", kind = MessageLike)]
pub struct KeyVerificationReadyEventContent {
/// The device ID which is initiating the request.
pub from_device: OwnedDeviceId,
/// The verification methods supported by the sender.
pub methods: Vec<VerificationMethod>,
/// Relation signaling which verification request this event is responding
/// to.
#[serde(rename = "m.relates_to")]
pub relates_to: Reference,
}
impl KeyVerificationReadyEventContent {
/// Creates a new `KeyVerificationReadyEventContent` with the given device
/// ID, methods and reference.
pub fn new(
from_device: OwnedDeviceId,
methods: Vec<VerificationMethod>,
relates_to: Reference,
) -> Self {
Self {
from_device,
methods,
relates_to,
}
}
}
// #[cfg(test)]
// mod tests {
// use crate::{owned_event_id, OwnedDeviceId};
// use serde_json::{from_value as from_json_value, json, to_value as
// to_json_value};
// use super::{KeyVerificationReadyEventContent,
// ToDeviceKeyVerificationReadyEventContent};
// use crate::{key::verification::VerificationMethod, relation::Reference};
// #[test]
// fn serialization() {
// let event_id = owned_event_id!("$1598361704261elfgc:localhost");
// let device: OwnedDeviceId = "123".into();
// let json_data = json!({
// "from_device": device,
// "methods": ["m.sas.v1"],
// "m.relates_to": {
// "rel_type": "m.reference",
// "event_id": event_id,
// }
// });
// let content = KeyVerificationReadyEventContent {
// from_device: device.clone(),
// relates_to: Reference { event_id },
// methods: vec![VerificationMethod::SasV1],
// };
// assert_eq!(to_json_value(&content).unwrap(), json_data);
// let json_data = json!({
// "from_device": device,
// "methods": ["m.sas.v1"],
// "transaction_id": "456",
// });
// let content = ToDeviceKeyVerificationReadyEventContent {
// from_device: device,
// transaction_id: "456".into(),
// methods: vec![VerificationMethod::SasV1],
// };
// assert_eq!(to_json_value(&content).unwrap(), json_data);
// }
// #[test]
// fn deserialization() {
// let json_data = json!({
// "from_device": "123",
// "methods": ["m.sas.v1"],
// "m.relates_to": {
// "rel_type": "m.reference",
// "event_id": "$1598361704261elfgc:localhost",
// }
// });
// let content =
// from_json_value::<KeyVerificationReadyEventContent>(json_data).unwrap();
// assert_eq!(content.from_device, "123");
// assert_eq!(content.methods, vec![VerificationMethod::SasV1]);
// assert_eq!(content.relates_to.event_id,
// "$1598361704261elfgc:localhost");
// let json_data = json!({
// "from_device": "123",
// "methods": ["m.sas.v1"],
// "transaction_id": "456",
// });
// let content =
// from_json_value::<ToDeviceKeyVerificationReadyEventContent>(json_data).
// unwrap(); assert_eq!(content.from_device, "123");
// assert_eq!(content.methods, vec![VerificationMethod::SasV1]);
// assert_eq!(content.transaction_id, "456");
// }
// }
| 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/verification/mac.rs | crates/core/src/events/key/verification/mac.rs | //! Types for the [`m.key.verification.mac`] event.
//!
//! [`m.key.verification.mac`]: https://spec.matrix.org/latest/client-server-api/#mkeyverificationmac
use std::collections::BTreeMap;
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{OwnedTransactionId, events::relation::Reference, serde::Base64};
/// The content of a to-device `m.key.verification.` event.
///
/// Sends the MAC of a device's key to the partner device.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.key.verification.mac", kind = ToDevice)]
pub struct ToDeviceKeyVerificationMacEventContent {
/// An opaque identifier for the verification process.
///
/// Must be the same as the one used for the `m.key.verification.start`
/// message.
pub transaction_id: OwnedTransactionId,
/// A map of the key ID to the MAC of the key, using the algorithm in the
/// verification process.
///
/// The MAC is encoded as unpadded base64.
pub mac: BTreeMap<String, Base64>,
/// The MAC of the comma-separated, sorted, list of key IDs given in the
/// `mac` property, encoded as unpadded base64.
pub keys: Base64,
}
impl ToDeviceKeyVerificationMacEventContent {
/// Creates a new `ToDeviceKeyVerificationMacEventContent` with the given
/// transaction ID, key ID to MAC map and key MAC.
pub fn new(
transaction_id: OwnedTransactionId,
mac: BTreeMap<String, Base64>,
keys: Base64,
) -> Self {
Self {
transaction_id,
mac,
keys,
}
}
}
/// The content of an in-room `m.key.verification.` event.
///
/// Sends the MAC of a device's key to the partner device.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.key.verification.mac", kind = MessageLike)]
pub struct KeyVerificationMacEventContent {
/// A map of the key ID to the MAC of the key, using the algorithm in the
/// verification process.
///
/// The MAC is encoded as unpadded base64.
pub mac: BTreeMap<String, Base64>,
/// The MAC of the comma-separated, sorted, list of key IDs given in the
/// `mac` property, encoded as unpadded base64.
pub keys: Base64,
/// Information about the related event.
#[serde(rename = "m.relates_to")]
pub relates_to: Reference,
}
impl KeyVerificationMacEventContent {
/// Creates a new `KeyVerificationMacEventContent` with the given key ID to
/// MAC map, key MAC and reference.
pub fn new(mac: BTreeMap<String, Base64>, keys: Base64, relates_to: Reference) -> Self {
Self {
mac,
keys,
relates_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/key/verification/request.rs | crates/core/src/events/key/verification/request.rs | //! Types for the [`m.key.verification.request`] event.
//!
//! [`m.key.verification.request`]: https://spec.matrix.org/latest/client-server-api/#mkeyverificationrequest
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use super::VerificationMethod;
use crate::{OwnedDeviceId, OwnedTransactionId, UnixMillis};
/// The content of an `m.key.verification.request` event.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.key.verification.request", kind = ToDevice)]
pub struct ToDeviceKeyVerificationRequestEventContent {
/// The device ID which is initiating the request.
pub from_device: OwnedDeviceId,
/// An opaque identifier for the verification request.
///
/// Must be unique with respect to the devices involved.
pub transaction_id: OwnedTransactionId,
/// The verification methods supported by the sender.
pub methods: Vec<VerificationMethod>,
/// The time in milliseconds for when the request was made.
///
/// If the request is in the future by more than 5 minutes or more than 10
/// minutes in the past, the message should be ignored by the receiver.
pub timestamp: UnixMillis,
}
impl ToDeviceKeyVerificationRequestEventContent {
/// Creates a new `ToDeviceKeyVerificationRequestEventContent` with the
/// given device ID, transaction ID, methods and timestamp.
pub fn new(
from_device: OwnedDeviceId,
transaction_id: OwnedTransactionId,
methods: Vec<VerificationMethod>,
timestamp: UnixMillis,
) -> Self {
Self {
from_device,
transaction_id,
methods,
timestamp,
}
}
}
| 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/verification/done.rs | crates/core/src/events/key/verification/done.rs | //! Types for the [`m.key.verification.done`] event.
//!
//! [`m.key.verification.done`]: https://spec.matrix.org/latest/client-server-api/#mkeyverificationdone
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{OwnedTransactionId, events::relation::Reference};
/// The content of a to-device `m.m.key.verification.done` event.
///
/// Event signaling that the interactive key verification has successfully
/// concluded.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.key.verification.done", kind = ToDevice)]
pub struct ToDeviceKeyVerificationDoneEventContent {
/// An opaque identifier for the verification process.
///
/// Must be the same as the one used for the `m.key.verification.start`
/// message.
pub transaction_id: OwnedTransactionId,
}
impl ToDeviceKeyVerificationDoneEventContent {
/// Creates a new `ToDeviceKeyVerificationDoneEventContent` with the given
/// transaction ID.
pub fn new(transaction_id: OwnedTransactionId) -> Self {
Self { transaction_id }
}
}
/// The payload for a in-room `m.key.verification.done` event.
///
/// Event signaling that the interactive key verification has successfully
/// concluded.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.key.verification.done", kind = MessageLike)]
pub struct KeyVerificationDoneEventContent {
/// Relation signaling which verification request this event is responding
/// to.
#[serde(rename = "m.relates_to")]
pub relates_to: Reference,
}
impl KeyVerificationDoneEventContent {
/// Creates a new `KeyVerificationDoneEventContent` with the given
/// reference.
pub fn new(relates_to: Reference) -> Self {
Self { relates_to }
}
}
#[cfg(test)]
mod tests {
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::KeyVerificationDoneEventContent;
use crate::{events::relation::Reference, owned_event_id};
#[test]
fn serialization() {
let event_id = owned_event_id!("$1598361704261elfgc:localhost");
let json_data = json!({
"m.relates_to": {
"rel_type": "m.reference",
"event_id": event_id,
}
});
let content = KeyVerificationDoneEventContent {
relates_to: Reference { event_id },
};
assert_eq!(to_json_value(&content).unwrap(), json_data);
}
#[test]
fn deserialization() {
let json_data = json!({
"m.relates_to": {
"rel_type": "m.reference",
"event_id": "$1598361704261elfgc:localhost",
}
});
let content = from_json_value::<KeyVerificationDoneEventContent>(json_data).unwrap();
assert_eq!(content.relates_to.event_id, "$1598361704261elfgc: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/key/verification/start.rs | crates/core/src/events/key/verification/start.rs | //! Types for the [`m.key.verification.start`] event.
//!
//! [`m.key.verification.start`]: https://spec.matrix.org/latest/client-server-api/#mkeyverificationstart
use std::{collections::BTreeMap, fmt};
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use super::{
HashAlgorithm, KeyAgreementProtocol, MessageAuthenticationCode, ShortAuthenticationString,
};
use crate::{OwnedDeviceId, OwnedTransactionId, events::relation::Reference, serde::Base64};
/// The content of a to-device `m.key.verification.start` event.
///
/// Begins an SAS key verification process.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.key.verification.start", kind = ToDevice)]
pub struct ToDeviceKeyVerificationStartEventContent {
/// The device ID which is initiating the process.
pub from_device: OwnedDeviceId,
/// An opaque identifier for the verification process.
///
/// Must be unique with respect to the devices involved. Must be the same as
/// the `transaction_id` given in the `m.key.verification.request` if
/// this process is originating from a request.
pub transaction_id: OwnedTransactionId,
/// Method specific content.
#[serde(flatten)]
pub method: StartMethod,
}
impl ToDeviceKeyVerificationStartEventContent {
/// Creates a new `ToDeviceKeyVerificationStartEventContent` with the given
/// device ID, transaction ID and method specific content.
pub fn new(
from_device: OwnedDeviceId,
transaction_id: OwnedTransactionId,
method: StartMethod,
) -> Self {
Self {
from_device,
transaction_id,
method,
}
}
}
/// The content of an in-room `m.key.verification.start` event.
///
/// Begins an SAS key verification process.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.key.verification.start", kind = MessageLike)]
pub struct KeyVerificationStartEventContent {
/// The device ID which is initiating the process.
pub from_device: OwnedDeviceId,
/// Method specific content.
#[serde(flatten)]
pub method: StartMethod,
/// Information about the related event.
#[serde(rename = "m.relates_to")]
pub relates_to: Reference,
}
impl KeyVerificationStartEventContent {
/// Creates a new `KeyVerificationStartEventContent` with the given device
/// ID, method and reference.
pub fn new(from_device: OwnedDeviceId, method: StartMethod, relates_to: Reference) -> Self {
Self {
from_device,
method,
relates_to,
}
}
}
/// An enum representing the different method specific
/// `m.key.verification.start` content.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[serde(untagged)]
pub enum StartMethod {
/// The `m.sas.v1` verification method.
SasV1(SasV1Content),
/// The `m.reciprocate.v1` verification method.
///
/// The spec entry for this method can be found [here].
///
/// [here]: https://spec.matrix.org/latest/client-server-api/#mkeyverificationstartmreciprocatev1
ReciprocateV1(ReciprocateV1Content),
/// Any unknown start method.
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(_CustomContent),
}
/// Method specific content of a unknown key verification method.
#[doc(hidden)]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[allow(clippy::exhaustive_structs)]
pub struct _CustomContent {
/// The name of the method.
pub method: String,
/// The additional fields that the method contains.
#[serde(flatten)]
pub data: BTreeMap<String, JsonValue>,
}
/// The payload of an `m.key.verification.start` event using the `m.sas.v1`
/// method.
#[derive(ToSchema, Deserialize, Serialize, Clone)]
#[serde(rename = "m.reciprocate.v1", tag = "method")]
pub struct ReciprocateV1Content {
/// The shared secret from the QR code, encoded using unpadded base64.
pub secret: Base64,
}
impl ReciprocateV1Content {
/// Create a new `ReciprocateV1Content` with the given shared secret.
///
/// The shared secret needs to come from the scanned QR code, encoded using
/// unpadded base64.
pub fn new(secret: Base64) -> Self {
Self { secret }
}
}
impl fmt::Debug for ReciprocateV1Content {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ReciprocateV1Content")
.finish_non_exhaustive()
}
}
/// The payload of an `m.key.verification.start` event using the `m.sas.v1`
/// method.
///
/// To create an instance of this type.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[serde(rename = "m.sas.v1", tag = "method")]
pub struct SasV1Content {
/// The key agreement protocols the sending device understands.
///
/// Must include at least `Curve25519` or `Curve25519HkdfSha256`.
pub key_agreement_protocols: Vec<KeyAgreementProtocol>,
/// The hash methods the sending device understands.
///
/// Must include at least `sha256`.
pub hashes: Vec<HashAlgorithm>,
/// The message authentication codes that the sending device understands.
///
/// Must include at least `hkdf-hmac-sha256.v2`. Should also include
/// `hkdf-hmac-sha256` for compatibility with older clients, though this
/// MAC is deprecated and will be removed in a future version of the
/// spec.
pub message_authentication_codes: Vec<MessageAuthenticationCode>,
/// The SAS methods the sending device (and the sending device's user)
/// understands.
///
/// Must include at least `decimal`. Optionally can include `emoji`.
pub short_authentication_string: Vec<ShortAuthenticationString>,
}
// #[cfg(test)]
// mod tests {
// use std::collections::BTreeMap;
// use crate::{event_id, serde::Base64};
// use assert_matches2::assert_matches;
// use serde_json::{from_value as from_json_value, json, to_value as
// to_json_value, Value as JsonValue};
// use super::{
// HashAlgorithm, KeyAgreementProtocol,
// KeyVerificationStartEventContent, MessageAuthenticationCode,
// ReciprocateV1Content, SasV1ContentInit, ShortAuthenticationString,
// StartMethod, ToDeviceKeyVerificationStartEventContent,
// _CustomContent, };
// use crate::{relation::Reference, ToDeviceEvent};
// #[test]
// fn serialization() {
// let key_verification_start_content =
// ToDeviceKeyVerificationStartEventContent { from_device:
// "123".into(), transaction_id: "456".into(),
// method: StartMethod::SasV1(
// SasV1ContentInit {
// hashes: vec![HashAlgorithm::Sha256],
// key_agreement_protocols:
// vec![KeyAgreementProtocol::Curve25519],
// message_authentication_codes:
// vec![MessageAuthenticationCode::HkdfHmacSha256V2],
// short_authentication_string: vec![ShortAuthenticationString::Decimal],
// }
// .into(),
// ),
// };
// let json_data = json!({
// "from_device": "123",
// "transaction_id": "456",
// "method": "m.sas.v1",
// "key_agreement_protocols": ["curve25519"],
// "hashes": ["sha256"],
// "message_authentication_codes": ["hkdf-hmac-sha256.v2"],
// "short_authentication_string": ["decimal"]
// });
// assert_eq!(to_json_value(&key_verification_start_content).unwrap(),
// json_data);
// let json_data = json!({
// "from_device": "123",
// "transaction_id": "456",
// "method": "m.sas.custom",
// "test": "field",
// });
// let key_verification_start_content =
// ToDeviceKeyVerificationStartEventContent { from_device:
// "123".into(), transaction_id: "456".into(),
// method: StartMethod::_Custom(_CustomContent {
// method: "m.sas.custom".to_owned(),
// data: vec![("test".to_owned(), JsonValue::from("field"))]
// .into_iter()
// .collect::<BTreeMap<String, JsonValue>>(),
// }),
// };
// assert_eq!(to_json_value(&key_verification_start_content).unwrap(),
// json_data);
// {
// let secret = Base64::new(b"This is a secret to
// everybody".to_vec());
// let key_verification_start_content =
// ToDeviceKeyVerificationStartEventContent { from_device:
// "123".into(), transaction_id: "456".into(),
// method:
// StartMethod::ReciprocateV1(ReciprocateV1Content::new(secret.clone())),
// };
// let json_data = json!({
// "from_device": "123",
// "method": "m.reciprocate.v1",
// "secret": secret,
// "transaction_id": "456"
// });
//
// assert_eq!(to_json_value(&key_verification_start_content).unwrap(),
// json_data); }
// }
// #[test]
// fn in_room_serialization() {
// let event_id = event_id!("$1598361704261elfgc:localhost");
// let key_verification_start_content = KeyVerificationStartEventContent
// { from_device: "123".into(),
// relates_to: Reference {
// event_id: event_id.to_owned(),
// },
// method: StartMethod::SasV1(
// SasV1ContentInit {
// hashes: vec![HashAlgorithm::Sha256],
// key_agreement_protocols:
// vec![KeyAgreementProtocol::Curve25519],
// message_authentication_codes:
// vec![MessageAuthenticationCode::HkdfHmacSha256V2],
// short_authentication_string: vec![ShortAuthenticationString::Decimal],
// }
// .into(),
// ),
// };
// let json_data = json!({
// "from_device": "123",
// "method": "m.sas.v1",
// "key_agreement_protocols": ["curve25519"],
// "hashes": ["sha256"],
// "message_authentication_codes": ["hkdf-hmac-sha256.v2"],
// "short_authentication_string": ["decimal"],
// "m.relates_to": {
// "rel_type": "m.reference",
// "event_id": event_id,
// }
// });
// assert_eq!(to_json_value(&key_verification_start_content).unwrap(),
// json_data);
// let secret = Base64::new(b"This is a secret to everybody".to_vec());
// let key_verification_start_content = KeyVerificationStartEventContent
// { from_device: "123".into(),
// relates_to: Reference {
// event_id: event_id.to_owned(),
// },
// method:
// StartMethod::ReciprocateV1(ReciprocateV1Content::new(secret.clone())),
// };
// let json_data = json!({
// "from_device": "123",
// "method": "m.reciprocate.v1",
// "secret": secret,
// "m.relates_to": {
// "rel_type": "m.reference",
// "event_id": event_id,
// }
// });
// assert_eq!(to_json_value(&key_verification_start_content).unwrap(),
// json_data); }
// #[test]
// fn deserialization() {
// let json = json!({
// "from_device": "123",
// "transaction_id": "456",
// "method": "m.sas.v1",
// "hashes": ["sha256"],
// "key_agreement_protocols": ["curve25519"],
// "message_authentication_codes": ["hkdf-hmac-sha256.v2"],
// "short_authentication_string": ["decimal"]
// });
// // Deserialize the content struct separately to verify `TryFromRaw`
// is implemented for it. let content =
// from_json_value::<ToDeviceKeyVerificationStartEventContent>(json).unwrap();
// assert_eq!(content.from_device, "123");
// assert_eq!(content.transaction_id, "456");
// assert_matches!(content.method, StartMethod::SasV1(sas));
// assert_eq!(sas.hashes, vec![HashAlgorithm::Sha256]);
// assert_eq!(sas.key_agreement_protocols,
// vec![KeyAgreementProtocol::Curve25519]); assert_eq!(
// sas.message_authentication_codes,
// vec![MessageAuthenticationCode::HkdfHmacSha256V2]
// );
// assert_eq!(
// sas.short_authentication_string,
// vec![ShortAuthenticationString::Decimal]
// );
// let json = json!({
// "content": {
// "from_device": "123",
// "transaction_id": "456",
// "method": "m.sas.v1",
// "key_agreement_protocols": ["curve25519"],
// "hashes": ["sha256"],
// "message_authentication_codes": ["hkdf-hmac-sha256.v2"],
// "short_authentication_string": ["decimal"]
// },
// "type": "m.key.verification.start",
// "sender": "@example:localhost",
// });
// let ev =
// from_json_value::<ToDeviceEvent<ToDeviceKeyVerificationStartEventContent>>(json).
// unwrap(); assert_eq!(ev.sender, "@example:localhost");
// assert_eq!(ev.content.from_device, "123");
// assert_eq!(ev.content.transaction_id, "456");
// assert_matches!(ev.content.method, StartMethod::SasV1(sas));
// assert_eq!(sas.hashes, vec![HashAlgorithm::Sha256]);
// assert_eq!(sas.key_agreement_protocols,
// vec![KeyAgreementProtocol::Curve25519]); assert_eq!(
// sas.message_authentication_codes,
// vec![MessageAuthenticationCode::HkdfHmacSha256V2]
// );
// assert_eq!(
// sas.short_authentication_string,
// vec![ShortAuthenticationString::Decimal]
// );
// let json = json!({
// "content": {
// "from_device": "123",
// "transaction_id": "456",
// "method": "m.sas.custom",
// "test": "field",
// },
// "type": "m.key.verification.start",
// "sender": "@example:localhost",
// });
// let ev =
// from_json_value::<ToDeviceEvent<ToDeviceKeyVerificationStartEventContent>>(json).
// unwrap(); assert_eq!(ev.sender, "@example:localhost");
// assert_eq!(ev.content.from_device, "123");
// assert_eq!(ev.content.transaction_id, "456");
// assert_matches!(ev.content.method, StartMethod::_Custom(custom));
// assert_eq!(custom.method, "m.sas.custom");
// assert_eq!(custom.data.get("test"), Some(&JsonValue::from("field")));
// let json = json!({
// "content": {
// "from_device": "123",
// "method": "m.reciprocate.v1",
// "secret": "c2VjcmV0Cg",
// "transaction_id": "456",
// },
// "type": "m.key.verification.start",
// "sender": "@example:localhost",
// });
// let ev =
// from_json_value::<ToDeviceEvent<ToDeviceKeyVerificationStartEventContent>>(json).
// unwrap(); assert_eq!(ev.sender, "@example:localhost");
// assert_eq!(ev.content.from_device, "123");
// assert_eq!(ev.content.transaction_id, "456");
// assert_matches!(ev.content.method,
// StartMethod::ReciprocateV1(reciprocate)); assert_eq!(reciprocate.
// secret.encode(), "c2VjcmV0Cg"); }
// #[test]
// fn in_room_deserialization() {
// let json = json!({
// "from_device": "123",
// "method": "m.sas.v1",
// "hashes": ["sha256"],
// "key_agreement_protocols": ["curve25519"],
// "message_authentication_codes": ["hkdf-hmac-sha256.v2"],
// "short_authentication_string": ["decimal"],
// "m.relates_to": {
// "rel_type": "m.reference",
// "event_id": "$1598361704261elfgc:localhost",
// }
// });
// // Deserialize the content struct separately to verify `TryFromRaw`
// is implemented for it. let content =
// from_json_value::<KeyVerificationStartEventContent>(json).unwrap();
// assert_eq!(content.from_device, "123");
// assert_eq!(content.relates_to.event_id,
// "$1598361704261elfgc:localhost");
// assert_matches!(content.method, StartMethod::SasV1(sas));
// assert_eq!(sas.hashes, vec![HashAlgorithm::Sha256]);
// assert_eq!(sas.key_agreement_protocols,
// vec![KeyAgreementProtocol::Curve25519]); assert_eq!(
// sas.message_authentication_codes,
// vec![MessageAuthenticationCode::HkdfHmacSha256V2]
// );
// assert_eq!(
// sas.short_authentication_string,
// vec![ShortAuthenticationString::Decimal]
// );
// let json = json!({
// "from_device": "123",
// "method": "m.reciprocate.v1",
// "secret": "c2VjcmV0Cg",
// "m.relates_to": {
// "rel_type": "m.reference",
// "event_id": "$1598361704261elfgc:localhost",
// }
// });
// let content =
// from_json_value::<KeyVerificationStartEventContent>(json).unwrap();
// assert_eq!(content.from_device, "123");
// assert_eq!(content.relates_to.event_id,
// "$1598361704261elfgc:localhost");
// assert_matches!(content.method,
// StartMethod::ReciprocateV1(reciprocate)); assert_eq!(reciprocate.
// secret.encode(), "c2VjcmV0Cg"); }
// }
| 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/notify.rs | crates/core/src/events/call/notify.rs | //! Type for the matrixRTC notify event ([MSC4075]).
//!
//! [MSC4075]: https://github.com/matrix-org/matrix-spec-proposals/pull/4075
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use super::member::Application;
use crate::events::Mentions;
/// The content of an `m.call.notify` event.
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize, EventContent)]
#[palpo_event(type = "m.call.notify", kind = MessageLike)]
pub struct CallNotifyEventContent {
/// A unique identifier for the call.
pub call_id: String,
/// The application this notify event applies to.
pub application: ApplicationType,
/// How this notify event should notify the receiver.
pub notify_type: NotifyType,
/// The users that are notified by this event (See [MSC3952] (Intentional
/// Mentions)).
///
/// [MSC3952]: https://github.com/matrix-org/matrix-spec-proposals/pull/3952
#[serde(rename = "m.mentions")]
pub mentions: Mentions,
}
impl CallNotifyEventContent {
/// Creates a new `CallNotifyEventContent` with the given configuration.
pub fn new(
call_id: String,
application: ApplicationType,
notify_type: NotifyType,
mentions: Mentions,
) -> Self {
Self {
call_id,
application,
notify_type,
mentions,
}
}
}
/// How this notify event should notify the receiver.
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize)]
pub enum NotifyType {
/// The receiving client should ring with an audible sound.
#[serde(rename = "ring")]
Ring,
/// The receiving client should display a visual notification.
#[serde(rename = "notify")]
Notify,
}
/// The type of matrix RTC application.
///
/// This is different to [`Application`] because application contains all the
/// information from the `m.call.member` event.
///
/// An `Application` can be converted into an `ApplicationType` using `.into()`.
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize)]
pub enum ApplicationType {
/// A VoIP call.
#[serde(rename = "m.call")]
Call,
}
impl From<Application> for ApplicationType {
fn from(val: Application) -> Self {
match val {
Application::Call(_) => ApplicationType::Call,
}
}
}
| 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/answer.rs | crates/core/src/events/call/answer.rs | //! Types for the [`m.call.answer`] event.
//!
//! [`m.call.answer`]: https://spec.matrix.org/latest/client-server-api/#mcallanswer
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
#[cfg(feature = "unstable-msc2747")]
use super::CallCapabilities;
use super::SessionDescription;
use crate::{OwnedVoipId, VoipVersionId};
/// The content of an `m.call.answer` event.
///
/// This event is sent by the callee when they wish to answer the call.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.call.answer", kind = MessageLike)]
pub struct CallAnswerEventContent {
/// The VoIP session description object.
pub answer: SessionDescription,
/// A unique identifier for the call.
pub call_id: OwnedVoipId,
/// **Required in VoIP version 1.** A unique ID for this session for the
/// duration of the call.
#[serde(skip_serializing_if = "Option::is_none")]
pub party_id: Option<OwnedVoipId>,
/// The version of the VoIP specification this messages adheres to.
pub version: VoipVersionId,
#[cfg(feature = "unstable-msc2747")]
/// The VoIP capabilities of the client.
#[serde(default, skip_serializing_if = "CallCapabilities::is_default")]
pub capabilities: CallCapabilities,
}
impl CallAnswerEventContent {
/// Creates an `CallAnswerEventContent` with the given answer, call ID and
/// VoIP version.
pub fn new(answer: SessionDescription, call_id: OwnedVoipId, version: VoipVersionId) -> Self {
Self {
answer,
call_id,
party_id: None,
version,
#[cfg(feature = "unstable-msc2747")]
capabilities: Default::default(),
}
}
/// Convenience method to create a VoIP version 0 `CallAnswerEventContent`
/// with all the required fields.
pub fn version_0(answer: SessionDescription, call_id: OwnedVoipId) -> Self {
Self::new(answer, call_id, VoipVersionId::V0)
}
/// Convenience method to create a VoIP version 1 `CallAnswerEventContent`
/// with all the required fields.
pub fn version_1(
answer: SessionDescription,
call_id: OwnedVoipId,
party_id: OwnedVoipId,
) -> Self {
Self {
answer,
call_id,
party_id: Some(party_id),
version: VoipVersionId::V1,
#[cfg(feature = "unstable-msc2747")]
capabilities: Default::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/call/negotiate.rs | crates/core/src/events/call/negotiate.rs | //! Types for the [`m.call.negotiate`] event.
//!
//! [`m.call.negotiate`]: https://spec.matrix.org/latest/client-server-api/#mcallnegotiate
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use super::SessionDescription;
use crate::{OwnedVoipId, VoipVersionId};
/// **Added in VoIP version 1.** The content of an `m.call.negotiate` event.
///
/// This event is sent by either party after the call is established to
/// renegotiate it. It can be used for media pause, hold/resume, ICE restarts
/// and voice/video call up/downgrading.
///
/// First an event must be sent with an `offer` session description, which is
/// replied to with an event with an `answer` session description.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.call.negotiate", kind = MessageLike)]
pub struct CallNegotiateEventContent {
/// The ID of the call this event relates to.
pub call_id: OwnedVoipId,
/// The unique ID for this session for the duration of the call.
///
/// Must be the same as the one sent by the previous invite or answer from
/// this session.
pub party_id: OwnedVoipId,
/// The version of the VoIP specification this messages adheres to.
pub version: VoipVersionId,
/// The time in milliseconds that the negotiation is valid for.
pub lifetime: u64,
/// The session description of the negotiation.
pub description: SessionDescription,
}
impl CallNegotiateEventContent {
/// Creates a `CallNegotiateEventContent` with the given call ID, party ID,
/// lifetime and description.
pub fn new(
call_id: OwnedVoipId,
party_id: OwnedVoipId,
version: VoipVersionId,
lifetime: u64,
description: SessionDescription,
) -> Self {
Self {
call_id,
party_id,
version,
lifetime,
description,
}
}
/// Convenience method to create a version 1 `CallNegotiateEventContent`
/// with all the required fields.
pub fn version_1(
call_id: OwnedVoipId,
party_id: OwnedVoipId,
lifetime: u64,
description: SessionDescription,
) -> Self {
Self::new(call_id, party_id, VoipVersionId::V1, lifetime, description)
}
}
| 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/select_answer.rs | crates/core/src/events/call/select_answer.rs | //! Types for the [`m.call.select_answer`] event.
//!
//! [`m.call.select_answer`]: https://spec.matrix.org/latest/client-server-api/#mcallselect_answer
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{OwnedVoipId, VoipVersionId};
/// **Added in VoIP version 1.** The content of an `m.call.select_answer` event.
///
/// This event is sent by the caller when it has chosen an answer.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.call.select_answer", kind = MessageLike)]
pub struct CallSelectAnswerEventContent {
/// The ID of the call this event relates to.
pub call_id: OwnedVoipId,
/// A unique ID for this session for the duration of the call.
///
/// Must be the same as the one sent by the previous invite from this
/// session.
pub party_id: OwnedVoipId,
/// The party ID of the selected answer to the previously sent invite.
pub selected_party_id: OwnedVoipId,
/// The version of the VoIP specification this messages adheres to.
///
/// Cannot be older than `VoipVersionId::V1`.
pub version: VoipVersionId,
}
impl CallSelectAnswerEventContent {
/// Creates a `CallSelectAnswerEventContent` with the given call ID, VoIP
/// version, party ID and selected party ID.
pub fn new(
call_id: OwnedVoipId,
party_id: OwnedVoipId,
selected_party_id: OwnedVoipId,
version: VoipVersionId,
) -> Self {
Self {
call_id,
party_id,
selected_party_id,
version,
}
}
/// Convenience method to create a version 1 `CallSelectAnswerEventContent`
/// with all the required fields.
pub fn version_1(
call_id: OwnedVoipId,
party_id: OwnedVoipId,
selected_party_id: OwnedVoipId,
) -> Self {
Self::new(call_id, party_id, selected_party_id, VoipVersionId::V1)
}
}
| 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/invite.rs | crates/core/src/events/call/invite.rs | //! Types for the [`m.call.invite`] event.
//!
//! [`m.call.invite`]: https://spec.matrix.org/latest/client-server-api/#mcallinvite
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
#[cfg(feature = "unstable-msc2747")]
use super::CallCapabilities;
use super::SessionDescription;
use crate::{OwnedUserId, OwnedVoipId, VoipVersionId};
/// The content of an `m.call.invite` event.
///
/// This event is sent by the caller when they wish to establish a call.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.call.invite", kind = MessageLike)]
pub struct CallInviteEventContent {
/// A unique identifier for the call.
pub call_id: OwnedVoipId,
/// **Required in VoIP version 1.** A unique ID for this session for the
/// duration of the call.
#[serde(skip_serializing_if = "Option::is_none")]
pub party_id: Option<OwnedVoipId>,
/// The time in milliseconds that the invite is valid for.
///
/// Once the invite age exceeds this value, clients should discard it. They
/// should also no longer show the call as awaiting an answer in the UI.
pub lifetime: u64,
/// The session description object.
pub offer: SessionDescription,
/// The version of the VoIP specification this messages adheres to.
pub version: VoipVersionId,
/// The VoIP capabilities of the client.
#[cfg(feature = "unstable-msc2747")]
#[serde(default, skip_serializing_if = "CallCapabilities::is_default")]
pub capabilities: CallCapabilities,
/// **Added in VoIP version 1.** The intended target of the invite, if any.
///
/// If this is `None`, the invite is intended for any member of the room,
/// except the sender.
///
/// The invite should be ignored if the invitee is set and doesn't match the
/// user's ID.
#[serde(skip_serializing_if = "Option::is_none")]
pub invitee: Option<OwnedUserId>,
}
impl CallInviteEventContent {
/// Creates a new `CallInviteEventContent` with the given call ID, lifetime,
/// offer and VoIP version.
pub fn new(
call_id: OwnedVoipId,
lifetime: u64,
offer: SessionDescription,
version: VoipVersionId,
) -> Self {
Self {
call_id,
party_id: None,
lifetime,
offer,
version,
#[cfg(feature = "unstable-msc2747")]
capabilities: Default::default(),
invitee: None,
}
}
/// Convenience method to create a version 0 `CallInviteEventContent` with
/// all the required fields.
pub fn version_0(call_id: OwnedVoipId, lifetime: u64, offer: SessionDescription) -> Self {
Self::new(call_id, lifetime, offer, VoipVersionId::V0)
}
/// Convenience method to create a version 1 `CallInviteEventContent` with
/// all the required fields.
pub fn version_1(
call_id: OwnedVoipId,
party_id: OwnedVoipId,
lifetime: u64,
offer: SessionDescription,
) -> Self {
Self {
call_id,
party_id: Some(party_id),
lifetime,
offer,
version: VoipVersionId::V1,
#[cfg(feature = "unstable-msc2747")]
capabilities: Default::default(),
invitee: 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/call/reject.rs | crates/core/src/events/call/reject.rs | //! Types for the [`m.call.reject`] event.
//!
//! [`m.call.reject`]: https://spec.matrix.org/latest/client-server-api/#mcallreject
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{OwnedVoipId, VoipVersionId};
/// **Added in VoIP version 1.** The content of an `m.call.reject` event.
///
/// Starting from VoIP version 1, this event is sent by the callee to reject an
/// invite.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.call.reject", kind = MessageLike)]
pub struct CallRejectEventContent {
/// The ID of the call this event relates to.
pub call_id: OwnedVoipId,
/// A unique ID for this session for the duration of the call.
pub party_id: OwnedVoipId,
/// The version of the VoIP specification this messages adheres to.
///
/// Cannot be older than `VoipVersionId::V1`.
pub version: VoipVersionId,
}
impl CallRejectEventContent {
/// Creates a `CallRejectEventContent` with the given call ID, VoIP version
/// and party ID.
pub fn new(call_id: OwnedVoipId, party_id: OwnedVoipId, version: VoipVersionId) -> Self {
Self {
call_id,
party_id,
version,
}
}
/// Convenience method to create a version 1 `CallRejectEventContent` with
/// all the required fields.
pub fn version_1(call_id: OwnedVoipId, party_id: OwnedVoipId) -> Self {
Self::new(call_id, party_id, VoipVersionId::V1)
}
}
| 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/hangup.rs | crates/core/src/events/call/hangup.rs | //! Types for the [`m.call.hangup`] event.
//!
//! [`m.call.hangup`]: https://spec.matrix.org/latest/client-server-api/#mcallhangup
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{OwnedVoipId, PrivOwnedStr, VoipVersionId, serde::StringEnum};
/// The content of an `m.call.hangup` event.
///
/// Sent by either party to signal their termination of the call.
///
/// In VoIP version 0, this can be sent either once the call has been
/// established or before to abort the call.
///
/// If the call is using VoIP version 1, this should only be sent by the caller
/// after sending the invite or by the callee after answering the invite. To
/// reject an invite, send an [`m.call.reject`] event.
///
/// [`m.call.reject`]: super::reject::CallRejectEventContent
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.call.hangup", kind = MessageLike)]
pub struct CallHangupEventContent {
/// A unique identifier for the call.
pub call_id: OwnedVoipId,
/// **Required in VoIP version 1.** A unique ID for this session for the
/// duration of the call.
///
/// Must be the same as the one sent by the previous invite or answer from
/// this session.
#[serde(skip_serializing_if = "Option::is_none")]
pub party_id: Option<OwnedVoipId>,
/// The version of the VoIP specification this messages adheres to.
pub version: VoipVersionId,
/// Error reason for the hangup.
///
/// Defaults to `Reason::UserHangup`.
#[serde(default)]
pub reason: Reason,
}
impl CallHangupEventContent {
/// Creates a new `CallHangupEventContent` with the given call ID and VoIP
/// version.
pub fn new(call_id: OwnedVoipId, version: VoipVersionId) -> Self {
Self {
call_id,
party_id: None,
version,
reason: Default::default(),
}
}
/// Convenience method to create a VoIP version 0 `CallHangupEventContent`
/// with all the required fields.
pub fn version_0(call_id: OwnedVoipId) -> Self {
Self::new(call_id, VoipVersionId::V0)
}
/// Convenience method to create a VoIP version 1 `CallHangupEventContent`
/// with all the required fields.
pub fn version_1(call_id: OwnedVoipId, party_id: OwnedVoipId, reason: Reason) -> Self {
Self {
call_id,
party_id: Some(party_id),
version: VoipVersionId::V1,
reason,
}
}
}
/// A reason for a hangup.
///
/// Should not be provided when the user naturally ends or rejects the call.
/// When there was an error in the call negotiation, this should be `ice_failed`
/// for when ICE negotiation fails or `invite_timeout` for when the other party
/// did not answer in time.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, Default, StringEnum)]
#[palpo_enum(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Reason {
/// ICE negotiation failure.
IceFailed,
/// Party did not answer in time.
InviteTimeout,
/// The connection failed after some media was exchanged.
///
/// Note that, in the case of an ICE renegotiation, a client should be sure
/// to send `ice_timeout` rather than `ice_failed` if media had
/// previously been received successfully, even if the ICE renegotiation
/// itself failed.
IceTimeout,
/// The user chose to end the call.
#[default]
UserHangup,
/// The client was unable to start capturing media in such a way as it is
/// unable to continue the call.
UserMediaFailed,
/// The user is busy.
UserBusy,
/// Some other failure occurred that meant the client was unable to continue
/// the call rather than the user choosing to end it.
UnknownError,
#[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/call/sdp_stream_metadata_changed.rs | crates/core/src/events/call/sdp_stream_metadata_changed.rs | //! Types for the [`m.call.sdp_stream_metadata_changed`] event.
//!
//! [`m.call.sdp_stream_metadata_changed`]: https://spec.matrix.org/latest/client-server-api/#mcallsdp_stream_metadata_changed
use std::collections::BTreeMap;
use crate::macros::EventContent;
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use super::StreamMetadata;
use crate::{OwnedVoipId, VoipVersionId};
/// The content of an `m.call.sdp_stream_metadata_changed` event.
///
/// This event is sent by any party when a stream metadata changes but no
/// negotiation is required.
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize, EventContent)]
#[palpo_event(type = "m.call.sdp_stream_metadata_changed", alias = "org.matrix.call.sdp_stream_metadata_changed", kind = MessageLike)]
pub struct CallSdpStreamMetadataChangedEventContent {
/// A unique identifier for the call.
pub call_id: OwnedVoipId,
/// A unique ID for this session for the duration of the call.
pub party_id: OwnedVoipId,
/// The version of the VoIP specification this messages adheres to.
///
/// Must be at least [`VoipVersionId::V1`].
pub version: VoipVersionId,
/// Metadata describing the streams that will be sent.
///
/// This is a map of stream ID to metadata about the stream.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub sdp_stream_metadata: BTreeMap<String, StreamMetadata>,
}
impl CallSdpStreamMetadataChangedEventContent {
/// Creates a new `SdpStreamMetadataChangedEventContent` with the given call
/// ID, party ID, VoIP version and stream metadata.
pub fn new(
call_id: OwnedVoipId,
party_id: OwnedVoipId,
version: VoipVersionId,
sdp_stream_metadata: BTreeMap<String, StreamMetadata>,
) -> Self {
Self {
call_id,
party_id,
version,
sdp_stream_metadata,
}
}
}
| 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/member.rs | crates/core/src/events/call/member.rs | //! Types for matrixRTC state events ([MSC3401]).
//!
//! This implements a newer/updated version of MSC3401.
//!
//! [MSC3401]: https://github.com/matrix-org/matrix-spec-proposals/pull/3401
mod focus;
mod member_data;
mod member_state_key;
pub use focus::*;
pub use member_data::*;
pub use member_state_key::*;
use std::time::Duration;
use as_variant::as_variant;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::macros::EventContent;
use crate::room_version_rules::RedactionRules;
use crate::{
OwnedDeviceId, PrivOwnedStr, UnixMillis,
events::{
PossiblyRedactedStateEventContent, RedactContent, RedactedStateEventContent,
StateEventType, StaticEventContent,
},
serde::StringEnum,
};
/// The member state event for a matrixRTC session.
///
/// This is the object containing all the data related to a matrix users
/// participation in a matrixRTC session. It consists of memberships / sessions.
#[derive(ToSchema, Clone, Debug, PartialEq, Serialize, Deserialize, EventContent)]
#[palpo_event(type = "org.matrix.msc3401.call.member", kind = State, state_key_type = CallMemberStateKey, custom_redacted, custom_possibly_redacted)]
#[serde(untagged)]
pub enum CallMemberEventContent {
/// The legacy format for m.call.member events. (An array of memberships. The devices of one
/// user.)
LegacyContent(LegacyMembershipContent),
/// Normal membership events. One event per membership. Multiple state keys will
/// be used to describe multiple devices for one user.
SessionContent(SessionMembershipData),
/// An empty content means this user has been in a rtc session but is not anymore.
Empty(EmptyMembershipData),
}
impl CallMemberEventContent {
/// Creates a new [`CallMemberEventContent`] with [`LegacyMembershipData`].
pub fn new_legacy(memberships: Vec<LegacyMembershipData>) -> Self {
Self::LegacyContent(LegacyMembershipContent {
memberships, //: memberships.into_iter().map(MembershipData::Legacy).collect(),
})
}
/// Creates a new [`CallMemberEventContent`] with [`SessionMembershipData`].
///
/// # Arguments
/// * `application` - The application that is creating the membership.
/// * `device_id` - The device ID of the member.
/// * `focus_active` - The active focus state of the member.
/// * `foci_preferred` - The preferred focus states of the member.
/// * `created_ts` - The timestamp when this state event chain for memberships was created. when
/// updating the event the `created_ts` should be copied from the previous state. Set to
/// `None` if this is the initial join event for the session.
/// * `expires` - The time after which the event is considered as expired. Defaults to 4 hours.
pub fn new(
application: Application,
device_id: OwnedDeviceId,
focus_active: ActiveFocus,
foci_preferred: Vec<Focus>,
created_ts: Option<UnixMillis>,
expires: Option<Duration>,
) -> Self {
Self::SessionContent(SessionMembershipData {
application,
device_id,
focus_active,
foci_preferred,
created_ts,
expires: expires.unwrap_or(Duration::from_secs(14_400)), // Default to 4 hours
})
}
/// Creates a new Empty [`CallMemberEventContent`] representing a left membership.
pub fn new_empty(leave_reason: Option<LeaveReason>) -> Self {
Self::Empty(EmptyMembershipData { leave_reason })
}
/// All non expired memberships in this member event.
///
/// In most cases you want tu use this method instead of the public
/// memberships field. The memberships field will also include expired
/// events.
///
/// # Arguments
///
/// * `origin_server_ts` - optionally the `origin_server_ts` can be passed
/// as a fallback in case the Membership does not contain `created_ts`.
/// (`origin_server_ts` will be ignored if `created_ts` is `Some`)
pub fn active_memberships(
&self,
origin_server_ts: Option<UnixMillis>,
) -> Vec<MembershipData<'_>> {
match self {
CallMemberEventContent::LegacyContent(content) => content
.memberships
.iter()
.map(MembershipData::Legacy)
.filter(|m| !m.is_expired(origin_server_ts))
.collect(),
CallMemberEventContent::SessionContent(content) => {
vec![MembershipData::Session(content)]
.into_iter()
.filter(|m| !m.is_expired(origin_server_ts))
.collect()
}
CallMemberEventContent::Empty(_) => Vec::new(),
}
}
/// All the memberships for this event. Can only contain multiple elements in the case of legacy
/// `m.call.member` state events.
pub fn memberships(&self) -> Vec<MembershipData<'_>> {
match self {
CallMemberEventContent::LegacyContent(content) => content
.memberships
.iter()
.map(MembershipData::Legacy)
.collect(),
CallMemberEventContent::SessionContent(content) => {
[content].map(MembershipData::Session).to_vec()
}
CallMemberEventContent::Empty(_) => Vec::new(),
}
}
/// Set the `created_ts` in this event.
///
/// Each call member event contains the `origin_server_ts` and `content.create_ts`.
/// `content.create_ts` is undefined for the initial event of a session (because the
/// `origin_server_ts` is not known on the client).
/// In the rust sdk we want to copy over the `origin_server_ts` of the event into the content.
/// (This allows to use `MinimalStateEvents` and still be able to determine if a membership is
/// expired)
pub fn set_created_ts_if_none(&mut self, origin_server_ts: UnixMillis) {
match self {
CallMemberEventContent::LegacyContent(content) => {
content
.memberships
.iter_mut()
.for_each(|m: &mut LegacyMembershipData| {
m.created_ts.get_or_insert(origin_server_ts);
});
}
CallMemberEventContent::SessionContent(m) => {
m.created_ts.get_or_insert(origin_server_ts);
}
_ => (),
}
}
}
/// This describes the CallMember event if the user is not part of the current session.
#[derive(ToSchema, PartialEq, Clone, Serialize, Deserialize, Debug)]
pub struct EmptyMembershipData {
/// An empty call member state event can optionally contain a leave reason.
/// If it is `None` the user has left the call ordinarily. (Intentional hangup)
#[serde(skip_serializing_if = "Option::is_none")]
pub leave_reason: Option<LeaveReason>,
}
/// This is the optional value for an empty membership event content:
/// [`CallMemberEventContent::Empty`].
///
/// It is used when the user disconnected and a Future ([MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140))
/// was used to update the membership after the client was not reachable anymore.
#[derive(ToSchema, Clone, StringEnum)]
#[palpo_enum(rename_all(prefix = "m.", rule = "snake_case"))]
pub enum LeaveReason {
/// The user left the call by losing network connection or closing
/// the client before it was able to send the leave event.
LostConnection,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
impl RedactContent for CallMemberEventContent {
type Redacted = RedactedCallMemberEventContent;
fn redact(self, _rules: &RedactionRules) -> Self::Redacted {
RedactedCallMemberEventContent {}
}
}
/// The PossiblyRedacted version of [`CallMemberEventContent`].
///
/// Since [`CallMemberEventContent`] has the [`CallMemberEventContent::Empty`] state it already is
/// compatible with the redacted version of the state event content.
pub type PossiblyRedactedCallMemberEventContent = CallMemberEventContent;
impl PossiblyRedactedStateEventContent for PossiblyRedactedCallMemberEventContent {
type StateKey = CallMemberStateKey;
fn event_type(&self) -> StateEventType {
StateEventType::CallMember
}
}
/// The Redacted version of [`CallMemberEventContent`].
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize)]
#[allow(clippy::exhaustive_structs)]
pub struct RedactedCallMemberEventContent {}
impl RedactedStateEventContent for RedactedCallMemberEventContent {
type StateKey = CallMemberStateKey;
fn event_type(&self) -> StateEventType {
StateEventType::CallMember
}
}
impl StaticEventContent for RedactedCallMemberEventContent {
const TYPE: &'static str = CallMemberEventContent::TYPE;
type IsPrefix = <CallMemberEventContent as StaticEventContent>::IsPrefix;
}
/// Legacy content with an array of memberships. See also: [`CallMemberEventContent`]
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct LegacyMembershipContent {
/// A list of all the memberships that user currently has in this room.
///
/// There can be multiple ones in case the user participates with multiple devices or there
/// are multiple RTC applications running.
///
/// e.g. a call and a spacial experience.
///
/// Important: This includes expired memberships.
/// To retrieve a list including only valid memberships,
/// see [`active_memberships`](CallMemberEventContent::active_memberships).
memberships: Vec<LegacyMembershipData>,
}
/// A membership describes one of the sessions this user currently partakes.
///
/// The application defines the type of the session.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(test, derive(PartialEq))]
pub struct Membership {
/// The type of the matrixRTC session the membership belongs to.
///
/// e.g. call, spacial, document...
#[serde(flatten)]
pub application: Application,
/// The device id of this membership.
///
/// The same user can join with their phone/computer.
pub device_id: String,
/// The duration in milliseconds relative to the time this membership joined
/// during which the membership is valid.
///
/// The time a member has joined is defined as:
/// `MIN(content.created_ts, event.origin_server_ts)`
#[serde(with = "palpo_core::serde::duration::ms")]
pub expires: Duration,
/// Stores a copy of the `origin_server_ts` of the initial session event.
///
/// If the membership is updated this field will be used to track to
/// original `origin_server_ts`.
#[serde(skip_serializing_if = "Option::is_none")]
pub created_ts: Option<UnixMillis>,
/// A list of the foci in use for this membership.
pub foci_active: Vec<Focus>,
/// The id of the membership.
///
/// This is required to guarantee uniqueness of the event.
/// Sending the same state event twice to synapse makes the HS drop the
/// second one and return 200.
#[serde(rename = "membershipID")]
pub membership_id: String,
}
impl Membership {
/// The application of the membership is "m.call" and the scope is "m.room".
pub fn is_room_call(&self) -> bool {
as_variant!(&self.application, Application::Call)
.is_some_and(|call| call.scope == CallScope::Room)
}
/// The application of the membership is "m.call".
pub fn is_call(&self) -> bool {
as_variant!(&self.application, Application::Call).is_some()
}
/// Checks if the event is expired.
///
/// Defaults to using `created_ts` of the `Membership`.
/// If no `origin_server_ts` is provided and the event does not contain
/// `created_ts` the event will be considered as not expired.
/// In this case, a warning will be logged.
///
/// # Arguments
///
/// * `origin_server_ts` - a fallback if `created_ts` is not present
pub fn is_expired(&self, origin_server_ts: Option<UnixMillis>) -> bool {
let ev_created_ts = self.created_ts.or(origin_server_ts);
if let Some(ev_created_ts) = ev_created_ts {
let now = UnixMillis::now().to_system_time();
let expire_ts = ev_created_ts.to_system_time().map(|t| t + self.expires);
now > expire_ts
} else {
// This should not be reached since we only allow events that have copied over
// the origin server ts. `set_created_ts_if_none`
warn!(
"Encountered a Call Member state event where the origin_ts (or origin_server_ts) could not be found.\
It is treated as a non expired event but this might be wrong."
);
false
}
}
}
// #[cfg(test)]
// mod tests {
// use std::time::Duration;
// use serde_json::json;
// use super::{
// Application, CallApplicationContent, CallMemberEventContent, CallScope, Membership,
// focus::{ActiveFocus, ActiveLivekitFocus, Focus, LivekitFocus},
// member_data::{
// Application, CallApplicationContent, CallScope, LegacyMembershipData, MembershipData,
// },
// };
// use crate::{
// call::member::{EmptyMembershipData, FocusSelection, SessionMembershipData},
// AnyStateEvent, StateEvent,
// };
// use crate::{owned_device_id,UnixMillis as TS};
// fn create_call_member_event_content() -> CallMemberEventContent {
// CallMemberEventContent::new(vec![Membership {
// application: Application::Call(CallApplicationContent {
// call_id: "123456".to_owned(),
// scope: CallScope::Room,
// }),
// device_id: "ABCDE".to_owned(),
// expires: Duration::from_secs(3600),
// foci_active: vec![Focus::Livekit(LivekitFocus {
// alias: "1".to_owned(),
// service_url: "https://livekit.com".to_owned(),
// })],
// membership_id: "0".to_owned(),
// created_ts: None,
// }])
// }
// #[test]
// fn serialize_call_member_event_content() {
// let call_member_event = &json!({
// "memberships": [
// {
// "application": "m.call",
// "call_id": "123456",
// "scope": "m.room",
// "device_id": "ABCDE",
// "expires": 3_600_000,
// "foci_active": [
// {
// "livekit_alias": "1",
// "livekit_service_url": "https://livekit.com",
// "type": "livekit"
// }
// ],
// "membershipID": "0"
// }
// ]
// });
// assert_eq!(
// call_member_event,
// &serde_json::to_value(create_call_member_event_content()).unwrap()
// );
// }
// #[test]
// fn deserialize_call_member_event_content() {
// let call_member_ev = CallMemberEventContent::new(
// Application::Call(CallApplicationContent {
// call_id: "123456".to_owned(),
// scope: CallScope::Room,
// }),
// owned_device_id!("THIS_DEVICE"),
// ActiveFocus::Livekit(ActiveLivekitFocus {
// focus_selection: FocusSelection::OldestMembership,
// }),
// vec![Focus::Livekit(LivekitFocus {
// alias: "room1".to_owned(),
// service_url: "https://livekit1.com".to_owned(),
// })],
// None,
// None,
// );
// let call_member_ev_json = json!({
// "application": "m.call",
// "call_id": "123456",
// "scope": "m.room",
// "expires": 14_400_000, // Default to 4 hours
// "device_id": "THIS_DEVICE",
// "focus_active":{
// "type": "livekit",
// "focus_selection": "oldest_membership"
// },
// "foci_preferred": [
// {
// "livekit_alias": "room1",
// "livekit_service_url": "https://livekit1.com",
// "type": "livekit"
// }
// ],
// });
// let ev_content: CallMemberEventContent =
// serde_json::from_value(call_member_ev_json).unwrap();
// assert_eq!(
// serde_json::to_string(&ev_content).unwrap(),
// serde_json::to_string(&call_member_ev).unwrap()
// );
// let empty = CallMemberEventContent::Empty(EmptyMembershipData { leave_reason: None });
// assert_eq!(
// serde_json::to_string(&json!({})).unwrap(),
// serde_json::to_string(&empty).unwrap()
// );
// }
// fn timestamps() -> (TS, TS, TS) {
// let now = TS::now();
// let one_second_ago = now
// .to_system_time()
// .unwrap()
// .checked_sub(Duration::from_secs(1))
// .unwrap();
// let two_hours_ago = now
// .to_system_time()
// .unwrap()
// .checked_sub(Duration::from_secs(60 * 60 * 2))
// .unwrap();
// (
// now,
// TS::from_system_time(one_second_ago).unwrap(),
// TS::from_system_time(two_hours_ago).unwrap(),
// )
// }
// #[test]
// fn legacy_memberships_do_expire() {
// let content_legacy = create_call_member_legacy_event_content();
// let (now, one_second_ago, two_hours_ago) = timestamps();
// assert_eq!(
// content_legacy.active_memberships(Some(one_second_ago)),
// content_legacy.memberships()
// );
// assert_eq!(
// content_legacy.active_memberships(Some(now)),
// content_legacy.memberships()
// );
// assert_eq!(
// content_legacy.active_memberships(Some(two_hours_ago)),
// (vec![] as Vec<MembershipData<'_>>)
// );
// }
// #[test]
// fn session_membership_does_expire() {
// let content = create_call_member_event_content();
// let (now, one_second_ago, two_hours_ago) = timestamps();
// assert_eq!(content.active_memberships(Some(now)), content.memberships());
// assert_eq!(
// content.active_memberships(Some(one_second_ago)),
// content.memberships()
// );
// assert_eq!(
// content.active_memberships(Some(two_hours_ago)),
// (vec![] as Vec<MembershipData<'_>>)
// );
// }
// #[test]
// fn set_created_ts() {
// let mut content_now = create_call_member_event_content();
// let mut content_two_hours_ago = create_call_member_event_content();
// let mut content_one_second_ago = create_call_member_event_content();
// let (now, one_second_ago, two_hours_ago) = timestamps();
// content_now.set_created_ts_if_none(now);
// content_one_second_ago.set_created_ts_if_none(one_second_ago);
// content_two_hours_ago.set_created_ts_if_none(two_hours_ago);
// assert_eq!(
// content_now.active_memberships(None),
// content_now.memberships()
// );
// assert_eq!(
// content_two_hours_ago.active_memberships(None),
// vec![] as Vec<&Membership>
// );
// assert_eq!(
// content_one_second_ago.active_memberships(None),
// content_one_second_ago.memberships()
// );
// // created_ts should not be overwritten.
// content_two_hours_ago.set_created_ts_if_none(one_second_ago);
// // There still should be no active membership.
// assert_eq!(
// content_two_hours_ago.active_memberships(None),
// vec![] as Vec<MembershipData<'_>>
// );
// }
// }
| 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/candidates.rs | crates/core/src/events/call/candidates.rs | //! Types for the [`m.call.candidates`] event.
//!
//! [`m.call.candidates`]: https://spec.matrix.org/latest/client-server-api/#mcallcandidates
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{OwnedVoipId, VoipVersionId};
/// The content of an `m.call.candidates` event.
///
/// This event is sent by callers after sending an invite and by the callee
/// after answering. Its purpose is to give the other party additional ICE
/// candidates to try using to communicate.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.call.candidates", kind = MessageLike)]
pub struct CallCandidatesEventContent {
/// A unique identifier for the call.
pub call_id: OwnedVoipId,
/// **Required in VoIP version 1.** The unique ID for this session for the
/// duration of the call.
///
/// Must be the same as the one sent by the previous invite or answer from
/// this session.
#[serde(skip_serializing_if = "Option::is_none")]
pub party_id: Option<OwnedVoipId>,
/// A list of candidates.
///
/// In VoIP version 1, this list should end with a `Candidate` with an empty
/// `candidate` field when no more candidates will be sent.
pub candidates: Vec<Candidate>,
/// The version of the VoIP specification this messages adheres to.
pub version: VoipVersionId,
}
impl CallCandidatesEventContent {
/// Creates a new `CallCandidatesEventContent` with the given call id,
/// candidate list and VoIP version.
pub fn new(call_id: OwnedVoipId, candidates: Vec<Candidate>, version: VoipVersionId) -> Self {
Self {
call_id,
candidates,
version,
party_id: None,
}
}
/// Convenience method to create a VoIP version 0
/// `CallCandidatesEventContent` with all the required fields.
pub fn version_0(call_id: OwnedVoipId, candidates: Vec<Candidate>) -> Self {
Self::new(call_id, candidates, VoipVersionId::V0)
}
/// Convenience method to create a VoIP version 1
/// `CallCandidatesEventContent` with all the required fields.
pub fn version_1(
call_id: OwnedVoipId,
party_id: OwnedVoipId,
candidates: Vec<Candidate>,
) -> Self {
Self {
call_id,
party_id: Some(party_id),
candidates,
version: VoipVersionId::V1,
}
}
}
/// An ICE (Interactive Connectivity Establishment) candidate.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Candidate {
/// The SDP "a" line of the candidate.
pub candidate: String,
/// The SDP media type this candidate is intended for.
pub sdp_mid: String,
/// The index of the SDP "m" line this candidate is intended for.
pub sdp_m_line_index: u64,
}
impl Candidate {
/// Creates a new `Candidate` with the given "a" line, SDP media type and
/// SDP "m" line.
pub fn new(candidate: String, sdp_mid: String, sdp_m_line_index: u64) -> Self {
Self {
candidate,
sdp_mid,
sdp_m_line_index,
}
}
}
| 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/member/focus.rs | crates/core/src/events/call/member/focus.rs | //! Types for MatrixRTC Focus/SFU configurations.
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::PrivOwnedStr;
use crate::macros::StringEnum;
/// Description of the SFU/Focus a membership can be connected to.
///
/// A focus can be any server powering the MatrixRTC session (SFU,
/// MCU). It serves as a node to redistribute RTC streams.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Focus {
/// LiveKit is one possible type of SFU/Focus that can be used for a MatrixRTC session.
Livekit(LivekitFocus),
}
/// The struct to describe LiveKit as a `preferred_foci`.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct LivekitFocus {
/// The alias where the LiveKit sessions can be reached.
#[serde(rename = "livekit_alias")]
pub alias: String,
/// The URL of the JWT service for the LiveKit instance.
#[serde(rename = "livekit_service_url")]
pub service_url: String,
}
impl LivekitFocus {
/// Initialize a [`LivekitFocus`].
///
/// # Arguments
///
/// * `alias` - The alias with which the LiveKit sessions can be reached.
/// * `service_url` - The url of the JWT server for the LiveKit instance.
pub fn new(alias: String, service_url: String) -> Self {
Self { alias, service_url }
}
}
/// Data to define the actively used Focus.
///
/// A focus can be any server powering the MatrixRTC session (SFU,
/// MCU). It serves as a node to redistribute RTC streams.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ActiveFocus {
/// LiveKit is one possible type of SFU/Focus that can be used for a MatrixRTC session.
Livekit(ActiveLivekitFocus),
}
/// The fields to describe the `active_foci`.
#[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct ActiveLivekitFocus {
/// The selection method used to select the LiveKit focus for the rtc session.
pub focus_selection: FocusSelection,
}
impl ActiveLivekitFocus {
/// Initialize a [`ActiveLivekitFocus`].
///
/// # Arguments
///
/// * `focus_selection` - The selection method used to select the LiveKit focus for the rtc
/// session.
pub fn new() -> Self {
Default::default()
}
}
/// How to select the active focus for LiveKit
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, Default, StringEnum)]
#[palpo_enum(rename_all = "snake_case")]
pub enum FocusSelection {
/// Select the active focus by using the oldest membership and the oldest focus.
#[default]
OldestMembership,
#[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/call/member/member_state_key.rs | crates/core/src/events/call/member/member_state_key.rs | use std::str::FromStr;
use salvo::oapi::ToSchema;
use serde::{
Serialize, Serializer,
de::{self, Deserialize, Deserializer, Unexpected},
};
use crate::{OwnedUserId, UserId};
/// A type that can be used as the `state_key` for call member state events.
/// Those state keys can be a combination of UserId and DeviceId.
#[derive(ToSchema, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[allow(clippy::exhaustive_structs)]
pub struct CallMemberStateKey {
key: CallMemberStateKeyEnum,
raw: Box<str>,
}
impl CallMemberStateKey {
/// Constructs a new CallMemberStateKey there are three possible formats:
/// - `_{UserId}_{MemberId}` example: `_@test:user.org_DEVICE_m.call`. `member_id:
/// Some(DEVICE_m.call)`, `underscore: true`
/// - `{UserId}_{MemberId}` example: `@test:user.org_DEVICE_m.call`. `member_id:
/// Some(DEVICE_m.call)`, `underscore: false`
/// - `{UserId}` example: `@test:user.org`. `member_id: None`, underscore is ignored:
/// `underscore: false|true`
///
/// The MemberId is a combination of the UserId and the session information
/// (session.application and session.id).
/// The session information is an opaque string that should not be parsed after creation.
pub fn new(user_id: OwnedUserId, member_id: Option<String>, underscore: bool) -> Self {
CallMemberStateKeyEnum::new(user_id, member_id, underscore).into()
}
/// Returns the user id in this state key.
/// (This is a cheap operations. The id is already type checked on initialization. And does
/// only returns a reference to an existing OwnedUserId.)
///
/// It is recommended to not use the state key to get the user id, but rather use the `sender`
/// field.
pub fn user_id(&self) -> &UserId {
match &self.key {
CallMemberStateKeyEnum::UnderscoreMemberId(u, _) => u,
CallMemberStateKeyEnum::MemberId(u, _) => u,
CallMemberStateKeyEnum::User(u) => u,
}
}
}
impl AsRef<str> for CallMemberStateKey {
fn as_ref(&self) -> &str {
&self.raw
}
}
impl From<CallMemberStateKeyEnum> for CallMemberStateKey {
fn from(value: CallMemberStateKeyEnum) -> Self {
let raw = value.to_string().into();
Self { key: value, raw }
}
}
impl FromStr for CallMemberStateKey {
type Err = KeyParseError;
fn from_str(state_key: &str) -> Result<Self, Self::Err> {
// Intentionally do not use CallMemberStateKeyEnum.into since this would reconstruct the
// state key string.
Ok(Self {
key: CallMemberStateKeyEnum::from_str(state_key)?,
raw: state_key.into(),
})
}
}
impl<'de> Deserialize<'de> for CallMemberStateKey {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = crate::serde::deserialize_cow_str(deserializer)?;
Self::from_str(&s).map_err(|err| de::Error::invalid_value(Unexpected::Str(&s), &err))
}
}
impl Serialize for CallMemberStateKey {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.as_ref())
}
}
/// This enum represents all possible formats for a call member event state key.
#[derive(ToSchema, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum CallMemberStateKeyEnum {
UnderscoreMemberId(OwnedUserId, String),
MemberId(OwnedUserId, String),
User(OwnedUserId),
}
impl CallMemberStateKeyEnum {
fn new(user_id: OwnedUserId, unique_member_id: Option<String>, underscore: bool) -> Self {
match (unique_member_id, underscore) {
(Some(member_id), true) => {
CallMemberStateKeyEnum::UnderscoreMemberId(user_id, member_id)
}
(Some(member_id), false) => CallMemberStateKeyEnum::MemberId(user_id, member_id),
(None, _) => CallMemberStateKeyEnum::User(user_id),
}
}
}
impl std::fmt::Display for CallMemberStateKeyEnum {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self {
CallMemberStateKeyEnum::UnderscoreMemberId(u, d) => write!(f, "_{u}_{d}"),
CallMemberStateKeyEnum::MemberId(u, d) => write!(f, "{u}_{d}"),
CallMemberStateKeyEnum::User(u) => f.write_str(u.as_str()),
}
}
}
impl FromStr for CallMemberStateKeyEnum {
type Err = KeyParseError;
fn from_str(state_key: &str) -> Result<Self, Self::Err> {
// Ignore leading underscore if present
// (used for avoiding auth rules on @-prefixed state keys)
let (state_key, has_underscore) = match state_key.strip_prefix('_') {
Some(s) => (s, true),
None => (state_key, false),
};
// Fail early if we cannot find the index of the ":"
let Some(colon_idx) = state_key.find(':') else {
return Err(KeyParseError::InvalidUser {
user_id: state_key.to_owned(),
error: crate::IdParseError::MissingColon,
});
};
let (user_id, member_id) = match state_key[colon_idx + 1..].find('_') {
None => {
return match UserId::parse(state_key) {
Ok(user_id) => {
if has_underscore {
Err(KeyParseError::LeadingUnderscoreNoMemberId)
} else {
Ok(CallMemberStateKeyEnum::new(user_id, None, has_underscore))
}
}
Err(err) => Err(KeyParseError::InvalidUser {
error: err,
user_id: state_key.to_owned(),
}),
};
}
Some(suffix_idx) => (
&state_key[..colon_idx + 1 + suffix_idx],
&state_key[colon_idx + 2 + suffix_idx..],
),
};
match UserId::parse(user_id) {
Ok(user_id) => {
if member_id.is_empty() {
return Err(KeyParseError::EmptyMemberId);
}
Ok(CallMemberStateKeyEnum::new(
user_id,
Some(member_id.to_owned()),
has_underscore,
))
}
Err(err) => Err(KeyParseError::InvalidUser {
user_id: user_id.to_owned(),
error: err,
}),
}
}
}
/// Error when trying to parse a call member state key.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum KeyParseError {
/// The user part of the state key is invalid.
#[error("uses a malformatted UserId in the UserId defined section.")]
InvalidUser {
/// The user Id that the parser thinks it should have parsed.
user_id: String,
/// The user Id parse error why if failed to parse it.
error: crate::IdParseError,
},
/// Uses a leading underscore but no trailing device id. The part after the underscore is a
/// valid user id.
#[error(
"uses a leading underscore but no trailing device id. The part after the underscore is a valid user id."
)]
LeadingUnderscoreNoMemberId,
/// Uses an empty memberId. (UserId with trailing underscore)
#[error("uses an empty memberId. (UserId with trailing underscore)")]
EmptyMemberId,
}
impl de::Expected for KeyParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"correct call member event key format. The provided string, {self})"
)
}
}
// #[cfg(test)]
// mod tests {
// use crate::user_id;
// use crate::call::member::{CallMemberStateKey, member_state_key::CallMemberStateKeyEnum};
// #[test]
// fn convert_state_key_enum_to_state_key() {
// let key = "_@user:domain.org_ABC";
// let state_key_enum = CallMemberStateKeyEnum::from_str(key).unwrap();
// // This generates state_key.raw from the enum
// let state_key: CallMemberStateKey = state_key_enum.into();
// // This compares state_key.raw (generated) with key (original)
// assert_eq!(state_key.as_ref(), key);
// // Compare to the from string without `CallMemberStateKeyEnum` step.
// let state_key_direct = CallMemberStateKey::new(
// user_id!("@user:domain.org").to_owned(),
// Some("ABC".to_owned()),
// true,
// );
// assert_eq!(state_key, state_key_direct);
// }
// #[test]
// fn convert_no_underscore_state_key_without_member_id() {
// let key = "@user:domain.org";
// let state_key_enum = CallMemberStateKeyEnum::from_str(key).unwrap();
// // This generates state_key.raw from the enum
// let state_key: CallMemberStateKey = state_key_enum.into();
// // This compares state_key.raw (generated) with key (original)
// assert_eq!(state_key.as_ref(), key);
// // Compare to the from string without `CallMemberStateKeyEnum` step.
// let state_key_direct =
// CallMemberStateKey::new(user_id!("@user:domain.org").to_owned(), None, false);
// assert_eq!(state_key, state_key_direct);
// }
// #[test]
// fn convert_no_underscore_state_key_with_member_id() {
// let key = "@user:domain.org_ABC_m.callTestId";
// let state_key_enum = CallMemberStateKeyEnum::from_str(key).unwrap();
// // This generates state_key.raw from the enum
// let state_key: CallMemberStateKey = state_key_enum.into();
// // This compares state_key.raw (generated) with key (original)
// assert_eq!(state_key.as_ref(), key);
// // Compare to the from string without `CallMemberStateKeyEnum` step.
// let state_key_direct = CallMemberStateKey::new(
// user_id!("@user:domain.org").to_owned(),
// Some("ABC_m.callTestId".to_owned()),
// false,
// );
// assert_eq!(state_key, state_key_direct);
// }
// }
| 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/member/member_data.rs | crates/core/src/events/call/member/member_data.rs | //! Types for MatrixRTC `m.call.member` state event content data ([MSC3401])
//!
//! [MSC3401]: https://github.com/matrix-org/matrix-spec-proposals/pull/3401
use std::time::Duration;
use as_variant::as_variant;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use super::focus::{ActiveFocus, ActiveLivekitFocus, Focus};
use crate::PrivOwnedStr;
use crate::macros::StringEnum;
use crate::{DeviceId, OwnedDeviceId, UnixMillis};
/// The data object that contains the information for one membership.
///
/// It can be a legacy or a normal MatrixRTC Session membership.
///
/// The legacy format contains time information to compute if it is expired or not.
/// SessionMembershipData does not have the concept of timestamp based expiration anymore.
/// The state event will reliably be set to empty when the user disconnects.
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub enum MembershipData<'a> {
/// The legacy format (using an array of memberships for each device -> one event per user)
Legacy(&'a LegacyMembershipData),
/// One event per device. `SessionMembershipData` contains all the information required to
/// represent the current membership state of one device.
Session(&'a SessionMembershipData),
}
impl MembershipData<'_> {
/// The application this RTC membership participates in (the session type, can be `m.call`...)
pub fn application(&self) -> &Application {
match self {
MembershipData::Legacy(data) => &data.application,
MembershipData::Session(data) => &data.application,
}
}
/// The device id of this membership.
pub fn device_id(&self) -> &DeviceId {
match self {
MembershipData::Legacy(data) => &data.device_id,
MembershipData::Session(data) => &data.device_id,
}
}
/// The active focus is a FocusType specific object that describes how this user
/// is currently connected.
///
/// It can use the foci_preferred list to choose one of the available (preferred)
/// foci or specific information on how to connect to this user.
///
/// Every user needs to converge to use the same focus_active type.
pub fn focus_active(&self) -> &ActiveFocus {
match self {
MembershipData::Legacy(_) => &ActiveFocus::Livekit(ActiveLivekitFocus {
focus_selection: super::focus::FocusSelection::OldestMembership,
}),
MembershipData::Session(data) => &data.focus_active,
}
}
/// The list of available/preferred options this user provides to connect to the call.
pub fn foci_preferred(&self) -> &Vec<Focus> {
match self {
MembershipData::Legacy(data) => &data.foci_active,
MembershipData::Session(data) => &data.foci_preferred,
}
}
/// The application of the membership is "m.call" and the scope is "m.room".
pub fn is_room_call(&self) -> bool {
as_variant!(self.application(), Application::Call)
.is_some_and(|call| call.scope == CallScope::Room)
}
/// The application of the membership is "m.call".
pub fn is_call(&self) -> bool {
as_variant!(self.application(), Application::Call).is_some()
}
/// Gets the created_ts of the event.
///
/// This is the `origin_server_ts` for session data.
/// For legacy events this can either be the origin server ts or a copy from the
/// `origin_server_ts` since we expect legacy events to get updated (when a new device
/// joins/leaves).
pub fn created_ts(&self) -> Option<UnixMillis> {
match self {
MembershipData::Legacy(data) => data.created_ts,
MembershipData::Session(data) => data.created_ts,
}
}
/// Checks if the event is expired.
///
/// Defaults to using `created_ts` of the [`MembershipData`].
/// If no `origin_server_ts` is provided and the event does not contain `created_ts`
/// the event will be considered as not expired.
/// In this case, a warning will be logged.
///
/// This method needs to be called periodically to check if the event is still valid.
///
/// # Arguments
///
/// * `origin_server_ts` - a fallback if [`MembershipData::created_ts`] is not present
pub fn is_expired(&self, origin_server_ts: Option<UnixMillis>) -> bool {
if let Some(expire_ts) = self.expires_ts(origin_server_ts) {
UnixMillis::now() > expire_ts
} else {
// This should not be reached since we only allow events that have copied over
// the origin server ts. `set_created_ts_if_none`
warn!(
"Encountered a Call Member state event where the expire_ts could not be constructed."
);
false
}
}
/// The unix timestamp at which the event will expire.
/// This allows to determine at what time the return value of
/// [`MembershipData::is_expired`] will change.
///
/// Defaults to using `created_ts` of the [`MembershipData`].
/// If no `origin_server_ts` is provided and the event does not contain `created_ts`
/// the event will be considered as not expired.
/// In this case, a warning will be logged.
///
/// # Arguments
///
/// * `origin_server_ts` - a fallback if [`MembershipData::created_ts`] is not present
pub fn expires_ts(&self, origin_server_ts: Option<UnixMillis>) -> Option<UnixMillis> {
let expires = match &self {
MembershipData::Legacy(data) => data.expires,
MembershipData::Session(data) => data.expires,
};
let ev_created_ts = self.created_ts().or(origin_server_ts)?.to_system_time();
ev_created_ts.and_then(|t| UnixMillis::from_system_time(t + expires))
}
}
/// A membership describes one of the sessions this user currently partakes.
///
/// The application defines the type of the session.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct LegacyMembershipData {
/// The type of the MatrixRTC session the membership belongs to.
///
/// e.g. call, spacial, document...
#[serde(flatten)]
pub application: Application,
/// The device id of this membership.
///
/// The same user can join with their phone/computer.
pub device_id: OwnedDeviceId,
/// The duration in milliseconds relative to the time this membership joined
/// during which the membership is valid.
///
/// The time a member has joined is defined as:
/// `MIN(content.created_ts, event.origin_server_ts)`
#[serde(with = "crate::serde::duration::ms")]
pub expires: Duration,
/// Stores a copy of the `origin_server_ts` of the initial session event.
///
/// If the membership is updated this field will be used to track the
/// original `origin_server_ts`.
#[serde(skip_serializing_if = "Option::is_none")]
pub created_ts: Option<UnixMillis>,
/// A list of the foci in use for this membership.
pub foci_active: Vec<Focus>,
/// The id of the membership.
///
/// This is required to guarantee uniqueness of the event.
/// Sending the same state event twice to synapse makes the HS drop the second one and return
/// 200.
#[serde(rename = "membershipID")]
pub membership_id: String,
}
/// Stores all the information for a MatrixRTC membership. (one for each device)
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct SessionMembershipData {
/// The type of the MatrixRTC session the membership belongs to.
///
/// e.g. call, spacial, document...
#[serde(flatten)]
pub application: Application,
/// The device id of this membership.
///
/// The same user can join with their phone/computer.
pub device_id: OwnedDeviceId,
/// A list of the foci that this membership proposes to use.
pub foci_preferred: Vec<Focus>,
/// Data required to determine the currently used focus by this member.
pub focus_active: ActiveFocus,
/// Stores a copy of the `origin_server_ts` of the initial session event.
///
/// If the membership is updated this field will be used to track the
/// original `origin_server_ts`.
#[serde(skip_serializing_if = "Option::is_none")]
pub created_ts: Option<UnixMillis>,
/// The duration in milliseconds relative to the time this membership joined
/// during which the membership is valid.
///
/// The time a member has joined is defined as:
/// `MIN(content.created_ts, event.origin_server_ts)`
#[serde(with = "crate::serde::duration::ms")]
pub expires: Duration,
}
/// The type of the matrixRTC session.
///
/// This is not the application/client used by the user but the
/// type of matrixRTC session e.g. calling (`m.call`), third-room, whiteboard
/// could be possible applications.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(tag = "application")]
pub enum Application {
/// The rtc application (session type) for VoIP call.
#[serde(rename = "m.call")]
Call(CallApplicationContent),
}
/// Call specific parameters membership parameters.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct CallApplicationContent {
/// An identifier for calls.
///
/// All members using the same `call_id` will end up in the same call.
///
/// Does not need to be a uuid.
///
/// `""` is used for room scoped calls.
pub call_id: String,
/// Who owns/joins/controls (can modify) the call.
pub scope: CallScope,
}
impl CallApplicationContent {
/// Initialize a [`CallApplicationContent`].
///
/// # Arguments
///
/// * `call_id` - An identifier for calls. All members using the same
/// `call_id` will end up in the same call. Does not need to be a uuid.
/// `""` is used for room scoped calls.
/// * `scope` - Who owns/joins/controls (can modify) the call.
pub fn new(call_id: String, scope: CallScope) -> Self {
Self { call_id, scope }
}
}
/// The call scope defines different call ownership models.
#[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"))]
pub enum CallScope {
/// A call which every user of a room can join and create.
///
/// There is no particular name associated with it.
///
/// There can only be one per room.
Room,
/// A user call is owned by a user.
///
/// Each user can create one there can be multiple per room. They are
/// started and ended by the owning user.
User,
#[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/secret/send.rs | crates/core/src/events/secret/send.rs | //! Types for the [`m.secret.send`] event.
//!
//! [`m.secret.send`]: https://spec.matrix.org/latest/client-server-api/#msecretsend
use std::fmt;
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::OwnedTransactionId;
/// The content of an `m.secret.send` event.
///
/// An event sent by a client to share a secret with another device, in response
/// to an `m.secret.request` event.
///
/// It must be encrypted as an `m.room.encrypted` event, then sent as a
/// to-device event.
#[derive(ToSchema, Clone, Deserialize, Serialize, EventContent)]
#[palpo_event(type = "m.secret.send", kind = ToDevice)]
pub struct ToDeviceSecretSendEventContent {
/// The ID of the request that this is a response to.
pub request_id: OwnedTransactionId,
/// The contents of the secret.
pub secret: String,
}
impl ToDeviceSecretSendEventContent {
/// Creates a new `SecretSendEventContent` with the given request ID and
/// secret.
pub fn new(request_id: OwnedTransactionId, secret: String) -> Self {
Self { request_id, secret }
}
}
impl fmt::Debug for ToDeviceSecretSendEventContent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ToDeviceSecretSendEventContent")
.field("request_id", &self.request_id)
.finish_non_exhaustive()
}
}
| 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/request.rs | crates/core/src/events/secret/request.rs | //! Types for the [`m.secret.request`] event.
//!
//! [`m.secret.request`]: https://spec.matrix.org/latest/client-server-api/#msecretrequest
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize, ser::SerializeStruct};
use crate::{
OwnedDeviceId, OwnedTransactionId, PrivOwnedStr, events::GlobalAccountDataEventType,
serde::StringEnum,
};
/// The content of an `m.secret.request` event.
///
/// Event sent by a client to request a secret from another device or to cancel
/// a previous request.
///
/// It is sent as an unencrypted to-device event.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize, EventContent)]
#[palpo_event(type = "m.secret.request", kind = ToDevice)]
pub struct ToDeviceSecretRequestEventContent {
/// The action for the request.
#[serde(flatten)]
pub action: RequestAction,
/// The ID of the device requesting the event.
pub requesting_device_id: OwnedDeviceId,
/// A random string uniquely identifying (with respect to the requester and
/// the target) the target for a secret.
///
/// If the secret is requested from multiple devices at the same time, the
/// same ID may be used for every target. The same ID is also used in
/// order to cancel a previous request.
pub request_id: OwnedTransactionId,
}
impl ToDeviceSecretRequestEventContent {
/// Creates a new `ToDeviceRequestEventContent` with the given action,
/// requesting device ID and request ID.
pub fn new(
action: RequestAction,
requesting_device_id: OwnedDeviceId,
request_id: OwnedTransactionId,
) -> Self {
Self {
action,
requesting_device_id,
request_id,
}
}
}
/// Action for an `m.secret.request` event.
#[derive(ToSchema, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Deserialize)]
#[serde(try_from = "RequestActionJsonRepr")]
pub enum RequestAction {
/// Request a secret by its name.
Request(SecretName),
/// Cancel a request for a secret.
RequestCancellation,
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(PrivOwnedStr),
}
impl Serialize for RequestAction {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut st = serializer.serialize_struct("request_action", 2)?;
match self {
Self::Request(name) => {
st.serialize_field("name", name)?;
st.serialize_field("action", "request")?;
st.end()
}
Self::RequestCancellation => {
st.serialize_field("action", "request_cancellation")?;
st.end()
}
RequestAction::_Custom(custom) => {
st.serialize_field("action", &custom.0)?;
st.end()
}
}
}
}
#[derive(Deserialize)]
struct RequestActionJsonRepr {
action: String,
name: Option<SecretName>,
}
impl TryFrom<RequestActionJsonRepr> for RequestAction {
type Error = &'static str;
fn try_from(value: RequestActionJsonRepr) -> Result<Self, Self::Error> {
match value.action.as_str() {
"request" => {
if let Some(name) = value.name {
Ok(RequestAction::Request(name))
} else {
Err("A secret name is required when the action is \"request\".")
}
}
"request_cancellation" => Ok(RequestAction::RequestCancellation),
_ => Ok(RequestAction::_Custom(PrivOwnedStr(value.action.into()))),
}
}
}
/// The name of a secret.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
pub enum SecretName {
/// Cross-signing master key (m.cross_signing.master).
#[palpo_enum(rename = "m.cross_signing.master")]
CrossSigningMasterKey,
/// Cross-signing user-signing key (m.cross_signing.user_signing).
#[palpo_enum(rename = "m.cross_signing.user_signing")]
CrossSigningUserSigningKey,
/// Cross-signing self-signing key (m.cross_signing.self_signing).
#[palpo_enum(rename = "m.cross_signing.self_signing")]
CrossSigningSelfSigningKey,
/// Recovery key (m.megolm_backup.v1).
#[palpo_enum(rename = "m.megolm_backup.v1")]
RecoveryKey,
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(PrivOwnedStr),
}
impl From<SecretName> for GlobalAccountDataEventType {
fn from(value: SecretName) -> Self {
GlobalAccountDataEventType::from(value.as_str())
}
}
// #[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::{RequestAction, SecretName,
// ToDeviceSecretRequestEventContent}; use crate::PrivOwnedStr;
// #[test]
// fn secret_request_serialization() {
// let content = ToDeviceSecretRequestEventContent::new(
// RequestAction::Request("org.example.some.secret".into()),
// "ABCDEFG".into(),
// "randomly_generated_id_9573".into(),
// );
// let json = json!({
// "name": "org.example.some.secret",
// "action": "request",
// "requesting_device_id": "ABCDEFG",
// "request_id": "randomly_generated_id_9573"
// });
// assert_eq!(to_json_value(&content).unwrap(), json);
// }
// #[test]
// fn secret_request_recovery_key_serialization() {
// let content = ToDeviceSecretRequestEventContent::new(
// RequestAction::Request(SecretName::RecoveryKey),
// "XYZxyz".into(),
// "this_is_a_request_id".into(),
// );
// let json = json!({
// "name": "m.megolm_backup.v1",
// "action": "request",
// "requesting_device_id": "XYZxyz",
// "request_id": "this_is_a_request_id"
// });
// assert_eq!(to_json_value(&content).unwrap(), json);
// }
// #[test]
// fn secret_custom_action_serialization() {
// let content = ToDeviceSecretRequestEventContent::new(
// RequestAction::_Custom(PrivOwnedStr("my_custom_action".into())),
// "XYZxyz".into(),
// "this_is_a_request_id".into(),
// );
// let json = json!({
// "action": "my_custom_action",
// "requesting_device_id": "XYZxyz",
// "request_id": "this_is_a_request_id"
// });
// assert_eq!(to_json_value(&content).unwrap(), json);
// }
// #[test]
// fn secret_request_cancellation_serialization() {
// let content = ToDeviceSecretRequestEventContent::new(
// RequestAction::RequestCancellation,
// "ABCDEFG".into(),
// "randomly_generated_id_9573".into(),
// );
// let json = json!({
// "action": "request_cancellation",
// "requesting_device_id": "ABCDEFG",
// "request_id": "randomly_generated_id_9573"
// });
// assert_eq!(to_json_value(&content).unwrap(), json);
// }
// #[test]
// fn secret_request_deserialization() {
// let json = json!({
// "name": "org.example.some.secret",
// "action": "request",
// "requesting_device_id": "ABCDEFG",
// "request_id": "randomly_generated_id_9573"
// });
// let content =
// from_json_value::<ToDeviceSecretRequestEventContent>(json).unwrap();
// assert_eq!(content.requesting_device_id, "ABCDEFG");
// assert_eq!(content.request_id, "randomly_generated_id_9573");
// assert_matches!(content.action, RequestAction::Request(secret));
// assert_eq!(secret.as_str(), "org.example.some.secret");
// }
// #[test]
// fn secret_request_cancellation_deserialization() {
// let json = json!({
// "action": "request_cancellation",
// "requesting_device_id": "ABCDEFG",
// "request_id": "randomly_generated_id_9573"
// });
// let content =
// from_json_value::<ToDeviceSecretRequestEventContent>(json).unwrap();
// assert_eq!(content.requesting_device_id, "ABCDEFG");
// assert_eq!(content.request_id, "randomly_generated_id_9573");
// assert_matches!(content.action, RequestAction::RequestCancellation);
// }
// #[test]
// fn secret_request_recovery_key_deserialization() {
// let json = json!({
// "name": "m.megolm_backup.v1",
// "action": "request",
// "requesting_device_id": "XYZxyz",
// "request_id": "this_is_a_request_id"
// });
// let content =
// from_json_value::<ToDeviceSecretRequestEventContent>(json).unwrap();
// assert_eq!(content.requesting_device_id, "XYZxyz");
// assert_eq!(content.request_id, "this_is_a_request_id");
// assert_matches!(content.action, RequestAction::Request(secret));
// assert_eq!(secret, SecretName::RecoveryKey);
// }
// #[test]
// fn secret_custom_action_deserialization() {
// let json = json!({
// "action": "my_custom_action",
// "requesting_device_id": "XYZxyz",
// "request_id": "this_is_a_request_id"
// });
// let content =
// from_json_value::<ToDeviceSecretRequestEventContent>(json).unwrap();
// assert_eq!(content.requesting_device_id, "XYZxyz");
// assert_eq!(content.request_id, "this_is_a_request_id");
// assert_eq!(
// content.action,
// RequestAction::_Custom(PrivOwnedStr("my_custom_action".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/room_key/withheld.rs | crates/core/src/events/room_key/withheld.rs | //! Types for the [`m.room_key.withheld`] event.
//!
//! [`m.room_key.withheld`]: https://spec.matrix.org/latest/client-server-api/#mroom_keywithheld
use std::borrow::Cow;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize, de};
use serde_json::value::RawValue as RawJsonValue;
use crate::PrivOwnedStr;
use crate::macros::{EventContent, StringEnum};
use crate::{
EventEncryptionAlgorithm, OwnedRoomId,
serde::{Base64, JsonObject, from_raw_json_value},
};
/// The content of an [`m.room_key.withheld`] event.
///
/// Typically encrypted as an `m.room.encrypted` event, then sent as a to-device event.
///
/// [`m.room_key.withheld`]: https://spec.matrix.org/latest/client-server-api/#mroom_keywithheld
#[derive(ToSchema, Clone, Debug, Serialize, EventContent)]
#[palpo_event(type = "m.room_key.withheld", kind = ToDevice)]
pub struct ToDeviceRoomKeyWithheldEventContent {
/// The encryption algorithm the key in this event is to be used with.
///
/// Must be `m.megolm.v1.aes-sha2`.
pub algorithm: EventEncryptionAlgorithm,
/// A machine-readable code for why the megolm key was not sent.
#[serde(flatten)]
pub code: RoomKeyWithheldCodeInfo,
/// A human-readable reason for why the key was not sent.
///
/// The receiving client should only use this string if it does not understand the code.
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
/// The unpadded base64-encoded device curve25519 key of the event's sender.
pub sender_key: Base64,
}
impl ToDeviceRoomKeyWithheldEventContent {
/// Creates a new `ToDeviceRoomKeyWithheldEventContent` with the given algorithm, code and
/// sender key.
pub fn new(
algorithm: EventEncryptionAlgorithm,
code: RoomKeyWithheldCodeInfo,
sender_key: Base64,
) -> Self {
Self {
algorithm,
code,
reason: None,
sender_key,
}
}
}
impl<'de> Deserialize<'de> for ToDeviceRoomKeyWithheldEventContent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
#[derive(Deserialize)]
struct ToDeviceRoomKeyWithheldEventContentDeHelper {
algorithm: EventEncryptionAlgorithm,
reason: Option<String>,
sender_key: Base64,
}
let json = Box::<RawJsonValue>::deserialize(deserializer)?;
let ToDeviceRoomKeyWithheldEventContentDeHelper {
algorithm,
reason,
sender_key,
} = from_raw_json_value(&json)?;
let code = from_raw_json_value(&json)?;
Ok(Self {
algorithm,
code,
reason,
sender_key,
})
}
}
/// The possible codes for why a megolm key was not sent, and the associated session data.
#[derive(ToSchema, Debug, Clone, Serialize)]
#[serde(tag = "code")]
pub enum RoomKeyWithheldCodeInfo {
/// `m.blacklisted`
///
/// The user or device was blacklisted.
#[serde(rename = "m.blacklisted")]
Blacklisted(Box<RoomKeyWithheldSessionData>),
/// `m.unverified`
///
/// The user or device was not verified, and the sender is only sharing keys with verified
/// users or devices.
#[serde(rename = "m.unverified")]
Unverified(Box<RoomKeyWithheldSessionData>),
/// `m.unauthorised`
///
/// The user or device is not allowed to have the key. For example, this could be sent in
/// response to a key request if the user or device was not in the room when the original
/// message was sent.
#[serde(rename = "m.unauthorised")]
Unauthorized(Box<RoomKeyWithheldSessionData>),
/// `m.unavailable`
///
/// Sent in reply to a key request if the device that the key is requested from does not have
/// the requested key.
#[serde(rename = "m.unavailable")]
Unavailable(Box<RoomKeyWithheldSessionData>),
/// `m.no_olm`
///
/// An olm session could not be established.
#[serde(rename = "m.no_olm")]
NoOlm,
#[doc(hidden)]
#[serde(untagged)]
_Custom(Box<CustomRoomKeyWithheldCodeInfo>),
}
impl RoomKeyWithheldCodeInfo {
/// Get the code of this `RoomKeyWithheldCodeInfo`.
pub fn code(&self) -> RoomKeyWithheldCode {
match self {
Self::Blacklisted(_) => RoomKeyWithheldCode::Blacklisted,
Self::Unverified(_) => RoomKeyWithheldCode::Unverified,
Self::Unauthorized(_) => RoomKeyWithheldCode::Unauthorized,
Self::Unavailable(_) => RoomKeyWithheldCode::Unavailable,
Self::NoOlm => RoomKeyWithheldCode::NoOlm,
Self::_Custom(info) => info.code.as_str().into(),
}
}
}
impl<'de> Deserialize<'de> for RoomKeyWithheldCodeInfo {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
#[derive(Debug, Deserialize)]
struct ExtractCode<'a> {
#[serde(borrow)]
code: Cow<'a, str>,
}
let json = Box::<RawJsonValue>::deserialize(deserializer)?;
let ExtractCode { code } = from_raw_json_value(&json)?;
Ok(match code.as_ref() {
"m.blacklisted" => Self::Blacklisted(from_raw_json_value(&json)?),
"m.unverified" => Self::Unverified(from_raw_json_value(&json)?),
"m.unauthorised" => Self::Unauthorized(from_raw_json_value(&json)?),
"m.unavailable" => Self::Unavailable(from_raw_json_value(&json)?),
"m.no_olm" => Self::NoOlm,
_ => Self::_Custom(from_raw_json_value(&json)?),
})
}
}
/// The session data associated to a withheld room key.
#[derive(ToSchema, Debug, Clone, Serialize, Deserialize)]
pub struct RoomKeyWithheldSessionData {
/// The room for the key.
pub room_id: OwnedRoomId,
/// The session ID of the key.
pub session_id: String,
}
impl RoomKeyWithheldSessionData {
/// Construct a new `RoomKeyWithheldSessionData` with the given room ID and session ID.
pub fn new(room_id: OwnedRoomId, session_id: String) -> Self {
Self {
room_id,
session_id,
}
}
}
/// The payload for a custom room key withheld code.
#[doc(hidden)]
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize)]
pub struct CustomRoomKeyWithheldCodeInfo {
/// A custom code.
code: String,
/// Remaining event content.
#[serde(flatten)]
data: JsonObject,
}
/// The possible codes for why a megolm key was not sent.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(Clone, StringEnum)]
#[palpo_enum(rename_all(prefix = "m.", rule = "snake_case"))]
#[non_exhaustive]
pub enum RoomKeyWithheldCode {
/// `m.blacklisted`
///
/// The user or device was blacklisted.
Blacklisted,
/// `m.unverified`
///
/// The user or device was not verified, and the sender is only sharing keys with verified
/// users or devices.
Unverified,
/// `m.unauthorised`
///
/// The user or device is not allowed to have the key. For example, this could be sent in
/// response to a key request if the user or device was not in the room when the original
/// message was sent.
Unauthorized,
/// `m.unavailable`
///
/// Sent in reply to a key request if the device that the key is requested from does not have
/// the requested key.
Unavailable,
/// `m.no_olm`
///
/// An olm session could not be established.
NoOlm,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
#[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::{
RoomKeyWithheldCodeInfo, RoomKeyWithheldSessionData, ToDeviceRoomKeyWithheldEventContent,
};
use crate::{EventEncryptionAlgorithm, owned_room_id, serde::Base64};
const PUBLIC_KEY: &[u8] = b"key";
const BASE64_ENCODED_PUBLIC_KEY: &str = "a2V5";
#[test]
fn serialization_no_olm() {
let content = ToDeviceRoomKeyWithheldEventContent::new(
EventEncryptionAlgorithm::MegolmV1AesSha2,
RoomKeyWithheldCodeInfo::NoOlm,
Base64::new(PUBLIC_KEY.to_owned()),
);
assert_eq!(
to_json_value(content).unwrap(),
json!({
"algorithm": "m.megolm.v1.aes-sha2",
"code": "m.no_olm",
"sender_key": BASE64_ENCODED_PUBLIC_KEY,
})
);
}
#[test]
fn serialization_blacklisted() {
let room_id = owned_room_id!("!roomid:localhost");
let content = ToDeviceRoomKeyWithheldEventContent::new(
EventEncryptionAlgorithm::MegolmV1AesSha2,
RoomKeyWithheldCodeInfo::Blacklisted(
RoomKeyWithheldSessionData::new(room_id.clone(), "unique_id".to_owned()).into(),
),
Base64::new(PUBLIC_KEY.to_owned()),
);
assert_eq!(
to_json_value(content).unwrap(),
json!({
"algorithm": "m.megolm.v1.aes-sha2",
"code": "m.blacklisted",
"sender_key": BASE64_ENCODED_PUBLIC_KEY,
"room_id": room_id,
"session_id": "unique_id",
})
);
}
#[test]
fn deserialization_no_olm() {
let json = json!({
"algorithm": "m.megolm.v1.aes-sha2",
"code": "m.no_olm",
"sender_key": BASE64_ENCODED_PUBLIC_KEY,
"reason": "Could not find an olm session",
});
let content = from_json_value::<ToDeviceRoomKeyWithheldEventContent>(json).unwrap();
assert_eq!(content.algorithm, EventEncryptionAlgorithm::MegolmV1AesSha2);
assert_eq!(content.sender_key, Base64::new(PUBLIC_KEY.to_owned()));
assert_eq!(
content.reason.as_deref(),
Some("Could not find an olm session")
);
assert_matches!(content.code, RoomKeyWithheldCodeInfo::NoOlm);
}
#[test]
fn deserialization_blacklisted() {
let room_id = owned_room_id!("!roomid:localhost");
let json = json!({
"algorithm": "m.megolm.v1.aes-sha2",
"code": "m.blacklisted",
"sender_key": BASE64_ENCODED_PUBLIC_KEY,
"room_id": room_id,
"session_id": "unique_id",
});
let content = from_json_value::<ToDeviceRoomKeyWithheldEventContent>(json).unwrap();
assert_eq!(content.algorithm, EventEncryptionAlgorithm::MegolmV1AesSha2);
assert_eq!(content.sender_key, Base64::new(PUBLIC_KEY.to_owned()));
assert_eq!(content.reason, None);
assert_matches!(
content.code,
RoomKeyWithheldCodeInfo::Blacklisted(session_data)
);
assert_eq!(session_data.room_id, room_id);
assert_eq!(session_data.session_id, "unique_id");
}
#[test]
fn custom_room_key_withheld_code_info_round_trip() {
let room_id = owned_room_id!("!roomid:localhost");
let json = json!({
"algorithm": "m.megolm.v1.aes-sha2",
"code": "dev.ruma.custom_code",
"sender_key": BASE64_ENCODED_PUBLIC_KEY,
"room_id": room_id,
"key": "value",
});
let content = from_json_value::<ToDeviceRoomKeyWithheldEventContent>(json.clone()).unwrap();
assert_eq!(content.code.code().as_str(), "dev.ruma.custom_code");
assert_eq!(to_json_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/audio/amplitude_serde.rs | crates/core/src/events/audio/amplitude_serde.rs | //! `Serialize` and `Deserialize` implementations for extensible events
//! (MSC1767).
use serde::Deserialize;
use super::Amplitude;
impl<'de> Deserialize<'de> for Amplitude {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let uint = u64::deserialize(deserializer)?;
Ok(Self(uint.min(Self::MAX.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/poll/unstable_end.rs | crates/core/src/events/poll/unstable_end.rs | //! Types for the `org.matrix.msc3381.poll.end` event, the unstable version of
//! `m.poll.end`.
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{OwnedEventId, events::relation::Reference};
/// The payload for an unstable poll end event.
///
/// This type can be generated from the unstable poll start and poll response
/// events with [`OriginalSyncUnstablePollStartEvent::compile_results()`].
///
/// This is the event content that should be sent for room versions that don't
/// support extensible events. As of Matrix 1.7, none of the stable room
/// versions (1 through 10) support extensible events.
///
/// To send a poll end event for a room version that supports extensible events,
/// use [`PollEndEventContent`].
///
/// [`OriginalSyncUnstablePollStartEvent::compile_results()`]: super::unstable_start::OriginalSyncUnstablePollStartEvent::compile_results
/// [`PollEndEventContent`]: super::end::PollEndEventContent
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize, EventContent)]
#[palpo_event(type = "org.matrix.msc3381.poll.end", kind = MessageLike)]
pub struct UnstablePollEndEventContent {
/// The text representation of the results.
#[serde(rename = "org.matrix.msc1767.text")]
pub text: String,
/// The poll end content.
#[serde(default, rename = "org.matrix.msc3381.poll.end")]
pub poll_end: UnstablePollEndContentBlock,
/// Information about the poll start event this responds to.
#[serde(rename = "m.relates_to")]
pub relates_to: Reference,
}
impl UnstablePollEndEventContent {
/// Creates a new `PollEndEventContent` with the given fallback
/// representation and that responds to the given poll start event ID.
pub fn new(text: impl Into<String>, poll_start_id: OwnedEventId) -> Self {
Self {
text: text.into(),
poll_end: UnstablePollEndContentBlock {},
relates_to: Reference::new(poll_start_id),
}
}
}
/// A block for the results of a poll.
///
/// This is currently an empty struct.
#[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)]
pub struct UnstablePollEndContentBlock {}
| 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/response.rs | crates/core/src/events/poll/response.rs | //! Types for the `m.poll.response` event.
use std::{ops::Deref, vec};
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use super::{PollResponseData, start::PollContentBlock, validate_selections};
use crate::{OwnedEventId, events::relation::Reference};
/// The payload for a poll response event.
///
/// This is the event content that should be sent for room versions that support
/// extensible events. As of Matrix 1.7, none of the stable room versions (1
/// through 10) support extensible events.
///
/// To send a poll response event for a room version that does not support
/// extensible events, use [`UnstablePollResponseEventContent`].
///
/// [`UnstablePollResponseEventContent`]: super::unstable_response::UnstablePollResponseEventContent
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize, EventContent)]
#[palpo_event(type = "m.poll.response", kind = MessageLike)]
pub struct PollResponseEventContent {
/// The user's selection.
#[serde(rename = "m.selections")]
pub selections: SelectionsContentBlock,
/// Whether this message is automated.
#[cfg(feature = "unstable-msc3955")]
#[serde(
default,
skip_serializing_if = "crate::serde::is_default",
rename = "org.matrix.msc1767.automated"
)]
pub automated: bool,
/// Information about the poll start event this responds to.
#[serde(rename = "m.relates_to")]
pub relates_to: Reference,
}
impl PollResponseEventContent {
/// Creates a new `PollResponseEventContent` that responds to the given poll
/// start event ID, with the given poll response content.
pub fn new(selections: SelectionsContentBlock, poll_start_id: OwnedEventId) -> Self {
Self {
selections,
#[cfg(feature = "unstable-msc3955")]
automated: false,
relates_to: Reference::new(poll_start_id),
}
}
}
impl OriginalSyncPollResponseEvent {
/// Get the data from this response necessary to compile poll results.
pub fn data(&self) -> PollResponseData<'_> {
PollResponseData {
sender: &self.sender,
origin_server_ts: self.origin_server_ts,
selections: &self.content.selections,
}
}
}
impl OriginalPollResponseEvent {
/// Get the data from this response necessary to compile poll results.
pub fn data(&self) -> PollResponseData<'_> {
PollResponseData {
sender: &self.sender,
origin_server_ts: self.origin_server_ts,
selections: &self.content.selections,
}
}
}
/// A block for selections content.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct SelectionsContentBlock(Vec<String>);
impl SelectionsContentBlock {
/// Whether this `SelectionsContentBlock` is empty.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Validate these selections against the given `PollContentBlock`.
///
/// Returns the list of valid selections in this `SelectionsContentBlock`,
/// or `None` if there is no valid selection.
pub fn validate<'a>(
&'a self,
poll: &PollContentBlock,
) -> Option<impl Iterator<Item = &'a str> + use<'a>> {
let answer_ids = poll.answers.iter().map(|a| a.id.as_str()).collect();
validate_selections(&answer_ids, poll.max_selections, &self.0)
}
}
impl From<Vec<String>> for SelectionsContentBlock {
fn from(value: Vec<String>) -> Self {
Self(value)
}
}
impl IntoIterator for SelectionsContentBlock {
type Item = String;
type IntoIter = vec::IntoIter<String>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl FromIterator<String> for SelectionsContentBlock {
fn from_iter<T: IntoIterator<Item = String>>(iter: T) -> Self {
Self(Vec::from_iter(iter))
}
}
impl Deref for SelectionsContentBlock {
type Target = [String];
fn deref(&self) -> &Self::Target {
&self.0
}
}
| 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/unstable_response.rs | crates/core/src/events/poll/unstable_response.rs | //! Types for the `org.matrix.msc3381.poll.response` event, the unstable version
//! of `m.poll.response`.
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use super::{PollResponseData, unstable_start::UnstablePollStartContentBlock, validate_selections};
use crate::{OwnedEventId, events::relation::Reference};
/// The payload for an unstable poll response event.
///
/// This is the event content that should be sent for room versions that don't
/// support extensible events. As of Matrix 1.7, none of the stable room
/// versions (1 through 10) support extensible events.
///
/// To send a poll response event for a room version that supports extensible
/// events, use [`PollResponseEventContent`].
///
/// [`PollResponseEventContent`]: super::response::PollResponseEventContent
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize, EventContent)]
#[palpo_event(type = "org.matrix.msc3381.poll.response", kind = MessageLike)]
pub struct UnstablePollResponseEventContent {
/// The response's content.
#[serde(rename = "org.matrix.msc3381.poll.response")]
pub poll_response: UnstablePollResponseContentBlock,
/// Information about the poll start event this responds to.
#[serde(rename = "m.relates_to")]
pub relates_to: Reference,
}
impl UnstablePollResponseEventContent {
/// Creates a new `UnstablePollResponseEventContent` that responds to the
/// given poll start event ID, with the given answers.
pub fn new(answers: Vec<String>, poll_start_id: OwnedEventId) -> Self {
Self {
poll_response: UnstablePollResponseContentBlock::new(answers),
relates_to: Reference::new(poll_start_id),
}
}
}
impl OriginalSyncUnstablePollResponseEvent {
/// Get the data from this response necessary to compile poll results.
pub fn data(&self) -> PollResponseData<'_> {
PollResponseData {
sender: &self.sender,
origin_server_ts: self.origin_server_ts,
selections: &self.content.poll_response.answers,
}
}
}
impl OriginalUnstablePollResponseEvent {
/// Get the data from this response necessary to compile poll results.
pub fn data(&self) -> PollResponseData<'_> {
PollResponseData {
sender: &self.sender,
origin_server_ts: self.origin_server_ts,
selections: &self.content.poll_response.answers,
}
}
}
/// An unstable block for poll response content.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct UnstablePollResponseContentBlock {
/// The selected answers for the response.
pub answers: Vec<String>,
}
impl UnstablePollResponseContentBlock {
/// Creates a new `UnstablePollResponseContentBlock` with the given answers.
pub fn new(answers: Vec<String>) -> Self {
Self { answers }
}
/// Validate these selections against the given
/// `UnstablePollStartContentBlock`.
///
/// Returns the list of valid selections in this
/// `UnstablePollResponseContentBlock`, or `None` if there is no valid
/// selection.
pub fn validate<'a>(
&'a self,
poll: &UnstablePollStartContentBlock,
) -> Option<impl Iterator<Item = &'a str> + use<'a>> {
let answer_ids = poll.answers.iter().map(|a| a.id.as_str()).collect();
validate_selections(&answer_ids, poll.max_selections, &self.answers)
}
}
impl From<Vec<String>> for UnstablePollResponseContentBlock {
fn from(value: Vec<String>) -> 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/poll/unstable_start.rs | crates/core/src/events/poll/unstable_start.rs | //! Types for the `org.matrix.msc3381.poll.start` event, the unstable version of
//! `m.poll.start`.
use std::ops::Deref;
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
mod content_serde;
mod unstable_poll_answers_serde;
mod unstable_poll_kind_serde;
use self::unstable_poll_answers_serde::UnstablePollAnswersDeHelper;
use super::{
PollResponseData, compile_unstable_poll_results, generate_poll_end_fallback_text,
start::{PollAnswers, PollAnswersError, PollContentBlock, PollKind},
unstable_end::UnstablePollEndEventContent,
};
use crate::{
OwnedEventId, UnixMillis,
events::{
MessageLikeEventContent, MessageLikeEventType, RedactContent,
RedactedMessageLikeEventContent, StaticEventContent, relation::Replacement,
room::message::RelationWithoutReplacement,
},
room_version_rules::RedactionRules,
};
/// The payload for an unstable poll start event.
///
/// This is the event content that should be sent for room versions that don't
/// support extensible events. As of Matrix 1.7, none of the stable room
/// versions (1 through 10) support extensible events.
///
/// To send a poll start event for a room version that supports extensible
/// events, use [`PollStartEventContent`].
///
/// [`PollStartEventContent`]: super::start::PollStartEventContent
#[derive(ToSchema, Clone, Debug, Serialize, EventContent)]
#[palpo_event(type = "org.matrix.msc3381.poll.start", kind = MessageLike, custom_redacted)]
#[serde(untagged)]
#[allow(clippy::large_enum_variant)]
pub enum UnstablePollStartEventContent {
/// A new poll start event.
New(NewUnstablePollStartEventContent),
/// A replacement poll start event.
Replacement(ReplacementUnstablePollStartEventContent),
}
impl UnstablePollStartEventContent {
/// Get the poll start content of this event content.
pub fn poll_start(&self) -> &UnstablePollStartContentBlock {
match self {
Self::New(c) => &c.poll_start,
Self::Replacement(c) => &c.relates_to.new_content.poll_start,
}
}
}
impl RedactContent for UnstablePollStartEventContent {
type Redacted = RedactedUnstablePollStartEventContent;
fn redact(self, _rules: &RedactionRules) -> Self::Redacted {
RedactedUnstablePollStartEventContent::default()
}
}
impl From<NewUnstablePollStartEventContent> for UnstablePollStartEventContent {
fn from(value: NewUnstablePollStartEventContent) -> Self {
Self::New(value)
}
}
impl From<ReplacementUnstablePollStartEventContent> for UnstablePollStartEventContent {
fn from(value: ReplacementUnstablePollStartEventContent) -> Self {
Self::Replacement(value)
}
}
impl OriginalSyncUnstablePollStartEvent {
/// Compile the results for this poll with the given response into an
/// `UnstablePollEndEventContent`.
///
/// It generates a default text representation of the results in English.
///
/// This uses [`compile_unstable_poll_results()`] internally.
pub fn compile_results<'a>(
&'a self,
responses: impl IntoIterator<Item = PollResponseData<'a>>,
) -> UnstablePollEndEventContent {
let poll_start = self.content.poll_start();
let full_results =
compile_unstable_poll_results(poll_start, responses, Some(UnixMillis::now()));
let results = full_results
.into_iter()
.map(|(id, users)| (id, users.len()))
.collect::<Vec<_>>();
// Get the text representation of the best answers.
let answers = poll_start
.answers
.iter()
.map(|a| (a.id.as_str(), a.text.as_str()))
.collect::<Vec<_>>();
let plain_text = generate_poll_end_fallback_text(&answers, results.into_iter());
UnstablePollEndEventContent::new(plain_text, self.event_id.clone())
}
}
/// A new unstable poll start event.
#[derive(ToSchema, Clone, Debug, Serialize)]
pub struct NewUnstablePollStartEventContent {
/// The poll content of the message.
#[serde(rename = "org.matrix.msc3381.poll.start")]
pub poll_start: UnstablePollStartContentBlock,
/// Text representation of the message, for clients that don't support
/// polls.
#[serde(rename = "org.matrix.msc1767.text")]
pub text: Option<String>,
/// Information about related messages.
#[serde(rename = "m.relates_to", skip_serializing_if = "Option::is_none")]
pub relates_to: Option<RelationWithoutReplacement>,
}
impl NewUnstablePollStartEventContent {
/// Creates a `NewUnstablePollStartEventContent` with the given poll
/// content.
pub fn new(poll_start: UnstablePollStartContentBlock) -> Self {
Self {
poll_start,
text: None,
relates_to: None,
}
}
/// Creates a `NewUnstablePollStartEventContent` with the given plain text
/// fallback representation and poll content.
pub fn plain_text(text: impl Into<String>, poll_start: UnstablePollStartContentBlock) -> Self {
Self {
poll_start,
text: Some(text.into()),
relates_to: None,
}
}
}
impl StaticEventContent for NewUnstablePollStartEventContent {
const TYPE: &'static str = UnstablePollStartEventContent::TYPE;
type IsPrefix = <UnstablePollStartEventContent as StaticEventContent>::IsPrefix;
}
impl MessageLikeEventContent for NewUnstablePollStartEventContent {
fn event_type(&self) -> MessageLikeEventType {
MessageLikeEventType::UnstablePollStart
}
}
/// Form of [`NewUnstablePollStartEventContent`] without relation.
///
/// To construct this type, construct a [`NewUnstablePollStartEventContent`] and
/// then use one of its `::from()` / `.into()` methods.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct NewUnstablePollStartEventContentWithoutRelation {
/// The poll content of the message.
#[serde(rename = "org.matrix.msc3381.poll.start")]
pub poll_start: UnstablePollStartContentBlock,
/// Text representation of the message, for clients that don't support
/// polls.
#[serde(rename = "org.matrix.msc1767.text")]
pub text: Option<String>,
}
impl From<NewUnstablePollStartEventContent> for NewUnstablePollStartEventContentWithoutRelation {
fn from(value: NewUnstablePollStartEventContent) -> Self {
let NewUnstablePollStartEventContent {
poll_start, text, ..
} = value;
Self { poll_start, text }
}
}
/// A replacement unstable poll start event.
#[derive(ToSchema, Clone, Debug)]
pub struct ReplacementUnstablePollStartEventContent {
/// The poll content of the message.
pub poll_start: Option<UnstablePollStartContentBlock>,
/// Text representation of the message, for clients that don't support
/// polls.
pub text: Option<String>,
/// Information about related messages.
pub relates_to: Replacement<NewUnstablePollStartEventContentWithoutRelation>,
}
impl ReplacementUnstablePollStartEventContent {
/// Creates a `ReplacementUnstablePollStartEventContent` with the given poll
/// content that replaces the event with the given ID.
///
/// The constructed content does not have a fallback by default.
pub fn new(poll_start: UnstablePollStartContentBlock, replaces: OwnedEventId) -> Self {
Self {
poll_start: None,
text: None,
relates_to: Replacement {
event_id: replaces,
new_content: NewUnstablePollStartEventContent::new(poll_start).into(),
},
}
}
/// Creates a `ReplacementUnstablePollStartEventContent` with the given
/// plain text fallback representation and poll content that replaces
/// the event with the given ID.
///
/// The constructed content does not have a fallback by default.
pub fn plain_text(
text: impl Into<String>,
poll_start: UnstablePollStartContentBlock,
replaces: OwnedEventId,
) -> Self {
Self {
poll_start: None,
text: None,
relates_to: Replacement {
event_id: replaces,
new_content: NewUnstablePollStartEventContent::plain_text(text, poll_start).into(),
},
}
}
}
impl StaticEventContent for ReplacementUnstablePollStartEventContent {
const TYPE: &'static str = UnstablePollStartEventContent::TYPE;
type IsPrefix = <UnstablePollStartEventContent as StaticEventContent>::IsPrefix;
}
impl MessageLikeEventContent for ReplacementUnstablePollStartEventContent {
fn event_type(&self) -> MessageLikeEventType {
MessageLikeEventType::UnstablePollStart
}
}
/// Redacted form of UnstablePollStartEventContent
#[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)]
pub struct RedactedUnstablePollStartEventContent {}
impl RedactedUnstablePollStartEventContent {
/// Creates an empty RedactedUnstablePollStartEventContent.
pub fn new() -> RedactedUnstablePollStartEventContent {
Self::default()
}
}
impl StaticEventContent for RedactedUnstablePollStartEventContent {
const TYPE: &'static str = UnstablePollStartEventContent::TYPE;
type IsPrefix = <UnstablePollStartEventContent as StaticEventContent>::IsPrefix;
}
impl RedactedMessageLikeEventContent for RedactedUnstablePollStartEventContent {
fn event_type(&self) -> MessageLikeEventType {
MessageLikeEventType::UnstablePollStart
}
}
/// An unstable block for poll start content.
#[derive(ToSchema, Debug, Clone, Serialize, Deserialize)]
pub struct UnstablePollStartContentBlock {
/// The question of the poll.
pub question: UnstablePollQuestion,
/// The kind of the poll.
#[serde(default, with = "unstable_poll_kind_serde")]
pub kind: PollKind,
/// The maximum number of responses a user is able to select.
///
/// Must be greater or equal to `1`.
///
/// Defaults to `1`.
#[serde(default = "PollContentBlock::default_max_selections")]
pub max_selections: u32,
/// The possible answers to the poll.
pub answers: UnstablePollAnswers,
}
impl UnstablePollStartContentBlock {
/// Creates a new `PollStartContent` with the given question and answers.
pub fn new(question: impl Into<String>, answers: UnstablePollAnswers) -> Self {
Self {
question: UnstablePollQuestion::new(question),
kind: Default::default(),
max_selections: PollContentBlock::default_max_selections(),
answers,
}
}
}
/// An unstable poll question.
#[derive(ToSchema, Debug, Clone, Serialize, Deserialize)]
pub struct UnstablePollQuestion {
/// The text representation of the question.
#[serde(rename = "org.matrix.msc1767.text")]
pub text: String,
}
impl UnstablePollQuestion {
/// Creates a new `UnstablePollQuestion` with the given plain text.
pub fn new(text: impl Into<String>) -> Self {
Self { text: text.into() }
}
}
/// The unstable answers to a poll.
///
/// Must include between 1 and 20 `UnstablePollAnswer`s.
///
/// To build this, use one of the `TryFrom` implementations.
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize)]
#[serde(try_from = "UnstablePollAnswersDeHelper")]
pub struct UnstablePollAnswers(Vec<UnstablePollAnswer>);
impl TryFrom<Vec<UnstablePollAnswer>> for UnstablePollAnswers {
type Error = PollAnswersError;
fn try_from(value: Vec<UnstablePollAnswer>) -> Result<Self, Self::Error> {
if value.len() < PollAnswers::MIN_LENGTH {
Err(PollAnswersError::NotEnoughValues)
} else if value.len() > PollAnswers::MAX_LENGTH {
Err(PollAnswersError::TooManyValues)
} else {
Ok(Self(value))
}
}
}
impl TryFrom<&[UnstablePollAnswer]> for UnstablePollAnswers {
type Error = PollAnswersError;
fn try_from(value: &[UnstablePollAnswer]) -> Result<Self, Self::Error> {
Self::try_from(value.to_owned())
}
}
impl Deref for UnstablePollAnswers {
type Target = [UnstablePollAnswer];
fn deref(&self) -> &Self::Target {
&self.0
}
}
/// Unstable poll answer.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct UnstablePollAnswer {
/// The ID of the answer.
///
/// This must be unique among the answers of a poll.
pub id: String,
/// The text representation of the answer.
#[serde(rename = "org.matrix.msc1767.text")]
pub text: String,
}
impl UnstablePollAnswer {
/// Creates a new `PollAnswer` with the given id and text representation.
pub fn new(id: impl Into<String>, text: impl Into<String>) -> Self {
Self {
id: id.into(),
text: text.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/poll/end.rs | crates/core/src/events/poll/end.rs | //! Types for the `m.poll.end` event.
use std::{
collections::{BTreeMap, btree_map},
ops::Deref,
};
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{
OwnedEventId,
events::{message::TextContentBlock, relation::Reference},
};
/// The payload for a poll end event.
///
/// This type can be generated from the poll start and poll response events with
/// [`OriginalSyncPollStartEvent::compile_results()`].
///
/// This is the event content that should be sent for room versions that support
/// extensible events. As of Matrix 1.7, none of the stable room versions (1
/// through 10) support extensible events.
///
/// To send a poll end event for a room version that does not support extensible
/// events, use [`UnstablePollEndEventContent`].
///
/// [`OriginalSyncPollStartEvent::compile_results()`]: super::start::OriginalSyncPollStartEvent::compile_results
/// [`UnstablePollEndEventContent`]: super::unstable_end::UnstablePollEndEventContent
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize, EventContent)]
#[palpo_event(type = "m.poll.end", kind = MessageLike)]
pub struct PollEndEventContent {
/// The text representation of the results.
#[serde(rename = "m.text")]
pub text: TextContentBlock,
/// The sender's perspective of the results.
#[serde(rename = "m.poll.results", skip_serializing_if = "Option::is_none")]
pub poll_results: Option<PollResultsContentBlock>,
/// 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 the poll start event this responds to.
#[serde(rename = "m.relates_to")]
pub relates_to: Reference,
}
impl PollEndEventContent {
/// Creates a new `PollEndEventContent` with the given fallback
/// representation and that responds to the given poll start event ID.
pub fn new(text: TextContentBlock, poll_start_id: OwnedEventId) -> Self {
Self {
text,
poll_results: None,
#[cfg(feature = "unstable-msc3955")]
automated: false,
relates_to: Reference::new(poll_start_id),
}
}
/// Creates a new `PollEndEventContent` with the given plain text fallback
/// representation and that responds to the given poll start event ID.
pub fn with_plain_text(plain_text: impl Into<String>, poll_start_id: OwnedEventId) -> Self {
Self {
text: TextContentBlock::plain(plain_text),
poll_results: None,
#[cfg(feature = "unstable-msc3955")]
automated: false,
relates_to: Reference::new(poll_start_id),
}
}
}
/// A block for the results of a poll.
///
/// This is a map of answer ID to number of votes.
#[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)]
pub struct PollResultsContentBlock(BTreeMap<String, u64>);
impl PollResultsContentBlock {
/// Get these results sorted from the highest number of votes to the lowest.
///
/// Returns a list of `(answer ID, number of votes)`.
pub fn sorted(&self) -> Vec<(&str, u64)> {
let mut sorted = self
.0
.iter()
.map(|(id, count)| (id.as_str(), *count))
.collect::<Vec<_>>();
sorted.sort_by(|(_, a), (_, b)| b.cmp(a));
sorted
}
}
impl From<BTreeMap<String, u64>> for PollResultsContentBlock {
fn from(value: BTreeMap<String, u64>) -> Self {
Self(value)
}
}
impl IntoIterator for PollResultsContentBlock {
type Item = (String, u64);
type IntoIter = btree_map::IntoIter<String, u64>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl FromIterator<(String, u64)> for PollResultsContentBlock {
fn from_iter<T: IntoIterator<Item = (String, u64)>>(iter: T) -> Self {
Self(BTreeMap::from_iter(iter))
}
}
impl Deref for PollResultsContentBlock {
type Target = BTreeMap<String, u64>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
| 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/start.rs | crates/core/src/events/poll/start.rs | //! Types for the `m.poll.start` event.
use std::ops::Deref;
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
mod poll_answers_serde;
use poll_answers_serde::PollAnswersDeHelper;
use super::{
PollResponseData, compile_poll_results,
end::{PollEndEventContent, PollResultsContentBlock},
generate_poll_end_fallback_text,
};
use crate::{
PrivOwnedStr, UnixMillis,
events::{message::TextContentBlock, room::message::Relation},
serde::StringEnum,
};
/// The payload for a poll start event.
///
/// This is the event content that should be sent for room versions that support
/// extensible events. As of Matrix 1.7, none of the stable room versions (1
/// through 10) support extensible events.
///
/// To send a poll start event for a room version that does not support
/// extensible events, use [`UnstablePollStartEventContent`].
///
/// [`UnstablePollStartEventContent`]: super::unstable_start::UnstablePollStartEventContent
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize, EventContent)]
#[palpo_event(type = "m.poll.start", kind = MessageLike, without_relation)]
pub struct PollStartEventContent {
/// The poll content of the message.
#[serde(rename = "m.poll")]
pub poll: PollContentBlock,
/// Text representation of the message, for clients that don't support
/// polls.
#[serde(rename = "m.text")]
pub text: TextContentBlock,
/// 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<PollStartEventContentWithoutRelation>>,
/// 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,
}
impl PollStartEventContent {
/// Creates a new `PollStartEventContent` with the given fallback
/// representation and poll content.
pub fn new(text: TextContentBlock, poll: PollContentBlock) -> Self {
Self {
poll,
text,
relates_to: None,
#[cfg(feature = "unstable-msc3955")]
automated: false,
}
}
/// Creates a new `PollStartEventContent` with the given plain text fallback
/// representation and poll content.
pub fn with_plain_text(plain_text: impl Into<String>, poll: PollContentBlock) -> Self {
Self::new(TextContentBlock::plain(plain_text), poll)
}
}
impl OriginalSyncPollStartEvent {
/// Compile the results for this poll with the given response into a
/// `PollEndEventContent`.
///
/// It generates a default text representation of the results in English.
///
/// This uses [`compile_poll_results()`] internally.
pub fn compile_results<'a>(
&'a self,
responses: impl IntoIterator<Item = PollResponseData<'a>>,
) -> PollEndEventContent {
let full_results =
compile_poll_results(&self.content.poll, responses, Some(UnixMillis::now()));
let results = full_results
.into_iter()
.map(|(id, users)| (id, users.len()))
.collect::<Vec<_>>();
// Construct the results and get the top answer(s).
let poll_results = PollResultsContentBlock::from_iter(
results
.iter()
.map(|(id, count)| ((*id).to_owned(), (*count).try_into().unwrap_or(u64::MAX))),
);
// Get the text representation of the best answers.
let answers = self
.content
.poll
.answers
.iter()
.map(|a| {
let text = a.text.find_plain().unwrap_or(&a.id);
(a.id.as_str(), text)
})
.collect::<Vec<_>>();
let plain_text = generate_poll_end_fallback_text(&answers, results.into_iter());
let mut end = PollEndEventContent::with_plain_text(plain_text, self.event_id.clone());
end.poll_results = Some(poll_results);
end
}
}
/// A block for poll content.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct PollContentBlock {
/// The question of the poll.
pub question: PollQuestion,
/// The kind of the poll.
#[serde(default, skip_serializing_if = "palpo_core::serde::is_default")]
pub kind: PollKind,
/// The maximum number of responses a user is able to select.
///
/// Must be greater or equal to `1`.
///
/// Defaults to `1`.
#[serde(
default = "PollContentBlock::default_max_selections",
skip_serializing_if = "PollContentBlock::max_selections_is_default"
)]
pub max_selections: u32,
/// The possible answers to the poll.
pub answers: PollAnswers,
}
impl PollContentBlock {
/// Creates a new `PollStartContent` with the given question and answers.
pub fn new(question: TextContentBlock, answers: PollAnswers) -> Self {
Self {
question: question.into(),
kind: Default::default(),
max_selections: Self::default_max_selections(),
answers,
}
}
pub(super) fn default_max_selections() -> u32{
1
}
fn max_selections_is_default(max_selections: &u32) -> bool {
max_selections == &Self::default_max_selections()
}
}
/// The question of a poll.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct PollQuestion {
/// The text representation of the question.
#[serde(rename = "m.text")]
pub text: TextContentBlock,
}
impl From<TextContentBlock> for PollQuestion {
fn from(text: TextContentBlock) -> Self {
Self { text }
}
}
/// The kind of poll.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, Default, StringEnum)]
pub enum PollKind {
/// The results are revealed once the poll is closed.
#[default]
#[palpo_enum(rename = "m.undisclosed")]
Undisclosed,
/// The votes are visible up until and including when the poll is closed.
#[palpo_enum(rename = "m.disclosed")]
Disclosed,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
/// The answers to a poll.
///
/// Must include between 1 and 20 `PollAnswer`s.
///
/// To build this, use the `TryFrom` implementations.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[serde(try_from = "PollAnswersDeHelper")]
pub struct PollAnswers(Vec<PollAnswer>);
impl PollAnswers {
/// The smallest number of values contained in a `PollAnswers`.
pub const MIN_LENGTH: usize = 1;
/// The largest number of values contained in a `PollAnswers`.
pub const MAX_LENGTH: usize = 20;
}
/// An error encountered when trying to convert to a `PollAnswers`.
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum PollAnswersError {
/// There are more than [`PollAnswers::MAX_LENGTH`] values.
#[error("too many values")]
TooManyValues,
/// There are less that [`PollAnswers::MIN_LENGTH`] values.
#[error("not enough values")]
NotEnoughValues,
}
impl TryFrom<Vec<PollAnswer>> for PollAnswers {
type Error = PollAnswersError;
fn try_from(value: Vec<PollAnswer>) -> Result<Self, Self::Error> {
if value.len() < Self::MIN_LENGTH {
Err(PollAnswersError::NotEnoughValues)
} else if value.len() > Self::MAX_LENGTH {
Err(PollAnswersError::TooManyValues)
} else {
Ok(Self(value))
}
}
}
impl TryFrom<&[PollAnswer]> for PollAnswers {
type Error = PollAnswersError;
fn try_from(value: &[PollAnswer]) -> Result<Self, Self::Error> {
Self::try_from(value.to_owned())
}
}
impl Deref for PollAnswers {
type Target = [PollAnswer];
fn deref(&self) -> &Self::Target {
&self.0
}
}
/// Poll answer.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct PollAnswer {
/// The ID of the answer.
///
/// This must be unique among the answers of a poll.
#[serde(rename = "m.id")]
pub id: String,
/// The text representation of the answer.
#[serde(rename = "m.text")]
pub text: TextContentBlock,
}
impl PollAnswer {
/// Creates a new `PollAnswer` with the given id and text representation.
pub fn new(id: String, text: TextContentBlock) -> Self {
Self { id, 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/poll/unstable_start/unstable_poll_kind_serde.rs | crates/core/src/events/poll/unstable_start/unstable_poll_kind_serde.rs | //! `Serialize` and `Deserialize` helpers for unstable poll kind (MSC3381).
use std::borrow::Cow;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::{PrivOwnedStr, events::poll::start::PollKind};
/// Serializes a PollKind using the unstable prefixes.
pub(super) fn serialize<S>(kind: &PollKind, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let s = match kind {
PollKind::Undisclosed => "org.matrix.msc3381.poll.undisclosed",
PollKind::Disclosed => "org.matrix.msc3381.poll.disclosed",
PollKind::_Custom(s) => &s.0,
};
s.serialize(serializer)
}
/// Deserializes a PollKind using the unstable prefixes.
pub(super) fn deserialize<'de, D>(deserializer: D) -> Result<PollKind, D::Error>
where
D: Deserializer<'de>,
{
let s = Cow::<'_, str>::deserialize(deserializer)?;
let kind = match &*s {
"org.matrix.msc3381.poll.undisclosed" => PollKind::Undisclosed,
"org.matrix.msc3381.poll.disclosed" => PollKind::Disclosed,
_ => PollKind::_Custom(PrivOwnedStr(s.into())),
};
Ok(kind)
}
| 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/unstable_start/content_serde.rs | crates/core/src/events/poll/unstable_start/content_serde.rs | use serde::{Deserialize, Deserializer, Serialize, de, ser::SerializeStruct};
use super::{
NewUnstablePollStartEventContent, NewUnstablePollStartEventContentWithoutRelation,
ReplacementUnstablePollStartEventContent, UnstablePollStartContentBlock,
UnstablePollStartEventContent,
};
use crate::{
EventId,
events::room::message::{Relation, deserialize_relation},
serde::{RawJsonValue, from_raw_json_value},
};
impl<'de> Deserialize<'de> for UnstablePollStartEventContent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let json = Box::<RawJsonValue>::deserialize(deserializer)?;
let mut deserializer = serde_json::Deserializer::from_str(json.get());
let relates_to: Option<Relation<NewUnstablePollStartEventContentWithoutRelation>> =
deserialize_relation(&mut deserializer).map_err(de::Error::custom)?;
let UnstablePollStartEventContentDeHelper { poll_start, text } =
from_raw_json_value(&json)?;
let c = match relates_to {
Some(Relation::Replacement(relates_to)) => ReplacementUnstablePollStartEventContent {
poll_start,
text,
relates_to,
}
.into(),
rel => {
let poll_start = poll_start
.ok_or_else(|| de::Error::missing_field("org.matrix.msc3381.poll.start"))?;
let relates_to = rel.map(|r| {
r.try_into()
.expect("Relation::Replacement has already been handled")
});
NewUnstablePollStartEventContent {
poll_start,
text,
relates_to,
}
.into()
}
};
Ok(c)
}
}
#[derive(Debug, Deserialize)]
struct UnstablePollStartEventContentDeHelper {
#[serde(rename = "org.matrix.msc3381.poll.start")]
poll_start: Option<UnstablePollStartContentBlock>,
#[serde(rename = "org.matrix.msc1767.text")]
text: Option<String>,
}
impl Serialize for ReplacementUnstablePollStartEventContent {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let len = 2 + self.poll_start.is_some() as usize + self.text.is_some() as usize;
let mut state =
serializer.serialize_struct("ReplacementUnstablePollStartEventContent", len)?;
if let Some(poll_start) = &self.poll_start {
state.serialize_field("org.matrix.msc3381.poll.start", poll_start)?;
}
if let Some(text) = &self.text {
state.serialize_field("org.matrix.msc1767.text", text)?;
}
state.serialize_field("m.new_content", &self.relates_to.new_content)?;
state.serialize_field(
"m.relates_to",
&ReplacementRelatesTo {
event_id: &self.relates_to.event_id,
},
)?;
state.end()
}
}
#[derive(Debug, Serialize)]
#[serde(tag = "rel_type", rename = "m.replace")]
struct ReplacementRelatesTo<'a> {
event_id: &'a EventId,
}
| 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/unstable_start/unstable_poll_answers_serde.rs | crates/core/src/events/poll/unstable_start/unstable_poll_answers_serde.rs | //! `Deserialize` helpers for unstable poll answers (MSC3381).
use serde::Deserialize;
use super::{UnstablePollAnswer, UnstablePollAnswers};
use crate::events::poll::start::{PollAnswers, PollAnswersError};
#[derive(Debug, Default, Deserialize)]
pub(crate) struct UnstablePollAnswersDeHelper(Vec<UnstablePollAnswer>);
impl TryFrom<UnstablePollAnswersDeHelper> for UnstablePollAnswers {
type Error = PollAnswersError;
fn try_from(helper: UnstablePollAnswersDeHelper) -> Result<Self, Self::Error> {
let mut answers = helper.0;
answers.truncate(PollAnswers::MAX_LENGTH);
UnstablePollAnswers::try_from(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/poll/start/poll_answers_serde.rs | crates/core/src/events/poll/start/poll_answers_serde.rs | //! `Serialize` and `Deserialize` implementations for extensible events
//! (MSC1767).
use serde::Deserialize;
use super::{PollAnswer, PollAnswers, PollAnswersError};
#[derive(Debug, Default, Deserialize)]
pub(crate) struct PollAnswersDeHelper(Vec<PollAnswer>);
impl TryFrom<PollAnswersDeHelper> for PollAnswers {
type Error = PollAnswersError;
fn try_from(helper: PollAnswersDeHelper) -> Result<Self, Self::Error> {
let mut answers = helper.0;
answers.truncate(PollAnswers::MAX_LENGTH);
PollAnswers::try_from(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/message/historical_serde.rs | crates/core/src/events/message/historical_serde.rs | //! Serde for old versions of MSC1767 still used in some types ([spec]).
//!
//! [spec]: https://github.com/matrix-org/matrix-spec-proposals/blob/d6046d8402e7a3c7a4fcbc9da16ea9bad5968992/proposals/1767-extensible-events.md
use serde::{Deserialize, Serialize};
use super::{TextContentBlock, TextRepresentation};
/// Historical `m.message` text content block from MSC1767.
#[derive(Clone, Default, Serialize, Deserialize)]
#[serde(try_from = "MessageContentBlockSerDeHelper")]
#[serde(into = "MessageContentBlockSerDeHelper")]
pub struct MessageContentBlock(Vec<TextRepresentation>);
impl From<MessageContentBlock> for TextContentBlock {
fn from(value: MessageContentBlock) -> Self {
Self(value.0)
}
}
impl From<TextContentBlock> for MessageContentBlock {
fn from(value: TextContentBlock) -> Self {
Self(value.0)
}
}
#[derive(Default, Serialize, Deserialize)]
pub(crate) struct MessageContentBlockSerDeHelper {
/// Plain text short form.
#[serde(
rename = "org.matrix.msc1767.text",
skip_serializing_if = "Option::is_none"
)]
text: Option<String>,
/// HTML short form.
#[serde(
rename = "org.matrix.msc1767.html",
skip_serializing_if = "Option::is_none"
)]
html: Option<String>,
/// Long form.
#[serde(
rename = "org.matrix.msc1767.message",
skip_serializing_if = "Option::is_none"
)]
message: Option<Vec<TextRepresentation>>,
}
impl TryFrom<MessageContentBlockSerDeHelper> for Vec<TextRepresentation> {
type Error = &'static str;
fn try_from(value: MessageContentBlockSerDeHelper) -> Result<Self, Self::Error> {
let MessageContentBlockSerDeHelper {
text,
html,
message,
} = value;
if let Some(message) = message {
Ok(message)
} else {
let message: Vec<_> = html
.map(TextRepresentation::html)
.into_iter()
.chain(text.map(TextRepresentation::plain))
.collect();
if !message.is_empty() {
Ok(message)
} else {
Err(
"missing at least one of fields `org.matrix.msc1767.text`, `org.matrix.msc1767.html` or `org.matrix.msc1767.message`",
)
}
}
}
}
impl TryFrom<MessageContentBlockSerDeHelper> for MessageContentBlock {
type Error = &'static str;
fn try_from(value: MessageContentBlockSerDeHelper) -> Result<Self, Self::Error> {
Ok(Self(value.try_into()?))
}
}
impl From<Vec<TextRepresentation>> for MessageContentBlockSerDeHelper {
fn from(value: Vec<TextRepresentation>) -> Self {
let has_shortcut =
|message: &TextRepresentation| matches!(&*message.mimetype, "text/plain" | "text/html");
if value.iter().all(has_shortcut) {
let mut helper = Self::default();
for message in value.into_iter() {
if message.mimetype == "text/plain" {
helper.text = Some(message.body);
} else if message.mimetype == "text/html" {
helper.html = Some(message.body);
}
}
helper
} else {
Self {
message: Some(value),
..Default::default()
}
}
}
}
impl From<MessageContentBlock> for MessageContentBlockSerDeHelper {
fn from(value: MessageContentBlock) -> Self {
value.0.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/rtc/notification.rs | crates/core/src/events/rtc/notification.rs | //! Type for the MatrixRTC notification event ([MSC4075]).
//!
//! Stable: `m.rtc.notification`
//! Unstable: `org.matrix.msc4075.rtc.notification`
//!
//! [MSC4075]: https://github.com/matrix-org/matrix-spec-proposals/pull/4075
use std::time::Duration;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::PrivOwnedStr;
use crate::UnixMillis;
use crate::events::{Mentions, relation::Reference};
use crate::macros::{EventContent, StringEnum};
/// The content of an `m.rtc.notification` event.
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize, EventContent)]
#[palpo_event(
type = "m.rtc.notification",
kind = MessageLike
)]
pub struct RtcNotificationEventContent {
/// Local timestamp observed by the sender device.
///
/// Used with `lifetime` to determine validity; receivers SHOULD compare with
/// `origin_server_ts` and prefer it if the difference is large.
pub sender_ts: UnixMillis,
/// Relative time from `sender_ts` during which the notification is considered valid.
#[serde(with = "crate::serde::duration::ms")]
pub lifetime: Duration,
/// Intentional mentions determining who should be notified.
#[serde(
rename = "m.mentions",
default,
skip_serializing_if = "Option::is_none"
)]
pub mentions: Option<Mentions>,
/// Optional reference to the related `m.rtc.member` event.
#[serde(rename = "m.relates_to", skip_serializing_if = "Option::is_none")]
pub relates_to: Option<Reference>,
/// How this notification should notify the receiver.
pub notification_type: NotificationType,
}
impl RtcNotificationEventContent {
/// Creates a new `RtcNotificationEventContent` with the given configuration.
pub fn new(
sender_ts: UnixMillis,
lifetime: Duration,
notification_type: NotificationType,
) -> Self {
Self {
sender_ts,
lifetime,
mentions: None,
relates_to: None,
notification_type,
}
}
/// Calculates the timestamp at which this notification is considered invalid.
/// This calculation is based on MSC4075 and tries to use the `sender_ts` as the starting point
/// and the `lifetime` as the duration for which the notification is valid.
///
/// The `sender_ts` cannot be trusted since it is a generated value by the sending client.
/// To mitigate issue because of misconfigured client clocks, the MSC requires
/// that the `origin_server_ts` is used as the starting point if the difference is large.
///
/// # Arguments:
///
/// - `max_sender_ts_offset` is the maximum allowed offset between the two timestamps. (default
/// 20s)
/// - `origin_server_ts` has to be set to the origin_server_ts from the event containing this
/// event content.
///
/// # Examples
/// To start a timer until this client should stop ringing for this notification:
/// `let duration_ring =
/// UnixMillis::now().saturated_sub(content.expiration_ts(event.
/// origin_server_ts(), None));`
pub fn expiration_ts(
&self,
origin_server_ts: UnixMillis,
max_sender_ts_offset: Option<u32>,
) -> UnixMillis {
let (larger, smaller) = if self.sender_ts.get() > origin_server_ts.get() {
(self.sender_ts.get(), origin_server_ts.get())
} else {
(origin_server_ts.get(), self.sender_ts.get())
};
let use_origin_server_ts =
larger.saturating_sub(smaller) > max_sender_ts_offset.unwrap_or(20_000).into();
let start_ts = if use_origin_server_ts {
origin_server_ts.get()
} else {
self.sender_ts.get()
};
UnixMillis(start_ts.saturating_add(self.lifetime.as_millis() as u64))
}
}
/// How this notification should notify the receiver.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[palpo_enum(rename_all = "snake_case")]
pub enum NotificationType {
/// The receiving client should ring with an audible sound.
Ring,
/// The receiving client should display a visual notification.
Notification,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use assert_matches2::assert_matches;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::{NotificationType, RtcNotificationEventContent};
use crate::events::{AnyMessageLikeEvent, Mentions, MessageLikeEvent};
use crate::{UnixMillis, owned_event_id};
#[test]
fn notification_event_serialization() {
let mut content = RtcNotificationEventContent::new(
UnixMillis(1_752_583_130_365),
Duration::from_millis(30_000),
NotificationType::Ring,
);
content.mentions = Some(Mentions::with_room_mention());
content.relates_to = Some(crate::events::relation::Reference::new(owned_event_id!(
"$m:ex"
)));
assert_eq!(
to_json_value(&content).unwrap(),
json!({
"sender_ts": 1_752_583_130_365_u64,
"lifetime": 30_000_u32,
"m.mentions": {"room": true},
"m.relates_to": {"rel_type": "m.reference", "event_id": "$m:ex"},
"notification_type": "ring"
})
);
}
#[test]
fn notification_event_deserialization() {
let json_data = json!({
"content": {
"sender_ts": 1_752_583_130_365_u64,
"lifetime": 30_000_u32,
"m.mentions": {"room": true},
"m.relates_to": {"rel_type": "m.reference", "event_id": "$m:ex"},
"notification_type": "notification"
},
"event_id": "$event:notareal.hs",
"origin_server_ts": 134_829_848,
"room_id": "!roomid:notareal.hs",
"sender": "@user:notareal.hs",
"type": "m.rtc.notification"
});
let event = from_json_value::<AnyMessageLikeEvent>(json_data).unwrap();
assert_matches!(
event,
AnyMessageLikeEvent::RtcNotification(MessageLikeEvent::Original(ev))
);
assert_eq!(ev.content.lifetime, Duration::from_millis(30_000));
}
#[test]
fn expiration_ts_computation() {
let content = RtcNotificationEventContent::new(
UnixMillis(100_365),
Duration::from_millis(30_000),
NotificationType::Ring,
);
// sender_ts is trustworthy
let origin_server_ts = UnixMillis(120_000);
assert_eq!(
content.expiration_ts(origin_server_ts, None),
UnixMillis(130_365)
);
// sender_ts is not trustworthy (sender_ts too small), origin_server_ts is used instead
let origin_server_ts = UnixMillis(200_000);
assert_eq!(
content.expiration_ts(origin_server_ts, None),
UnixMillis(230_000)
);
// sender_ts is not trustworthy (sender_ts too large), origin_server_ts is used instead
let origin_server_ts = UnixMillis(50_000);
assert_eq!(
content.expiration_ts(origin_server_ts, None),
UnixMillis(80_000)
);
// using a custom max offset (result in origin_server_ts)
let origin_server_ts = UnixMillis(130_200);
assert_eq!(
content.expiration_ts(origin_server_ts, Some(100)),
UnixMillis(160_200)
);
// using a custom max offset (result in sender_ts)
let origin_server_ts = UnixMillis(100_300);
assert_eq!(
content.expiration_ts(origin_server_ts, Some(100)),
UnixMillis(130_365)
);
}
}
| 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/decline.rs | crates/core/src/events/rtc/decline.rs | //! Type for the MatrixRTC decline event ([MSC4310]).
//!
//! Unstable: `org.matrix.msc4310.rtc.decline`
//!
//! This event is sent as a reference relation to an `m.rtc.notification` event.
//!
//! [MSC4310]: https://github.com/matrix-org/matrix-spec-proposals/pull/4310
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::events::relation::Reference;
use crate::macros::EventContent;
/// The content of an `m.rtc.decline` event.
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize, EventContent)]
#[palpo_event(type = "org.matrix.msc4310.rtc.decline", alias = "m.rtc.decline", kind = MessageLike)]
pub struct RtcDeclineEventContent {
/// The reference to the original call notification message event.
///
/// This must be an `m.reference` to the `m.rtc.notification` / `m.call.notify` event.
#[serde(rename = "m.relates_to")]
pub relates_to: Reference,
}
impl RtcDeclineEventContent {
/// Creates a new `RtcDeclineEventContent` targeting the given notification event id.
pub fn new<E: Into<crate::OwnedEventId>>(notification_event_id: E) -> Self {
Self {
relates_to: Reference::new(notification_event_id.into()),
}
}
}
#[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::RtcDeclineEventContent;
use crate::events::{AnyMessageLikeEvent, MessageLikeEvent};
#[test]
fn decline_event_serialization() {
let content = RtcDeclineEventContent::new(owned_event_id!("$abc:example.org"));
let value = to_json_value(&content).unwrap();
assert_eq!(
value,
json!({
"m.relates_to": {
"rel_type": "m.reference",
"event_id": "$abc:example.org"
},
})
);
}
#[test]
fn decline_event_deserialization() {
let json_data = json!({
"content": {
"m.relates_to": {
"rel_type": "m.reference",
"event_id": "$abc:example.org"
},
},
"event_id": "$event:notareal.hs",
"origin_server_ts": 134_829_848,
"room_id": "!roomid:notareal.hs",
"sender": "@user:notareal.hs",
"type": "m.rtc.decline"
});
let event = from_json_value::<AnyMessageLikeEvent>(json_data).unwrap();
assert_matches!(
event,
AnyMessageLikeEvent::RtcDecline(MessageLikeEvent::Original(decline_event))
);
assert_eq!(decline_event.sender, "@user:notareal.hs");
assert_eq!(decline_event.origin_server_ts.get(), 134_829_848);
assert_eq!(decline_event.room_id, "!roomid:notareal.hs");
assert_eq!(
decline_event.content.relates_to.event_id,
"$abc:example.org"
);
}
}
| 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/child.rs | crates/core/src/events/space/child.rs | //! Types for the [`m.space.child`] event.
//!
//! [`m.space.child`]: https://spec.matrix.org/latest/client-server-api/#mspacechild
use crate::macros::{Event, EventContent};
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{OwnedRoomId, OwnedServerName, OwnedUserId, UnixMillis};
/// The content of an `m.space.child` event.
///
/// The admins of a space can advertise rooms and subspaces for their space by
/// setting `m.space.child` state events.
///
/// The `state_key` is the ID of a child room or space, and the content must
/// contain a `via` key which gives a list of candidate servers that can be used
/// to join the room.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.space.child", kind = State, state_key_type = OwnedRoomId)]
pub struct SpaceChildEventContent {
/// List of candidate servers that can be used to join the room.
pub via: Vec<OwnedServerName>,
/// Provide a default ordering of siblings in the room list.
///
/// Rooms are sorted based on a lexicographic ordering of the Unicode
/// codepoints of the characters in `order` values. Rooms with no
/// `order` come last, in ascending numeric order
/// of the origin_server_ts of their m.room.create events, or ascending
/// lexicographic order of their room_ids in case of equal
/// `origin_server_ts`. `order`s which are not strings, or do
/// not consist solely of ascii characters in the range `\x20` (space) to
/// `\x7E` (`~`), or consist of more than 50 characters, are forbidden
/// and the field should be ignored if received.
#[serde(skip_serializing_if = "Option::is_none")]
pub order: Option<String>,
/// Space admins can mark particular children of a space as "suggested".
///
/// This mainly serves as a hint to clients that that they can be displayed
/// differently, for example by showing them eagerly in the room list. A
/// child which is missing the `suggested` property is treated
/// identically to a child with `"suggested": false`. A suggested child may
/// be a room or a subspace.
///
/// Defaults to `false`.
#[serde(default, skip_serializing_if = "palpo_core::serde::is_default")]
pub suggested: bool,
}
impl SpaceChildEventContent {
/// Creates a new `SpaceChildEventContent` with the given routing servers.
pub fn new(via: Vec<OwnedServerName>) -> Self {
Self {
via,
order: None,
suggested: false,
}
}
}
/// An `m.space.child` event represented as a Stripped State Event with an added
/// `origin_server_ts` key.
#[derive(ToSchema, Clone, Debug, Event)]
pub struct HierarchySpaceChildEvent {
/// The content of the space child event.
pub content: SpaceChildEventContent,
/// The fully-qualified ID of the user who sent this event.
pub sender: OwnedUserId,
/// The room ID of the child.
pub state_key: OwnedRoomId,
/// Timestamp in milliseconds on originating homeserver when this event was
/// sent.
pub origin_server_ts: UnixMillis,
}
// #[cfg(test)]
// mod tests {
// use crate::{server_name, UnixMillis};
// use serde_json::{from_value as from_json_value, json, to_value as
// to_json_value};
// use super::{HierarchySpaceChildEvent, SpaceChildEventContent};
// #[test]
// fn space_child_serialization() {
// let content = SpaceChildEventContent {
// via: vec![server_name!("example.com").to_owned()],
// order: Some("uwu".to_owned()),
// suggested: false,
// };
// let json = json!({
// "via": ["example.com"],
// "order": "uwu",
// });
// assert_eq!(to_json_value(&content).unwrap(), json);
// }
// #[test]
// fn space_child_empty_serialization() {
// let content = SpaceChildEventContent {
// via: vec![],
// order: None,
// suggested: false,
// };
// let json = json!({ "via": [] });
// assert_eq!(to_json_value(&content).unwrap(), json);
// }
// #[test]
// fn hierarchy_space_child_deserialization() {
// let json = json!({
// "content": {
// "via": [
// "example.org"
// ]
// },
// "origin_server_ts": 1_629_413_349,
// "sender": "@alice:example.org",
// "state_key": "!a:example.org",
// "type": "m.space.child"
// });
// let ev = from_json_value::<HierarchySpaceChildEvent>(json).unwrap();
// assert_eq!(ev.origin_server_ts, UnixMillis(uint!(1_629_413_349)));
// assert_eq!(ev.sender, "@alice:example.org");
// assert_eq!(ev.state_key, "!a:example.org");
// assert_eq!(ev.content.via, ["example.org"]);
// assert_eq!(ev.content.order, None);
// assert!(!ev.content.suggested);
// }
// }
| 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/parent.rs | crates/core/src/events/space/parent.rs | //! Types for the [`m.space.parent`] event.
//!
//! [`m.space.parent`]: https://spec.matrix.org/latest/client-server-api/#mspaceparent
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{OwnedRoomId, OwnedServerName};
/// The content of an `m.space.parent` event.
///
/// Rooms can claim parents via the `m.space.parent` state event.
///
/// Similar to `m.space.child`, the `state_key` is the ID of the parent space,
/// and the content must contain a `via` key which gives a list of candidate
/// servers that can be used to join the parent.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[palpo_event(type = "m.space.parent", kind = State, state_key_type = OwnedRoomId)]
pub struct SpaceParentEventContent {
/// List of candidate servers that can be used to join the room.
pub via: Vec<OwnedServerName>,
/// Determines whether this is the main parent for the space.
///
/// When a user joins a room with a canonical parent, clients may switch to
/// view the room in the context of that space, peeking into it in order
/// to find other rooms and group them together. In practice, well
/// behaved rooms should only have one `canonical` parent, but
/// given this is not enforced: if multiple are present the client should
/// select the one with the lowest room ID, as determined via a
/// lexicographic ordering of the Unicode code-points.
///
/// Defaults to `false`.
#[serde(default, skip_serializing_if = "palpo_core::serde::is_default")]
pub canonical: bool,
}
impl SpaceParentEventContent {
/// Creates a new `SpaceParentEventContent` with the given routing servers.
pub fn new(via: Vec<OwnedServerName>) -> Self {
Self {
via,
canonical: false,
}
}
}
#[cfg(test)]
mod tests {
use serde_json::{json, to_value as to_json_value};
use super::SpaceParentEventContent;
use crate::server_name;
#[test]
fn space_parent_serialization() {
let content = SpaceParentEventContent {
via: vec![server_name!("example.com").to_owned()],
canonical: true,
};
let json = json!({
"via": ["example.com"],
"canonical": true,
});
assert_eq!(to_json_value(&content).unwrap(), json);
}
#[test]
fn space_parent_empty_serialization() {
let content = SpaceParentEventContent {
via: vec![],
canonical: false,
};
let json = json!({ "via": [] });
assert_eq!(to_json_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/policy/rule.rs | crates/core/src/events/policy/rule.rs | //! Modules and types for events in the `m.policy.rule` namespace.
pub mod room;
pub mod server;
pub mod user;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{PrivOwnedStr, serde::StringEnum};
/// The payload for policy rule events.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct PolicyRuleEventContent {
/// The entity affected by this rule.
///
/// Glob characters `*` and `?` can be used to match zero or more characters
/// or exactly one character respectively.
pub entity: String,
/// The suggested action to take.
pub recommendation: Recommendation,
/// The human-readable description for the recommendation.
pub reason: String,
}
impl PolicyRuleEventContent {
/// Creates a new `PolicyRuleEventContent` with the given entity,
/// recommendation and reason.
pub fn new(entity: String, recommendation: Recommendation, reason: String) -> Self {
Self {
entity,
recommendation,
reason,
}
}
}
/// The possibly redacted form of [`PolicyRuleEventContent`].
///
/// This type is used when it's not obvious whether the content is redacted or
/// not.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct PossiblyRedactedPolicyRuleEventContent {
/// The entity affected by this rule.
///
/// Glob characters `*` and `?` can be used to match zero or more characters
/// or exactly one character respectively.
#[serde(skip_serializing_if = "Option::is_none")]
pub entity: Option<String>,
/// The suggested action to take.
#[serde(skip_serializing_if = "Option::is_none")]
pub recommendation: Option<Recommendation>,
/// The human-readable description for the recommendation.
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
/// The possible actions that can be taken.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[non_exhaustive]
pub enum Recommendation {
/// Entities affected by the rule should be banned from participation where
/// possible.
#[palpo_enum(rename = "m.ban")]
Ban,
#[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/policy/rule/user.rs | crates/core/src/events/policy/rule/user.rs | //! Types for the [`m.policy.rule.user`] event.
//!
//! [`m.policy.rule.user`]: https://spec.matrix.org/latest/client-server-api/#mpolicyruleuser
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use super::{PolicyRuleEventContent, PossiblyRedactedPolicyRuleEventContent};
use crate::events::{PossiblyRedactedStateEventContent, StateEventType, StaticEventContent};
/// The content of an `m.policy.rule.user` event.
///
/// This event type is used to apply rules to user entities.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[allow(clippy::exhaustive_structs)]
#[palpo_event(type = "m.policy.rule.user", kind = State, state_key_type = String, custom_possibly_redacted)]
pub struct PolicyRuleUserEventContent(pub PolicyRuleEventContent);
/// The possibly redacted form of [`PolicyRuleUserEventContent`].
///
/// This type is used when it's not obvious whether the content is redacted or
/// not.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[allow(clippy::exhaustive_structs)]
pub struct PossiblyRedactedPolicyRuleUserEventContent(pub PossiblyRedactedPolicyRuleEventContent);
impl PossiblyRedactedStateEventContent for PossiblyRedactedPolicyRuleUserEventContent {
type StateKey = String;
fn event_type(&self) -> StateEventType {
StateEventType::PolicyRuleUser
}
}
impl StaticEventContent for PossiblyRedactedPolicyRuleUserEventContent {
const TYPE: &'static str = PolicyRuleUserEventContent::TYPE;
type IsPrefix = <PolicyRuleUserEventContent 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/policy/rule/server.rs | crates/core/src/events/policy/rule/server.rs | //! Types for the [`m.policy.rule.server`] event.
//!
//! [`m.policy.rule.server`]: https://spec.matrix.org/latest/client-server-api/#mpolicyruleserver
use crate::macros::EventContent;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use super::{PolicyRuleEventContent, PossiblyRedactedPolicyRuleEventContent};
use crate::events::{PossiblyRedactedStateEventContent, StateEventType, StaticEventContent};
/// The content of an `m.policy.rule.server` event.
///
/// This event type is used to apply rules to server entities.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[allow(clippy::exhaustive_structs)]
#[palpo_event(type = "m.policy.rule.server", kind = State, state_key_type = String, custom_possibly_redacted)]
pub struct PolicyRuleServerEventContent(pub PolicyRuleEventContent);
/// The possibly redacted form of [`PolicyRuleServerEventContent`].
///
/// This type is used when it's not obvious whether the content is redacted or
/// not.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[allow(clippy::exhaustive_structs)]
pub struct PossiblyRedactedPolicyRuleServerEventContent(pub PossiblyRedactedPolicyRuleEventContent);
impl PossiblyRedactedStateEventContent for PossiblyRedactedPolicyRuleServerEventContent {
type StateKey = String;
fn event_type(&self) -> StateEventType {
StateEventType::PolicyRuleServer
}
}
impl StaticEventContent for PossiblyRedactedPolicyRuleServerEventContent {
const TYPE: &'static str = PolicyRuleServerEventContent::TYPE;
type IsPrefix = <PolicyRuleServerEventContent 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/policy/rule/room.rs | crates/core/src/events/policy/rule/room.rs | //! Types for the [`m.policy.rule.room`] event.
//!
//! [`m.policy.rule.room`]: https://spec.matrix.org/latest/client-server-api/#mpolicyruleroom
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use super::{PolicyRuleEventContent, PossiblyRedactedPolicyRuleEventContent};
use crate::events::{PossiblyRedactedStateEventContent, StateEventType, StaticEventContent};
use crate::macros::EventContent;
/// The content of an `m.policy.rule.room` event.
///
/// This event type is used to apply rules to room entities.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, EventContent)]
#[allow(clippy::exhaustive_structs)]
#[palpo_event(type = "m.policy.rule.room", kind = State, state_key_type = String, custom_possibly_redacted)]
pub struct PolicyRuleRoomEventContent(pub PolicyRuleEventContent);
/// The possibly redacted form of [`PolicyRuleRoomEventContent`].
///
/// This type is used when it's not obvious whether the content is redacted or
/// not.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[allow(clippy::exhaustive_structs)]
pub struct PossiblyRedactedPolicyRuleRoomEventContent(pub PossiblyRedactedPolicyRuleEventContent);
impl PossiblyRedactedStateEventContent for PossiblyRedactedPolicyRuleRoomEventContent {
type StateKey = String;
fn event_type(&self) -> StateEventType {
StateEventType::PolicyRuleRoom
}
}
impl StaticEventContent for PossiblyRedactedPolicyRuleRoomEventContent {
const TYPE: &'static str = PolicyRuleRoomEventContent::TYPE;
type IsPrefix = <PolicyRuleRoomEventContent as StaticEventContent>::IsPrefix;
}
// #[cfg(test)]
// mod tests {
// use crate::serde::RawJson;
// use serde_json::{from_value as from_json_value, json, to_value as
// to_json_value};
// use super::{OriginalPolicyRuleRoomEvent, PolicyRuleRoomEventContent};
// use crate::policy::rule::{PolicyRuleEventContent, Recommendation};
// #[test]
// fn serialization() {
// let content = PolicyRuleRoomEventContent(PolicyRuleEventContent {
// entity: "#*:example.org".into(),
// reason: "undesirable content".into(),
// recommendation: Recommendation::Ban,
// });
// let json = json!({
// "entity": "#*:example.org",
// "reason": "undesirable content",
// "recommendation": "m.ban"
// });
// assert_eq!(to_json_value(content).unwrap(), json);
// }
// #[test]
// fn deserialization() {
// let json = json!({
// "content": {
// "entity": "#*:example.org",
// "reason": "undesirable content",
// "recommendation": "m.ban"
// },
// "event_id": "$143273582443PhrSn:example.org",
// "origin_server_ts": 1_432_735_824_653_u64,
// "room_id": "!jEsUZKDJdhlrceRyVU:example.org",
// "sender": "@example:example.org",
// "state_key": "rule:#*:example.org",
// "type": "m.policy.rule.room",
// "unsigned": {
// "age": 1234
// }
// });
// from_json_value::<RawJson<OriginalPolicyRuleRoomEvent>>(json)
// .unwrap()
// .deserialize()
// .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/media/content.rs | crates/core/src/media/content.rs | /// `GET /_matrix/media/*/download/{serverName}/{mediaId}`
///
/// Retrieve content from the media store.
use std::time::Duration;
use reqwest::Url;
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
// use crate::http_headers::CROSS_ORIGIN_RESOURCE_POLICY;
use crate::sending::{SendRequest, SendResult};
use crate::{OwnedMxcUri, OwnedServerName};
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixmediav3downloadservernamemediaid
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: None,
// history: {
// 1.0 => "/_matrix/media/r0/download/:server_name/:media_id",
// 1.1 => "/_matrix/media/v3/download/:server_name/:media_id",
// }
// };
pub fn content_request(origin: &str, args: ContentReqArgs) -> SendResult<SendRequest> {
let url = Url::parse(&format!(
"{origin}/_matrix/media/v3/download/{}/{}?allow_remote={}&allow_redirect={}",
args.server_name, args.media_id, args.allow_remote, args.allow_redirect
))?;
Ok(crate::sending::get(url))
}
/// Request type for the `get_media_content` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct ContentReqArgs {
/// The server name from the mxc:// URI (the authoritory component).
#[salvo(parameter(parameter_in = Path))]
pub server_name: OwnedServerName,
/// The media ID from the mxc:// URI (the path component).
#[salvo(parameter(parameter_in = Path))]
pub media_id: String,
/// Whether to fetch media deemed remote.
///
/// Used to prevent routing loops. Defaults to `true`.
#[salvo(parameter(parameter_in = Query))]
#[serde(
default = "crate::serde::default_true",
skip_serializing_if = "crate::serde::is_true"
)]
pub allow_remote: bool,
/// The maximum duration that the client is willing to wait to start
/// receiving data, in the case that the content has not yet been
/// uploaded.
///
/// The default value is 20 seconds.
#[salvo(parameter(parameter_in = Query))]
#[serde(
with = "crate::serde::duration::ms",
default = "crate::client::media::default_download_timeout",
skip_serializing_if = "crate::client::media::is_default_download_timeout"
)]
pub timeout_ms: Duration,
/// Whether the server may return a 307 or 308 redirect response that points
/// at the relevant media content.
///
/// Unless explicitly set to `true`, the server must return the media
/// content itself.
#[salvo(parameter(parameter_in = Query))]
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub allow_redirect: bool,
}
#[derive(ToParameters, Deserialize, Debug)]
pub struct ContentWithFileNameReqArgs {
/// The server name from the mxc:// URI (the authoritory component).
#[salvo(parameter(parameter_in = Path))]
pub server_name: OwnedServerName,
/// The media ID from the mxc:// URI (the path component).
#[salvo(parameter(parameter_in = Path))]
pub media_id: String,
#[salvo(parameter(parameter_in = Path))]
pub filename: String,
/// Whether to fetch media deemed remote.
///
/// Used to prevent routing loops. Defaults to `true`.
#[salvo(parameter(parameter_in = Query))]
#[serde(
default = "crate::serde::default_true",
skip_serializing_if = "crate::serde::is_true"
)]
pub allow_remote: bool,
/// The maximum duration that the client is willing to wait to start
/// receiving data, in the case that the content has not yet been
/// uploaded.
///
/// The default value is 20 seconds.
#[salvo(parameter(parameter_in = Query))]
#[serde(
with = "crate::serde::duration::ms",
default = "crate::client::media::default_download_timeout",
skip_serializing_if = "crate::client::media::is_default_download_timeout"
)]
pub timeout_ms: Duration,
/// Whether the server may return a 307 or 308 redirect response that points
/// at the relevant media content.
///
/// Unless explicitly set to `true`, the server must return the media
/// content itself.
#[salvo(parameter(parameter_in = Query))]
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub allow_redirect: bool,
}
// /// Response type for the `get_media_content` endpoint.
// #[derive(ToSchema, Serialize, Debug)]
// pub struct Content {
// /// The content that was previously uploaded.
// pub data: Vec<u8>,
// /// The content type of the file that was previously uploaded.
// pub content_type: Option<String>,
// /// The value of the `Content-Disposition` HTTP header, possibly
// containing the name of the /// file that was previously uploaded.
// ///
// /// See [MDN] for the syntax.
// ///
// /// [MDN]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#Syntax
// pub content_disposition: Option<String>,
// /// The value of the `Cross-Origin-Resource-Policy` HTTP header.
// ///
// /// See [MDN] for the syntax.
// ///
// /// [MDN]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy#syntax
// pub cross_origin_resource_policy: Option<String>,
// }
// impl Content {
// /// Creates a new `Response` with the given file contents.
// ///
// /// The Cross-Origin Resource Policy defaults to `cross-origin`.
// pub fn new(data: Vec<u8>) -> Self {
// Self {
// data,
// content_type: None,
// content_disposition: None,
// cross_origin_resource_policy: Some("cross-origin".to_owned()),
// }
// }
// }
// impl Scribe for Content {
// fn render(self, res: &mut Response) {
// let Self {
// data,
// content_type,
// content_disposition,
// cross_origin_resource_policy,
// } = self;
// if let Some(content_type) = content_type {
// res.add_header(CONTENT_TYPE, content_type, true);
// }
// if let Some(content_disposition) = content_disposition {
// res.add_header(CONTENT_DISPOSITION, content_disposition, true);
// }
// if let Some(cross_origin_resource_policy) =
// cross_origin_resource_policy {
// res.add_header("cross-origin-resource-policy", cross_origin_resource_policy,
// true); }
// res.write_body(data);
// }
// }
/// `POST /_matrix/media/*/upload`
///
/// Upload content to the media store.
/// `/v3/` ([spec])
///
/// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixmediav3upload
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/media/r0/upload",
// 1.1 => "/_matrix/media/v3/upload",
// }
// };
#[derive(ToParameters, Deserialize, Debug)]
pub struct CreateContentReqArgs {
/// The name of the file being uploaded.
#[salvo(parameter(parameter_in = Query))]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub filename: Option<String>,
/// The content type of the file being uploaded.
#[serde(rename = "content-type")]
#[salvo(parameter(parameter_in = Header))]
pub content_type: Option<String>,
/// Should the server return a blurhash or not.
///
/// This uses the unstable prefix in
/// [MSC2448](https://github.com/matrix-org/matrix-spec-proposals/pull/2448).
#[salvo(parameter(parameter_in = Query))]
#[serde(
default,
skip_serializing_if = "crate::serde::is_default",
rename = "xyz.amorgan.generate_blurhash"
)]
pub generate_blurhash: bool,
}
/// Response type for the `create_media_content` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct CreateContentResBody {
/// The MXC URI for the uploaded content.
pub content_uri: OwnedMxcUri,
/// The [BlurHash](https://blurha.sh) for the uploaded content.
///
/// This uses the unstable prefix in
/// [MSC2448](https://github.com/matrix-org/matrix-spec-proposals/pull/2448).
pub blurhash: Option<String>,
}
impl CreateContentResBody {
/// Creates a new `Response` with the given MXC URI.
pub fn new(content_uri: OwnedMxcUri) -> Self {
Self {
content_uri,
blurhash: None,
}
}
}
// /// `PUT /_matrix/media/*/upload/{serverName}/{mediaId}`
// ///
// /// Upload media to an MXC URI that was created with create_mxc_uri.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#put_matrixmediav3uploadservernamemediaid
// const METADATA: Metadata = metadata! {
// method: PUT,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/media/unstable/fi.mau.msc2246/upload/:server_name/:media_id",
// 1.7 => "/_matrix/media/v3/upload/:server_name/:media_id",
// }
// };
/// Request type for the `create_content_async` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct UploadContentReqArgs {
/// The server name from the mxc:// URI (the authoritory component).
#[salvo(parameter(parameter_in = Path))]
pub server_name: OwnedServerName,
/// The media ID from the mxc:// URI (the path component).
#[salvo(parameter(parameter_in = Path))]
pub media_id: String,
/// The file contents to upload.
// #[palpo_api(raw_body)]
// pub file: Vec<u8>,
/// The content type of the file being uploaded.
#[salvo(rename="content-type", parameter(parameter_in = Header))]
pub content_type: Option<String>,
/// The name of the file being uploaded.
#[salvo(parameter(parameter_in = Query))]
#[serde(skip_serializing_if = "Option::is_none")]
pub filename: Option<String>,
// TODO: How does this and msc2448 (blurhash) interact?
}
// /// `GET /_matrix/media/*/download/{serverName}/{mediaId}/{fileName}`
// ///
// /// Retrieve content from the media store, specifying a filename to return.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixmediav3downloadservernamemediaidfilename
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: None,
// history: {
// 1.0 => "/_matrix/media/r0/download/:server_name/:media_id/:filename",
// 1.1 => "/_matrix/media/v3/download/:server_name/:media_id/:filename",
// }
// };
/// Request type for the `get_media_content_as_filename` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct ContentAsFileNameReqArgs {
/// The server name from the mxc:// URI (the authoritory component).
#[salvo(parameter(parameter_in = Path))]
pub server_name: OwnedServerName,
/// The media ID from the mxc:// URI (the path component).
#[salvo(parameter(parameter_in = Path))]
pub media_id: String,
/// The filename to return in the `Content-Disposition` header.
#[salvo(parameter(parameter_in = Path))]
pub filename: String,
/// Whether to fetch media deemed remote.
///
/// Used to prevent routing loops. Defaults to `true`.
#[salvo(parameter(parameter_in = Query))]
#[serde(
default = "crate::serde::default_true",
skip_serializing_if = "crate::serde::is_true"
)]
pub allow_remote: bool,
/// The maximum duration that the client is willing to wait to start
/// receiving data, in the case that the content has not yet been
/// uploaded.
///
/// The default value is 20 seconds.
#[salvo(parameter(parameter_in = Query))]
#[serde(
with = "crate::serde::duration::ms",
default = "crate::client::media::default_download_timeout",
skip_serializing_if = "crate::client::media::is_default_download_timeout"
)]
pub timeout_ms: Duration,
/// Whether the server may return a 307 or 308 redirect response that points
/// at the relevant media content.
///
/// Unless explicitly set to `true`, the server must return the media
/// content itself.
#[salvo(parameter(parameter_in = Query))]
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub allow_redirect: bool,
}
// /// Response type for the `get_media_content_as_filename` endpoint.
// #[derive(ToSchema, Serialize, Debug)]
// pub struct ContentAsFileNameResBody {
// /// The content that was previously uploaded.
// #[palpo_api(raw_body)]
// pub file: Vec<u8>,
// /// The content type of the file that was previously uploaded.
// #[palpo_api(header = CONTENT_TYPE)]
// pub content_type: Option<String>,
// /// The value of the `Content-Disposition` HTTP header, possibly
// containing the name of the /// file that was previously uploaded.
// ///
// /// See [MDN] for the syntax.
// ///
// /// [MDN]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#Syntax
// #[palpo_api(header = CONTENT_DISPOSITION)]
// pub content_disposition: Option<String>,
// /// The value of the `Cross-Origin-Resource-Policy` HTTP header.
// ///
// /// See [MDN] for the syntax.
// ///
// /// [MDN]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy#syntax
// #[palpo_api(header = CROSS_ORIGIN_RESOURCE_POLICY)]
// pub cross_origin_resource_policy: Option<String>,
// }
// impl ContentAsFileNameResBody {
// /// Creates a new `Response` with the given file.
// ///
// /// The Cross-Origin Resource Policy defaults to `cross-origin`.
// pub fn new(file: Vec<u8>) -> Self {
// Self {
// file,
// content_type: None,
// content_disposition: None,
// cross_origin_resource_policy: Some("cross-origin".to_owned()),
// }
// }
// }
// `GET /_matrix/media/*/thumbnail/{serverName}/{mediaId}`
//
// Get a thumbnail of content from the media store.
// `/v3/` ([spec])
//
// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixmediav3thumbnailservernamemediaid
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: true,
// authentication: None,
// history: {
// 1.0 => "/_matrix/media/r0/thumbnail/:server_name/:media_id",
// 1.1 => "/_matrix/media/v3/thumbnail/:server_name/:media_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/client/user.rs | crates/core/src/client/user.rs | //! `POST /_matrix/client/*/user/{user_id}/openid/request_token`
//!
//! Request an OpenID 1.0 token to verify identity with a third party.
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3useruser_idopenidrequest_token
use std::time::Duration;
use salvo::prelude::*;
use serde::Serialize;
use crate::{OwnedServerName, authentication::TokenType};
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/user/:user_id/openid/request_token",
// 1.1 => "/_matrix/client/v3/user/:user_id/openid/request_token",
// }
// };
// /// Request type for the `request_openid_token` endpoint.
// pub struct Requesxt {
// /// User ID of authenticated user.
// #[salvo(parameter(parameter_in = Path))]
// pub user_id: OwnedUserId,
// }
/// Response type for the `request_openid_token` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct RequstOpenidTokenResBody {
/// Access token for verifying user's identity.
pub access_token: String,
/// Access token type.
pub token_type: TokenType,
/// HomeServer domain for verification of user's identity.
pub matrix_server_name: OwnedServerName,
/// Seconds until token expiration.
#[serde(with = "crate::serde::duration::secs")]
pub expires_in: Duration,
}
impl RequstOpenidTokenResBody {
/// Creates a new `Response` with the given access token, token type, server
/// name and expiration duration.
pub fn new(
access_token: String,
token_type: TokenType,
matrix_server_name: OwnedServerName,
expires_in: Duration,
) -> Self {
Self {
access_token,
token_type,
matrix_server_name,
expires_in,
}
}
}
| 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/client/rtc.rs | crates/core/src/client/rtc.rs | //! [MatrixRTC] endpoints.
//!
//! [MatrixRTC]: https://github.com/matrix-org/matrix-spec-proposals/pull/4143
pub mod transports;
| 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/client/event.rs | crates/core/src/client/event.rs | 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/client/discovery.rs | crates/core/src/client/discovery.rs | //! Server discovery endpoints.
pub mod auth_metadata;
pub mod capabilities;
pub mod client;
pub mod support;
pub mod versions;
pub mod homeserver;
| 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/client/user_directory.rs | crates/core/src/client/user_directory.rs | //! `POST /_matrix/client/*/user_directory/search`
//!
//! Performs a search for users.
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3user_directorysearch
use salvo::oapi::{ToParameters, ToSchema};
use serde::{Deserialize, Serialize};
use crate::{OwnedMxcUri, OwnedUserId};
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/user_directory/search",
// 1.1 => "/_matrix/client/v3/user_directory/search",
// }
// };
#[derive(ToParameters, Deserialize, Debug)]
pub struct SearchUsersReqArgs {
/// Language tag to determine the collation to use for the
/// (case-insensitive) search.
///
/// See [MDN] for the syntax.
///
/// [MDN]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Language#Syntax
#[salvo(parameter(parameter_in = Header))]
pub accept_language: Option<String>,
}
/// Request type for the `search_users` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct SearchUsersReqBody {
/// The term to search for.
pub search_term: String,
/// The maximum number of results to return.
///
/// Defaults to 10.
#[serde(default = "default_limit", skip_serializing_if = "is_default_limit")]
pub limit: usize,
// /// Language tag to determine the collation to use for the (case-insensitive) search.
// ///
// /// See [MDN] for the syntax.
// ///
// /// [MDN]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Language#Syntax
// #[palpo_api(header = ACCEPT_LANGUAGE)]
// pub language: Option<String>,
}
/// Response type for the `search_users` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct SearchUsersResBody {
/// Ordered by rank and then whether or not profile info is available.
pub results: Vec<SearchedUser>,
/// Indicates if the result list has been truncated by the limit.
pub limited: bool,
}
impl SearchUsersResBody {
/// Creates a new `Response` with the given results and limited flag
pub fn new(results: Vec<SearchedUser>, limited: bool) -> Self {
Self { results, limited }
}
}
fn default_limit() -> usize {
10
}
fn is_default_limit(limit: &usize) -> bool {
limit == &default_limit()
}
/// User data as result of a search.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct SearchedUser {
/// The user's matrix user ID.
pub user_id: OwnedUserId,
/// The display name of the user, if one exists.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
/// The avatar url, as an MXC, if one exists.
#[serde(
skip_serializing_if = "Option::is_none",
default,
deserialize_with = "crate::serde::empty_string_as_none"
)]
pub avatar_url: Option<OwnedMxcUri>,
}
impl SearchedUser {
/// Create a new `User` with the given `UserId`.
pub fn new(user_id: OwnedUserId) -> Self {
Self {
user_id,
display_name: None,
avatar_url: 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/client/key.rs | crates/core/src/client/key.rs | /// Endpoints for key management
pub mod claim_key;
use std::{
collections::{BTreeMap, btree_map},
ops::Deref,
time::Duration,
};
pub use claim_key::*;
use salvo::oapi::{ToParameters, ToSchema};
use serde::{Deserialize, Serialize};
use crate::{
DeviceKeyAlgorithm, OwnedDeviceId, OwnedDeviceKeyId, OwnedUserId, PrivOwnedStr,
client::uiaa::AuthData,
encryption::{CrossSigningKey, DeviceKeys, OneTimeKey},
serde::{JsonValue, RawJson, RawJsonValue, StringEnum},
};
/// An iterator over signed key IDs and their associated data.
#[derive(Debug)]
pub struct SignedKeysIter<'a>(pub(super) btree_map::Iter<'a, Box<str>, Box<RawJsonValue>>);
impl<'a> Iterator for SignedKeysIter<'a> {
type Item = (&'a str, &'a RawJsonValue);
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(|(id, val)| (&**id, &**val))
}
}
// /// `POST /_matrix/client/*/keys/query`
// ///
// /// Returns the current devices and identity keys for the given users.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3keysquery
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/keys/query",
// 1.1 => "/_matrix/client/v3/keys/query",
// }
// };
/// Request type for the `get_keys` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct KeysReqBody {
/// The time (in milliseconds) to wait when downloading keys from remote
/// servers.
///
/// 10 seconds is the recommended default.
#[serde(
with = "crate::serde::duration::opt_ms",
default,
skip_serializing_if = "Option::is_none"
)]
pub timeout: Option<Duration>,
/// The keys to be downloaded.
///
/// An empty list indicates all devices for the corresponding user.
pub device_keys: BTreeMap<OwnedUserId, Vec<OwnedDeviceId>>,
}
/// Response type for the `get_keys` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct KeysResBody {
/// If any remote homeservers could not be reached, they are recorded here.
///
/// The names of the properties are the names of the unreachable servers.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
#[salvo(schema(value_type = Object, additional_properties = true))]
pub failures: BTreeMap<String, JsonValue>,
/// Information on the queried devices.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub device_keys: BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceId, DeviceKeys>>,
/// Information on the master cross-signing keys of the queried users.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub master_keys: BTreeMap<OwnedUserId, CrossSigningKey>,
/// Information on the self-signing keys of the queried users.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub self_signing_keys: BTreeMap<OwnedUserId, CrossSigningKey>,
/// Information on the user-signing keys of the queried users.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub user_signing_keys: BTreeMap<OwnedUserId, CrossSigningKey>,
}
// /// `POST /_matrix/client/*/keys/upload`
// ///
// /// Publishes end-to-end encryption keys for the device.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3keysupload
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/keys/upload",
// 1.1 => "/_matrix/client/v3/keys/upload",
// }
// };
/// Request type for the `upload_keys` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct UploadKeysReqBody {
/// Identity keys for the device.
///
/// May be absent if no new identity keys are required.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub device_keys: Option<DeviceKeys>,
/// One-time public keys for "pre-key" messages.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub one_time_keys: BTreeMap<OwnedDeviceKeyId, OneTimeKey>,
/// Fallback public keys for "pre-key" messages.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub fallback_keys: BTreeMap<OwnedDeviceKeyId, OneTimeKey>,
}
/// Response type for the `upload_keys` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct UploadKeysResBody {
/// For each key algorithm, the number of unclaimed one-time keys of that
/// type currently held on the server for this device.
pub one_time_key_counts: BTreeMap<DeviceKeyAlgorithm, u64>,
}
impl UploadKeysResBody {
/// Creates a new `Response` with the given one time key counts.
pub fn new(one_time_key_counts: BTreeMap<DeviceKeyAlgorithm, u64>) -> Self {
Self {
one_time_key_counts,
}
}
}
// /// `GET /_matrix/client/*/keys/changes`
// ///
// /// Gets a list of users who have updated their device identity keys since a
// /// previous sync token. `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3keyschanges
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/keys/changes",
// 1.1 => "/_matrix/client/v3/keys/changes",
// }
// };
/// Request type for the `get_key_changes` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct KeyChangesReqArgs {
/// The desired start point of the list.
///
/// Should be the next_batch field from a response to an earlier call to
/// /sync.
#[salvo(parameter(parameter_in = Query))]
pub from: String,
/// The desired end point of the list.
///
/// Should be the next_batch field from a recent call to /sync - typically
/// the most recent such call.
#[salvo(parameter(parameter_in = Query))]
pub to: String,
}
/// Response type for the `get_key_changes` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct KeyChangesResBody {
/// The Matrix User IDs of all users who updated their device identity keys.
pub changed: Vec<OwnedUserId>,
/// The Matrix User IDs of all users who may have left all the end-to-end
/// encrypted rooms they previously shared with the user.
pub left: Vec<OwnedUserId>,
}
impl KeyChangesResBody {
/// Creates a new `Response` with the given changed and left user ID lists.
pub fn new(changed: Vec<OwnedUserId>, left: Vec<OwnedUserId>) -> Self {
Self { changed, left }
}
}
// /// `POST /_matrix/client/*/keys/device_signing/upload`
// ///
// /// Publishes cross signing keys for the user.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3keysdevice_signingupload
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/client/unstable/keys/device_signing/upload",
// 1.1 => "/_matrix/client/v3/keys/device_signing/upload",
// }
// };
/// Request type for the `upload_signing_keys` endpoint.
#[derive(ToSchema, Deserialize, Clone, Debug)]
pub struct UploadSigningKeysReqBody {
/// Additional authentication information for the user-interactive
/// authentication API.
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "crate::serde::empty_as_none"
)]
pub auth: Option<AuthData>,
/// The user's master key.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub master_key: Option<CrossSigningKey>,
/// The user's self-signing key.
///
/// Must be signed with the accompanied master, or by the user's most
/// recently uploaded master key if no master key is included in the
/// request.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub self_signing_key: Option<CrossSigningKey>,
/// The user's user-signing key.
///
/// Must be signed with the accompanied master, or by the user's most
/// recently uploaded master key if no master key is included in the
/// request.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub user_signing_key: Option<CrossSigningKey>,
}
// /// `POST /_matrix/client/*/keys/signatures/upload`
// ///
// /// Publishes cross-signing signatures for the user.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3keyssignaturesupload
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/client/unstable/keys/signatures/upload",
// 1.1 => "/_matrix/client/v3/keys/signatures/upload",
// }
// };
/// Request type for the `upload_signatures` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct UploadSignaturesReqBody(pub BTreeMap<OwnedUserId, SignedKeys>);
impl Deref for UploadSignaturesReqBody {
type Target = BTreeMap<OwnedUserId, SignedKeys>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
/// Response type for the `upload_signatures` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct UploadSignaturesResBody {
/// Signature processing failures.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub failures: BTreeMap<OwnedUserId, BTreeMap<String, Failure>>,
}
impl UploadSignaturesResBody {
/// Creates an empty `Response`.
pub fn new(failures: BTreeMap<OwnedUserId, BTreeMap<String, Failure>>) -> Self {
Self { failures }
}
}
/// A map of key IDs to signed key objects.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(transparent)]
pub struct SignedKeys(BTreeMap<Box<str>, Box<RawJsonValue>>);
impl SignedKeys {
/// Creates an empty `SignedKeys` map.
pub fn new() -> Self {
Self::default()
}
/// Add the given device keys.
pub fn add_device_keys(&mut self, device_id: OwnedDeviceId, device_keys: RawJson<DeviceKeys>) {
self.0
.insert(device_id.as_str().into(), device_keys.into_inner());
}
/// Add the given cross signing keys.
pub fn add_cross_signing_keys(
&mut self,
cross_signing_key_id: Box<str>,
cross_signing_keys: RawJson<CrossSigningKey>,
) {
self.0
.insert(cross_signing_key_id, cross_signing_keys.into_inner());
}
/// Returns an iterator over the keys.
pub fn iter(&self) -> SignedKeysIter<'_> {
SignedKeysIter(self.0.iter())
}
}
/// A failure to process a signed key.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct Failure {
/// Machine-readable error code.
errcode: FailureErrorCode,
/// Human-readable error message.
error: String,
}
/// Error code for signed key processing failures.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[non_exhaustive]
#[palpo_enum(rename_all(prefix = "M_", rule = "SCREAMING_SNAKE_CASE"))]
pub enum FailureErrorCode {
/// The signature is invalid.
InvalidSignature,
#[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/client/register.rs | crates/core/src/client/register.rs | //! `POST /_matrix/client/*/register`
//!
//! Register an account on this homeserver.
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3register
use std::time::Duration;
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{
OwnedClientSecret, OwnedDeviceId, OwnedSessionId, OwnedUserId,
client::{
account::{LoginType, RegistrationKind},
uiaa::AuthData,
},
};
/// Request type for the `register` endpoint.
#[derive(ToSchema, Deserialize, Default, Debug)]
pub struct RegisterReqBody {
/// The desired password for the account.
///
/// May be empty for accounts that should not be able to log in again
/// with a password, e.g., for guest or application service accounts.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub password: Option<String>,
/// Localpart of the desired Matrix ID.
///
/// If omitted, the homeserver MUST generate a Matrix ID local part.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub username: Option<String>,
/// ID of the client device.
///
/// If this does not correspond to a known client device, a new device will
/// be created. The server will auto-generate a device_id if this is not
/// specified.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub device_id: Option<OwnedDeviceId>,
/// A display name to assign to the newly-created device.
///
/// Ignored if `device_id` corresponds to a known device.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub initial_device_display_name: Option<String>,
/// Additional authentication information for the user-interactive
/// authentication API.
///
/// Note that this information is not used to define how the registered user
/// should be authenticated, but is instead used to authenticate the
/// register call itself. It should be left empty, or omitted, unless an
/// earlier call returned an response with status code 401.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auth: Option<AuthData>,
/// Kind of account to register
///
/// Defaults to `User` if omitted.
#[salvo(parameter(parameter_in = Query))]
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub kind: RegistrationKind,
/// If `true`, an `access_token` and `device_id` should not be returned
/// from this call, therefore preventing an automatic login.
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub inhibit_login: bool,
/// Login `type` used by Appservices.
///
/// Appservices can [bypass the registration flows][admin] entirely by
/// providing their token in the header and setting this login `type` to
/// `m.login.application_service`.
///
/// [admin]: https://spec.matrix.org/latest/application-service-api/#server-admin-style-permissions
#[serde(default, rename = "type", skip_serializing_if = "Option::is_none")]
pub login_type: Option<LoginType>,
/// If set to `true`, the client supports [refresh tokens].
///
/// [refresh tokens]: https://spec.matrix.org/latest/client-server-api/#refreshing-access-tokens
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub refresh_token: bool,
}
impl RegisterReqBody {
pub fn is_default(&self) -> bool {
self.password.is_none()
&& self.username.is_none()
&& self.device_id.is_none()
&& self.initial_device_display_name.is_none()
&& self.auth.is_none()
&& self.kind == Default::default()
&& !self.inhibit_login
&& self.login_type.is_none()
&& !self.refresh_token
}
}
/// Response type for the `register` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct RegisterResBody {
/// An access token for the account.
///
/// This access token can then be used to authorize other requests.
///
/// Required if the request's `inhibit_login` was set to `false`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub access_token: Option<String>,
/// The fully-qualified Matrix ID that has been registered.
pub user_id: OwnedUserId,
/// ID of the registered device.
///
/// Will be the same as the corresponding parameter in the request, if one
/// was specified.
///
/// Required if the request's `inhibit_login` was set to `false`.
pub device_id: Option<OwnedDeviceId>,
/// A [refresh token] for the account.
///
/// This token can be used to obtain a new access token when it expires by
/// calling the [`refresh_token`] endpoint.
///
/// Omitted if the request's `inhibit_login` was set to `true`.
///
/// [refresh token]: https://spec.matrix.org/latest/client-server-api/#refreshing-access-tokens
/// [`refresh_token`]: crate::session::refresh_token
#[serde(default, skip_serializing_if = "Option::is_none")]
pub refresh_token: Option<String>,
/// The lifetime of the access token, in milliseconds.
///
/// Once the access token has expired, a new access token can be obtained by
/// using the provided refresh token. If no refresh token is provided,
/// the client will need to re-login to obtain a new access token.
///
/// If this is `None`, the client can assume that the access token will not
/// expire.
///
/// Omitted if the request's `inhibit_login` was set to `true`.
#[serde(
with = "palpo_core::serde::duration::opt_ms",
default,
skip_serializing_if = "Option::is_none",
rename = "expires_in_ms"
)]
pub expires_in: Option<Duration>,
}
// /// `GET /_matrix/client/*/register/available`
// /// 1.0 => "/_matrix/client/r0/register/available",
// /// 1.1 => "/_matrix/client/v3/register/available",
// ///
// /// Checks to see if a username is available, and valid, for the server.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3registeravailable
/// Response type for the `get_username_availability` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct AvailableResBody {
/// A flag to indicate that the username is available.
/// This should always be true when the server replies with 200 OK.
pub available: bool,
}
impl AvailableResBody {
/// Creates a new `AvailableResBody` with the given availability.
pub fn new(available: bool) -> Self {
Self { available }
}
}
// /// `GET /_matrix/client/*/register/m.login.registration_token/validity`
// ///
// /// Checks to see if the given registration token is valid.
// /// `/v1/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv1registermloginregistration_tokenvalidity
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: true,
// authentication: None,
// history: {
// unstable =>
// "/_matrix/client/unstable/org.matrix.msc3231/register/org.matrix.msc3231.login.registration_token/validity",
// 1.2 => "/_matrix/client/v1/register/m.login.registration_token/validity",
// }
// };
/// Request type for the `check_registration_token_validity` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct ValidateTokenReqBody {
/// The registration token to check the validity of.
pub registration_token: String,
}
/// Response type for the `check_registration_token_validity` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct ValidateTokenResBody {
/// A flag to indicate that the registration token is valid.
pub valid: bool,
}
// `POST /_matrix/client/*/register/email/requestToken`
// /// Request a registration token with a 3rd party email.
// ///
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3registeremailrequesttoken
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: false,
// authentication: None,
// history: {
// 1.0 => "/_matrix/client/r0/register/email/requestToken",
// 1.1 => "/_matrix/client/v3/register/email/requestToken",
// }
// };
/// Request type for the `request_registration_token_via_email` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct TokenVisEmailReqBody {
/// Client-generated secret string used to protect this session.
pub client_secret: OwnedClientSecret,
/// The email address.
pub email: String,
/// Used to distinguish protocol level retries from requests to re-send the
/// email.
pub send_attempt: u64,
/// Return URL for identity server to redirect the client back to.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
/// Response type for the `request_registration_token_via_email` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct TokenVisEmailResBody {
/// The session identifier given by the identity server.
pub sid: OwnedSessionId,
/// URL to submit validation token to.
///
/// If omitted, verification happens without client.
#[serde(
skip_serializing_if = "Option::is_none",
default,
deserialize_with = "crate::serde::empty_string_as_none"
)]
pub submit_url: Option<String>,
}
// /// `POST /_matrix/client/*/register/msisdn/requestToken`
// ///
// /// Request a registration token with a phone number.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3registermsisdnrequesttoken
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: false,
// authentication: None,
// history: {
// 1.0 => "/_matrix/client/r0/register/msisdn/requestToken",
// 1.1 => "/_matrix/client/v3/register/msisdn/requestToken",
// }
// };
/// Request type for the `request_registration_token_via_msisdn` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct TokenVisMsisdnReqBody {
/// Client-generated secret string used to protect this session.
pub client_secret: OwnedClientSecret,
/// Two-letter ISO 3166 country code for the phone number.
pub country: String,
/// Phone number to validate.
pub phone_number: String,
/// Used to distinguish protocol level retries from requests to re-send the
/// SMS.
pub send_attempt: u64,
/// Return URL for identity server to redirect the client back to.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
/// Response type for the `request_registration_token_via_msisdn` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct TokenVisMsisdnResBody {
/// The session identifier given by the identity server.
pub sid: OwnedSessionId,
/// URL to submit validation token to.
///
/// If omitted, verification happens without client.
#[serde(
skip_serializing_if = "Option::is_none",
default,
deserialize_with = "crate::serde::empty_string_as_none"
)]
pub submit_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/client/device.rs | crates/core/src/client/device.rs | use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use crate::client::uiaa::AuthData;
/// Endpoints for managing devices.
use crate::{OwnedDeviceId, UnixMillis};
/// Information about a registered device.
#[derive(ToSchema, Clone, Debug, Deserialize, Hash, Serialize)]
pub struct Device {
/// Device ID
pub device_id: OwnedDeviceId,
/// Public display name of the device.
pub display_name: Option<String>,
/// Most recently seen IP address of the session.
pub last_seen_ip: Option<String>,
/// Unix timestamp that the session was last active.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_seen_ts: Option<UnixMillis>,
}
impl Device {
/// Creates a new `Device` with the given device ID.
pub fn new(device_id: OwnedDeviceId) -> Self {
Self {
device_id,
display_name: None,
last_seen_ip: None,
last_seen_ts: None,
}
}
}
// /// `DELETE /_matrix/client/*/devices/{deviceId}`
// ///
// /// Delete a device for authenticated user.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#delete_matrixclientv3devicesdeviceid
// const METADATA: Metadata = metadata! {
// method: DELETE,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/devices/:device_id",
// 1.1 => "/_matrix/client/v3/devices/:device_id",
// }
// };
/// Request type for the `delete_device` endpoint.
#[derive(ToSchema, Deserialize, Default, Debug)]
pub struct DeleteDeviceReqBody {
/// Additional authentication information for the user-interactive
/// authentication API.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auth: Option<AuthData>,
}
// /// `POST /_matrix/client/*/delete_devices`
// ///
// /// Delete specified devices.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3delete_devices
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/delete_devices",
// 1.1 => "/_matrix/client/v3/delete_devices",
// }
// };
/// Request type for the `delete_devices` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct DeleteDevicesReqBody {
/// List of devices to delete.
pub devices: Vec<OwnedDeviceId>,
/// Additional authentication information for the user-interactive
/// authentication API.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auth: Option<AuthData>,
}
// /// `GET /_matrix/client/*/devices/{deviceId}`
// ///
// /// Get a device for authenticated user.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3devicesdeviceid
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/devices/:device_id",
// 1.1 => "/_matrix/client/v3/devices/:device_id",
// }
// };
// /// Request type for the `get_device` endpoint.
// pub struct Rexquest {
// /// The device to retrieve.
// #[salvo(parameter(parameter_in = Path))]
// pub device_id: OwnedDeviceId,
// }
/// Response type for the `get_device` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct DeviceResBody(pub Device);
impl DeviceResBody {
/// Creates a new `Response` with the given device.
pub fn new(device: Device) -> Self {
Self(device)
}
}
// /// `GET /_matrix/client/*/devices`
// ///
// /// Get registered devices for authenticated user.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3devices
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/devices",
// 1.1 => "/_matrix/client/v3/devices",
// }
// };
/// Response type for the `get_devices` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct DevicesResBody {
/// A list of all registered devices for this user
pub devices: Vec<Device>,
}
// impl Response {
// /// Creates a new `Response` with the given devices.
// pub fn new(devices: Vec<Device>) -> Self {
// Self { devices }
// }
// }
// /// `PUT /_matrix/client/*/devices/{deviceId}`
// ///
/// Update metadata for a device, or create a new device.
///
/// Only application services can use this endpoint to create new devices.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#put_matrixclientv3devicesdeviceid
// const METADATA: Metadata = metadata! {
// method: PUT,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/devices/:device_id",
// 1.1 => "/_matrix/client/v3/devices/:device_id",
// }
// };
/// Request type for the `update_device` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct UpdatedDeviceReqBody {
/// The new display name for this device.
///
/// If this is `None`, the display name won't be changed.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display_name: 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/client/presence.rs | crates/core/src/client/presence.rs | /// `PUT /_matrix/client/*/presence/{user_id}/status`
///
/// Set presence status for this user.
/// `/v3/` ([spec])
///
/// [spec]: https://spec.matrix.org/latest/client-server-api/#put_matrixclientv3presenceuser_idstatus
use std::time::Duration;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::presence::PresenceState;
// const METADATA: Metadata = metadata! {
// method: PUT,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/presence/:user_id/status",
// 1.1 => "/_matrix/client/v3/presence/:user_id/status",
// }
// };
/// Request type for the `set_presence` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct SetPresenceReqBody {
// /// The user whose presence state will be updated.
// #[salvo(parameter(parameter_in = Path))]
// pub user_id: OwnedUserId,
/// The new presence state.
pub presence: PresenceState,
/// The status message to attach to this state.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status_msg: Option<String>,
}
// /// `GET /_matrix/client/*/presence/{user_id}/status`
// ///
// /// Get presence status for this user.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3presenceuser_idstatus
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/presence/:user_id/status",
// 1.1 => "/_matrix/client/v3/presence/:user_id/status",
// }
// };
// /// Request type for the `get_presence` endpoint.
// pub struct Reqxuest {
// /// The user whose presence state will be retrieved.
// #[salvo(parameter(parameter_in = Path))]
// pub user_id: OwnedUserId,
// }
/// Response type for the `get_presence` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct PresenceResBody {
/// The state message for this user if one was set.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status_msg: Option<String>,
/// Whether or not the user is currently active.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub currently_active: Option<bool>,
/// The length of time in milliseconds since an action was performed by the
/// user.
#[serde(
with = "crate::serde::duration::opt_ms",
default,
skip_serializing_if = "Option::is_none"
)]
pub last_active_ago: Option<Duration>,
/// The user's presence state.
pub presence: PresenceState,
}
impl PresenceResBody {
/// Creates a new `Response` with the given presence state.
pub fn new(presence: PresenceState) -> Self {
Self {
presence,
status_msg: None,
currently_active: None,
last_active_ago: 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/client/push.rs | crates/core/src/client/push.rs | //! Endpoints for push notifications.
mod notification;
mod push_rule;
mod pusher;
pub use notification::*;
pub use push_rule::*;
pub use pusher::*;
| 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/client/session.rs | crates/core/src/client/session.rs | use std::{borrow::Cow, fmt, time::Duration};
use salvo::prelude::*;
use serde::{
Deserialize, Deserializer, Serialize,
de::{self, DeserializeOwned},
};
use serde_json::Value as JsonValue;
use crate::{
OwnedDeviceId, OwnedMxcUri, OwnedUserId, PrivOwnedStr,
client::uiaa::{AuthData, UserIdentifier},
serde::{JsonObject, StringEnum},
};
// /// `POST /_matrix/client/*/refresh`
// ///
// /// Refresh an access token.
// ///
// /// Clients should use the returned access token when making subsequent API
// /// calls, and store the returned refresh token (if given) in order to refresh
// /// the new access token when necessary.
// ///
// /// After an access token has been refreshed, a server can choose to invalidate
// /// the old access token immediately, or can choose not to, for example if the
// /// access token would expire soon anyways. Clients should not make any
// /// assumptions about the old access token still being valid, and should use the
// /// newly provided access token instead.
// ///
// /// The old refresh token remains valid until the new access token or refresh
// /// token is used, at which point the old refresh token is revoked.
// ///
// /// Note that this endpoint does not require authentication via an access token.
// /// Authentication is provided via the refresh token.
// ///
// /// Application Service identity assertion is disabled for this endpoint.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3refresh
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: true,
// authentication: None,
// history: {
// unstable => "/_matrix/client/unstable/org.matrix.msc2918/refresh",
// 1.3 => "/_matrix/client/v3/refresh",
// }
// };
/// Request type for the `refresh` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct RefreshTokenReqBody {
/// The refresh token.
pub refresh_token: String,
}
/// Response type for the `refresh` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct RefreshTokenResBody {
/// The new access token to use.
pub access_token: String,
/// The new refresh token to use when the access token needs to be refreshed
/// again.
///
/// If this is `None`, the old refresh token can be re-used.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub refresh_token: Option<String>,
/// The lifetime of the access token, in milliseconds.
///
/// If this is `None`, the client can assume that the access token will not
/// expire.
#[serde(
with = "crate::serde::duration::opt_ms",
default,
skip_serializing_if = "Option::is_none"
)]
pub expires_in_ms: Option<Duration>,
}
impl RefreshTokenResBody {
/// Creates a new `Response` with the given access token.
pub fn new(access_token: String) -> Self {
Self {
access_token,
refresh_token: None,
expires_in_ms: None,
}
}
}
// /// `POST /_matrix/client/*/login`
// ///
// /// Login to the homeserver.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3login
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: true,
// authentication: None,
// history: {
// 1.0 => "/_matrix/client/r0/login",
// 1.1 => "/_matrix/client/v3/login",
// }
// };
/// Request type for the `login` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct LoginReqBody {
/// The authentication mechanism.
#[serde(flatten)]
pub login_info: LoginInfo,
/// ID of the client device
#[serde(default, skip_serializing_if = "Option::is_none")]
pub device_id: Option<OwnedDeviceId>,
/// A display name to assign to the newly-created device.
///
/// Ignored if `device_id` corresponds to a known device.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub initial_device_display_name: Option<String>,
/// If set to `true`, the client supports [refresh tokens].
///
/// [refresh tokens]: https://spec.matrix.org/latest/client-server-api/#refreshing-access-tokens
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub refresh_token: bool,
}
/// Response type for the `login` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct LoginResBody {
/// The fully-qualified Matrix ID that has been registered.
pub user_id: OwnedUserId,
/// An access token for the account.
pub access_token: String,
/// ID of the logged-in device.
///
/// Will be the same as the corresponding parameter in the request, if one
/// was specified.
pub device_id: OwnedDeviceId,
/// Client configuration provided by the server.
///
/// If present, clients SHOULD use the provided object to reconfigure
/// themselves.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub well_known: Option<DiscoveryInfo>,
/// A [refresh token] for the account.
///
/// This token can be used to obtain a new access token when it expires by
/// calling the [`refresh_token`] endpoint.
///
/// [refresh token]: https://spec.matrix.org/latest/client-server-api/#refreshing-access-tokens
/// [`refresh_token`]: crate::session::refresh_token
#[serde(default, skip_serializing_if = "Option::is_none")]
pub refresh_token: Option<String>,
/// The lifetime of the access token, in milliseconds.
///
/// Once the access token has expired, a new access token can be obtained by
/// using the provided refresh token. If no refresh token is provided,
/// the client will need to re-login to obtain a new access token.
///
/// If this is `None`, the client can assume that the access token will not
/// expire.
#[serde(
with = "crate::serde::duration::opt_ms",
default,
skip_serializing_if = "Option::is_none",
rename = "expires_in_ms"
)]
pub expires_in: Option<Duration>,
}
impl LoginResBody {
/// Creates a new `Response` with the given user ID, access token and device
/// ID.
pub fn new(user_id: OwnedUserId, access_token: String, device_id: OwnedDeviceId) -> Self {
Self {
user_id,
access_token,
device_id,
well_known: None,
refresh_token: None,
expires_in: None,
}
}
}
/// The authentication mechanism.
#[derive(ToSchema, Clone, Serialize)]
#[serde(untagged)]
pub enum LoginInfo {
/// An identifier and password are supplied to authenticate.
Password(Password),
/// Token-based login.
Token(Token),
/// JSON Web Token
Jwt(Token),
/// Application Service-specific login.
Appservice(Appservice),
#[doc(hidden)]
_Custom(CustomLoginInfo),
}
impl LoginInfo {
/// Creates a new `IncomingLoginInfo` with the given `login_type` string,
/// session and data.
///
/// Prefer to use the public variants of `IncomingLoginInfo` where possible;
/// this constructor is meant be used for unsupported authentication
/// mechanisms only and does not allow setting arbitrary data for
/// supported ones.
///
/// # Errors
///
/// Returns an error if the `login_type` is known and serialization of
/// `data` to the corresponding `IncomingLoginInfo` variant fails.
pub fn new(login_type: &str, data: JsonObject) -> serde_json::Result<Self> {
Ok(match login_type {
"m.login.password" => Self::Password(serde_json::from_value(JsonValue::Object(data))?),
"m.login.token" => Self::Token(serde_json::from_value(JsonValue::Object(data))?),
"m.login.application_service" => {
Self::Appservice(serde_json::from_value(JsonValue::Object(data))?)
}
_ => Self::_Custom(CustomLoginInfo {
login_type: login_type.into(),
extra: data,
}),
})
}
}
impl fmt::Debug for LoginInfo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// Print `Password { .. }` instead of `Password(Password { .. })`
match self {
Self::Password(inner) => inner.fmt(f),
Self::Token(inner) => inner.fmt(f),
Self::Jwt(inner) => inner.fmt(f),
Self::Appservice(inner) => inner.fmt(f),
Self::_Custom(inner) => inner.fmt(f),
}
}
}
impl<'de> Deserialize<'de> for LoginInfo {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
fn from_json_value<T: DeserializeOwned, E: de::Error>(val: JsonValue) -> Result<T, E> {
serde_json::from_value(val).map_err(E::custom)
}
// FIXME: Would be better to use serde_json::value::RawValue, but that would
// require implementing Deserialize manually for Request, bc.
// `#[serde(flatten)]` breaks things.
let json = JsonValue::deserialize(deserializer)?;
let login_type = json["type"]
.as_str()
.ok_or_else(|| de::Error::missing_field("type"))?;
match login_type {
"m.login.password" => from_json_value(json).map(Self::Password),
"m.login.token" => from_json_value(json).map(Self::Token),
"org.matrix.login.jwt" => from_json_value(json).map(Self::Jwt),
"m.login.application_service" => from_json_value(json).map(Self::Appservice),
_ => from_json_value(json).map(Self::_Custom),
}
}
}
/// An identifier and password to supply as authentication.
#[derive(ToSchema, Clone, Deserialize, Serialize)]
#[serde(tag = "type", rename = "m.login.password")]
pub struct Password {
/// Identification information for the user.
pub identifier: UserIdentifier,
/// The password.
pub password: String,
}
impl Password {
/// Creates a new `Password` with the given identifier and password.
pub fn new(identifier: UserIdentifier, password: String) -> Self {
Self {
identifier,
password,
}
}
}
impl fmt::Debug for Password {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self {
identifier,
password: _,
} = self;
f.debug_struct("Password")
.field("identifier", identifier)
.finish_non_exhaustive()
}
}
/// A token to supply as authentication.
#[derive(ToSchema, Clone, Deserialize, Serialize)]
#[serde(tag = "type", rename = "m.login.token")]
pub struct Token {
/// The token.
pub token: String,
}
impl Token {
/// Creates a new `Token` with the given token.
pub fn new(token: String) -> Self {
Self { token }
}
}
impl fmt::Debug for Token {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self { token: _ } = self;
f.debug_struct("Token").finish_non_exhaustive()
}
}
/// An identifier to supply for Application Service authentication.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[serde(tag = "type", rename = "m.login.application_service")]
pub struct Appservice {
/// Identification information for the user.
pub identifier: UserIdentifier,
}
impl Appservice {
/// Creates a new `Appservice` with the given identifier.
pub fn new(identifier: UserIdentifier) -> Self {
Self { identifier }
}
}
#[doc(hidden)]
#[derive(ToSchema, Clone, Deserialize, Serialize)]
#[non_exhaustive]
pub struct CustomLoginInfo {
#[serde(rename = "type")]
login_type: String,
#[serde(flatten)]
#[salvo(schema(value_type = Object, additional_properties = true))]
extra: JsonObject,
}
impl fmt::Debug for CustomLoginInfo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self {
login_type,
extra: _,
} = self;
f.debug_struct("CustomLoginInfo")
.field("login_type", login_type)
.finish_non_exhaustive()
}
}
/// Client configuration provided by the server.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct DiscoveryInfo {
/// Information about the homeserver to connect to.
#[serde(rename = "m.homeserver")]
pub homeserver: HomeServerInfo,
/// Information about the identity server to connect to.
#[serde(default, rename = "m.identity_server")]
pub identity_server: Option<IdentityServerInfo>,
}
impl DiscoveryInfo {
/// Create a new `DiscoveryInfo` with the given homeserver.
pub fn new(homeserver: HomeServerInfo) -> Self {
Self {
homeserver,
identity_server: None,
}
}
}
/// Information about the homeserver to connect to.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct HomeServerInfo {
/// The base URL for the homeserver for client-server connections.
pub base_url: String,
}
impl HomeServerInfo {
/// Create a new `HomeServerInfo` with the given base url.
pub fn new(base_url: String) -> Self {
Self { base_url }
}
}
/// Information about the identity server to connect to.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct IdentityServerInfo {
/// The base URL for the identity server for client-server connections.
pub base_url: String,
}
impl IdentityServerInfo {
/// Create a new `IdentityServerInfo` with the given base url.
pub fn new(base_url: String) -> Self {
Self { base_url }
}
}
// /// `GET /_matrix/client/*/login`
// ///
// /// Gets the homeserver's supported login types to authenticate users. Clients
// /// should pick one of these and supply it as the type when logging in.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3login
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: true,
// authentication: None,
// history: {
// 1.0 => "/_matrix/client/r0/login",
// 1.1 => "/_matrix/client/v3/login",
// }
// };
/// Response type for the `get_login_types` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct LoginTypesResBody {
/// The homeserver's supported login types.
pub flows: Vec<LoginType>,
}
impl LoginTypesResBody {
/// Creates a new `Response` with the given login types.
pub fn new(flows: Vec<LoginType>) -> Self {
Self { flows }
}
}
/// An authentication mechanism.
#[derive(ToSchema, Clone, Debug, Serialize)]
#[serde(untagged)]
pub enum LoginType {
/// A password is supplied to authenticate.
Password(PasswordLoginType),
/// Token-based login.
Token(TokenLoginType),
/// JSON Web Token type.
Jwt(JwtLoginType),
/// SSO-based login.
Sso(SsoLoginType),
/// Appsrvice login.
Appservice(AppserviceLoginType),
/// Custom login type.
#[doc(hidden)]
_Custom(Box<CustomLoginType>),
}
impl LoginType {
pub fn password() -> Self {
Self::Password(PasswordLoginType::new())
}
pub fn appservice() -> Self {
Self::Appservice(AppserviceLoginType::new())
}
pub fn jwt() -> Self {
Self::Jwt(JwtLoginType::new())
}
/// Creates a new `LoginType` with the given `login_type` string and data.
///
/// Prefer to use the public variants of `LoginType` where possible; this
/// constructor is meant be used for unsupported login types only and
/// does not allow setting arbitrary data for supported ones.
pub fn new(login_type: &str, data: JsonObject) -> serde_json::Result<Self> {
fn from_json_object<T: DeserializeOwned>(obj: JsonObject) -> serde_json::Result<T> {
serde_json::from_value(JsonValue::Object(obj))
}
Ok(match login_type {
"m.login.password" => Self::Password(from_json_object(data)?),
"m.login.token" => Self::Token(from_json_object(data)?),
"org.matrix.login.jwt" => Self::Jwt(from_json_object(data)?),
"m.login.sso" => Self::Sso(from_json_object(data)?),
"m.login.application_service" => Self::Appservice(from_json_object(data)?),
_ => Self::_Custom(Box::new(CustomLoginType {
type_: login_type.to_owned(),
data,
})),
})
}
/// Returns a reference to the `login_type` string.
pub fn login_type(&self) -> &str {
match self {
Self::Password(_) => "m.login.password",
Self::Token(_) => "m.login.token",
Self::Jwt(_) => "org.matrix.login.jwt",
Self::Sso(_) => "m.login.sso",
Self::Appservice(_) => "m.login.application_service",
Self::_Custom(c) => &c.type_,
}
}
/// Returns the associated data.
///
/// Prefer to use the public variants of `LoginType` where possible; this
/// method is meant to be used for unsupported login types only.
pub fn data(&self) -> Cow<'_, JsonObject> {
fn serialize<T: Serialize>(obj: &T) -> JsonObject {
match serde_json::to_value(obj).expect("login type serialization to succeed") {
JsonValue::Object(obj) => obj,
_ => panic!("all login types must serialize to objects"),
}
}
match self {
Self::Password(d) => Cow::Owned(serialize(d)),
Self::Token(d) => Cow::Owned(serialize(d)),
Self::Jwt(d) => Cow::Owned(serialize(d)),
Self::Sso(d) => Cow::Owned(serialize(d)),
Self::Appservice(d) => Cow::Owned(serialize(d)),
Self::_Custom(c) => Cow::Borrowed(&c.data),
}
}
}
/// The payload for password login.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
#[serde(tag = "type", rename = "m.login.password")]
pub struct PasswordLoginType {}
impl PasswordLoginType {
/// Creates a new `PasswordLoginType`.
pub fn new() -> Self {
Self {}
}
}
/// The payload for token-based login.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
#[serde(tag = "type", rename = "m.login.token")]
pub struct TokenLoginType {
/// Whether the homeserver supports the `POST /login/get_token` endpoint.
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub get_login_token: bool,
}
impl TokenLoginType {
/// Creates a new `TokenLoginType`.
pub fn new() -> Self {
Self {
get_login_token: false,
}
}
}
/// The payload for JWT-based login.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
#[serde(tag = "type", rename = "org.matrix.login.jwt")]
pub struct JwtLoginType {}
impl JwtLoginType {
/// Creates a new `JwtLoginType`.
pub fn new() -> Self {
Self {}
}
}
/// The payload for SSO login.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
#[serde(tag = "type", rename = "m.login.sso")]
pub struct SsoLoginType {
/// The identity provider choices.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub identity_providers: Vec<IdentityProvider>,
}
impl SsoLoginType {
/// Creates a new `SsoLoginType`.
pub fn new() -> Self {
Self::default()
}
}
/// An SSO login identity provider.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct IdentityProvider {
/// The ID of the provider.
pub id: String,
/// The display name of the provider.
pub name: String,
/// The icon for the provider.
pub icon: Option<OwnedMxcUri>,
/// The brand identifier for the provider.
pub brand: Option<IdentityProviderBrand>,
}
impl IdentityProvider {
/// Creates an `IdentityProvider` with the given `id` and `name`.
pub fn new(id: String, name: String) -> Self {
Self {
id,
name,
icon: None,
brand: None,
}
}
}
/// An SSO login identity provider brand identifier.
///
/// The predefined ones can be found in the matrix-spec-proposals repo in a
/// [separate document][matrix-spec-proposals].
///
/// [matrix-spec-proposals]: https://github.com/matrix-org/matrix-spec-proposals/blob/v1.1/informal/idp-brands.md
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
pub enum IdentityProviderBrand {
/// The [Apple] brand.
///
/// [Apple]: https://developer.apple.com/design/human-interface-guidelines/sign-in-with-apple/overview/buttons/
#[palpo_enum(rename = "apple")]
Apple,
/// The [Facebook](https://developers.facebook.com/docs/facebook-login/web/login-button/) brand.
#[palpo_enum(rename = "facebook")]
Facebook,
/// The [GitHub](https://github.com/logos) brand.
#[palpo_enum(rename = "github")]
GitHub,
/// The [GitLab](https://about.gitlab.com/press/press-kit/) brand.
#[palpo_enum(rename = "gitlab")]
GitLab,
/// The [Google](https://developers.google.com/identity/branding-guidelines) brand.
#[palpo_enum(rename = "google")]
Google,
/// The [Twitter] brand.
///
/// [Twitter]: https://developer.twitter.com/en/docs/authentication/guides/log-in-with-twitter#tab1
#[palpo_enum(rename = "twitter")]
Twitter,
/// A custom brand.
#[doc(hidden)]
#[salvo(schema(value_type = String))]
_Custom(PrivOwnedStr),
}
/// The payload for Application Service login.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
#[serde(tag = "type", rename = "m.login.application_service")]
pub struct AppserviceLoginType {}
impl AppserviceLoginType {
/// Creates a new `AppserviceLoginType`.
pub fn new() -> Self {
Self::default()
}
}
/// A custom login payload.
#[doc(hidden)]
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[allow(clippy::exhaustive_structs)]
pub struct CustomLoginType {
/// A custom type
///
/// This field is named `type_` instead of `type` because the latter is a
/// reserved keyword in Rust.
#[serde(rename = "type")]
pub type_: String,
/// Remaining type content
#[serde(flatten)]
#[salvo(schema(value_type = Object, additional_properties = true))]
pub data: JsonObject,
}
// /// `GET /_matrix/client/*/login/get_token`
// ///
// /// Generate a single-use, time-limited, `m.login.token` token.
// /// `/v1/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv1loginget_token
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/client/unstable/org.matrix.msc3882/login/get_token",
// 1.7 => "/_matrix/client/v1/login/get_token",
// }
// };
/// Request type for the `login` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct TokenReqBody {
/// Additional authentication information for the user-interactive
/// authentication API.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auth: Option<AuthData>,
}
/// Response type for the `login` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct TokenResBody {
/// The time remaining in milliseconds until the homeserver will no longer
/// accept the token.
///
/// 2 minutes is recommended as a default.
#[serde(with = "crate::serde::duration::ms", rename = "expires_in_ms")]
pub expires_in: Duration,
/// The login token for the `m.login.token` login flow.
pub login_token: String,
}
impl TokenResBody {
/// Creates a new `Response` with the given expiration duration and login
/// token.
pub fn new(expires_in: Duration, login_token: String) -> Self {
Self {
expires_in,
login_token,
}
}
/// Creates a new `Response` with the default expiration duration and the
/// given login token.
pub fn with_default_expiration_duration(login_token: String) -> Self {
Self::new(Self::default_expiration_duration(), login_token)
}
fn default_expiration_duration() -> Duration {
// 2 minutes.
Duration::from_secs(2 * 60)
}
}
// #[cfg(test)]
// mod tests {
// use assert_matches2::assert_matches;
// use super::{LoginInfo, Token};
// use crate::uiaa::UserIdentifier;
// use assert_matches2::assert_matches;
// use serde::{Deserialize, Serialize};
// use serde_json::{from_value as from_json_value, json, to_value as
// to_json_value, Value as JsonValue};
// use super::{IdentityProvider, IdentityProviderBrand, LoginType,
// SsoLoginType, TokenLoginType};
// #[derive(Debug, Deserialize, Serialize)]
// struct Wrapper {
// flows: Vec<LoginType>,
// }
// #[test]
// fn deserialize_password_login_type() {
// let wrapper = from_json_value::<Wrapper>(json!({
// "flows": [
// { "type": "m.login.password" }
// ],
// }))
// .unwrap();
// assert_eq!(wrapper.flows.len(), 1);
// assert_matches!(&wrapper.flows[0], LoginType::Password(_));
// }
// #[test]
// fn deserialize_custom_login_type() {
// let wrapper = from_json_value::<Wrapper>(json!({
// "flows": [
// {
// "type": "io.palpo.custom",
// "color": "green",
// }
// ],
// }))
// .unwrap();
// assert_eq!(wrapper.flows.len(), 1);
// assert_matches!(&wrapper.flows[0], LoginType::_Custom(custom));
// assert_eq!(custom.type_, "io.palpo.custom");
// assert_eq!(custom.data.len(), 1);
// assert_eq!(custom.data.get("color"),
// Some(&JsonValue::from("green"))); }
// #[test]
// fn deserialize_sso_login_type() {
// let wrapper = from_json_value::<Wrapper>(json!({
// "flows": [
// {
// "type": "m.login.sso",
// "identity_providers": [
// {
// "id": "oidc-gitlab",
// "name": "GitLab",
// "icon": "mxc://localhost/gitlab-icon",
// "brand": "gitlab"
// },
// {
// "id": "custom",
// "name": "Custom",
// }
// ]
// }
// ],
// }))
// .unwrap();
// assert_eq!(wrapper.flows.len(), 1);
// let flow = &wrapper.flows[0];
// assert_matches!(flow, LoginType::Sso(SsoLoginType {
// identity_providers })); assert_eq!(identity_providers.len(), 2);
// let provider = &identity_providers[0];
// assert_eq!(provider.id, "oidc-gitlab");
// assert_eq!(provider.name, "GitLab");
// assert_eq!(provider.icon.as_deref(),
// Some(mxc_uri!("mxc://localhost/gitlab-icon"))); assert_eq!(provider.
// brand, Some(IdentityProviderBrand::GitLab));
// let provider = &identity_providers[1];
// assert_eq!(provider.id, "custom");
// assert_eq!(provider.name, "Custom");
// assert_eq!(provider.icon, None);
// assert_eq!(provider.brand, None);
// }
// #[test]
// fn serialize_sso_login_type() {
// let wrapper = to_json_value(Wrapper {
// flows: vec![
// LoginType::Token(TokenLoginType::new()),
// LoginType::Sso(SsoLoginType {
// identity_providers: vec![IdentityProvider {
// id: "oidc-github".into(),
// name: "GitHub".into(),
// icon: Some("mxc://localhost/github-icon".into()),
// brand: Some(IdentityProviderBrand::GitHub),
// }],
// }),
// ],
// })
// .unwrap();
// assert_eq!(
// wrapper,
// json!({
// "flows": [
// {
// "type": "m.login.token"
// },
// {
// "type": "m.login.sso",
// "identity_providers": [
// {
// "id": "oidc-github",
// "name": "GitHub",
// "icon": "mxc://localhost/github-icon",
// "brand": "github"
// },
// ]
// }
// ],
// })
// );
// }
// #[test]
// fn deserialize_login_type() {
// assert_matches!(
// from_json_value(json!({
// "type": "m.login.password",
// "identifier": {
// "type": "m.id.user",
// "user": "cheeky_monkey"
// },
// "password": "ilovebananas"
// }))
// .unwrap(),
// LoginInfo::Password(login)
// );
// assert_matches!(login.identifier,
// UserIdentifier::UserIdOrLocalpart(user)); assert_eq!(user,
// "cheeky_monkey"); assert_eq!(login.password, "ilovebananas");
// assert_matches!(
// from_json_value(json!({
// "type": "m.login.token",
// "token": "1234567890abcdef"
// }))
// .unwrap(),
// LoginInfo::Token(Token { token })
// );
// assert_eq!(token, "1234567890abcdef");
// }
// }
| 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/client/filter.rs | crates/core/src/client/filter.rs | //! Endpoints for event filters.
// pub mod create_filter;
// pub mod get_filter;
mod lazy_load;
mod url;
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
pub use self::{lazy_load::LazyLoadOptions, url::UrlFilter};
use crate::{OwnedRoomId, OwnedUserId, PrivOwnedStr, serde::StringEnum};
/// Format to use for returned events.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, Default, StringEnum)]
#[palpo_enum(rename_all = "snake_case")]
#[non_exhaustive]
pub enum EventFormat {
/// Client format, as described in the Client API.
#[default]
Client,
/// Raw events from federation.
Federation,
#[doc(hidden)]
#[salvo(schema(value_type = String))]
_Custom(PrivOwnedStr),
}
/// Filters to be applied to room events.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct RoomEventFilter {
/// A list of event types to exclude.
///
/// If this list is absent then no event types are excluded. A matching type
/// will be excluded even if it is listed in the 'types' filter. A '*'
/// can be used as a wildcard to match any sequence of characters.
#[serde(default, skip_serializing_if = "<[_]>::is_empty")]
pub not_types: Vec<String>,
/// A list of room IDs to exclude.
///
/// If this list is absent then no rooms are excluded. A matching room will
/// be excluded even if it is listed in the 'rooms' filter.
#[serde(default, skip_serializing_if = "<[_]>::is_empty")]
pub not_rooms: Vec<OwnedRoomId>,
/// The maximum number of events to return.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<usize>,
/// A list of room IDs to include.
///
/// If this list is absent then all rooms are included.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rooms: Option<Vec<OwnedRoomId>>,
/// A list of sender IDs to exclude.
///
/// If this list is absent then no senders are excluded. A matching sender
/// will be excluded even if it is listed in the 'senders' filter.
#[serde(default, skip_serializing_if = "<[_]>::is_empty")]
pub not_senders: Vec<OwnedUserId>,
/// A list of senders IDs to include.
///
/// If this list is absent then all senders are included.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub senders: Option<Vec<OwnedUserId>>,
/// A list of event types to include.
///
/// If this list is absent then all event types are included. A '*' can be
/// used as a wildcard to match any sequence of characters.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub types: Option<Vec<String>>,
/// Controls whether to include events with a URL key in their content.
///
/// * `None`: No filtering
/// * `Some(EventsWithUrl)`: Only events with a URL
/// * `Some(EventsWithoutUrl)`: Only events without a URL
#[serde(
default,
rename = "contains_url",
skip_serializing_if = "Option::is_none"
)]
pub url_filter: Option<UrlFilter>,
/// Options to control lazy-loading of membership events.
///
/// Defaults to `LazyLoadOptions::Disabled`.
#[serde(flatten)]
pub lazy_load_options: LazyLoadOptions,
/// Whether to enable [per-thread notification counts].
///
/// Only applies to the [`sync_events`] endpoint.
///
/// [per-thread notification counts]: https://spec.matrix.org/latest/client-server-api/#receiving-notifications
/// [`sync_events`]: crate::sync::sync_events
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub unread_thread_notifications: bool,
}
impl RoomEventFilter {
/// Creates an empty `RoomEventFilter`.
///
/// You can also use the [`Default`] implementation.
pub fn empty() -> Self {
Self::default()
}
/// Creates a new `RoomEventFilter` that can be used to ignore all room
/// events.
pub fn ignore_all() -> Self {
Self {
types: Some(vec![]),
..Default::default()
}
}
/// Creates a new `RoomEventFilter` with [room member lazy-loading] enabled.
///
/// Redundant membership events are disabled.
///
/// [room member lazy-loading]: https://spec.matrix.org/latest/client-server-api/#lazy-loading-room-members
pub fn with_lazy_loading() -> Self {
Self {
lazy_load_options: LazyLoadOptions::Enabled {
include_redundant_members: false,
},
..Default::default()
}
}
pub fn with_limit(limit: usize) -> Self {
Self {
limit: Some(limit),
..Default::default()
}
}
/// Returns `true` if all fields are empty.
pub fn is_empty(&self) -> bool {
self.not_types.is_empty()
&& self.not_rooms.is_empty()
&& self.limit.is_none()
&& self.rooms.is_none()
&& self.not_senders.is_empty()
&& self.senders.is_none()
&& self.types.is_none()
&& self.url_filter.is_none()
&& self.lazy_load_options.is_disabled()
&& !self.unread_thread_notifications
}
}
/// Filters to be applied to room data.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct RoomDataFilter {
/// Include rooms that the user has left in the sync.
///
/// Defaults to `false`.
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub include_leave: bool,
/// The per user account data to include for rooms.
#[serde(default, skip_serializing_if = "crate::serde::is_empty")]
pub account_data: RoomEventFilter,
/// The message and state update events to include for rooms.
#[serde(default, skip_serializing_if = "crate::serde::is_empty")]
pub timeline: RoomEventFilter,
/// The events that aren't recorded in the room history, e.g. typing and
/// receipts, to include for rooms.
#[serde(default, skip_serializing_if = "crate::serde::is_empty")]
pub ephemeral: RoomEventFilter,
/// The state events to include for rooms.
#[serde(default, skip_serializing_if = "crate::serde::is_empty")]
pub state: RoomEventFilter,
/// A list of room IDs to exclude.
///
/// If this list is absent then no rooms are excluded. A matching room will
/// be excluded even if it is listed in the 'rooms' filter. This filter
/// is applied before the filters in `ephemeral`, `state`, `timeline` or
/// `account_data`.
#[serde(default, skip_serializing_if = "<[_]>::is_empty")]
pub not_rooms: Vec<OwnedRoomId>,
/// A list of room IDs to include.
///
/// If this list is absent then all rooms are included. This filter is
/// applied before the filters in `ephemeral`, `state`, `timeline` or
/// `account_data`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rooms: Option<Vec<OwnedRoomId>>,
}
impl RoomDataFilter {
/// Creates an empty `RoomDataFilter`.
///
/// You can also use the [`Default`] implementation.
pub fn empty() -> Self {
Self::default()
}
/// Creates a new `RoomDataFilter` that can be used to ignore all room
/// events (of any type).
pub fn ignore_all() -> Self {
Self {
rooms: Some(vec![]),
..Default::default()
}
}
/// Creates a new `RoomDataFilter` with [room member lazy-loading] enabled.
///
/// Redundant membership events are disabled.
///
/// [room member lazy-loading]: https://spec.matrix.org/latest/client-server-api/#lazy-loading-room-members
pub fn with_lazy_loading() -> Self {
Self {
state: RoomEventFilter::with_lazy_loading(),
..Default::default()
}
}
/// Returns `true` if all fields are empty.
pub fn is_empty(&self) -> bool {
!self.include_leave
&& self.account_data.is_empty()
&& self.timeline.is_empty()
&& self.ephemeral.is_empty()
&& self.state.is_empty()
&& self.not_rooms.is_empty()
&& self.rooms.is_none()
}
}
/// Filter for non-room data.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct NonRoomDataFilter {
/// A list of event types to exclude.
///
/// If this list is absent then no event types are excluded. A matching type
/// will be excluded even if it is listed in the 'types' filter. A '*'
/// can be used as a wildcard to match any sequence of characters.
#[serde(default, skip_serializing_if = "<[_]>::is_empty")]
pub not_types: Vec<String>,
/// The maximum number of events to return.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<usize>,
/// A list of senders IDs to include.
///
/// If this list is absent then all senders are included.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub senders: Option<Vec<OwnedUserId>>,
/// A list of event types to include.
///
/// If this list is absent then all event types are included. A '*' can be
/// used as a wildcard to match any sequence of characters.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub types: Option<Vec<String>>,
/// A list of sender IDs to exclude.
///
/// If this list is absent then no senders are excluded. A matching sender
/// will be excluded even if it is listed in the 'senders' filter.
#[serde(default, skip_serializing_if = "<[_]>::is_empty")]
pub not_senders: Vec<OwnedUserId>,
}
impl NonRoomDataFilter {
/// Creates an empty `Filter`.
///
/// You can also use the [`Default`] implementation.
pub fn empty() -> Self {
Self::default()
}
/// Creates a new `Filter` that can be used to ignore all events.
pub fn ignore_all() -> Self {
Self {
types: Some(vec![]),
..Default::default()
}
}
/// Returns `true` if all fields are empty.
pub fn is_empty(&self) -> bool {
self.not_types.is_empty()
&& self.limit.is_none()
&& self.senders.is_none()
&& self.types.is_none()
&& self.not_senders.is_empty()
}
}
/// A filter definition
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct FilterDefinition {
/// List of event fields to include.
///
/// If this list is absent then all fields are included. The entries may
/// include '.' characters to indicate sub-fields. So ['content.body']
/// will include the 'body' field of the 'content' object. A literal '.'
/// or '\' character in a field name may be escaped using a '\'. A server
/// may include more fields than were requested.
#[serde(skip_serializing_if = "Option::is_none")]
pub event_fields: Option<Vec<String>>,
/// The format to use for events.
///
/// 'client' will return the events in a format suitable for clients.
/// 'federation' will return the raw event as received over federation.
/// The default is 'client'.
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub event_format: EventFormat,
/// The presence updates to include.
#[serde(default, skip_serializing_if = "crate::serde::is_empty")]
pub presence: NonRoomDataFilter,
/// The user account data that isn't associated with rooms to include.
#[serde(default, skip_serializing_if = "crate::serde::is_empty")]
pub account_data: NonRoomDataFilter,
/// Filters to be applied to room data.
#[serde(default, skip_serializing_if = "crate::serde::is_empty")]
pub room: RoomDataFilter,
}
impl FilterDefinition {
/// Creates an empty `FilterDefinition`.
///
/// You can also use the [`Default`] implementation.
pub fn empty() -> Self {
Self::default()
}
/// Creates a new `FilterDefinition` that can be used to ignore all events.
pub fn ignore_all() -> Self {
Self {
account_data: NonRoomDataFilter::ignore_all(),
room: RoomDataFilter::ignore_all(),
presence: NonRoomDataFilter::ignore_all(),
..Default::default()
}
}
/// Creates a new `FilterDefinition` with [room member lazy-loading]
/// enabled.
///
/// Redundant membership events are disabled.
///
/// [room member lazy-loading]: https://spec.matrix.org/latest/client-server-api/#lazy-loading-room-members
pub fn with_lazy_loading() -> Self {
Self {
room: RoomDataFilter::with_lazy_loading(),
..Default::default()
}
}
/// Returns `true` if all fields are empty.
pub fn is_empty(&self) -> bool {
self.event_fields.is_none()
&& self.event_format == EventFormat::Client
&& self.presence.is_empty()
&& self.account_data.is_empty()
&& self.room.is_empty()
}
}
// /// `POST /_matrix/client/*/user/{user_id}/filter`
// ///
// /// Create a new filter for event retrieval.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3useruser_idfilter
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/user/:user_id/filter",
// 1.1 => "/_matrix/client/v3/user/:user_id/filter",
// }
// };
/// Request type for the `create_filter` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct CreateFilterReqBody {
// /// The ID of the user uploading the filter.
// ///
// /// The access token must be authorized to make requests for this user ID.
// #[salvo(parameter(parameter_in = Path))]
// pub user_id: OwnedUserId,
/// The filter definition.
#[serde(flatten)]
pub filter: FilterDefinition,
}
/// Response type for the `create_filter` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct CreateFilterResBody {
/// The ID of the filter that was created.
pub filter_id: String,
}
impl CreateFilterResBody {
/// Creates a new `Response` with the given filter ID.
pub fn new(filter_id: String) -> Self {
Self { filter_id }
}
}
// /// `GET /_matrix/client/*/user/{user_id}/filter/{filter_id}`
// ///
// /// Retrieve a previously created filter.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3useruser_idfilterfilterid
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/user/:user_id/filter/:filter_id",
// 1.1 => "/_matrix/client/v3/user/:user_id/filter/:filter_id",
// }
// };
/// Response type for the `get_filter` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct FilterResBody(
/// The filter definition.
pub FilterDefinition,
);
impl FilterResBody {
/// Creates a new `Response` with the given filter definition.
pub fn new(filter: FilterDefinition) -> Self {
Self(filter)
}
}
macro_rules! can_be_empty {
($ty:ident) => {
impl crate::serde::CanBeEmpty for $ty {
fn is_empty(&self) -> bool {
self.is_empty()
}
}
};
}
can_be_empty!(RoomDataFilter);
can_be_empty!(FilterDefinition);
can_be_empty!(RoomEventFilter);
can_be_empty!(NonRoomDataFilter);
// #[cfg(test)]
// mod tests {
// use serde_json::{from_value as from_json_value, json, to_value as
// to_json_value};
// use super::{Filter, FilterDefinition, LazyLoadOptions, RoomDataFilter,
// RoomEventFilter, UrlFilter};
// #[test]
// fn deserialize_request() {
// crateapi::IncomingRequest as _;
// use super::Request;
// let req = Request::try_from_http_request(
// http::Request::builder()
// .method(http::Method::POST)
// .uri("https://matrix.org/_matrix/client/r0/user/@foo:bar.com/filter")
// .body(b"{}" as &[u8])
// .unwrap(),
// &["@foo:bar.com"],
// )
// .unwrap();
// assert_eq!(req.user_id, "@foo:bar.com");
// assert!(req.filter.is_empty());
// }
// #[test]
// fn serialize_request() {
// use crate::{
// api::{MatrixVersion, OutgoingRequest, SendAccessToken},
// owned_user_id,
// };
// use crate::client::filter::FilterDefinition;
// let req = super::Request::new(owned_user_id!("@foo:bar.com"),
// FilterDefinition::default()) .try_into_http_request::<Vec<u8>>(
// "https://matrix.org",
// SendAccessToken::IfRequired("tok"),
// &[MatrixVersion::V1_1],
// )
// .unwrap();
// assert_eq!(req.body(), b"{}");
// }
// #[test]
// fn default_filters_are_empty() -> serde_json::Result<()> {
// assert_eq!(to_json_value(NonRoomDataFilter::default())?, json!({}));
// assert_eq!(to_json_value(FilterDefinition::default())?, json!({}));
// assert_eq!(to_json_value(RoomEventFilter::default())?, json!({}));
// assert_eq!(to_json_value(RoomDataFilter::default())?, json!({}));
// Ok(())
// }
// #[test]
// fn filter_definition_roundtrip() -> serde_json::Result<()> {
// let filter = FilterDefinition::default();
// let filter_str = to_json_value(&filter)?;
// let incoming_filter =
// from_json_value::<FilterDefinition>(filter_str)?; assert!
// (incoming_filter.is_empty());
// Ok(())
// }
// #[test]
// fn room_filter_definition_roundtrip() -> serde_json::Result<()> {
// let filter = RoomDataFilter::default();
// let room_filter = to_json_value(filter)?;
// let incoming_room_filter =
// from_json_value::<RoomDataFilter>(room_filter)?; assert!
// (incoming_room_filter.is_empty());
// Ok(())
// }
// #[test]
// fn issue_366() {
// let obj = json!({
// "lazy_load_members": true,
// "filter_json": { "contains_url": true, "types":
// ["m.room.message"] }, "types": ["m.room.message"],
// "not_types": [],
// "rooms": null,
// "not_rooms": [],
// "senders": null,
// "not_senders": [],
// "contains_url": true,
// });
// let filter: RoomEventFilter = from_json_value(obj).unwrap();
// assert_eq!(filter.types, Some(vec!["m.room.message".to_owned()]));
// assert_eq!(filter.not_types, vec![""; 0]);
// assert_eq!(filter.rooms, None);
// assert_eq!(filter.not_rooms, vec![""; 0]);
// assert_eq!(filter.senders, None);
// assert_eq!(filter.not_senders, vec![""; 0]);
// assert_eq!(filter.limit, None);
// assert_eq!(filter.url_filter, Some(UrlFilter::EventsWithUrl));
// assert_eq!(
// filter.lazy_load_options,
// LazyLoadOptions::Enabled {
// include_redundant_members: false
// }
// );
// }
// }
| 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/client/redact.rs | crates/core/src/client/redact.rs | //! `PUT /_matrix/client/*/rooms/{room_id}/redact/{event_id}/{txn_id}`
//!
//! Redact an event, stripping all information not critical to the event graph
//! integrity.
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/latest/client-server-api/#put_matrixclientv3roomsroomidredacteventidtxnid
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{OwnedEventId, OwnedRoomId, OwnedTransactionId};
// const METADATA: Metadata = metadata! {
// method: PUT,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/rooms/:room_id/redact/:event_id/:txn_id",
// 1.1 => "/_matrix/client/v3/rooms/:room_id/redact/:event_id/:txn_id",
// }
// };
#[derive(ToParameters, Deserialize, Debug)]
pub struct RedactEventReqArgs {
/// The ID of the room of the event to redact.
#[salvo(parameter(parameter_in = Path))]
pub room_id: OwnedRoomId,
/// The ID of the event to redact.
#[salvo(parameter(parameter_in = Path))]
pub event_id: OwnedEventId,
/// The transaction ID for this event.
///
/// Clients should generate a unique ID across requests within the
/// same session. A session is identified by an access token, and
/// persists when the [access token is refreshed].
///
/// It will be used by the server to ensure idempotency of requests.
///
/// [access token is refreshed]: https://spec.matrix.org/latest/client-server-api/#refreshing-access-tokens
#[salvo(parameter(parameter_in = Path))]
pub txn_id: OwnedTransactionId,
}
/// Request type for the `redact_event` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct RedactEventReqBody {
/// The reason for the redaction.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
/// Response type for the `redact_event` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct RedactEventResBody {
/// The ID of the redacted event.
pub event_id: OwnedEventId,
}
| 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/client/relation.rs | crates/core/src/client/relation.rs | use salvo::oapi::{ToParameters, ToSchema};
use serde::{Deserialize, Serialize};
/// `GET /_matrix/client/*/rooms/{room_id}/relations/{event_id}/{rel_type}/
/// {event_type}`
///
/// Get the child events for a given parent event which relate to the parent
/// using the given `rel_type` and having the given `event_type`.
use crate::events::{AnyMessageLikeEvent, TimelineEventType, relation::RelationType};
use crate::{Direction, OwnedEventId, OwnedRoomId, serde::RawJson};
// /// `/v1/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv1roomsroomidrelationseventidreltypeeventtype
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/client/unstable/rooms/:room_id/relations/:event_id/:rel_type/:event_type",
// 1.3 => "/_matrix/client/v1/rooms/:room_id/relations/:event_id/:rel_type/:event_type",
// }
// };
/// Request type for the `get_relating_events_with_rel_type_and_event_type`
/// endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct RelatingEventsWithRelTypeAndEventTypeReqArgs {
/// The ID of the room containing the parent event.
#[salvo(parameter(parameter_in = Path))]
pub room_id: OwnedRoomId,
/// The ID of the parent event whose child events are to be returned.
#[salvo(parameter(parameter_in = Path))]
pub event_id: OwnedEventId,
/// The relationship type to search for.
#[salvo(parameter(parameter_in = Path))]
pub rel_type: RelationType,
/// The event type of child events to search for.
///
/// Note that in encrypted rooms this will typically always be
/// `m.room.encrypted` regardless of the event type contained within the
/// encrypted payload.
#[salvo(parameter(parameter_in = Path))]
pub event_type: TimelineEventType,
/// The pagination token to start returning results from.
///
/// If `None`, results start at the most recent topological event known to
/// the server.
///
/// Can be a `next_batch` token from a previous call, or a returned `start`
/// token from `/messages` or a `next_batch` token from `/sync`.
///
/// Note that when paginating the `from` token should be "after" the `to`
/// token in terms of topological ordering, because it is only possible
/// to paginate "backwards" through events, starting at `from`.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[salvo(parameter(parameter_in = Query))]
pub from: Option<String>,
/// The direction to return events from.
///
/// Defaults to [`Direction::Backward`].
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
#[salvo(parameter(parameter_in = Query))]
pub dir: Direction,
/// The pagination token to stop returning results at.
///
/// If `None`, results continue up to `limit` or until there are no more
/// events.
///
/// Like `from`, this can be a previous token from a prior call to this
/// endpoint or from `/messages` or `/sync`.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[salvo(parameter(parameter_in = Query))]
pub to: Option<String>,
/// The maximum number of results to return in a single `chunk`.
///
/// The server can and should apply a maximum value to this parameter to
/// avoid large responses.
///
/// Similarly, the server should apply a default value when not supplied.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[salvo(parameter(parameter_in = Query))]
pub limit: Option<usize>,
/// Whether to include events which relate indirectly to the given event.
///
/// These are events related to the given event via two or more direct
/// relationships.
///
/// It is recommended that homeservers traverse at least 3 levels of
/// relationships. Implementations may perform more but should be
/// careful to not infinitely recurse.
///
/// Default to `false`.
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
#[salvo(parameter(parameter_in = Query))]
pub recurse: bool,
}
// /// `GET /_matrix/client/*/rooms/{room_id}/relations/{event_id}/{relType}`
// ///
// /// Get the child events for a given parent event which relate to the parent
// /// using the given `rel_type`.
//
// /// `/v1/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv1roomsroomidrelationseventidreltype
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/client/unstable/rooms/:room_id/relations/:event_id/:rel_type",
// 1.3 => "/_matrix/client/v1/rooms/:room_id/relations/:event_id/:rel_type",
// }
// };
/// Request type for the `get_relating_events_with_rel_type` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct RelatingEventsWithRelTypeReqArgs {
/// The ID of the room containing the parent event.
#[salvo(parameter(parameter_in = Path))]
pub room_id: OwnedRoomId,
/// The ID of the parent event whose child events are to be returned.
#[salvo(parameter(parameter_in = Path))]
pub event_id: OwnedEventId,
/// The relationship type to search for.
#[salvo(parameter(parameter_in = Path))]
pub rel_type: RelationType,
/// The pagination token to start returning results from.
///
/// If `None`, results start at the most recent topological event known to
/// the server.
///
/// Can be a `next_batch` token from a previous call, or a returned `start`
/// token from `/messages` or a `next_batch` token from `/sync`.
///
/// Note that when paginating the `from` token should be "after" the `to`
/// token in terms of topological ordering, because it is only possible
/// to paginate "backwards" through events, starting at `from`.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[salvo(parameter(parameter_in = Query))]
pub from: Option<String>,
/// The direction to return events from.
///
/// Defaults to [`Direction::Backward`].
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
#[salvo(parameter(parameter_in = Query))]
pub dir: Direction,
/// The pagination token to stop returning results at.
///
/// If `None`, results continue up to `limit` or until there are no more
/// events.
///
/// Like `from`, this can be a previous token from a prior call to this
/// endpoint or from `/messages` or `/sync`.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[salvo(parameter(parameter_in = Query))]
pub to: Option<String>,
/// The maximum number of results to return in a single `chunk`.
///
/// The server can and should apply a maximum value to this parameter to
/// avoid large responses.
///
/// Similarly, the server should apply a default value when not supplied.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[salvo(parameter(parameter_in = Query))]
pub limit: Option<usize>,
/// Whether to include events which relate indirectly to the given event.
///
/// These are events related to the given event via two or more direct
/// relationships.
///
/// It is recommended that homeservers traverse at least 3 levels of
/// relationships. Implementations may perform more but should be
/// careful to not infinitely recurse.
///
/// Default to `false`.
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
#[salvo(parameter(parameter_in = Query))]
pub recurse: bool,
}
// /// `GET /_matrix/client/*/rooms/{room_id}/relations/{event_id}`
// ///
// /// Get the child events for a given parent event.
// /// `/v1/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv1roomsroomidrelationseventid
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/client/unstable/rooms/:room_id/relations/:event_id",
// 1.3 => "/_matrix/client/v1/rooms/:room_id/relations/:event_id",
// }
// };
/// Request type for the `get_relating_events` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct RelatingEventsReqArgs {
/// The ID of the room containing the parent event.
#[salvo(parameter(parameter_in = Path))]
pub room_id: OwnedRoomId,
/// The ID of the parent event whose child events are to be returned.
#[salvo(parameter(parameter_in = Path))]
pub event_id: OwnedEventId,
/// The pagination token to start returning results from.
///
/// If `None`, results start at the most recent topological event known to
/// the server.
///
/// Can be a `next_batch` or `prev_batch` token from a previous call, or a
/// returned `start` token from `/messages` or a `next_batch` token from
/// `/sync`.
///
/// Note that when paginating the `from` token should be "after" the `to`
/// token in terms of topological ordering, because it is only possible
/// to paginate "backwards" through events, starting at `from`.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[salvo(parameter(parameter_in = Query))]
pub from: Option<String>,
/// The direction to return events from.
///
/// Defaults to [`Direction::Backward`].
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
#[salvo(parameter(parameter_in = Query))]
pub dir: Direction,
/// The pagination token to stop returning results at.
///
/// If `None`, results continue up to `limit` or until there are no more
/// events.
///
/// Like `from`, this can be a previous token from a prior call to this
/// endpoint or from `/messages` or `/sync`.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[salvo(parameter(parameter_in = Query))]
pub to: Option<String>,
/// The maximum number of results to return in a single `chunk`.
///
/// The server can and should apply a maximum value to this parameter to
/// avoid large responses.
///
/// Similarly, the server should apply a default value when not supplied.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[salvo(parameter(parameter_in = Query))]
pub limit: Option<usize>,
/// Whether to include events which relate indirectly to the given event.
///
/// These are events related to the given event via two or more direct
/// relationships.
///
/// It is recommended that homeservers traverse at least 3 levels of
/// relationships. Implementations may perform more but should be
/// careful to not infinitely recurse.
///
/// Default to `false`.
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
#[salvo(parameter(parameter_in = Query))]
pub recurse: bool,
}
/// Response type for the `get_relating_events` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct RelationEventsResBody {
/// The paginated child events which point to the parent.
///
/// The events returned are ordered topologically, most-recent first.
///
/// If no events are related to the parent or the pagination yields no
/// results, an empty `chunk` is returned.
#[salvo(schema(value_type = Object, additional_properties = true))]
pub chunk: Vec<RawJson<AnyMessageLikeEvent>>,
/// An opaque string representing a pagination token.
///
/// If this is `None`, there are no more results to fetch and the client
/// should stop paginating.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub next_batch: Option<String>,
/// An opaque string representing a pagination token.
///
/// If this is `None`, this is the start of the result set, i.e. this is the
/// first batch/page.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub prev_batch: Option<String>,
/// If `recurse` was set on the request, the depth to which the server
/// recursed.
///
/// If `recurse` was not set, this field must be absent.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub recursion_depth: Option<u64>,
}
| 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/client/appservice.rs | crates/core/src/client/appservice.rs | /// `POST /_matrix/client/*/appservice/{appserviceId}/ping}`
///
/// Ask the homeserver to ping the application service to ensure the connection
/// works. `/v1/` ([spec])
///
/// [spec]: https://spec.matrix.org/latest/application-service-api/#post_matrixclientv1appserviceappserviceidping
use std::time::Duration;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::{OwnedTransactionId, room::Visibility};
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// unstable =>
// "/_matrix/client/unstable/fi.mau.msc2659/appservice/:appservice_id/ping",
// 1.7 => "/_matrix/client/v1/appservice/:appservice_id/ping",
// }
// };
/// Request type for the `request_ping` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct PingReqBody {
/// The appservice ID of the appservice to ping.
///
/// This must be the same as the appservice whose `as_token` is being used
/// to authenticate the request.
#[salvo(parameter(parameter_in = Path))]
pub appservice_id: String,
/// Transaction ID that is passed through to the `POST /_matrix/app/v1/ping`
/// call.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub transaction_id: Option<OwnedTransactionId>,
}
/// Response type for the `request_ping` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct PingResBody {
/// The duration in milliseconds that the `POST /_matrix/app/v1/ping`
/// request took from the homeserver's point of view.
#[serde(with = "crate::serde::duration::ms", rename = "duration_ms")]
pub duration: Duration,
}
impl PingResBody {
/// Creates an `Response` with the given duration.
pub fn new(duration: Duration) -> Self {
Self { duration }
}
}
// /// `PUT /_matrix/client/*/directory/list/appservice/{networkId}/{room_id}`
// ///
// /// Updates the visibility of a given room on the application service's room
// /// directory.
//
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/application-service-api/#put_matrixclientv3directorylistappservicenetworkidroomid
// const METADATA: Metadata = metadata! {
// method: PUT,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/directory/list/appservice/:network_id/:room_id",
// 1.1 => "/_matrix/client/v3/directory/list/appservice/:network_id/:room_id",
// }
// };
/// Request type for the `set_room_visibility` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct UpdateRoomReqBody {
/// Whether the room should be visible (public) in the directory or not
/// (private).
pub visibility: Visibility,
}
| 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/client/state.rs | crates/core/src/client/state.rs | use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{
OwnedEventId, OwnedRoomId, UnixMillis,
events::{AnyStateEvent, AnyStateEventContent, StateEventType},
serde::RawJson,
};
// /// `GET /_matrix/client/*/rooms/{room_id}/state/{eventType}/{stateKey}`
// ///
// /// Get state events associated with a given key.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3roomsroomidstateeventtypestatekey
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/rooms/:room_id/state/:event_type/:state_key",
// 1.1 => "/_matrix/client/v3/rooms/:room_id/state/:event_type/:state_key",
// }
// };
/// Request type for the `get_state_events_for_key` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct StateEventsForKeyReqArgs {
/// The room to look up the state for.
#[salvo(parameter(parameter_in = Path))]
pub room_id: OwnedRoomId,
/// The type of state to look up.
#[salvo(parameter(parameter_in = Path))]
pub event_type: StateEventType,
/// The key of the state to look up.
#[salvo(parameter(parameter_in = Path))]
pub state_key: String,
/// Optional parameter to return the event content
/// or the full state event.
#[salvo(parameter(parameter_in = Query))]
pub format: Option<StateEventFormat>,
}
/// The format to use for the returned data.
#[derive(ToSchema, Default, Deserialize, Debug, PartialEq, Clone, Copy)]
#[serde(rename_all = "lowercase")]
pub enum StateEventFormat {
/// Will return only the content of the state event.
///
/// This is the default value if the format is unspecified in the request.
#[default]
Content,
/// Will return the entire event in the usual format suitable for clients, including fields
/// like event ID, sender and timestamp.
Event,
}
#[derive(ToParameters, Deserialize, Debug)]
pub struct StateEventsForEmptyKeyReqArgs {
/// The room to look up the state for.
#[salvo(parameter(parameter_in = Path))]
pub room_id: OwnedRoomId,
/// The type of state to look up.
#[salvo(parameter(parameter_in = Path))]
pub event_type: StateEventType,
/// Optional parameter to return the event content
/// or the full state event.
#[salvo(parameter(parameter_in = Query))]
pub format: Option<String>,
}
/// Response type for the `get_state_events_for_key` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct StateEventsForKeyResBody {
/// The content of the state event.
///
/// This is `serde_json::Value` due to complexity issues with returning only
/// the actual JSON content without a top level key.
#[serde(flatten, skip_serializing_if = "Option::is_none")]
pub content: Option<serde_json::Value>,
/// The full state event
///
/// This is `serde_json::Value` due to complexity issues with returning only
/// the actual JSON content without a top level key.
#[serde(flatten, skip_serializing_if = "Option::is_none")]
pub event: Option<serde_json::Value>,
}
impl StateEventsForKeyResBody {
/// Creates a new `Response` with the given content.
pub fn new(content: serde_json::Value, event: serde_json::Value) -> Self {
Self {
content: Some(content),
event: Some(event),
}
}
}
// /// `GET /_matrix/client/*/rooms/{room_id}/state`
// ///
// /// Get state events for a room.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3roomsroomidstate
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/rooms/:room_id/state",
// 1.1 => "/_matrix/client/v3/rooms/:room_id/state",
// }
// };
// /// Request type for the `get_state_events` endpoint.
// pub struct StateEventsReqBody {
// /// The room to look up the state for.
// #[salvo(parameter(parameter_in = Path))]
// pub room_id: OwnedRoomId,
// }
/// Response type for the `get_state_events` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct StateEventsResBody(
/// If the user is a member of the room this will be the current state of
/// the room as a list of events.
///
/// If the user has left the room then this will be the state of the room
/// when they left as a list of events.
#[salvo(schema(value_type = Vec<Object>, additional_properties = true))]
Vec<RawJson<AnyStateEvent>>,
);
impl StateEventsResBody {
/// Creates a new `Response` with the given room state.
pub fn new(room_state: Vec<RawJson<AnyStateEvent>>) -> Self {
Self(room_state)
}
}
// /// `PUT /_matrix/client/*/rooms/{room_id}/state/{eventType}/{stateKey}`
// ///
// /// Send a state event to a room associated with a given state key.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#put_matrixclientv3roomsroomidstateeventtypestatekey
// const METADATA: Metadata = metadata! {
// method: PUT,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/rooms/:room_id/state/:event_type/:state_key",
// 1.1 => "/_matrix/client/v3/rooms/:room_id/state/:event_type/:state_key",
// }
// };
/// Request type for the `send_state_event` endpoint.
// #[derive(ToSchema, Deserialize, Debug)]
// pub struct SendStateEventReqBody {
// // /// The room to set the state in.
// // pub room_id: OwnedRoomId,
// // /// The type of event to send.
// // pub event_type: StateEventType,
// /// The state_key for the state to send.
// pub state_key: Option<String>,
// /// The event content to send.
// #[salvo(schema(value_type = Object, additional_properties = true))]
// pub body: RawJson<AnyStateEventContent>,
// /// Timestamp to use for the `origin_server_ts` of the event.
// ///
// /// This is called [timestamp massaging] and can only be used by Appservices.
// ///
// /// Note that this does not change the position of the event in the timeline.
// ///
// /// [timestamp massaging]: https://spec.matrix.org/latest/application-service-api/#timestamp-massaging
// pub timestamp: Option<UnixMillis>,
// }
#[derive(ToSchema, Deserialize, Debug)]
pub struct SendStateEventReqBody(
/// The event content to send.
#[salvo(schema(value_type = Object, additional_properties = true))]
pub RawJson<AnyStateEventContent>,
);
/// Response type for the `send_state_event` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct SendStateEventResBody {
/// A unique identifier for the event.
pub event_id: OwnedEventId,
}
impl SendStateEventResBody {
/// Creates a new `Response` with the given event id.
pub fn new(event_id: OwnedEventId) -> Self {
Self { event_id }
}
}
/// Data in the request's query string.
#[derive(Serialize, Deserialize, Debug)]
struct RequestQuery {
/// Timestamp to use for the `origin_server_ts` of the event.
#[serde(default, rename = "ts", skip_serializing_if = "Option::is_none")]
timestamp: Option<UnixMillis>,
}
| 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/client/media.rs | crates/core/src/client/media.rs | /// Endpoints for the media repository.
mod content;
use std::time::Duration;
pub use content::*;
use reqwest::Url;
use salvo::oapi::{ToParameters, ToSchema};
use serde::{Deserialize, Serialize};
use crate::{
OwnedMxcUri, OwnedServerName, ServerName, UnixMillis,
media::ResizeMethod,
sending::{SendRequest, SendResult},
serde::{RawJsonValue, to_raw_json_value},
};
/// The default duration that the client should be willing to wait to start
/// receiving data.
pub(crate) fn default_download_timeout() -> Duration {
Duration::from_secs(20)
}
/// Whether the given duration is the default duration that the client should be
/// willing to wait to start receiving data.
pub(crate) fn is_default_download_timeout(timeout: &Duration) -> bool {
timeout.as_secs() == 20
}
// /// `POST /_matrix/media/*/create`
// ///
// /// Create an MXC URI without content.
// /// `/v1/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixmediav1create
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/media/unstable/fi.mau.msc2246/create",
// 1.7 => "/_matrix/media/v1/create",
// }
// };
/// Response type for the `create_mxc_uri` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct CreateMxcUriResBody {
/// The MXC URI for the about to be uploaded content.
pub content_uri: OwnedMxcUri,
/// The time at which the URI will expire if an upload has not been started.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unused_expires_at: Option<UnixMillis>,
}
// impl CreateMxcUriResBody {
// /// Creates a new `Response` with the given MXC URI.
// pub fn new(content_uri: OwnedMxcUri) -> Self {
// Self {
// content_uri,
// unused_expires_at: None,
// }
// }
// }
// /// `GET /_matrix/media/*/config`
// ///
// /// Gets the config for the media repository.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixmediav3config
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/media/r0/config",
// 1.1 => "/_matrix/media/v3/config",
// }
// };
/// Response type for the `get_media_config` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct ConfigResBody {
/// Maximum size of upload in bytes.
#[serde(rename = "m.upload.size")]
pub upload_size: u64,
}
impl ConfigResBody {
/// Creates a new `Response` with the given maximum upload size.
pub fn new(upload_size: u64) -> Self {
Self { upload_size }
}
}
// /// `GET /_matrix/media/*/preview_url`
// ///
// /// Get a preview for a URL.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixmediav3preview_url
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/media/r0/preview_url",
// 1.1 => "/_matrix/media/v3/preview_url",
// }
// };
/// Request type for the `get_media_preview` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct MediaPreviewReqArgs {
/// URL to get a preview of.
#[salvo(parameter(parameter_in = Query))]
pub url: String,
/// Preferred point in time (in milliseconds) to return a preview for.
#[salvo(parameter(parameter_in = Query))]
pub ts: Option<UnixMillis>,
}
/// Response type for the `get_media_preview` endpoint.
#[derive(ToSchema, Serialize, Default, Debug)]
#[salvo(schema(value_type = Object))]
pub struct MediaPreviewResBody(
/// OpenGraph-like data for the URL.
///
/// Differences from OpenGraph: the image size in bytes is added to the
/// `matrix:image:size` field, and `og:image` returns the MXC URI to the
/// image, if any.
pub Option<Box<RawJsonValue>>,
);
impl MediaPreviewResBody {
/// Creates an empty `Response`.
pub fn new() -> Self {
Default::default()
}
/// Creates a new `Response` with the given OpenGraph data (in a
/// `serde_json::value::RawValue`).
pub fn from_raw_value(data: Box<RawJsonValue>) -> Self {
Self(Some(data))
}
/// Creates a new `Response` with the given OpenGraph data (in any kind of
/// serializable object).
pub fn from_serialize<T: Serialize>(data: &T) -> serde_json::Result<Self> {
Ok(Self(Some(to_raw_json_value(data)?)))
}
}
pub fn thumbnail_request(
origin: &str,
server: &ServerName,
args: ThumbnailReqArgs,
) -> SendResult<SendRequest> {
let mut url = Url::parse(&format!(
"{origin}/_matrix/media/v3/thumbnail/{server}/{}",
args.media_id
))?;
{
let mut query = url.query_pairs_mut();
query.append_pair("width", &args.width.to_string());
query.append_pair("height", &args.height.to_string());
query.append_pair("allow_remote", &args.allow_remote.to_string());
query.append_pair("timeout_ms", &args.timeout_ms.as_millis().to_string());
query.append_pair("allow_redirect", &args.allow_redirect.to_string());
}
Ok(crate::sending::get(url))
}
/// Request type for the `get_content_thumbnail` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct ThumbnailReqArgs {
/// The server name from the mxc:// URI (the authoritory component).
#[salvo(parameter(parameter_in = Path))]
pub server_name: OwnedServerName,
/// The media ID from the mxc:// URI (the path component).
#[salvo(parameter(parameter_in = Path))]
pub media_id: String,
/// The desired resizing method.
#[salvo(parameter(parameter_in = Query))]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub method: Option<ResizeMethod>,
/// The *desired* width of the thumbnail.
///
/// The actual thumbnail may not match the size specified.
#[salvo(parameter(parameter_in = Query))]
pub width: u32,
/// The *desired* height of the thumbnail.
///
/// The actual thumbnail may not match the size specified.
#[salvo(parameter(parameter_in = Query))]
pub height: u32,
/// Whether to fetch media deemed remote.
///
/// Used to prevent routing loops. Defaults to `true`.
#[salvo(parameter(parameter_in = Query))]
#[serde(
default = "crate::serde::default_true",
skip_serializing_if = "crate::serde::is_true"
)]
pub allow_remote: bool,
/// The maximum duration that the client is willing to wait to start
/// receiving data, in the case that the content has not yet been
/// uploaded.
///
/// The default value is 20 seconds.
#[salvo(parameter(parameter_in = Query))]
#[serde(
with = "crate::serde::duration::ms",
default = "crate::client::media::default_download_timeout",
skip_serializing_if = "crate::media::is_default_download_timeout"
)]
pub timeout_ms: Duration,
/// Whether the server may return a 307 or 308 redirect response that points
/// at the relevant media content.
///
/// Unless explicitly set to `true`, the server must return the media
/// content itself.
#[salvo(parameter(parameter_in = Query))]
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub allow_redirect: bool,
}
// /// Response type for the `get_content_thumbnail` endpoint.
// #[derive(ToSchema, Serialize, Debug)]
// pub struct ThumbnailResBody {
// /// A thumbnail of the requested content.
// #[palpo_api(raw_body)]
// pub file: Vec<u8>,
// /// The content type of the thumbnail.
// #[palpo_api(header = CONTENT_TYPE)]
// pub content_type: Option<String>,
// /// The value of the `Cross-Origin-Resource-Policy` HTTP header.
// ///
// /// See [MDN] for the syntax.
// ///
// /// [MDN]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy#syntax
// #[palpo_api(header = CROSS_ORIGIN_RESOURCE_POLICY)]
// pub cross_origin_resource_policy: Option<String>,
// }
// impl ThumbnailResBody {
// /// Creates a new `Response` with the given thumbnail.
// ///
// /// The Cross-Origin Resource Policy defaults to `cross-origin`.
// pub fn new(file: Vec<u8>) -> Self {
// file,
// content_type: None,
// cross_origin_resource_policy: Some("cross-origin".to_owned()),
// }
// Self {
// }
// }
// #[cfg(test)]
// mod tests {
// use crate::RawJsonValue;
// use assert_matches2::assert_matches;
// use serde_json::{from_value as from_json_value, json, value::to_raw_value
// as to_raw_json_value};
// // Since BTreeMap<String, Box<RawJsonValue>> deserialization doesn't seem
// to // work, test that Option<RawJsonValue> works
// #[test]
// fn raw_json_deserialize() {
// type OptRawJson = Option<Box<RawJsonValue>>;
// assert_matches!(from_json_value::<OptRawJson>(json!(null)).unwrap(),
// None); from_json_value::<OptRawJson>(json!("test")).unwrap().
// unwrap(); from_json_value::<OptRawJson>(json!({ "a": "b"
// })).unwrap().unwrap(); }
// // For completeness sake, make sure serialization works too
// #[test]
// fn raw_json_serialize() {
// to_raw_json_value(&json!(null)).unwrap();
// to_raw_json_value(&json!("string")).unwrap();
// to_raw_json_value(&json!({})).unwrap();
// to_raw_json_value(&json!({ "a": "b" })).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/client/search.rs | crates/core/src/client/search.rs | //! `POST /_matrix/client/*/search`
//!
//! Search events.
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3search
use std::collections::BTreeMap;
use salvo::oapi::{ToParameters, ToSchema};
use serde::{Deserialize, Serialize};
use crate::{
OwnedEventId, OwnedMxcUri, OwnedRoomId, OwnedUserId, PrivOwnedStr,
client::filter::RoomEventFilter,
events::{AnyStateEvent, AnyTimelineEvent},
serde::{RawJson, StringEnum},
};
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/search",
// 1.1 => "/_matrix/client/v3/search",
// }
// };
#[derive(ToParameters, Deserialize, Debug)]
pub struct SearchReqArgs {
/// The point to return events from.
///
/// If given, this should be a `next_batch` result from a previous call to
/// this endpoint.
#[salvo(parameter(parameter_in = Query))]
pub next_batch: Option<String>,
}
/// Request type for the `search` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct SearchReqBody {
// /// The point to return events from.
// ///
// /// If given, this should be a `next_batch` result from a previous call to this endpoint.
// #[salvo(parameter(parameter_in = Query))]
// pub next_batch: Option<String>,
/// Describes which categories to search in and their criteria.
pub search_categories: Categories,
}
#[derive(ToSchema, Serialize, Debug)]
pub struct SearchResBody {
/// Describes which categories to search in and their criteria.
pub search_categories: ResultCategories,
}
impl SearchResBody {
/// Creates a new `Response` with the given search results.
pub fn new(search_categories: ResultCategories) -> Self {
Self { search_categories }
}
}
/// Categories of events that can be searched for.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct Categories {
/// Criteria for searching room events.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub room_events: Option<Criteria>,
}
impl Categories {
/// Creates an empty `Categories`.
pub fn new() -> Self {
Default::default()
}
}
/// Criteria for searching a category of events.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct Criteria {
/// The string to search events for.
pub search_term: String,
/// The keys to search for.
///
/// Defaults to all keys.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub keys: Option<Vec<SearchKeys>>,
/// A `Filter` to apply to the search.
#[serde(skip_serializing_if = "RoomEventFilter::is_empty")]
pub filter: RoomEventFilter,
/// The order in which to search for results.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub order_by: Option<OrderBy>,
/// Configures whether any context for the events returned are included in
/// the response.
#[serde(default, skip_serializing_if = "EventContext::is_default")]
pub event_context: EventContext,
/// Requests the server return the current state for each room returned.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub include_state: Option<bool>,
/// Requests that the server partitions the result set based on the provided
/// list of keys.
#[serde(default, skip_serializing_if = "Groupings::is_empty")]
pub groupings: Groupings,
}
impl Criteria {
/// Creates a new `Criteria` with the given search term.
pub fn new(search_term: String) -> Self {
Self {
search_term,
keys: None,
filter: RoomEventFilter::default(),
order_by: None,
event_context: Default::default(),
include_state: None,
groupings: Default::default(),
}
}
}
/// Configures whether any context for the events returned are included in the
/// response.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct EventContext {
/// How many events before the result are returned.
#[serde(
default = "default_event_context_limit",
skip_serializing_if = "is_default_event_context_limit"
)]
pub before_limit: u64,
/// How many events after the result are returned.
#[serde(
default = "default_event_context_limit",
skip_serializing_if = "is_default_event_context_limit"
)]
pub after_limit: u64,
/// Requests that the server returns the historic profile information for
/// the users that sent the events that were returned.
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub include_profile: bool,
}
fn default_event_context_limit() -> u64 {
5
}
#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_default_event_context_limit(val: &u64) -> bool {
*val == default_event_context_limit()
}
impl EventContext {
/// Creates an `EventContext` with all-default values.
pub fn new() -> Self {
Self {
before_limit: default_event_context_limit(),
after_limit: default_event_context_limit(),
include_profile: false,
}
}
/// Returns whether all fields have their default value.
pub fn is_default(&self) -> bool {
self.before_limit == default_event_context_limit()
&& self.after_limit == default_event_context_limit()
&& !self.include_profile
}
}
impl Default for EventContext {
fn default() -> Self {
Self::new()
}
}
/// Context for search results, if requested.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct EventContextResult {
/// Pagination token for the end of the chunk.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub end: Option<String>,
/// Events just after the result.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub events_after: Vec<RawJson<AnyTimelineEvent>>,
/// Events just before the result.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub events_before: Vec<RawJson<AnyTimelineEvent>>,
/// The historic profile information of the users that sent the events
/// returned.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub profile_info: BTreeMap<OwnedUserId, UserProfile>,
/// Pagination token for the start of the chunk.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub start: Option<String>,
}
impl EventContextResult {
/// Creates an empty `EventContextResult`.
pub fn new() -> Self {
Default::default()
}
/// Returns whether all fields are `None` or an empty list.
pub fn is_empty(&self) -> bool {
self.end.is_none()
&& self.events_after.is_empty()
&& self.events_before.is_empty()
&& self.profile_info.is_empty()
&& self.start.is_none()
}
}
/// A grouping for partitioning the result set.
#[derive(ToSchema, Clone, Default, Debug, Deserialize, Serialize)]
pub struct Grouping {
/// The key within events to use for this grouping.
pub key: Option<GroupingKey>,
}
impl Grouping {
/// Creates an empty `Grouping`.
pub fn new() -> Self {
Default::default()
}
/// Returns whether `key` is `None`.
pub fn is_empty(&self) -> bool {
self.key.is_none()
}
}
/// The key within events to use for this grouping.
#[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 GroupingKey {
/// `room_id`
RoomId,
/// `sender`
Sender,
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(PrivOwnedStr),
}
/// Requests that the server partitions the result set based on the provided
/// list of keys.
#[derive(ToSchema, Clone, Default, Debug, Deserialize, Serialize)]
pub struct Groupings {
/// List of groups to request.
#[serde(default, skip_serializing_if = "<[_]>::is_empty")]
pub group_by: Vec<Grouping>,
}
impl Groupings {
/// Creates an empty `Groupings`.
pub fn new() -> Self {
Default::default()
}
/// Returns `true` if all fields are empty.
pub fn is_empty(&self) -> bool {
self.group_by.is_empty()
}
}
/// The keys to search for.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[non_exhaustive]
pub enum SearchKeys {
/// content.body
#[palpo_enum(rename = "content.body")]
ContentBody,
/// content.name
#[palpo_enum(rename = "content.name")]
ContentName,
/// content.topic
#[palpo_enum(rename = "content.topic")]
ContentTopic,
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(PrivOwnedStr),
}
/// The order in which to search for results.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[palpo_enum(rename_all = "snake_case")]
pub enum OrderBy {
/// Prioritize recent events.
Recent,
/// Prioritize events by a numerical ranking of how closely they matched the
/// search criteria.
Rank,
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(PrivOwnedStr),
}
/// Categories of events that can be searched for.
#[derive(ToSchema, Clone, Default, Debug, Deserialize, Serialize)]
pub struct ResultCategories {
/// Room event results.
#[serde(default, skip_serializing_if = "ResultRoomEvents::is_empty")]
pub room_events: ResultRoomEvents,
}
impl ResultCategories {
/// Creates an empty `ResultCategories`.
pub fn new() -> Self {
Default::default()
}
}
/// Categories of events that can be searched for.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct ResultRoomEvents {
/// An approximate count of the total number of results found.
#[serde(skip_serializing_if = "Option::is_none")]
pub count: Option<u64>,
/// Any groups that were requested.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub groups: BTreeMap<GroupingKey, BTreeMap<OwnedRoomIdOrUserId, ResultGroup>>,
/// Token that can be used to get the next batch of results, by passing as
/// the `next_batch` parameter to the next call.
///
/// If this field is absent, there are no more results.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub next_batch: Option<String>,
/// List of results in the requested order.
// #[serde(default, skip_serializing_if = "Vec::is_empty")]
#[serde(default)]
pub results: Vec<SearchResult>,
/// The current state for every room in the results.
///
/// This is included if the request had the `include_state` key set with a
/// value of `true`.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub state: BTreeMap<OwnedRoomId, Vec<RawJson<AnyStateEvent>>>,
/// List of words which should be highlighted, useful for stemming which may
/// change the query terms.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub highlights: Vec<String>,
}
impl ResultRoomEvents {
/// Creates an empty `ResultRoomEvents`.
pub fn new() -> Self {
Default::default()
}
/// Returns `true` if all fields are empty / `None`.
pub fn is_empty(&self) -> bool {
self.count.is_none()
&& self.groups.is_empty()
&& self.next_batch.is_none()
&& self.results.is_empty()
&& self.state.is_empty()
&& self.highlights.is_empty()
}
}
/// A grouping of results, if requested.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct ResultGroup {
/// Token that can be used to get the next batch of results in the group, by
/// passing as the `next_batch` parameter to the next call.
///
/// If this field is absent, there are no more results in this group.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub next_batch: Option<String>,
/// Key that can be used to order different groups.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub order: Option<u64>,
/// Which results are in this group.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub results: Vec<OwnedEventId>,
}
impl ResultGroup {
/// Creates an empty `ResultGroup`.
pub fn new() -> Self {
Default::default()
}
/// Returns `true` if all fields are empty / `None`.
pub fn is_empty(&self) -> bool {
self.next_batch.is_none() && self.order.is_none() && self.results.is_empty()
}
}
/// A search result.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct SearchResult {
/// Context for result, if requested.
#[serde(default, skip_serializing_if = "EventContextResult::is_empty")]
pub context: EventContextResult,
/// A number that describes how closely this result matches the search.
///
/// Higher is closer.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rank: Option<f64>,
/// The event that matched.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub result: Option<RawJson<AnyTimelineEvent>>,
}
impl SearchResult {
/// Creates an empty `SearchResult`.
pub fn new() -> Self {
Default::default()
}
/// Returns `true` if all fields are empty / `None`.
pub fn is_empty(&self) -> bool {
self.context.is_empty() && self.rank.is_none() && self.result.is_none()
}
}
/// A user profile.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct UserProfile {
/// The user's avatar URL, if set.
#[serde(
skip_serializing_if = "Option::is_none",
default,
deserialize_with = "crate::serde::empty_string_as_none"
)]
pub avatar_url: Option<OwnedMxcUri>,
/// The user's display name, if set.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
}
impl UserProfile {
/// Creates an empty `UserProfile`.
pub fn new() -> Self {
Default::default()
}
/// Returns `true` if all fields are `None`.
pub fn is_empty(&self) -> bool {
self.avatar_url.is_none() && self.display_name.is_none()
}
}
/// Represents either a room or user ID for returning grouped search results.
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[allow(clippy::exhaustive_enums)]
pub enum OwnedRoomIdOrUserId {
/// Represents a room ID.
RoomId(OwnedRoomId),
/// Represents a user ID.
UserId(OwnedUserId),
}
| 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/client/rendezvous.rs | crates/core/src/client/rendezvous.rs | //! `POST /_matrix/client/*/rendezvous/`
//!
//! Create a rendezvous session.
pub mod unstable {
//! `msc4108` ([MSC])
//!
//! [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/4108
use http::header::{CONTENT_TYPE, ETAG, EXPIRES, LAST_MODIFIED};
#[cfg(feature = "client")]
use crate::api::error::FromHttpResponseError;
use crate::{
api::{auth_scheme::NoAuthentication, error::HeaderDeserializationError},
metadata,
};
use serde::{Deserialize, Serialize};
use url::Url;
use web_time::SystemTime;
metadata! {
method: POST,
rate_limited: true,
authentication: NoAuthentication,
history: {
unstable("org.matrix.msc4108") => "/_matrix/client/unstable/org.matrix.msc4108/rendezvous",
}
}
/// Request type for the `POST` `rendezvous` endpoint.
#[derive(Debug, Default, Clone)]
pub struct Request {
/// Any data up to maximum size allowed by the server.
pub content: String,
}
#[cfg(feature = "client")]
impl crate::api::OutgoingRequest for Request {
type EndpointError = crate::Error;
type IncomingResponse = Response;
fn try_into_http_request<T: Default + bytes::BufMut>(
self,
base_url: &str,
_: crate::api::auth_scheme::SendAccessToken<'_>,
considering: std::borrow::Cow<'_, crate::api::SupportedVersions>,
) -> Result<http::Request<T>, crate::api::error::IntoHttpError> {
use http::header::CONTENT_LENGTH;
use crate::api::Metadata;
let url = Self::make_endpoint_url(considering, base_url, &[], "")?;
let body = self.content.as_bytes();
let content_length = body.len();
Ok(http::Request::builder()
.method(Self::METHOD)
.uri(url)
.header(CONTENT_TYPE, "text/plain")
.header(CONTENT_LENGTH, content_length)
.body(crate::serde::slice_to_buf(body))?)
}
}
#[cfg(feature = "server")]
impl crate::api::IncomingRequest for Request {
type EndpointError = crate::Error;
type OutgoingResponse = Response;
fn try_from_http_request<B, S>(
request: http::Request<B>,
_path_args: &[S],
) -> Result<Self, crate::api::error::FromHttpRequestError>
where
B: AsRef<[u8]>,
S: AsRef<str>,
{
const EXPECTED_CONTENT_TYPE: &str = "text/plain";
use crate::api::error::DeserializationError;
Self::check_request_method(request.method())?;
let content_type = request
.headers()
.get(CONTENT_TYPE)
.ok_or(HeaderDeserializationError::MissingHeader(CONTENT_TYPE.to_string()))?;
let content_type = content_type.to_str()?;
if content_type != EXPECTED_CONTENT_TYPE {
Err(HeaderDeserializationError::InvalidHeaderValue {
header: CONTENT_TYPE.to_string(),
expected: EXPECTED_CONTENT_TYPE.to_owned(),
unexpected: content_type.to_owned(),
}
.into())
} else {
let body = request.into_body().as_ref().to_vec();
let content = String::from_utf8(body)
.map_err(|e| DeserializationError::Utf8(e.utf8_error()))?;
Ok(Self { content })
}
}
}
impl Request {
/// Creates a new `Request` with the given content.
pub fn new(content: String) -> Self {
Self { content }
}
}
/// Response type for the `POST` `rendezvous` endpoint.
#[derive(Debug, Clone)]
pub struct Response {
/// The absolute URL of the rendezvous session.
pub url: Url,
/// ETag for the current payload at the rendezvous session as
/// per [RFC7232](https://httpwg.org/specs/rfc7232.html#header.etag).
pub etag: String,
/// The expiry time of the rendezvous as per
/// [RFC7234](https://httpwg.org/specs/rfc7234.html#header.expires).
pub expires: SystemTime,
/// The last modified date of the payload as
/// per [RFC7232](https://httpwg.org/specs/rfc7232.html#header.last-modified)
pub last_modified: SystemTime,
}
#[derive(Serialize, Deserialize)]
struct ResponseBody {
url: Url,
}
#[cfg(feature = "client")]
impl crate::api::IncomingResponse for Response {
type EndpointError = crate::Error;
fn try_from_http_response<T: AsRef<[u8]>>(
response: http::Response<T>,
) -> Result<Self, FromHttpResponseError<Self::EndpointError>> {
use crate::api::EndpointError;
if response.status().as_u16() >= 400 {
return Err(FromHttpResponseError::Server(
Self::EndpointError::from_http_response(response),
));
}
let get_date = |header: http::HeaderName| -> Result<SystemTime, FromHttpResponseError<Self::EndpointError>> {
let date = response
.headers()
.get(&header)
.ok_or_else(|| HeaderDeserializationError::MissingHeader(header.to_string()))?;
let date = crate::http_headers::http_date_to_system_time(date)?;
Ok(date)
};
let etag = response
.headers()
.get(ETAG)
.ok_or(HeaderDeserializationError::MissingHeader(ETAG.to_string()))?
.to_str()?
.to_owned();
let expires = get_date(EXPIRES)?;
let last_modified = get_date(LAST_MODIFIED)?;
let body: ResponseBody = serde_json::from_slice(response.body().as_ref())?;
Ok(Self { url: body.url, etag, expires, last_modified })
}
}
#[cfg(feature = "server")]
impl crate::api::OutgoingResponse for Response {
fn try_into_http_response<T: Default + bytes::BufMut>(
self,
) -> Result<http::Response<T>, crate::api::error::IntoHttpError> {
use http::header::{CACHE_CONTROL, PRAGMA};
let body = ResponseBody { url: self.url };
let body = crate::serde::json_to_buf(&body)?;
let expires = crate::http_headers::system_time_to_http_date(&self.expires)?;
let last_modified = crate::http_headers::system_time_to_http_date(&self.last_modified)?;
Ok(http::Response::builder()
.status(http::StatusCode::OK)
.header(CONTENT_TYPE, crate::http_headers::APPLICATION_JSON)
.header(PRAGMA, "no-cache")
.header(CACHE_CONTROL, "no-store")
.header(ETAG, self.etag)
.header(EXPIRES, expires)
.header(LAST_MODIFIED, last_modified)
.body(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/client/backup.rs | crates/core/src/client/backup.rs | /// Endpoints for server-side key backups.
use std::collections::BTreeMap;
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{
OwnedRoomId,
identifiers::CrossSigningOrDeviceSignatures,
serde::{Base64, RawJson, RawJsonValue},
};
/// A wrapper around a mapping of session IDs to key data.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct RoomKeyBackup {
/// A map of session IDs to key data.
pub sessions: BTreeMap<String, KeyBackupData>,
}
impl RoomKeyBackup {
/// Creates a new `RoomKeyBackup` with the given sessions.
pub fn new(sessions: BTreeMap<String, KeyBackupData>) -> Self {
Self { sessions }
}
}
/// The algorithm used for storing backups.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "algorithm", content = "auth_data")]
pub enum BackupAlgorithm {
/// `m.megolm_backup.v1.curve25519-aes-sha2` backup algorithm.
#[serde(rename = "m.megolm_backup.v1.curve25519-aes-sha2")]
MegolmBackupV1Curve25519AesSha2 {
/// The curve25519 public key used to encrypt the backups, encoded in
/// unpadded base64.
#[salvo(schema(value_type = String))]
public_key: Base64,
/// Signatures of the auth_data as Signed JSON.
#[salvo(schema(value_type = Object, additional_properties = true))]
signatures: CrossSigningOrDeviceSignatures,
},
}
/// Information about the backup key.
///
/// To create an instance of this type.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct KeyBackupData {
/// The index of the first message in the session that the key can decrypt.
pub first_message_index: u64,
/// The number of times this key has been forwarded via key-sharing between
/// devices.
pub forwarded_count: u64,
/// Whether the device backing up the key verified the device that the key
/// is from.
pub is_verified: bool,
/// Encrypted data about the session.
pub session_data: RawJson<EncryptedSessionData>,
}
/// The encrypted algorithm-dependent data for backups.
///
/// To create an instance of this type.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct EncryptedSessionData {
/// Unpadded base64-encoded public half of the ephemeral key.
#[salvo(schema(value_type = String))]
pub ephemeral: Base64,
/// Ciphertext, encrypted using AES-CBC-256 with PKCS#7 padding, encoded in
/// base64.
#[salvo(schema(value_type = String))]
pub ciphertext: Base64,
/// First 8 bytes of MAC key, encoded in base64.
#[salvo(schema(value_type = String))]
pub mac: Base64,
}
// /// `PUT /_matrix/client/*/room_keys/keys/{room_id}`
// ///
// /// Store keys in the backup for a room.
//
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#put_matrixclientv3room_keyskeysroomid
// const METADATA: Metadata = metadata! {
// method: PUT,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/client/unstable/room_keys/keys/:room_id",
// 1.0 => "/_matrix/client/r0/room_keys/keys/:room_id",
// 1.1 => "/_matrix/client/v3/room_keys/keys/:room_id",
// }
// };
/// Response type for the `add_backup_keys_for_room` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct ModifyKeysResBody {
/// An opaque string representing stored keys in the backup.
///
/// Clients can compare it with the etag value they received in the request
/// of their last key storage request.
pub etag: String,
/// The number of keys stored in the backup.
pub count: u64,
}
impl ModifyKeysResBody {
/// Creates an new `Response` with the given etag and count.
pub fn new(etag: String, count: u64) -> Self {
Self { etag, count }
}
}
// /// `PUT /_matrix/client/*/room_keys/keys/{room_id}/{sessionId}`
// ///
// /// Store keys in the backup for a session.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#put_matrixclientv3room_keyskeysroomidsessionid
// const METADATA: Metadata = metadata! {
// method: PUT,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/client/unstable/room_keys/keys/:room_id/:session_id",
// 1.0 => "/_matrix/client/r0/room_keys/keys/:room_id/:session_id",
// 1.1 => "/_matrix/client/v3/room_keys/keys/:room_id/:session_id",
// }
// };
/// Request type for the `add_backup_keys_for_session` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct AddKeysForSessionReqBody(
/// The key information to store.
#[salvo(schema(value_type = Object, additional_properties = true))]
pub KeyBackupData,
);
// /// `POST /_matrix/client/*/room_keys/version`
// ///
// /// Create a new backup version.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3room_keysversion
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/client/unstable/room_keys/version",
// 1.1 => "/_matrix/client/v3/room_keys/version",
// }
// };
/// Request type for the `create_backup_version` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct CreateVersionReqBody(
/// The algorithm used for storing backups.
pub RawJson<BackupAlgorithm>,
);
/// Response type for the `create_backup_version` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct CreateVersionResBody {
/// The backup version.
pub version: String,
}
impl CreateVersionResBody {
/// Creates a new `Response` with the given version.
pub fn new(version: String) -> Self {
Self { version }
}
}
// /// `PUT /_matrix/client/*/room_keys/keys`
// ///
// /// Store keys in the backup.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#put_matrixclientv3room_keyskeys
// const METADATA: Metadata = metadata! {
// method: PUT,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/client/unstable/room_keys/keys",
// 1.1 => "/_matrix/client/v3/room_keys/keys",
// }
// };
/// Request type for the `add_backup_keys` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct AddKeysReqBody {
/// A map of room IDs to session IDs to key data to store.
pub rooms: BTreeMap<OwnedRoomId, RoomKeyBackup>,
}
// /// `DELETE /_matrix/client/*/room_keys/keys/{room_id}`
// ///
// /// Delete keys from a backup for a given room.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#delete_matrixclientv3room_keyskeysroomid
// const METADATA: Metadata = metadata! {
// method: DELETE,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/client/unstable/room_keys/keys/:room_id",
// 1.0 => "/_matrix/client/r0/room_keys/keys/:room_id",
// 1.1 => "/_matrix/client/v3/room_keys/keys/:room_id",
// }
// };
/// Request type for the `delete_backup_keys_for_room` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct KeysForRoomReqArgs {
/// The backup version from which to delete keys.
#[salvo(parameter(parameter_in = Query))]
pub version: i64,
/// The ID of the room to delete keys from.
#[salvo(parameter(parameter_in = Path))]
pub room_id: OwnedRoomId,
}
// /// `DELETE /_matrix/client/*/room_keys/keys/{room_id}/{session_id}`
// ///
// /// Delete keys from a backup for a given session.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#delete_matrixclientv3room_keyskeysroomidsessionid
// const METADATA: Metadata = metadata! {
// method: DELETE,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/client/unstable/room_keys/keys/:room_id/:session_id",
// 1.0 => "/_matrix/client/r0/room_keys/keys/:room_id/:session_id",
// 1.1 => "/_matrix/client/v3/room_keys/keys/:room_id/:session_id",
// }
// };
// /// `DELETE /_matrix/client/*/room_keys/keys`
// ///
// /// Delete all keys from a backup.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#delete_matrixclientv3room_keyskeys
// ///
// /// This deletes keys from a backup version, but not the version itself.
// const METADATA: Metadata = metadata! {
// method: DELETE,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/client/unstable/room_keys/keys",
// 1.0 => "/_matrix/client/r0/room_keys/keys",
// 1.1 => "/_matrix/client/v3/room_keys/keys",
// }
// };
// /// Request type for the `delete_backup_keys` endpoint.
// #[derive(ToSchema, Deserialize, Debug)]
// pub struct DeleteKeysReqBody {
// /// The backup version from which to delete keys.
// #[salvo(parameter(parameter_in = Query))]
// pub version: String,
// }
// /// `GET /_matrix/client/*/room_keys/version/{version}`
// ///
// /// Get information about a specific backup.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3room_keysversionversion
// https://github.com/rust-lang/rust/issues/112615
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/client/unstable/room_keys/version/:version",
// 1.1 => "/_matrix/client/v3/room_keys/version/:version",
// }
// };
/// Response type for the `get_backup_info` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct VersionResBody {
/// The algorithm used for storing backups.
#[serde(flatten)]
pub algorithm: BackupAlgorithm,
/// The number of keys stored in the backup.
pub count: u64,
/// An opaque string representing stored keys in the backup.
///
/// Clients can compare it with the etag value they received in the request
/// of their last key storage request.
pub etag: String,
/// The backup version.
pub version: String,
}
impl VersionResBody {
/// Creates a new `Response` with the given algorithm, key count, etag and
/// version.
pub fn new(algorithm: BackupAlgorithm, count: u64, etag: String, version: String) -> Self {
Self {
algorithm,
count,
etag,
version,
}
}
}
// #[derive(Deserialize)]
// pub(crate) struct ResponseBodyRepr {
// pub algorithm: Box<RawJsonValue>,
// pub auth_data: Box<RawJsonValue>,
// pub count: u64,
// pub etag: String,
// pub version: String,
// }
// #[derive(Serialize)]
// pub(crate) struct RefResponseBodyRepr<'a> {
// pub algorithm: &'a RawJsonValue,
// pub auth_data: &'a RawJsonValue,
// pub count: u64,
// pub etag: &'a str,
// pub version: &'a str,
// }
#[derive(Deserialize, Serialize)]
pub(crate) struct AlgorithmWithData {
pub algorithm: Box<RawJsonValue>,
pub auth_data: Box<RawJsonValue>,
}
// impl<'de> Deserialize<'de> for ResponseBody {
// fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
// where
// D: Deserializer<'de>,
// {
// let ResponseBodyRepr {
// algorithm,
// auth_data,
// count,
// etag,
// version,
// } = ResponseBodyRepr::deserialize(deserializer)?;
// let algorithm =
// RawJson::from_json(to_raw_json_value(&AlgorithmWithData { algorithm,
// auth_data }).unwrap());
// Ok(Self {
// algorithm,
// count,
// etag,
// version,
// })
// }
// }
// impl Serialize for ResponseBody {
// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
// where
// S: serde::Serializer,
// {
// let ResponseBody {
// algorithm,
// count,
// etag,
// version,
// } = self;
// let AlgorithmWithData { algorithm, auth_data } =
// algorithm.deserialize_as().map_err(ser::Error::custom)?;
// let repr = RefResponseBodyRepr {
// algorithm: &algorithm,
// auth_data: &auth_data,
// count: *count,
// etag,
// version,
// };
// repr.serialize(serializer)
// }
// }
// /// `GET /_matrix/client/*/room_keys/keys/{room_id}`
// ///
// /// Retrieve sessions from the backup for a given room.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3room_keyskeysroomid
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/client/unstable/room_keys/keys/:room_id",
// 1.0 => "/_matrix/client/r0/room_keys/keys/:room_id",
// 1.1 => "/_matrix/client/v3/room_keys/keys/:room_id",
// }
// };
/// Request type for the `get_backup_keys_for_room` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct AddKeysForRoomReqBody {
/// A map of session IDs to key data.
#[salvo(schema(value_type = Object, additional_properties = true))]
pub sessions: BTreeMap<String, KeyBackupData>,
}
impl AddKeysForRoomReqBody {
/// Creates a new `Response` with the given sessions.
pub fn new(sessions: BTreeMap<String, KeyBackupData>) -> Self {
Self { sessions }
}
}
// /// `GET /_matrix/client/*/room_keys/keys/{room_id}/{session_id}`
// ///
// /// Retrieve a key from the backup for a given session.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3room_keyskeysroomidsessionid
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/client/unstable/room_keys/keys/:room_id/:session_id",
// 1.0 => "/_matrix/client/r0/room_keys/keys/:room_id/:session_id",
// 1.1 => "/_matrix/client/v3/room_keys/keys/:room_id/:session_id",
// }
// };
/// Request type for the `get_backup_keys_for_session` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct KeysForSessionReqArgs {
/// The backup version to retrieve keys from.
#[salvo(parameter(parameter_in = Query))]
pub version: i64,
/// The ID of the room that the requested key is for.
#[salvo(parameter(parameter_in = Path))]
pub room_id: OwnedRoomId,
/// The ID of the megolm session whose key is requested.
#[salvo(parameter(parameter_in = Path))]
pub session_id: String,
}
// /// Response type for the `get_backup_keys_for_session` endpoint.
// #[derive(ToSchema, Serialize, Debug)]
// pub struct KeysForSessionResBody (
// /// Information about the requested backup key.
// pub RawJson<KeyBackupData>,
// );
// impl KeysForSessionResBody {
// /// Creates a new `Response` with the given key_data.
// pub fn new(key_data: RawJson<KeyBackupData>) -> Self {
// Self (key_data)
// }
// }
// /// `GET /_matrix/client/*/room_keys/keys`
// ///
// /// Retrieve all keys from a backup version.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3room_keyskeys
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/client/unstable/room_keys/keys",
// 1.0 => "/_matrix/client/r0/room_keys/keys",
// 1.1 => "/_matrix/client/v3/room_keys/keys",
// }
// };
// /// Request type for the `get_backup_keys` endpoint.
// pub struct Requxest {
// /// The backup version to retrieve keys from.
// #[salvo(parameter(parameter_in = Query))]
// pub version: String,
// }
/// Response type for the `get_backup_keys` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct KeysResBody {
/// A map from room IDs to session IDs to key data.
pub rooms: BTreeMap<OwnedRoomId, RawJson<RoomKeyBackup>>,
}
impl KeysResBody {
/// Creates a new `Response` with the given room key backups.
pub fn new(rooms: BTreeMap<OwnedRoomId, RawJson<RoomKeyBackup>>) -> Self {
Self { rooms }
}
}
#[derive(ToSchema, Serialize, Debug)]
pub struct KeysForRoomResBody {
/// A map from room IDs to session IDs to key data.
pub sessions: BTreeMap<OwnedRoomId, RawJson<RoomKeyBackup>>,
}
impl KeysForRoomResBody {
/// Creates a new `Response` with the given room key backups.
pub fn new(sessions: BTreeMap<OwnedRoomId, RawJson<RoomKeyBackup>>) -> Self {
Self { sessions }
}
}
// /// `PUT /_matrix/client/*/room_keys/version/{version}`
// ///
// /// Update information about an existing backup.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#put_matrixclientv3room_keysversionversion
// const METADATA: Metadata = metadata! {
// method: PUT,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/client/unstable/room_keys/version/:version",
// 1.1 => "/_matrix/client/v3/room_keys/version/:version",
// }
// };
/// Request type for the `update_backup_version` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct UpdateVersionReqBody(
/// The algorithm used for storing backups.
pub BackupAlgorithm,
);
| 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/client/http_header.rs | crates/core/src/client/http_header.rs | //! Helpers for HTTP headers with the `http` crate.
#![allow(clippy::declare_interior_mutable_const)]
use http::{HeaderValue, header::HeaderName};
use web_time::{Duration, SystemTime, UNIX_EPOCH};
use crate::error::{HeaderDeserializationError, HeaderSerializationError};
pub use crate::http_headers::{
ContentDisposition, ContentDispositionParseError, ContentDispositionType, TokenString,
TokenStringParseError,
};
/// The [`Cross-Origin-Resource-Policy`] HTTP response header.
///
/// [`Cross-Origin-Resource-Policy`]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy
pub const CROSS_ORIGIN_RESOURCE_POLICY: HeaderName =
HeaderName::from_static("cross-origin-resource-policy");
/// Convert as `SystemTime` to a HTTP date header value.
pub fn system_time_to_http_date(
time: &SystemTime,
) -> Result<HeaderValue, HeaderSerializationError> {
let mut buffer = [0; 29];
let duration = time
.duration_since(UNIX_EPOCH)
.map_err(|_| HeaderSerializationError::InvalidHttpDate)?;
date_header::format(duration.as_secs(), &mut buffer)
.map_err(|_| HeaderSerializationError::InvalidHttpDate)?;
Ok(HeaderValue::from_bytes(&buffer).expect("date_header should produce a valid header value"))
}
/// Convert a header value representing a HTTP date to a `SystemTime`.
pub fn http_date_to_system_time(
value: &HeaderValue,
) -> Result<SystemTime, HeaderDeserializationError> {
let bytes = value.as_bytes();
let ts = date_header::parse(bytes).map_err(|_| HeaderDeserializationError::InvalidHttpDate)?;
UNIX_EPOCH
.checked_add(Duration::from_secs(ts))
.ok_or(HeaderDeserializationError::InvalidHttpDate)
}
| 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/client/membership.rs | crates/core/src/client/membership.rs | //! Endpoints for room membership.
use std::collections::BTreeMap;
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use crate::events::room::member::RoomMemberEvent;
use crate::serde::{JsonValue, RawJson, StringEnum};
use crate::third_party::Medium;
use crate::{
OwnedMxcUri, OwnedRoomId, OwnedServerName, OwnedServerSigningKeyId, OwnedUserId, PrivOwnedStr,
};
/// A signature of an `m.third_party_invite` token to prove that this user owns
/// a third party identity which has been invited to the room.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct ThirdPartySigned {
/// The Matrix ID of the user who issued the invite.
pub sender: OwnedUserId,
/// The Matrix ID of the invitee.
pub mxid: OwnedUserId,
/// The state key of the `m.third_party_invite` event.
pub token: String,
/// A signatures object containing a signature of the entire signed object.
pub signatures: BTreeMap<OwnedServerName, BTreeMap<OwnedServerSigningKeyId, String>>,
}
impl ThirdPartySigned {
/// Creates a new `ThirdPartySigned` from the given sender and invitee user
/// IDs, state key token and signatures.
pub fn new(
sender: OwnedUserId,
mxid: OwnedUserId,
token: String,
signatures: BTreeMap<OwnedServerName, BTreeMap<OwnedServerSigningKeyId, String>>,
) -> Self {
Self {
sender,
mxid,
token,
signatures,
}
}
}
/// Represents third party IDs to invite to the room.
///
/// To create an instance of this type.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct InviteThreepid {
/// Hostname and port of identity server to be used for account lookups.
pub id_server: String,
/// An access token registered with the identity server.
pub id_access_token: String,
/// Type of third party ID.
pub medium: Medium,
/// Third party identifier.
pub address: String,
}
// const METADATA: Metadata = metadata! {
// method: `POST,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/rooms/:room_id/ban",
// 1.1 => "/_matrix/client/v3/rooms/:room_id/ban",
// }
// };
/// Request type for the `ban_user` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct BanUserReqBody {
// /// The room to kick the user from.
// #[salvo(parameter(parameter_in = Path))]
// pub room_id: OwnedRoomId,
/// The user to ban.
pub user_id: OwnedUserId,
/// The reason for banning the user.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
// /// `POST /_matrix/client/*/rooms/{room_id}/unban`
// ///
// /// Unban a user from a room.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3roomsroomidunban
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/rooms/:room_id/unban",
// 1.1 => "/_matrix/client/v3/rooms/:room_id/unban",
// }
// };
/// Request type for the `unban_user` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct UnbanUserReqBody {
// /// The room to unban the user from.
// #[salvo(parameter(parameter_in = Path))]
// pub room_id: OwnedRoomId,
/// The user to unban.
pub user_id: OwnedUserId,
/// Optional reason for unbanning the user.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
/// Distinguishes between invititations by Matrix or third party identifiers.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[serde(untagged)]
pub enum InvitationRecipient {
/// Used to invite user by their Matrix identifier.
UserId {
/// Matrix identifier of user.
user_id: OwnedUserId,
},
/// Used to invite user by a third party identifier.
ThirdPartyId(InviteThreepid),
}
// /// `POST /_matrix/client/*/rooms/{room_id}/kick`
// ///
// /// Kick a user from a room.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3roomsroomidkick
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/rooms/:room_id/kick",
// 1.1 => "/_matrix/client/v3/rooms/:room_id/kick",
// }
// };
/// Request type for the `kick_user` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct KickUserReqBody {
// /// The room to kick the user from.
// #[salvo(parameter(parameter_in = Path))]
// pub room_id: OwnedRoomId,
/// The user to kick.
pub user_id: OwnedUserId,
/// The reason for kicking the user.
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
// /// `POST /_matrix/client/*/rooms/{room_id}/invite`
// ///
// /// Invite a user to a room.
// /// `/v3/` ([spec (MXID)][spec-mxid], [spec (3PID)][spec-3pid])
// ///
// /// This endpoint has two forms: one to invite a user
// /// [by their Matrix identifier][spec-mxid], and one to invite a user
// /// [by their third party identifier][spec-3pid].
// ///
// /// [spec-mxid]: https://spec.matrix.org/v1.9/client-server-api/#post_matrixclientv3roomsroomidinvite
// /// [spec-3pid]: https://spec.matrix.org/v1.9/client-server-api/#post_matrixclientv3roomsroomidinvite-1
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/rooms/:room_id/invite",
// 1.1 => "/_matrix/client/v3/rooms/:room_id/invite",
// }
// };
/// Request type for the `invite_user` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct InviteUserReqBody {
/// The user to invite.
#[serde(flatten)]
pub recipient: InvitationRecipient,
/// Optional reason for inviting the user.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
// /// `POST /_matrix/client/*/rooms/{room_id}/leave`
// ///
// /// Leave a room.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3roomsroomidleave
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/rooms/:room_id/leave",
// 1.1 => "/_matrix/client/v3/rooms/:room_id/leave",
// }
// };
/// Request type for the `leave_room` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct LeaveRoomReqBody {
/// Optional reason to be included as the `reason` on the subsequent
/// membership event.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
// /// `GET /_matrix/client/*/user/mutual_rooms/{user_id}`
// ///
// /// Get mutual rooms with another user.
// /// `/unstable/` ([spec])
// ///
// /// [spec]: https://github.com/matrix-org/matrix-spec-proposals/blob/hs/shared-rooms/proposals/2666-get-rooms-in-common.md
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/client/unstable/uk.half-shot.msc2666/user/mutual_rooms",
// }
// };
/// Request type for the `mutual_rooms` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct MutualRoomsReqBody {
/// The user to search mutual rooms for.
#[salvo(parameter(parameter_in = Query))]
pub user_id: OwnedUserId,
/// The `next_batch_token` returned from a previous response, to get the
/// next batch of rooms.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[salvo(parameter(parameter_in = Query))]
pub batch_token: Option<String>,
}
/// Response type for the `mutual_rooms` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct MutualRoomsResBody {
/// A list of rooms the user is in together with the authenticated user.
pub joined: Vec<OwnedRoomId>,
/// An opaque string, returned when the server paginates this response.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub next_batch_token: Option<String>,
}
impl MutualRoomsResBody {
/// Creates a `Response` with the given room ids.
pub fn new(joined: Vec<OwnedRoomId>) -> Self {
Self {
joined,
next_batch_token: None,
}
}
/// Creates a `Response` with the given room ids, together with a batch
/// token.
pub fn with_token(joined: Vec<OwnedRoomId>, token: String) -> Self {
Self {
joined,
next_batch_token: Some(token),
}
}
}
// /// `GET /_matrix/client/*/joined_rooms`
// ///
// /// Get a list of the user's current rooms.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3joined_rooms
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/joined_rooms",
// 1.1 => "/_matrix/client/v3/joined_rooms",
// }
// };
/// Response type for the `joined_rooms` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct JoinedRoomsResBody {
/// A list of the rooms the user is in, i.e. the ID of each room in
/// which the user has joined membership.
pub joined_rooms: Vec<OwnedRoomId>,
}
impl JoinedRoomsResBody {
/// Creates a new `Response` with the given joined rooms.
pub fn new(joined_rooms: Vec<OwnedRoomId>) -> Self {
Self { joined_rooms }
}
}
// /// `POST /_matrix/client/*/rooms/{room_id}/forget`
// ///
// /// Forget a room.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3roomsroomidforget
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/rooms/:room_id/forget",
// 1.1 => "/_matrix/client/v3/rooms/:room_id/forget",
// }
// };
// /// Request type for the `forget_room` endpoint.
// pub struct ForgetReqBody {
// /// The room to forget.
// #[salvo(parameter(parameter_in = Path))]
// pub room_id: OwnedRoomId,
// }
// /// `POST /_matrix/client/*/rooms/{room_id}/join`
// ///
// /// Join a room using its ID.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3roomsroomidjoin
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/rooms/:room_id/join",
// 1.1 => "/_matrix/client/v3/rooms/:room_id/join",
// }
// };
/// Request type for the `join_room_by_id` endpoint.
#[derive(ToSchema, Deserialize, Default, Debug)]
pub struct JoinRoomReqBody {
/// The signature of a `m.third_party_invite` token to prove that this user
/// owns a third party identity which has been invited to the room.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub third_party_signed: Option<ThirdPartySigned>,
/// Optional reason for joining the room.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
/// Optional extra parameters to be sent to the server.
#[serde(default, flatten, skip_serializing_if = "BTreeMap::is_empty")]
#[salvo(schema(value_type = Object, additional_properties = true))]
pub extra_data: BTreeMap<String, JsonValue>,
}
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/join/:room_id_or_alias",
// 1.1 => "/_matrix/client/v3/join/:room_id_or_alias",
// }
// };
// /// Request type for the `join_room_by_id_or_alias` endpoint.
// #[derive(ToSchema, Default, Deserialize, Debug)]
// pub struct JoinRoomByIdOrAliasReqBody {
// /// The signature of a `m.third_party_invite` token to prove that this user
// /// owns a third party identity which has been invited to the room.
// pub third_party_signed: Option<ThirdPartySigned>,
// /// Optional reason for joining the room.
// #[serde(skip_serializing_if = "Option::is_none")]
// pub reason: Option<String>,
// }
/// Response type for the `join_room_by_id` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct JoinRoomResBody {
/// The room that the user joined.
pub room_id: OwnedRoomId,
}
impl JoinRoomResBody {
/// Creates a new `Response` with the given room id.
pub fn new(room_id: OwnedRoomId) -> Self {
Self { room_id }
}
}
// /// `GET /_matrix/client/*/rooms/{room_id}/members`
// ///
// /// Get membership events for a room.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3roomsroomidmembers
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/rooms/:room_id/members",
// 1.1 => "/_matrix/client/v3/rooms/:room_id/members",
// }
// };
/// Request type for the `get_member_events` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct MembersReqArgs {
/// The room to get the member events for.
#[salvo(parameter(parameter_in = Path))]
pub room_id: OwnedRoomId,
/// The point in time (pagination token) to return members for in the room.
///
/// This token can be obtained from a prev_batch token returned for each
/// room by the sync API.
#[serde(skip_serializing_if = "Option::is_none")]
#[salvo(parameter(parameter_in = Query))]
pub at: Option<String>,
/// The kind of memberships to filter for.
///
/// Defaults to no filtering if unspecified. When specified alongside
/// not_membership, the two parameters create an 'or' condition: either
/// the membership is the same as membership or is not the same as
/// not_membership.
#[serde(skip_serializing_if = "Option::is_none")]
#[salvo(parameter(parameter_in = Query))]
pub membership: Option<MembershipEventFilter>,
/// The kind of memberships to *exclude* from the results.
///
/// Defaults to no filtering if unspecified.
#[serde(skip_serializing_if = "Option::is_none")]
#[salvo(parameter(parameter_in = Query))]
pub not_membership: Option<MembershipEventFilter>,
}
/// Response type for the `get_member_events` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct MembersResBody {
/// A list of member events.
#[salvo(schema(value_type = Vec<Object>))]
pub chunk: Vec<RawJson<RoomMemberEvent>>,
}
impl MembersResBody {
/// Creates a new `Response` with the given member event chunk.
pub fn new(chunk: Vec<RawJson<RoomMemberEvent>>) -> Self {
Self { chunk }
}
}
/// The kind of membership events to filter for.
#[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 MembershipEventFilter {
/// The user has joined.
Join,
/// The user has been invited.
Invite,
/// The user has left.
Leave,
/// The user has been banned.
Ban,
/// The user has knocked.
Knock,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
// /// `GET /_matrix/client/*/rooms/{room_id}/joined_members`
// ///
// /// Get a map of user IDs to member info objects for members of the room.
// /// Primarily for use in Application Services.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3roomsroomidjoined_members
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/rooms/:room_id/joined_members",
// 1.1 => "/_matrix/client/v3/rooms/:room_id/joined_members",
// }
// };
// /// Request type for the `joined_members` endpoint.
// pub struct JoinedMembersReqBody {
// /// The room to get the members of.
// #[salvo(parameter(parameter_in = Path))]
// pub room_id: OwnedRoomId,
// }
/// Response type for the `joined_members` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct JoinedMembersResBody {
/// A list of the rooms the user is in, i.e.
/// the ID of each room in which the user has joined membership.
pub joined: BTreeMap<OwnedUserId, RoomMember>,
}
impl JoinedMembersResBody {
/// Creates a new `Response` with the given joined rooms.
pub fn new(joined: BTreeMap<OwnedUserId, RoomMember>) -> Self {
Self { joined }
}
}
/// Information about a room member.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct RoomMember {
/// The display name of the user.
// #[serde(default, skip_serializing_if = "Option::is_none")]
#[serde(default)]
pub display_name: Option<String>,
/// The mxc avatar url of the user.
#[serde(
// skip_serializing_if = "Option::is_none",
default,
deserialize_with = "crate::serde::empty_string_as_none"
)]
pub avatar_url: Option<OwnedMxcUri>,
}
impl RoomMember {
/// Creates an empty `RoomMember`.
pub fn new(display_name: Option<String>, avatar_url: Option<OwnedMxcUri>) -> Self {
Self {
display_name,
avatar_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/client/typing.rs | crates/core/src/client/typing.rs | //! `PUT /_matrix/client/*/rooms/{room_id}/typing/{user_id}`
//!
//! Send a typing event to a room.
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/latest/client-server-api/#put_matrixclientv3roomsroomidtypinguser_id
use std::time::Duration;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Deserializer, Serialize, de::Error};
// const METADATA: Metadata = metadata! {
// method: PUT,
// authentication: AccessToken,
// rate_limited: true,
// history: {
// 1.0 => "/_matrix/client/r0/rooms/:room_id/typing/:user_id",
// 1.1 => "/_matrix/client/v3/rooms/:room_id/typing/:user_id",
// }
// };
// /// Request type for the `create_typing_event` endpoint.
// #[derive(ToParameters, Deserialize, Debug)]
// pub struct CreateTypingEventReqArgs {
// /// The room in which the user is typing.
// #[salvo(parameter(parameter_in = Path))]
// pub room_id: OwnedRoomId,
// /// The user who has started to type.
// #[salvo(parameter(parameter_in = Path))]
// pub user_id: OwnedUserId,
// }
/// Request type for the `create_typing_event` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct CreateTypingEventReqBody {
/// Whether the user is typing within a length of time or not.
#[serde(flatten)]
pub state: Typing,
}
/// A mark for whether the user is typing within a length of time or not.
#[derive(ToSchema, Clone, Copy, Debug, Serialize)]
#[serde(into = "TypingInner")]
#[allow(clippy::exhaustive_enums)]
pub enum Typing {
/// Not typing.
No,
/// Typing during the specified length of time.
Yes(Duration),
}
#[derive(Deserialize, Serialize)]
struct TypingInner {
typing: bool,
#[serde(
with = "crate::serde::duration::opt_ms",
default,
skip_serializing_if = "Option::is_none"
)]
timeout: Option<Duration>,
}
impl From<Typing> for TypingInner {
fn from(typing: Typing) -> Self {
match typing {
Typing::No => Self {
typing: false,
timeout: None,
},
Typing::Yes(time) => Self {
typing: true,
timeout: Some(time),
},
}
}
}
impl<'de> Deserialize<'de> for Typing {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let inner = TypingInner::deserialize(deserializer)?;
match (inner.typing, inner.timeout) {
(false, _) => Ok(Self::No),
(true, Some(time)) => Ok(Self::Yes(time)),
_ => Err(D::Error::missing_field("timeout")),
}
}
}
| 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/client/sync_events.rs | crates/core/src/client/sync_events.rs | //! `GET /_matrix/client/*/sync`
//!
//! Get all new events from all rooms since the last sync or a given point in
//! time.
use salvo::prelude::*;
use serde::{self, Deserialize, Serialize};
pub mod v3;
pub mod v5;
/// Unread notifications count.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct UnreadNotificationsCount {
/// The number of unread notifications with the highlight flag set.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub highlight_count: Option<u64>,
/// The total number of unread notifications.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub notification_count: Option<u64>,
}
impl UnreadNotificationsCount {
/// Creates an empty `UnreadNotificationsCount`.
pub fn new() -> Self {
Default::default()
}
/// Returns true if there are no notification count updates.
pub fn is_empty(&self) -> bool {
self.highlight_count.is_none() && self.notification_count.is_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/client/server.rs | crates/core/src/client/server.rs | //! `GET /_matrix/client/*/admin/whois/{user_id}`
//!
//! Get information about a particular user.
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3adminwhoisuser_id
use std::collections::BTreeMap;
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{OwnedUserId, UnixMillis};
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/admin/whois/:user_id",
// 1.1 => "/_matrix/client/v3/admin/whois/:user_id",
// }
// };
// /// Request type for the `get_user_info` endpoint.
// #[derive(ToParameters, Deserialize, Debug)]
// pub struct UserInfoReqArgs {
// /// The user to look up.
// #[salvo(parameter(parameter_in = Path))]
// pub user_id: OwnedUserId,
// }
/// Response type for the `get_user_info` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct UserInfoResBody {
/// The Matrix user ID of the user.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub user_id: Option<OwnedUserId>,
/// A map of the user's device identifiers to information about that device.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub devices: BTreeMap<String, DeviceInfo>,
}
/// Information about a user's device.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct DeviceInfo {
/// A list of user sessions on this device.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub sessions: Vec<SessionInfo>,
}
impl DeviceInfo {
/// Create a new `DeviceInfo` with no sessions.
pub fn new() -> Self {
Self::default()
}
}
/// Information about a user session.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct SessionInfo {
/// A list of connections in this session.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub connections: Vec<ConnectionInfo>,
}
impl SessionInfo {
/// Create a new `SessionInfo` with no connections.
pub fn new() -> Self {
Self::default()
}
}
/// Information about a connection in a user session.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct ConnectionInfo {
/// Most recently seen IP address of the session.
pub ip: Option<String>,
/// Time when that the session was last active.
pub last_seen: Option<UnixMillis>,
/// User agent string last seen in the session.
pub user_agent: Option<String>,
}
impl ConnectionInfo {
/// Create a new `ConnectionInfo` 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/client/voip.rs | crates/core/src/client/voip.rs | //! `GET /_matrix/client/*/voip/turnServer`
//!
//! Get credentials for the client to use when initiating VoIP calls.
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3voipturnserver
use std::time::Duration;
use salvo::prelude::*;
use serde::Serialize;
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/voip/turnServer",
// 1.1 => "/_matrix/client/v3/voip/turnServer",
// }
// };
/// Response type for the `turn_server_info` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct TurnServerResBody {
/// The username to use.
pub username: String,
/// The password to use.
pub password: String,
/// A list of TURN URIs.
pub uris: Vec<String>,
/// The time-to-live in seconds.
#[serde(with = "palpo_core::serde::duration::secs")]
pub ttl: Duration,
}
impl TurnServerResBody {
/// Creates a new `Response` with the given username, password, TURN URIs
/// and time-to-live.
pub fn new(username: String, password: String, uris: Vec<String>, ttl: Duration) -> Self {
Self {
username,
password,
uris,
ttl,
}
}
}
| 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/client/authenticated_media.rs | crates/core/src/client/authenticated_media.rs | //! Authenticated endpoints for the [content repository].
//!
//! [content repository]: https://spec.matrix.org/latest/client-server-api/#content-repository
pub mod get_content;
pub mod get_content_as_filename;
pub mod get_content_thumbnail;
pub mod get_media_config;
pub mod get_media_preview;
| 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/client/space.rs | crates/core/src/client/space.rs | use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{
EventEncryptionAlgorithm, OwnedMxcUri, OwnedRoomAliasId, OwnedRoomId, RoomVersionId,
events::space::child::HierarchySpaceChildEvent, room::RoomType, serde::RawJson,
space::SpaceRoomJoinRule,
};
/// Endpoints for spaces.
///
/// See the [Matrix specification][spec] for more details about spaces.
///
/// [spec]: https://spec.matrix.org/latest/client-server-api/#spaces
/// A chunk of a space hierarchy response, describing one room.
///
/// To create an instance of this type.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct SpaceHierarchyRoomsChunk {
/// The canonical alias of the room, if any.
#[serde(
skip_serializing_if = "Option::is_none",
default,
deserialize_with = "crate::serde::empty_string_as_none"
)]
pub canonical_alias: Option<OwnedRoomAliasId>,
/// The name of the room, if any.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// The number of members joined to the room.
#[serde(default)]
pub num_joined_members: u64,
/// The ID of the room.
pub room_id: OwnedRoomId,
/// The topic of the room, if any.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub topic: Option<String>,
/// Whether the room may be viewed by guest users without joining.
#[serde(default)]
pub world_readable: bool,
/// Whether guest users may join the room and participate in it.
///
/// If they can, they will be subject to ordinary power level rules like any
/// other user.
#[serde(default)]
pub guest_can_join: bool,
/// The URL for the room's avatar, if one is set.
#[serde(
skip_serializing_if = "Option::is_none",
default,
deserialize_with = "crate::serde::empty_string_as_none"
)]
pub avatar_url: Option<OwnedMxcUri>,
/// The join rule of the room.
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub join_rule: SpaceRoomJoinRule,
/// The type of room from `m.room.create`, if any.
#[serde(skip_serializing_if = "Option::is_none")]
pub room_type: Option<RoomType>,
/// The stripped `m.space.child` events of the space-room.
///
/// If the room is not a space-room, this should be empty.
pub children_state: Vec<RawJson<HierarchySpaceChildEvent>>,
/// If the room is encrypted, the algorithm used for this room.
#[serde(
skip_serializing_if = "Option::is_none",
rename = "im.nheko.summary.encryption",
alias = "encryption"
)]
pub encryption: Option<EventEncryptionAlgorithm>,
/// Version of the room.
#[serde(
skip_serializing_if = "Option::is_none",
rename = "im.nheko.summary.room_version",
alias = "im.nheko.summary.version",
alias = "room_version"
)]
pub room_version: Option<RoomVersionId>,
/// If the room is a restricted room, these are the room IDs which are
/// specified by the join rules.
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub allowed_room_ids: Vec<OwnedRoomId>,
}
// /// `GET /_matrix/client/*/rooms/{room_id}/hierarchy`
// ///
// /// Paginates over the space tree in a depth-first manner to locate child rooms
// /// of a given space. `/v1/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv1roomsroomidhierarchy
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/client/unstable/org.matrix.msc2946/rooms/:room_id/hierarchy",
// 1.2 => "/_matrix/client/v1/rooms/:room_id/hierarchy",
// }
// };
/// Request type for the `hierarchy` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct HierarchyReqArgs {
/// The room ID of the space to get a hierarchy for.
#[salvo(parameter(parameter_in = Path))]
pub room_id: OwnedRoomId,
/// A pagination token from a previous result.
///
/// If specified, `max_depth` and `suggested_only` cannot be changed from
/// the first request.
#[salvo(parameter(parameter_in = Query))]
pub from: Option<String>,
/// The maximum number of rooms to include per response.
#[salvo(parameter(parameter_in = Query))]
pub limit: Option<usize>,
/// How far to go into the space.
///
/// When reached, no further child rooms will be returned.
#[salvo(parameter(parameter_in = Query))]
pub max_depth: Option<usize>,
/// Whether or not the server should only consider suggested rooms.
///
/// Suggested rooms are annotated in their `m.space.child` event contents.
///
/// Defaults to `false`.
#[salvo(parameter(parameter_in = Query))]
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub suggested_only: bool,
}
/// Response type for the `hierarchy` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct HierarchyResBody {
/// A token to supply to from to keep paginating the responses.
///
/// Not present when there are no further results.
#[serde(skip_serializing_if = "Option::is_none")]
pub next_batch: Option<String>,
/// A paginated chunk of the space children.
pub rooms: Vec<SpaceHierarchyRoomsChunk>,
}
| 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/client/tag.rs | crates/core/src/client/tag.rs | use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{
OwnedRoomId, OwnedUserId,
events::tag::{TagInfo, Tags},
};
// /// `GET /_matrix/client/*/user/{user_id}/rooms/{room_id}/tags`
// ///
// /// Get the tags associated with a room.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3useruser_idroomsroomidtags
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/user/:user_id/rooms/:room_id/tags",
// 1.1 => "/_matrix/client/v3/user/:user_id/rooms/:room_id/tags",
// }
// };
// /// Request type for the `get_tags` endpoint.
// #[derive(ToParameters, Deserialize, Debug)]
// pub struct TagsReqArgs {
// /// The user whose tags will be retrieved.
// #[salvo(parameter(parameter_in = Path))]
// pub user_id: OwnedUserId,
// /// The room from which tags will be retrieved.
// #[salvo(parameter(parameter_in = Path))]
// pub room_id: OwnedRoomId,
// }
/// Response type for the `get_tags` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct TagsResBody {
/// The user's tags for the room.
#[salvo(schema(value_type = Object, additional_properties = true))]
pub tags: Tags,
}
impl TagsResBody {
/// Creates a new `Response` with the given tags.
pub fn new(tags: Tags) -> Self {
Self { tags }
}
}
// /// `DELETE /_matrix/client/*/user/{user_id}/rooms/{room_id}/tags/{tag}`
// ///
// /// Remove a tag from a room.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#put_matrixclientv3useruser_idroomsroomidtagstag
// const METADATA: Metadata = metadata! {
// method: DELETE,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/user/:user_id/rooms/:room_id/tags/:tag",
// 1.1 => "/_matrix/client/v3/user/:user_id/rooms/:room_id/tags/:tag",
// }
// };
// /// Request type for the `delete_tag` endpoint.
// pub struct DeleteTagReqBody {
// /// The user whose tag will be deleted.
// #[salvo(parameter(parameter_in = Path))]
// pub user_id: OwnedUserId,
// /// The tagged room.
// #[salvo(parameter(parameter_in = Path))]
// pub room_id: OwnedRoomId,
// /// The name of the tag to delete.
// #[salvo(parameter(parameter_in = Path))]
// pub tag: String,
// }
// /// `PUT /_matrix/client/*/user/{user_id}/rooms/{room_id}/tags/{tag}`
// ///
// /// Add a new tag to a room.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#put_matrixclientv3useruser_idroomsroomidtagstag
// const METADATA: Metadata = metadata! {
// method: PUT,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/user/:user_id/rooms/:room_id/tags/:tag",
// 1.1 => "/_matrix/client/v3/user/:user_id/rooms/:room_id/tags/:tag",
// }
// };
/// Request args for the `create_tag` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct OperateTagReqArgs {
/// The ID of the user creating the tag.
#[salvo(parameter(parameter_in = Path))]
pub user_id: OwnedUserId,
/// The room to tag.
#[salvo(parameter(parameter_in = Path))]
pub room_id: OwnedRoomId,
/// The name of the tag to create.
#[salvo(parameter(parameter_in = Path))]
pub tag: String,
}
/// Request type for the `create_tag` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct UpsertTagReqBody {
/// Info about the tag.
pub tag_info: TagInfo,
}
| 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/client/message.rs | crates/core/src/client/message.rs | use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{
Direction, OwnedEventId, OwnedRoomId, OwnedTransactionId, UnixMillis,
client::filter::RoomEventFilter,
events::{AnyStateEvent, AnyTimelineEvent, MessageLikeEventType},
serde::RawJson,
};
// /// `GET /_matrix/client/*/rooms/{room_id}/messages`
// ///
// /// Get message events for a room.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3roomsroomidmessages
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/rooms/:room_id/messages",
// 1.1 => "/_matrix/client/v3/rooms/:room_id/messages",
// }
// };
/// Request type for the `get_message_events` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct MessagesReqArgs {
/// The room to get events from.
#[salvo(parameter(parameter_in = Path))]
pub room_id: OwnedRoomId,
/// The token to start returning events from.
///
/// This token can be obtained from a `prev_batch` token returned for each
/// room by the sync endpoint, or from a `start` or `end` token returned
/// by a previous request to this endpoint.
///
/// If this is `None`, the server will return messages from the start or end
/// of the history visible to the user, depending on the value of
/// [`dir`][Self::dir].
#[serde(default)]
#[salvo(parameter(parameter_in = Query))]
pub from: Option<String>,
/// The token to stop returning events at.
///
/// This token can be obtained from a `prev_batch` token returned for each
/// room by the sync endpoint, or from a `start` or `end` token returned
/// by a previous request to this endpoint.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[salvo(parameter(parameter_in = Query))]
pub to: Option<String>,
/// The direction to return events from.
#[serde(default)]
#[salvo(parameter(parameter_in = Query))]
pub dir: Direction,
/// The maximum number of events to return.
///
/// Default: `10`.
#[serde(default = "default_limit", skip_serializing_if = "is_default_limit")]
#[salvo(parameter(parameter_in = Query))]
pub limit: usize,
/// A [`RoomEventFilter`] to filter returned events with.
#[serde(
with = "crate::serde::json_string",
default,
skip_serializing_if = "RoomEventFilter::is_empty"
)]
#[salvo(parameter(parameter_in = Query))]
pub filter: RoomEventFilter,
}
/// Response type for the `get_message_events` endpoint.
#[derive(ToSchema, Default, Serialize, Debug)]
pub struct MessagesResBody {
/// The token the pagination starts from.
pub start: String,
/// The token the pagination ends at.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub end: Option<String>,
/// A list of room events.
#[serde(default)]
#[salvo(schema(value_type = Object, additional_properties = true))]
pub chunk: Vec<RawJson<AnyTimelineEvent>>,
/// A list of state events relevant to showing the `chunk`.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
#[salvo(schema(value_type = Object, additional_properties = true))]
pub state: Vec<RawJson<AnyStateEvent>>,
}
fn default_limit() -> usize {
10
}
#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_default_limit(val: &usize) -> bool {
*val == default_limit()
}
// /// `PUT /_matrix/client/*/rooms/{room_id}/send/{eventType}/{txn_id}`
// ///
// /// Send a message event to a room.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#put_matrixclientv3roomsroomidsendeventtypetxnid
// const METADATA: Metadata = metadata! {
// method: PUT,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/rooms/:room_id/send/:event_type/:txn_id",
// 1.1 => "/_matrix/client/v3/rooms/:room_id/send/:event_type/:txn_id",
// }
// };
/// Request type for the `create_message_event` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct CreateMessageWithTxnReqArgs {
/// The room to send the event to.
#[salvo(parameter(parameter_in = Path))]
pub room_id: OwnedRoomId,
/// The type of event to send.
#[salvo(parameter(parameter_in = Path))]
pub event_type: MessageLikeEventType,
/// The transaction ID for this event.
///
/// Clients should generate a unique ID across requests within the
/// same session. A session is identified by an access token, and
/// persists when the [access token is refreshed].
///
/// It will be used by the server to ensure idempotency of requests.
///
/// [access token is refreshed]: https://spec.matrix.org/latest/client-server-api/#refreshing-access-tokens
#[salvo(parameter(parameter_in = Path))]
pub txn_id: OwnedTransactionId,
// /// The event content to send.
// #[salvo(schema(value_type = Object, additional_properties = true))]
// pub body: RawJson<AnyMessageLikeEventContent>,
/// Timestamp to use for the `origin_server_ts` of the event.
///
/// This is called [timestamp massaging] and can only be used by
/// Appservices.
///
/// Note that this does not change the position of the event in the
/// timeline.
///
/// [timestamp massaging]: https://spec.matrix.org/latest/application-service-api/#timestamp-massaging
#[salvo(parameter(parameter_in = Query))]
#[serde(skip_serializing_if = "Option::is_none", rename = "ts")]
pub timestamp: Option<UnixMillis>,
}
/// Request type for the `create_message_event` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct CreateMessageReqArgs {
/// The room to send the event to.
#[salvo(parameter(parameter_in = Path))]
pub room_id: OwnedRoomId,
/// The type of event to send.
#[salvo(parameter(parameter_in = Path))]
pub event_type: MessageLikeEventType,
// /// The event content to send.
// #[salvo(schema(value_type = Object, additional_properties = true))]
// pub body: RawJson<AnyMessageLikeEventContent>,
/// Timestamp to use for the `origin_server_ts` of the event.
///
/// This is called [timestamp massaging] and can only be used by
/// Appservices.
///
/// Note that this does not change the position of the event in the
/// timeline.
///
/// [timestamp massaging]: https://spec.matrix.org/latest/application-service-api/#timestamp-massaging
#[salvo(parameter(parameter_in = Query))]
#[serde(skip_serializing_if = "Option::is_none", rename = "ts")]
pub timestamp: Option<UnixMillis>,
}
/// Response type for the `create_message_event` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct SendMessageResBody {
/// A unique identifier for the event.
pub event_id: OwnedEventId,
}
impl SendMessageResBody {
/// Creates a new `Response` 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/client/uiaa.rs | crates/core/src/client/uiaa.rs | //! Module for [User-Interactive Authentication API][uiaa] types.
//!
//! [uiaa]: https://spec.matrix.org/latest/client-server-api/#user-interactive-authentication-api
use std::error::Error as StdError;
use std::{borrow::Cow, fmt, marker::PhantomData};
use serde::{Deserialize, Deserializer, Serialize, de};
use serde_json::value::RawValue as RawJsonValue;
use crate::PrivOwnedStr;
use crate::error::AuthenticateError;
pub use crate::error::ErrorKind;
use crate::serde::StringEnum;
mod auth_data;
mod auth_params;
pub mod get_uiaa_fallback_page;
pub use self::{auth_data::*, auth_params::*};
/// The type of an authentication stage.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(Clone, StringEnum)]
#[non_exhaustive]
pub enum AuthType {
/// Password-based authentication (`m.login.password`).
#[palpo_enum(rename = "m.login.password")]
Password,
/// Google ReCaptcha 2.0 authentication (`m.login.recaptcha`).
#[palpo_enum(rename = "m.login.recaptcha")]
ReCaptcha,
/// Email-based authentication (`m.login.email.identity`).
#[palpo_enum(rename = "m.login.email.identity")]
EmailIdentity,
/// Phone number-based authentication (`m.login.msisdn`).
#[palpo_enum(rename = "m.login.msisdn")]
Msisdn,
/// SSO-based authentication (`m.login.sso`).
#[palpo_enum(rename = "m.login.sso")]
Sso,
/// Dummy authentication (`m.login.dummy`).
#[palpo_enum(rename = "m.login.dummy")]
Dummy,
/// Registration token-based authentication (`m.login.registration_token`).
#[palpo_enum(rename = "m.login.registration_token")]
RegistrationToken,
/// Terms of service (`m.login.terms`).
///
/// This type is only valid during account registration.
#[palpo_enum(rename = "m.login.terms")]
Terms,
/// OAuth 2.0 (`m.oauth`).
///
/// This type is only valid with the cross-signing keys upload endpoint, after logging in with
/// the OAuth 2.0 API.
#[palpo_enum(rename = "m.oauth", alias = "org.matrix.cross_signing_reset")]
OAuth,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
/// Information about available authentication flows and status for User-Interactive Authenticiation
/// API.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct UiaaInfo {
/// List of authentication flows available for this endpoint.
pub flows: Vec<AuthFlow>,
/// List of stages in the current flow completed by the client.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub completed: Vec<AuthType>,
/// Authentication parameters required for the client to complete authentication.
///
/// To create a `Box<RawJsonValue>`, use `serde_json::value::to_raw_value`.
// #[serde(skip_serializing_if = "Option::is_none")] // commented for complement test DELETE TestDeviceManagement/DELETE_/device/{deviceId}
pub params: Option<Box<RawJsonValue>>,
/// Session key for client to use to complete authentication.
#[serde(skip_serializing_if = "Option::is_none")]
pub session: Option<String>,
/// Authentication-related errors for previous request returned by homeserver.
#[serde(flatten, skip_serializing_if = "Option::is_none")]
pub auth_error: Option<AuthError>,
}
impl UiaaInfo {
/// Creates a new `UiaaInfo` with the given flows.
pub fn new(flows: Vec<AuthFlow>) -> Self {
Self {
flows,
completed: Vec::new(),
params: None,
session: None,
auth_error: None,
}
}
/// Get the parameters for the given [`AuthType`], if they are available in the `params` object.
///
/// Returns `Ok(Some(_))` if the parameters for the authentication type were found and the
/// deserialization worked, `Ok(None)` if the parameters for the authentication type were not
/// found, and `Err(_)` if the parameters for the authentication type were found but their
/// deserialization failed.
///
/// # Example
///
/// ```
/// use palpo_core::client::uiaa::{AuthType, UiaaInfo, LoginTermsParams};
///
/// # let uiaa_info = UiaaInfo::new(Vec::new());
/// let login_terms_params = uiaa_info.params::<LoginTermsParams>(&AuthType::Terms)?;
/// # Ok::<(), serde_json::Error>(())
/// ```
pub fn params<'a, T: Deserialize<'a>>(
&'a self,
auth_type: &AuthType,
) -> Result<Option<T>, serde_json::Error> {
struct AuthTypeVisitor<'b, T> {
auth_type: &'b AuthType,
_phantom: PhantomData<T>,
}
impl<'de, T> de::Visitor<'de> for AuthTypeVisitor<'_, T>
where
T: Deserialize<'de>,
{
type Value = Option<T>;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a key-value map")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: de::MapAccess<'de>,
{
let mut params = None;
while let Some(key) = map.next_key::<Cow<'de, str>>()? {
if AuthType::from(key) == *self.auth_type {
params = Some(map.next_value()?);
} else {
map.next_value::<de::IgnoredAny>()?;
}
}
Ok(params)
}
}
let Some(params) = &self.params else {
return Ok(None);
};
let mut deserializer = serde_json::Deserializer::from_str(params.get());
deserializer.deserialize_map(AuthTypeVisitor {
auth_type,
_phantom: PhantomData,
})
}
}
impl fmt::Display for UiaaInfo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "User-Interactive Authentication required.")
}
}
impl StdError for UiaaInfo {}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct AuthError {
#[serde(flatten)]
pub kind: ErrorKind,
#[serde(rename = "error")]
pub message: String,
}
impl AuthError {
pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
Self {
kind,
message: message.into(),
}
}
pub fn forbidden(message: impl Into<String>, authenticate: Option<AuthenticateError>) -> Self {
Self::new(ErrorKind::Forbidden { authenticate }, message)
}
pub fn unauthorized(message: impl Into<String>) -> Self {
Self::new(ErrorKind::Unauthorized, message)
}
}
/// Description of steps required to authenticate via the User-Interactive Authentication API.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct AuthFlow {
/// Ordered list of stages required to complete authentication.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub stages: Vec<AuthType>,
}
impl AuthFlow {
/// Creates a new `AuthFlow` with the given stages.
///
/// To create an empty `AuthFlow`, use `AuthFlow::default()`.
pub fn new(stages: Vec<AuthType>) -> Self {
Self { stages }
}
}
// /// Contains either a User-Interactive Authentication API response body or a Matrix error.
// #[derive(Clone, Debug)]
// #[allow(clippy::exhaustive_enums)]
// pub enum UiaaResponse {
// /// User-Interactive Authentication API response
// AuthResponse(UiaaInfo),
// /// Matrix error response
// MatrixError(MatrixError),
// }
// impl fmt::Display for UiaaResponse {
// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// match self {
// Self::AuthResponse(_) => write!(f, "User-Interactive Authentication required."),
// Self::MatrixError(err) => write!(f, "{err}"),
// }
// }
// }
// impl From<MatrixError> for UiaaResponse {
// fn from(error: MatrixError) -> Self {
// Self::MatrixError(error)
// }
// }
// impl EndpointError for UiaaResponse {
// fn from_http_response<T: AsRef<[u8]>>(response: http::Response<T>) -> Self {
// if response.status() == http::StatusCode::UNAUTHORIZED
// && let Ok(uiaa_info) = from_json_slice(response.body().as_ref())
// {
// return Self::AuthResponse(uiaa_info);
// }
// Self::MatrixError(MatrixError::from_http_response(response))
// }
// }
// impl std::error::Error for UiaaResponse {}
// impl OutgoingResponse for UiaaResponse {
// fn try_into_http_response<T: Default + BufMut>(
// self,
// ) -> Result<http::Response<T>, IntoHttpError> {
// match self {
// UiaaResponse::AuthResponse(authentication_info) => http::Response::builder()
// .header(http::header::CONTENT_TYPE, crate::http_headers::APPLICATION_JSON)
// .status(http::StatusCode::UNAUTHORIZED)
// .body(crate::serde::json_to_buf(&authentication_info)?)
// .map_err(Into::into),
// UiaaResponse::MatrixError(error) => error.try_into_http_response(),
// }
// }
// }
// #[cfg(test)]
// mod tests {
// use assert_matches2::assert_matches;
// use crate::serde::JsonObject;
// use serde_json::{from_value as from_json_value, json};
// use super::{AuthType, LoginTermsParams, OAuthParams, UiaaInfo};
// #[test]
// fn uiaa_info_params() {
// let json = json!({
// "flows": [{
// "stages": ["m.login.terms", "m.login.email.identity", "local.custom.stage"],
// }],
// "params": {
// "local.custom.stage": {
// "foo": "bar",
// },
// "m.login.terms": {
// "policies": {
// "privacy": {
// "en-US": {
// "name": "Privacy Policy",
// "url": "http://matrix.local/en-US/privacy",
// },
// "fr-FR": {
// "name": "Politique de confidentialité",
// "url": "http://matrix.local/fr-FR/privacy",
// },
// "version": "1",
// },
// },
// }
// },
// "session": "abcdef",
// });
// let info = from_json_value::<UiaaInfo>(json).unwrap();
// assert_matches!(info.params::<JsonObject>(&AuthType::EmailIdentity), Ok(None));
// assert_matches!(
// info.params::<JsonObject>(&AuthType::from("local.custom.stage")),
// Ok(Some(_))
// );
// assert_matches!(info.params::<LoginTermsParams>(&AuthType::Terms), Ok(Some(params)));
// assert_eq!(params.policies.len(), 1);
// let policy = params.policies.get("privacy").unwrap();
// assert_eq!(policy.version, "1");
// assert_eq!(policy.translations.len(), 2);
// let translation = policy.translations.get("en-US").unwrap();
// assert_eq!(translation.name, "Privacy Policy");
// assert_eq!(translation.url, "http://matrix.local/en-US/privacy");
// let translation = policy.translations.get("fr-FR").unwrap();
// assert_eq!(translation.name, "Politique de confidentialité");
// assert_eq!(translation.url, "http://matrix.local/fr-FR/privacy");
// }
// #[test]
// fn uiaa_info_oauth_params() {
// let url = "http://auth.matrix.local/reset";
// let stable_json = json!({
// "flows": [{
// "stages": ["m.oauth"],
// }],
// "params": {
// "m.oauth": {
// "url": url,
// }
// },
// "session": "abcdef",
// });
// let unstable_json = json!({
// "flows": [{
// "stages": ["org.matrix.cross_signing_reset"],
// }],
// "params": {
// "org.matrix.cross_signing_reset": {
// "url": url,
// }
// },
// "session": "abcdef",
// });
// let info = from_json_value::<UiaaInfo>(stable_json).unwrap();
// assert_matches!(info.params::<OAuthParams>(&AuthType::OAuth), Ok(Some(params)));
// assert_eq!(params.url, url);
// let info = from_json_value::<UiaaInfo>(unstable_json).unwrap();
// assert_matches!(info.params::<OAuthParams>(&AuthType::OAuth), Ok(Some(params)));
// assert_eq!(params.url, 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/client/room.rs | crates/core/src/client/room.rs | /// Endpoints for room management.
mod alias;
mod summary;
mod thread;
mod thread_msc4306;
mod thread_msc4308;
pub use alias::*;
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
pub use summary::*;
pub use thread::*;
pub use thread_msc4306::*;
pub use thread_msc4308::*;
use crate::{
OwnedEventId, OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedUserId, PrivOwnedStr,
RoomVersionId,
client::{filter::RoomEventFilter, membership::InviteThreepid},
events::{
AnyInitialStateEvent, AnyRoomAccountDataEvent, AnyStateEvent, AnyTimelineEvent,
room::{
create::PreviousRoom, member::MembershipState,
power_levels::RoomPowerLevelsEventContent,
},
},
room::{RoomType, Visibility},
serde::{RawJson, StringEnum},
};
// /// `POST /_matrix/client/*/createRoom`
// ///
// /// Create a new room.
//
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3createroom
//
// /// Whether or not a newly created room will be listed in the room directory.
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/createRoom",
// 1.1 => "/_matrix/client/v3/createRoom",
// }
// };
/// Request type for the `create_room` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct CreateRoomReqBody {
/// Extra keys to be added to the content of the `m.room.create`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub creation_content: Option<RawJson<CreationContent>>,
/// List of state events to send to the new room.
///
/// Takes precedence over events set by preset, but gets overridden by name
/// and topic keys.
#[serde(default, skip_serializing_if = "<[_]>::is_empty")]
pub initial_state: Vec<RawJson<AnyInitialStateEvent>>,
/// A list of user IDs to invite to the room.
///
/// This will tell the server to invite everyone in the list to the newly
/// created room.
#[serde(default, skip_serializing_if = "<[_]>::is_empty")]
pub invite: Vec<OwnedUserId>,
/// List of third party IDs of users to invite.
#[serde(default, skip_serializing_if = "<[_]>::is_empty")]
pub invite_3pid: Vec<InviteThreepid>,
/// If set, this sets the `is_direct` flag on room invites.
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub is_direct: bool,
/// If this is included, an `m.room.name` event will be sent into the room
/// to indicate the name of the room.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// Power level content to override in the default power level event.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub power_level_content_override: Option<RawJson<RoomPowerLevelsEventContent>>,
/// Convenience parameter for setting various default state events based on
/// a preset.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub preset: Option<RoomPreset>,
/// The desired room alias local part.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub room_alias_name: Option<String>,
// /// The desired custom room ID, local part or fully qualified.
// #[serde(alias = "fi.mau.room_id", skip_serializing_if = "Option::is_none")]
// pub room_id: Option<String>,
/// Room version to set for the room.
///
/// Defaults to homeserver's default if not specified.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub room_version: Option<RoomVersionId>,
/// If this is included, an `m.room.topic` event will be sent into the room
/// to indicate the topic for the room.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub topic: Option<String>,
/// A public visibility indicates that the room will be shown in the
/// published room list.
///
/// A private visibility will hide the room from the published room list.
/// Defaults to `Private`.
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub visibility: Visibility,
}
/// Response type for the `create_room` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct CreateRoomResBody {
/// The created room's ID.
pub room_id: OwnedRoomId,
}
/// Extra options to be added to the `m.room.create` event.
///
/// This is the same as the event content struct for `m.room.create`, but
/// without some fields that servers are supposed to ignore.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct CreationContent {
/// A list of user IDs to consider as additional creators, and hence grant an "infinite"
/// immutable power level, from room version 12 onwards.
#[serde(default, skip_serializing_if = "<[_]>::is_empty")]
pub additional_creators: Vec<OwnedUserId>,
/// Whether users on other servers can join this room.
///
/// Defaults to `true` if key does not exist.
#[serde(
rename = "m.federate",
default = "crate::serde::default_true",
skip_serializing_if = "crate::serde::is_true"
)]
pub federate: bool,
/// A reference to the room this room replaces, if the previous room was
/// upgraded.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub predecessor: Option<PreviousRoom>,
/// The room type.
///
/// This is currently only used for spaces.
#[serde(default, skip_serializing_if = "Option::is_none", rename = "type")]
pub room_type: Option<RoomType>,
}
impl CreationContent {
/// Creates a new `CreationContent` with all fields defaulted.
pub fn new() -> Self {
Self {
additional_creators: Vec::new(),
federate: true,
predecessor: None,
room_type: None,
}
}
// /// Given a `CreationContent` and the other fields that a homeserver has to
// fill, construct /// a `RoomCreateEventContent`.
// pub fn into_event_content(self, creator: OwnedUserId, room_version:
// RoomVersionId) -> RoomCreateEventContent { assign!
// (RoomCreateEventContent::new_v1(creator), { federate:
// self.federate, room_version: room_version,
// predecessor: self.predecessor,
// room_type: self.room_type
// })
// }
/// Returns whether all fields have their default value.
pub fn is_empty(&self) -> bool {
self.federate && self.predecessor.is_none() && self.room_type.is_none()
}
}
impl Default for CreationContent {
fn default() -> Self {
Self::new()
}
}
/// A convenience parameter for setting a few default state events.
#[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 RoomPreset {
/// `join_rules` is set to `invite` and `history_visibility` is set to
/// `shared`.
PrivateChat,
/// `join_rules` is set to `public` and `history_visibility` is set to
/// `shared`.
PublicChat,
/// Same as `PrivateChat`, but all initial invitees get the same power level
/// as the creator.
TrustedPrivateChat,
#[doc(hidden)]
#[salvo(schema(value_type = String))]
_Custom(PrivOwnedStr),
}
// /// `POST /_matrix/client/*/rooms/{room_id}/upgrade`
// ///
// /// Upgrades a room to a particular version.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3roomsroomidupgrade
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/rooms/:room_id/upgrade",
// 1.1 => "/_matrix/client/v3/rooms/:room_id/upgrade",
// }
// };
/// Request type for the `upgrade_room` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct UpgradeRoomReqBody {
/// A list of user IDs to consider as additional creators, and hence grant an "infinite"
/// immutable power level, from room version 12 onwards.
#[serde(default, skip_serializing_if = "<[_]>::is_empty")]
pub additional_creators: Vec<OwnedUserId>,
/// ID of the room to be upgraded.
// #[salvo(parameter(parameter_in = Path))]
// pub room_id: OwnedRoomId,
/// New version for the room.
pub new_version: RoomVersionId,
}
/// Response type for the `upgrade_room` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct UpgradeRoomResBody {
/// ID of the new room.
pub replacement_room: OwnedRoomId,
}
// /// `GET /_matrix/client/*/rooms/{room_id}/timestamp_to_event`
// ///
// /// Get the ID of the event closest to the given timestamp.
// /// `/v1/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv1roomsroomidtimestamp_to_event
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/client/unstable/org.matrix.msc3030/rooms/:room_id/timestamp_to_event",
// 1.6 => "/_matrix/client/v1/rooms/:room_id/timestamp_to_event",
// }
// };
// /// `GET /_matrix/client/*/rooms/{room_id}/event/{event_id}`
// ///
// /// Get a single event based on roomId/eventId
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3roomsroomideventeventid
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/rooms/:room_id/event/:event_id",
// 1.1 => "/_matrix/client/v3/rooms/:room_id/event/:event_id",
// }
// };
/// Response type for the `get_room_event` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct RoomEventResBody(
/// Arbitrary JSON of the event body.
pub RawJson<AnyTimelineEvent>,
);
impl RoomEventResBody {
/// Creates a new `Response` with the given event.
pub fn new(event: RawJson<AnyTimelineEvent>) -> Self {
Self(event)
}
}
// /// `POST /_matrix/client/*/rooms/{room_id}/report/{event_id}`
// ///
// /// Report content as inappropriate.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3roomsroomidreporteventid
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/rooms/:room_id/report/:event_id",
// 1.1 => "/_matrix/client/v3/rooms/:room_id/report/:event_id",
// }
// };
/// Request type for the `report_content` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct ReportContentReqArgs {
/// Room in which the event to be reported is located.
#[salvo(parameter(parameter_in = Path))]
pub room_id: OwnedRoomId,
/// Event to report.
#[salvo(parameter(parameter_in = Path))]
pub event_id: OwnedEventId,
}
#[derive(ToSchema, Deserialize, Debug)]
pub struct ReportContentReqBody {
/// Integer between -100 and 0 rating offensivness.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub score: Option<i64>,
/// Reason to report content.
///
/// May be blank.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/rooms/:room_id/read_markers",
// 1.1 => "/_matrix/client/v3/rooms/:room_id/read_markers",
// }
// };
/// Request type for the `set_read_marker` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct SetReadMarkerReqBody {
// /// The room ID to set the read marker in for the user.
// #[salvo(parameter(parameter_in = Path))]
// pub room_id: OwnedRoomId,
/// The event ID the fully-read marker should be located at.
///
/// The event MUST belong to the room.
///
/// This is equivalent to calling the [`create_receipt`] endpoint with a
/// [`ReceiptType::FullyRead`].
///
/// [`create_receipt`]: crate::receipt::create_receipt
/// [`ReceiptType::FullyRead`]: crate::receipt::create_receipt::v3::ReceiptType::FullyRead
#[serde(
default,
rename = "m.fully_read",
skip_serializing_if = "Option::is_none"
)]
pub fully_read: Option<OwnedEventId>,
/// The event ID to set the public read receipt location at.
///
/// This is equivalent to calling the [`create_receipt`] endpoint with a
/// [`ReceiptType::Read`].
///
/// [`create_receipt`]: crate::receipt::create_receipt
/// [`ReceiptType::Read`]: crate::receipt::create_receipt::v3::ReceiptType::Read
#[serde(default, rename = "m.read", skip_serializing_if = "Option::is_none")]
pub read_receipt: Option<OwnedEventId>,
/// The event ID to set the private read receipt location at.
///
/// This is equivalent to calling the [`create_receipt`] endpoint with a
/// [`ReceiptType::ReadPrivate`].
///
/// [`create_receipt`]: crate::receipt::create_receipt
/// [`ReceiptType::ReadPrivate`]: crate::receipt::create_receipt::v3::ReceiptType::ReadPrivate
#[serde(
default,
rename = "m.read.private",
skip_serializing_if = "Option::is_none"
)]
pub private_read_receipt: Option<OwnedEventId>,
}
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/rooms/:room_id/context/:event_id",
// 1.1 => "/_matrix/client/v3/rooms/:room_id/context/:event_id",
// }
// };
// /// Request type for the `get_context` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct ContextReqArgs {
/// The room to get events from.
#[salvo(parameter(parameter_in = Path))]
pub room_id: OwnedRoomId,
/// The event to get context around.
#[salvo(parameter(parameter_in = Path))]
pub event_id: OwnedEventId,
/// The maximum number of context events to return.
///
/// This limit applies to the sum of the `events_before` and `events_after`
/// arrays. The requested event ID is always returned in `event` even if
/// the limit is `0`.
///
/// Defaults to 10.
#[salvo(parameter(parameter_in = Query))]
#[serde(default = "default_limit", skip_serializing_if = "is_default_limit")]
pub limit: usize,
/// A RoomEventFilter to filter returned events with.
#[salvo(parameter(parameter_in = Query))]
#[serde(
with = "crate::serde::json_string",
default,
skip_serializing_if = "RoomEventFilter::is_empty"
)]
pub filter: RoomEventFilter,
}
fn default_limit() -> usize {
10
}
/// Response type for the `get_context` endpoint.
#[derive(ToSchema, Serialize, Default, Debug)]
pub struct ContextResBody {
/// A token that can be used to paginate backwards with.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub start: Option<String>,
/// A token that can be used to paginate forwards with.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub end: Option<String>,
/// A list of room events that happened just before the requested event,
/// in reverse-chronological order.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
#[salvo(schema(value_type = Object, additional_properties = true))]
pub events_before: Vec<RawJson<AnyTimelineEvent>>,
/// Details of the requested event.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[salvo(schema(value_type = Object, additional_properties = true))]
pub event: Option<RawJson<AnyTimelineEvent>>,
/// A list of room events that happened just after the requested event,
/// in chronological order.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
#[salvo(schema(value_type = Object, additional_properties = true))]
pub events_after: Vec<RawJson<AnyTimelineEvent>>,
/// The state of the room at the last event returned.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
#[salvo(schema(value_type = Object, additional_properties = true))]
pub state: Vec<RawJson<AnyStateEvent>>,
}
impl ContextResBody {
/// Creates an empty `Response`.
pub fn new() -> Self {
Default::default()
}
}
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// unstable =>
// "/_matrix/client/unstable/xyz.amorgan.knock/knock/:room_id_or_alias",
// 1.1 => "/_matrix/client/v3/knock/:room_id_or_alias",
// }
// };
/// Request type for the `knock_room` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct KnockReqArgs {
/// The room the user should knock on.
#[salvo(parameter(parameter_in = Path))]
pub room_id_or_alias: OwnedRoomOrAliasId,
/// The servers to attempt to knock on the room through.
///
/// One of the servers must be participating in the room.
#[salvo(parameter(parameter_in = Query))]
#[serde(default, skip_serializing_if = "<[_]>::is_empty")]
pub server_name: Vec<OwnedServerName>,
}
/// Request type for the `knock_room` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct KnockReqBody {
/// The reason for joining a room.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
#[serde(default)]
pub via: Vec<OwnedServerName>,
}
/// Response type for the `knock_room` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct KnockResBody {
/// The room that the user knocked on.
pub room_id: OwnedRoomId,
}
impl KnockResBody {
/// Creates a new `Response` with the given room ID.
pub fn new(room_id: OwnedRoomId) -> Self {
Self { room_id }
}
}
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/rooms/:room_id/initialSync",
// 1.1 => "/_matrix/client/v3/rooms/:room_id/initialSync",
// }
// };
/// Request type for the `get_room_event` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct InitialSyncReqArgs {
/// The ID of the room.
#[salvo(parameter(parameter_in = Path))]
pub room_id: OwnedRoomId,
/// Limit messages chunks size
#[salvo(parameter(parameter_in = Query))]
#[serde(skip_serializing_if = "Option::is_none")]
pub limit: Option<usize>,
}
/// Response type for the `get_room_event` endpoint.
#[derive(ToSchema, Deserialize, Serialize, Debug)]
pub struct InitialSyncResBody {
/// The private data that this user has attached to this room.
#[serde(skip_serializing_if = "Option::is_none")]
pub account_data: Option<Vec<RawJson<AnyRoomAccountDataEvent>>>,
/// The user’s membership state in this room. One of: [invite, join, leave,
/// ban].
#[serde(skip_serializing_if = "Option::is_none")]
pub membership: Option<MembershipState>,
/// The pagination chunk for this room.
#[serde(skip_serializing_if = "Option::is_none")]
pub messages: Option<PaginationChunk>,
/// The ID of this room.
pub room_id: OwnedRoomId,
/// If the user is a member of the room this will be the current state of
/// the room as a list of events. If the user has left the room this
/// will be the state of the room when they left it.
#[serde(skip_serializing_if = "Option::is_none")]
pub state: Option<Vec<RawJson<AnyStateEvent>>>,
/// Whether this room is visible to the /publicRooms API or not.
/// One of: [private, public].
#[serde(skip_serializing_if = "Option::is_none")]
pub visibility: Option<Visibility>,
}
/// Page of timeline events
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct PaginationChunk {
/// If the user is a member of the room this will be a list of the most
/// recent messages for this room. If the user has left the room this
/// will be the messages that preceded them leaving. This array will
/// consist of at most limit elements.
pub chunk: Vec<RawJson<AnyTimelineEvent>>,
/// A token which correlates to the end of chunk. Can be passed to
/// /rooms/<room_id>/messages to retrieve later events.
pub end: String,
/// A token which correlates to the start of chunk. Can be passed to
/// /rooms/<room_id>/messages to retrieve earlier events. If no earlier
/// events are available, this property may be omitted from the
/// response.
#[serde(skip_serializing_if = "Option::is_none")]
pub start: 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/client/directory.rs | crates/core/src/client/directory.rs | use salvo::prelude::*;
use serde::{Deserialize, Serialize};
/// `POST /_matrix/client/*/publicRooms`
///
/// Get the list of rooms in this homeserver's public directory.
/// `/v3/` ([spec])
///
/// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3publicrooms
use crate::directory::{PublicRoomFilter, RoomNetwork};
use crate::{OwnedServerName, room::Visibility};
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/publicRooms",
// 1.1 => "/_matrix/client/v3/publicRooms",
// }
// };
/// Request type for the `get_filtered_public_rooms` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct PublicRoomsFilteredReqBody {
/// The server to fetch the public room lists from.
///
/// `None` means the server this request is sent to.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[salvo(parameter(parameter_in = Query))]
pub server: Option<OwnedServerName>,
/// Limit for the number of results to return.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<usize>,
/// Pagination token from a previous request.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub since: Option<String>,
/// Filter to apply to the results.
#[serde(default, skip_serializing_if = "PublicRoomFilter::is_empty")]
pub filter: PublicRoomFilter,
/// Network to fetch the public room lists from.
#[serde(flatten, skip_serializing_if = "crate::serde::is_default")]
pub room_network: RoomNetwork,
}
// /// `GET /_matrix/client/*/publicRooms`
// ///
// /// Get the list of rooms in this homeserver's public directory.
//
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3publicrooms
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: None,
// history: {
// 1.0 => "/_matrix/client/r0/publicRooms",
// 1.1 => "/_matrix/client/v3/publicRooms",
// }
// };
/// Request type for the `get_public_rooms` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct PublicRoomsReqArgs {
/// Limit for the number of results to return.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[salvo(parameter(parameter_in = Query))]
pub limit: Option<usize>,
/// Pagination token from a previous request.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[salvo(parameter(parameter_in = Query))]
pub since: Option<String>,
/// The server to fetch the public room lists from.
///
/// `None` means the server this request is sent to.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[salvo(parameter(parameter_in = Query))]
pub server: Option<OwnedServerName>,
}
// /// `GET /_matrix/client/*/directory/list/room/{room_id}`
// ///
// /// Get the visibility of a public room on a directory.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3directorylistroomroomid
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: None,
// history: {
// 1.0 => "/_matrix/client/r0/directory/list/room/:room_id",
// 1.1 => "/_matrix/client/v3/directory/list/room/:room_id",
// }
// };
// /// Request type for the `get_room_visibility` endpoint.
// pub struct Requestx {
// /// The ID of the room of which to request the visibility.
// #[salvo(parameter(parameter_in = Path))]
// pub room_id: OwnedRoomId,
// }
/// Response type for the `get_room_visibility` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct VisibilityResBody {
/// Visibility of the room.
pub visibility: Visibility,
}
impl VisibilityResBody {
/// Creates a new `Response` with the given visibility.
pub fn new(visibility: Visibility) -> Self {
Self { visibility }
}
}
// /// `PUT /_matrix/client/*/directory/list/room/{room_id}`
// ///
// /// Set the visibility of a public room on a directory.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#put_matrixclientv3directorylistroomroomid
// const METADATA: Metadata = metadata! {
// method: PUT,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/directory/list/room/:room_id",
// 1.1 => "/_matrix/client/v3/directory/list/room/:room_id",
// }
// };
/// Request type for the `set_room_visibility` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct SetRoomVisibilityReqBody {
// /// The ID of the room of which to set the visibility.
// #[salvo(parameter(parameter_in = Path))]
// pub room_id: OwnedRoomId,
/// New visibility setting for the room.
pub visibility: Visibility,
}
| 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/client/dehydrated_device.rs | crates/core/src/client/dehydrated_device.rs | //! Endpoints for managing dehydrated devices.
use serde::{Deserialize, Serialize};
use crate::{PrivOwnedStr, serde::StringEnum};
/// Data for a dehydrated device.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(try_from = "Helper", into = "Helper")]
pub enum DehydratedDeviceData {
/// The `org.matrix.msc3814.v1.olm` variant of a dehydrated device.
V1(DehydratedDeviceV1),
}
impl DehydratedDeviceData {
/// Get the algorithm this dehydrated device uses.
pub fn algorithm(&self) -> DeviceDehydrationAlgorithm {
match self {
DehydratedDeviceData::V1(_) => DeviceDehydrationAlgorithm::V1,
}
}
}
/// The `org.matrix.msc3814.v1.olm` variant of a dehydrated device.
#[derive(Clone, Debug)]
pub struct DehydratedDeviceV1 {
/// The pickle of the `Olm` account of the device.
///
/// The pickle will contain the private parts of the long-term identity keys
/// of the device as well as a collection of one-time keys.
pub device_pickle: String,
}
impl DehydratedDeviceV1 {
/// Create a [`DehydratedDeviceV1`] struct from a device pickle.
pub fn new(device_pickle: String) -> Self {
Self { device_pickle }
}
}
/// The algorithms used for dehydrated devices.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(Clone, StringEnum)]
#[non_exhaustive]
pub enum DeviceDehydrationAlgorithm {
/// The `org.matrix.msc3814.v1.olm` device dehydration algorithm.
#[palpo_enum(rename = "org.matrix.msc3814.v1.olm")]
V1,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
#[derive(Deserialize, Serialize)]
struct Helper {
algorithm: DeviceDehydrationAlgorithm,
device_pickle: String,
}
impl TryFrom<Helper> for DehydratedDeviceData {
type Error = serde_json::Error;
fn try_from(value: Helper) -> Result<Self, Self::Error> {
match value.algorithm {
DeviceDehydrationAlgorithm::V1 => Ok(DehydratedDeviceData::V1(DehydratedDeviceV1 {
device_pickle: value.device_pickle,
})),
_ => Err(serde::de::Error::custom(
"Unsupported device dehydration algorithm.",
)),
}
}
}
impl From<DehydratedDeviceData> for Helper {
fn from(value: DehydratedDeviceData) -> Self {
let algorithm = value.algorithm();
match value {
DehydratedDeviceData::V1(d) => Self {
algorithm,
device_pickle: d.device_pickle,
},
}
}
}
| 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/client/profile.rs | crates/core/src/client/profile.rs | /// `GET /_matrix/client/*/profile/{user_id}/avatar_url`
///
/// Get the avatar URL of a user.
/// `/v3/` ([spec])
///
/// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3profileuser_idavatar_url
use std::borrow::Cow;
use salvo::prelude::*;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::{from_value as from_json_value, to_value as to_json_value};
use crate::OwnedMxcUri;
use crate::serde::{JsonValue, StringEnum};
mod profile_field_serde;
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: None,
// history: {
// 1.0 => "/_matrix/client/r0/profile/:user_id/avatar_url",
// 1.1 => "/_matrix/client/v3/profile/:user_id/avatar_url",
// }
// };
// /// Request type for the `get_avatar_url` endpoint.
// pub struct Requexst {
// /// The user whose avatar URL will be retrieved.
// #[salvo(parameter(parameter_in = Path))]
// pub user_id: OwnedUserId,
// }
/// Response type for the `get_avatar_url` endpoint.
#[derive(ToSchema, Serialize, Deserialize, Debug)]
pub struct AvatarUrlResBody {
/// The user's avatar URL, if set.
#[serde(
skip_serializing_if = "Option::is_none",
default,
deserialize_with = "crate::serde::empty_string_as_none"
)]
pub avatar_url: Option<OwnedMxcUri>,
/// 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(
default,
rename = "xyz.amorgan.blurhash",
skip_serializing_if = "Option::is_none"
)]
pub blurhash: Option<String>,
}
impl AvatarUrlResBody {
/// Creates a new `Response` with the given avatar URL.
pub fn new(avatar_url: Option<OwnedMxcUri>) -> Self {
Self {
avatar_url,
blurhash: None,
}
}
}
/// `GET /_matrix/client/*/profile/{user_id}/display_name`
///
/// Get the display name of a user.
/// `/v3/` ([spec])
///
/// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3profileuser_iddisplay_name
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: None,
// history: {
// 1.0 => "/_matrix/client/r0/profile/:user_id/display_name",
// 1.1 => "/_matrix/client/v3/profile/:user_id/display_name",
// }
// };
/// Response type for the `get_display_name` endpoint.
#[derive(ToSchema, Serialize, Deserialize, Debug)]
pub struct DisplayNameResBody {
/// The user's display name, if set.
#[serde(
default,
rename = "displayname",
skip_serializing_if = "Option::is_none"
)]
pub display_name: Option<String>,
}
impl DisplayNameResBody {
/// Creates a new `Response` with the given display name.
pub fn new(display_name: Option<String>) -> Self {
Self { display_name }
}
}
// /// `PUT /_matrix/client/*/profile/{user_id}/avatar_url`
// ///
// /// Set the avatar URL of the user.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#put_matrixclientv3profileuser_idavatar_url
// const METADATA: Metadata = metadata! {
// method: PUT,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/profile/:user_id/avatar_url",
// 1.1 => "/_matrix/client/v3/profile/:user_id/avatar_url",
// }
// };
/// Request type for the `set_avatar_url` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct SetAvatarUrlReqBody {
/// The new avatar URL for the user.
///
/// `None` is used to unset the avatar.
#[serde(default, deserialize_with = "crate::serde::empty_string_as_none")]
pub avatar_url: Option<OwnedMxcUri>,
/// 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).
#[cfg(feature = "unstable-msc2448")]
#[serde(
default,
rename = "xyz.amorgan.blurhash",
skip_serializing_if = "Option::is_none"
)]
pub blurhash: Option<String>,
}
// /// `PUT /_matrix/client/*/profile/{user_id}/display_name`
// ///
// /// Set the display name of the user.
//
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#put_matrixclientv3profileuser_iddisplay_name
// const METADATA: Metadata = metadata! {
// method: PUT,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/profile/:user_id/display_name",
// 1.1 => "/_matrix/client/v3/profile/:user_id/display_name",
// }
// };
/// Request type for the `set_display_name` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct SetDisplayNameReqBody {
/// The new display name for the user.
#[serde(
default,
skip_serializing_if = "Option::is_none",
alias = "displayname"
)]
pub display_name: Option<String>,
}
/// Trait implemented by types representing a field in a user's profile having a statically-known
/// name.
pub trait StaticProfileField {
/// The type for the value of the field.
type Value: Sized + Serialize + DeserializeOwned;
/// The string representation of this field.
const NAME: &str;
}
/// The user's avatar URL.
#[derive(Debug, Clone, Copy)]
#[allow(clippy::exhaustive_structs)]
pub struct AvatarUrl;
impl StaticProfileField for AvatarUrl {
type Value = OwnedMxcUri;
const NAME: &str = "avatar_url";
}
/// The user's display name.
#[derive(Debug, Clone, Copy)]
#[allow(clippy::exhaustive_structs)]
pub struct DisplayName;
impl StaticProfileField for DisplayName {
type Value = String;
const NAME: &str = "displayname";
}
/// The possible fields of a user's profile.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[palpo_enum(rename_all = "snake_case")]
pub enum ProfileFieldName {
/// The user's avatar URL.
AvatarUrl,
/// The user's display name.
#[palpo_enum(rename = "displayname")]
DisplayName,
/// The user's time zone.
#[palpo_enum(rename = "m.tz")]
TimeZone,
#[doc(hidden)]
_Custom(crate::PrivOwnedStr),
}
/// The possible values of a field of a user's profile.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ProfileFieldValue {
/// The user's avatar URL.
AvatarUrl(OwnedMxcUri),
/// The user's display name.
#[serde(rename = "displayname")]
DisplayName(String),
/// The user's time zone.
#[serde(rename = "m.tz")]
TimeZone(String),
#[doc(hidden)]
#[serde(untagged)]
_Custom(CustomProfileFieldValue),
}
impl ProfileFieldValue {
/// Construct a new `ProfileFieldValue` with the given field and value.
///
/// Prefer to use the public variants of `ProfileFieldValue` where possible; this constructor is
/// meant to be used for unsupported fields only and does not allow setting arbitrary data for
/// supported ones.
///
/// # Errors
///
/// Returns an error if the `field` is known and serialization of `value` to the corresponding
/// `ProfileFieldValue` variant fails.
pub fn new(field: &str, value: JsonValue) -> serde_json::Result<Self> {
Ok(match field {
"avatar_url" => Self::AvatarUrl(from_json_value(value)?),
"displayname" => Self::DisplayName(from_json_value(value)?),
_ => Self::_Custom(CustomProfileFieldValue {
field: field.to_owned(),
value,
}),
})
}
/// The name of the field for this value.
pub fn field_name(&self) -> ProfileFieldName {
match self {
Self::AvatarUrl(_) => ProfileFieldName::AvatarUrl,
Self::DisplayName(_) => ProfileFieldName::DisplayName,
Self::TimeZone(_) => ProfileFieldName::TimeZone,
Self::_Custom(CustomProfileFieldValue { field, .. }) => field.as_str().into(),
}
}
/// Returns the value of the field.
///
/// Prefer to use the public variants of `ProfileFieldValue` where possible; this method is
/// meant to be used for custom fields only.
pub fn value(&self) -> Cow<'_, JsonValue> {
match self {
Self::AvatarUrl(value) => {
Cow::Owned(to_json_value(value).expect("value should serialize successfully"))
}
Self::DisplayName(value) => {
Cow::Owned(to_json_value(value).expect("value should serialize successfully"))
}
Self::TimeZone(value) => {
Cow::Owned(to_json_value(value).expect("value should serialize successfully"))
}
Self::_Custom(c) => Cow::Borrowed(&c.value),
}
}
}
/// A custom value for a user's profile field.
#[derive(Debug, Clone, PartialEq, Eq)]
#[doc(hidden)]
pub struct CustomProfileFieldValue {
/// The name of the field.
field: String,
/// The value of the field
value: JsonValue,
}
// /// Endpoint version history valid only for profile fields that didn't exist before Matrix 1.16.
// const EXTENDED_PROFILE_FIELD_HISTORY: VersionHistory = VersionHistory::new(
// &[(
// Some("uk.tcpip.msc4133"),
// "/_matrix/client/unstable/uk.tcpip.msc4133/profile/{user_id}/{field}",
// )],
// &[(
// StablePathSelector::Version(MatrixVersion::V1_16),
// "/_matrix/client/v3/profile/{user_id}/{field}",
// )],
// None,
// None,
// );
#[cfg(test)]
mod tests {
use crate::owned_mxc_uri;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::ProfileFieldValue;
#[test]
fn serialize_profile_field_value() {
// Avatar URL.
let value = ProfileFieldValue::AvatarUrl(owned_mxc_uri!("mxc://localhost/abcdef"));
assert_eq!(
to_json_value(value).unwrap(),
json!({ "avatar_url": "mxc://localhost/abcdef" })
);
// Display name.
let value = ProfileFieldValue::DisplayName("Alice".to_owned());
assert_eq!(
to_json_value(value).unwrap(),
json!({ "displayname": "Alice" })
);
// Custom field.
let value = ProfileFieldValue::new("custom_field", "value".into()).unwrap();
assert_eq!(
to_json_value(value).unwrap(),
json!({ "custom_field": "value" })
);
}
#[test]
fn deserialize_any_profile_field_value() {
// Avatar URL.
let json = json!({ "avatar_url": "mxc://localhost/abcdef" });
assert_eq!(
from_json_value::<ProfileFieldValue>(json).unwrap(),
ProfileFieldValue::AvatarUrl(owned_mxc_uri!("mxc://localhost/abcdef"))
);
// Display name.
let json = json!({ "displayname": "Alice" });
assert_eq!(
from_json_value::<ProfileFieldValue>(json).unwrap(),
ProfileFieldValue::DisplayName("Alice".to_owned())
);
// Custom field.
let json = json!({ "custom_field": "value" });
let value = from_json_value::<ProfileFieldValue>(json).unwrap();
assert_eq!(value.field_name().as_str(), "custom_field");
assert_eq!(value.value().as_str(), Some("value"));
// Error if the object is empty.
let json = json!({});
from_json_value::<ProfileFieldValue>(json).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/client/account.rs | crates/core/src/client/account.rs | pub mod data;
pub mod threepid;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use crate::macros::StringEnum;
use crate::{
OwnedClientSecret, OwnedDeviceId, OwnedSessionId, OwnedUserId, PrivOwnedStr,
client::uiaa::AuthData,
};
/// Additional authentication information for requestToken endpoints.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct IdentityServerInfo {
/// The ID server to send the onward request to as a hostname with an
/// appended colon and port number if the port is not the default.
pub id_server: String,
/// Access token previously registered with identity server.
pub id_access_token: String,
}
impl IdentityServerInfo {
/// Creates a new `IdentityServerInfo` with the given server name and access
/// token.
pub fn new(id_server: String, id_access_token: String) -> Self {
Self {
id_server,
id_access_token,
}
}
}
/// Possible values for deleting or unbinding 3PIDs.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[palpo_enum(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum ThirdPartyIdRemovalStatus {
/// Either the homeserver couldn't determine the right identity server to
/// contact, or the identity server refused the operation.
NoSupport,
/// Success.
Success,
#[doc(hidden)]
#[salvo(schema(value_type = String))]
_Custom(PrivOwnedStr),
}
/// The kind of account being registered.
#[derive(ToSchema, Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RegistrationKind {
/// A guest account
///
/// These accounts may have limited permissions and may not be supported by
/// all servers.
Guest,
/// A regular user account
#[default]
User,
}
/// The login type.
#[derive(ToSchema, Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub enum LoginType {
/// An appservice-specific login type
#[serde(rename = "m.login.application_service")]
Appservice,
}
/// WhoamiResBody type for the `whoami` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct WhoamiResBody {
/// The id of the user that owns the access token.
pub user_id: OwnedUserId,
/// The device ID associated with the access token, if any.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub device_id: Option<OwnedDeviceId>,
/// If `true`, the user is a guest user.
#[serde(default, skip_serializing_if = "palpo_core::serde::is_default")]
pub is_guest: bool,
}
impl WhoamiResBody {
/// Creates a new `Response` with the given user ID.
pub fn new(user_id: OwnedUserId, is_guest: bool) -> Self {
Self {
user_id,
device_id: None,
is_guest,
}
}
}
// `POST /_matrix/client/*/account/deactivate`
//
// Deactivate the current user's account.
// `/v3/` ([spec])
//
// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3accountdeactivate
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/account/deactivate",
// 1.1 => "/_matrix/client/v3/account/deactivate",
// }
// };
/// Request type for the `deactivate` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct DeactivateReqBody {
/// Additional authentication information for the user-interactive
/// authentication API.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auth: Option<AuthData>,
/// Identity server from which to unbind the user's third party
/// identifier.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id_server: Option<String>,
/// Whether the user would like their content to be erased as much as
/// possible from the server.
///
/// Defaults to `false`.
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub erase: bool,
}
/// Response type for the `deactivate` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct DeactivateResBody {
/// Result of unbind operation.
pub id_server_unbind_result: ThirdPartyIdRemovalStatus,
}
impl DeactivateResBody {
/// Creates a new `Response` with the given unbind result.
pub fn new(id_server_unbind_result: ThirdPartyIdRemovalStatus) -> Self {
Self {
id_server_unbind_result,
}
}
}
/// Request type for the `change_password` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct ChangePasswordReqBody {
/// The new password for the account.
pub new_password: String,
/// True to revoke the user's other access tokens, and their associated
/// devices if the request succeeds.
///
/// Defaults to true.
///
/// When false, the server can still take advantage of the soft logout
/// method for the user's remaining devices.
#[serde(
default = "crate::serde::default_true",
skip_serializing_if = "crate::serde::is_true"
)]
pub logout_devices: bool,
/// Additional authentication information for the user-interactive
/// authentication API.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auth: Option<AuthData>,
}
// `POST /_matrix/client/*/account/password/email/requestToken`
//
// Request that a password change token is sent to the given email address.
// `/v3/` ([spec])
//
// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3accountpasswordemailrequesttoken
// 1.0 => "/_matrix/client/r0/account/password/email/requestToken",
// 1.1 => "/_matrix/client/v3/account/password/email/requestToken",
/// Request type for the `request_password_change_token_via_email` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct TokenViaEmailReqBody {
/// Client-generated secret string used to protect this session.
pub client_secret: OwnedClientSecret,
/// The email address.
pub email: String,
/// Used to distinguish protocol level retries from requests to re-send the
/// email.
pub send_attempt: u64,
/// Return URL for identity server to redirect the client back to.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
/// Response type for the `request_password_change_token_via_email` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct TokenViaEmailResBody {
/// The session identifier given by the identity server.
pub sid: OwnedSessionId,
/// URL to submit validation token to.
///
/// If omitted, verification happens without client.
#[serde(
skip_serializing_if = "Option::is_none",
default,
deserialize_with = "crate::serde::empty_string_as_none"
)]
pub submit_url: Option<String>,
}
// `POST /_matrix/client/*/account/password/msisdn/requestToken`
//
// Request that a password change token is sent to the given phone number.
// `/v3/` ([spec])
//
// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3accountpasswordmsisdnrequesttoken
// 1.0 => "/_matrix/client/r0/account/password/msisdn/requestToken",
// 1.1 => "/_matrix/client/v3/account/password/msisdn/requestToken",
/// Request type for the `request_password_change_token_via_msisdn` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct TokenViaMsisdnReqBody {
/// Client-generated secret string used to protect this session.
pub client_secret: OwnedClientSecret,
/// Two-letter ISO 3166 country code for the phone number.
pub country: String,
/// Phone number to validate.
pub phone_number: String,
/// Used to distinguish protocol level retries from requests to re-send the
/// SMS.
pub send_attempt: u64,
/// Return URL for identity server to redirect the client back to.
#[serde(skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
/// Response type for the `request_password_change_token_via_msisdn` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct TokenViaMsisdnResBody {
/// The session identifier given by the identity server.
pub sid: OwnedSessionId,
/// URL to submit validation token to.
///
/// If omitted, verification happens without client.
#[serde(
skip_serializing_if = "Option::is_none",
default,
deserialize_with = "crate::serde::empty_string_as_none"
)]
pub submit_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/client/push/notification.rs | crates/core/src/client/push/notification.rs | //! `GET /_matrix/client/*/notifications`
//!
//! Paginate through the list of events that the user has been, or would have
//! been notified about. `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3notifications
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{OwnedRoomId, UnixMillis, events::AnySyncTimelineEvent, push::Action, serde::RawJson};
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/notifications",
// 1.1 => "/_matrix/client/v3/notifications",
// }
// };
#[derive(ToSchema, Default, Serialize, Deserialize)]
pub struct NotificationsReqBody {
/// Pagination token given to retrieve the next set of events.
#[salvo(parameter(parameter_in = Query))]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub from: Option<String>,
/// Limit on the number of events to return in this request.
#[salvo(parameter(parameter_in = Query))]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<usize>,
/// Allows basic filtering of events returned.
///
/// Supply "highlight" to return only events where the notification had the
/// 'highlight' tweak set.
#[salvo(parameter(parameter_in = Query))]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub only: Option<String>,
}
// /// Request type for the `get_notifications` endpoint.
// #[derive(Default)]
// pub struct NotificationsReqBody {
// /// Pagination token given to retrieve the next set of events.
// #[salvo(parameter(parameter_in = Query))]
// #[serde(skip_serializing_if = "Option::is_none")]
// pub from: Option<String>,
// /// Limit on the number of events to return in this request.
// #[salvo(parameter(parameter_in = Query))]
// #[serde(skip_serializing_if = "Option::is_none")]
// pub limit: Option<usize>,
// /// Allows basic filtering of events returned.
// ///
// /// Supply "highlight" to return only events where the notification had
// the 'highlight' /// tweak set.
// #[salvo(parameter(parameter_in = Query))]
// #[serde(skip_serializing_if = "Option::is_none")]
// pub only: Option<String>,
// }
/// Response type for the `get_notifications` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct NotificationsResBody {
/// The token to supply in the from param of the next /notifications request
/// in order to request more events.
///
/// If this is absent, there are no more results.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
/// The list of events that triggered notifications.
pub notifications: Vec<Notification>,
}
impl NotificationsResBody {
/// Creates a new `Response` with the given notifications.
pub fn new(notifications: Vec<Notification>) -> Self {
Self {
next_token: None,
notifications,
}
}
}
/// Represents a notification.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct Notification {
/// The actions to perform when the conditions for this rule are met.
pub actions: Vec<Action>,
/// The event that triggered the notification.
pub event: RawJson<AnySyncTimelineEvent>,
/// The profile tag of the rule that matched this event.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub profile_tag: Option<String>,
/// Indicates whether the user has sent a read receipt indicating that they
/// have read this message.
pub read: bool,
/// The ID of the room in which the event was posted.
pub room_id: OwnedRoomId,
/// The time at which the event notification was sent.
pub ts: UnixMillis,
}
| 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/client/push/push_rule.rs | crates/core/src/client/push/push_rule.rs | use salvo::prelude::*;
/// `GET /_matrix/client/*/pushrules/{scope}/{kind}/{rule_id}`
///
/// Retrieve a single specified push rule.
/// `/v3/` ([spec])
///
/// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3pushrulesscopekindruleid
use serde::{Deserialize, Serialize};
use crate::push::{Action, PushCondition, PushRule, RuleKind, RuleScope, Ruleset};
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/pushrules/:scope/:kind/:rule_id",
// 1.1 => "/_matrix/client/v3/pushrules/:scope/:kind/:rule_id",
// }
// };
/// Response type for the `get_pushrule` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct RuleResBody {
/// The specific push rule.
#[serde(flatten)]
pub rule: PushRule,
}
impl RuleResBody {
/// Creates a new `Response` with the given rule.
pub fn new(rule: PushRule) -> Self {
Self { rule }
}
}
// /// `GET /_matrix/client/*/pushrules/`
// ///
// /// Retrieve all push rulesets for this user.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3pushrules
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/pushrules/",
// 1.1 => "/_matrix/client/v3/pushrules/",
// }
// };
/// Response type for the `get_pushrules_all` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct RulesResBody {
/// The global ruleset.
pub global: Ruleset,
}
impl RulesResBody {
/// Creates a new `Response` with the given global ruleset.
pub fn new(global: Ruleset) -> Self {
Self { global }
}
}
/// `PUT /_matrix/client/*/pushrules/{scope}/{kind}/{rule_id}`
///
/// This endpoint allows the creation and modification of push rules for this
/// user ID. `/v3/` ([spec])
///
/// [spec]: https://spec.matrix.org/latest/client-server-api/#put_matrixclientv3pushrulesscopekindruleid
// const METADATA: Metadata = metadata! {
// method: PUT,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/pushrules/:scope/:kind/:rule_id",
// 1.1 => "/_matrix/client/v3/pushrules/:scope/:kind/:rule_id",
// }
// };
// /// Request type for the `set_pushrule` endpoint.
// #[derive(ToSchema, Deserialize, Debug)]
// pub struct SetRuleReqBody {
// /// The scope to set the rule in.
// pub scope: RuleScope,
// /// The rule.
// pub rule: NewPushRule,
// /// Use 'before' with a rule_id as its value to make the new rule the
// /// next-most important rule with respect to the given user defined rule.
// #[serde(default)]
// pub before: Option<String>,
// /// This makes the new rule the next-less important rule relative to the
// /// given user defined rule.
// #[serde(default)]
// pub after: Option<String>,
// }
#[derive(ToParameters, Deserialize, Serialize, Debug)]
pub struct SetRuleReqArgs {
#[salvo(parameter(parameter_in = Path))]
pub scope: RuleScope,
#[salvo(parameter(parameter_in = Path))]
pub kind: RuleKind,
#[salvo(parameter(parameter_in = Path))]
pub rule_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[salvo(parameter(parameter_in = Query))]
pub before: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[salvo(parameter(parameter_in = Query))]
pub after: Option<String>,
}
// #[derive(ToSchema, Deserialize, Debug)]
// pub enum SetRuleReqBody {
// Simple(SimpleReqBody),
// Patterned(PatternedReqBody),
// Conditional(ConditionalReqBody),
// }
#[derive(ToSchema, Deserialize, Debug)]
pub struct SimpleReqBody {
pub actions: Vec<Action>,
}
#[derive(ToSchema, Deserialize, Debug)]
pub struct PatternedReqBody {
pub actions: Vec<Action>,
pub pattern: String,
}
#[derive(ToSchema, Deserialize, Debug)]
pub struct ConditionalReqBody {
pub actions: Vec<Action>,
pub conditions: Vec<PushCondition>,
}
// impl From<NewPushRule> for SetRuleReqBody {
// fn from(rule: NewPushRule) -> Self {
// match rule {
// NewPushRule::Override(r) =>
// SetRuleReqBody::Conditional(ConditionalReqBody { actions:
// r.actions, conditions: r.conditions,
// }),
// NewPushRule::Content(r) =>
// SetRuleReqBody::Patterned(PatternedReqBody { actions:
// r.actions, pattern: r.pattern,
// }),
// NewPushRule::Room(r) => SetRuleReqBody::Simple(SimpleReqBody {
// actions: r.actions }), NewPushRule::Sender(r) =>
// SetRuleReqBody::Simple(SimpleReqBody { actions: r.actions }),
// NewPushRule::Underride(r) => SetRuleReqBody::Conditional(ConditionalReqBody {
// actions: r.actions,
// conditions: r.conditions,
// }),
// _ => unreachable!("variant added to NewPushRule not covered by
// SetRuleReqBody"), }
// }
// }
// /// `PUT /_matrix/client/*/pushrules/{scope}/{kind}/{rule_id}/enabled`
// ///
// /// This endpoint allows clients to enable or disable the specified push rule.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#put_matrixclientv3pushrulesscopekindruleidenabled
// const METADATA: Metadata = metadata! {
// method: PUT,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/pushrules/:scope/:kind/:rule_id/enabled",
// 1.1 => "/_matrix/client/v3/pushrules/:scope/:kind/:rule_id/enabled",
// }
// };
/// Request type for the `set_pushrule_enabled` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct SetRuleEnabledReqBody {
// /// The scope to fetch a rule from.
// #[salvo(parameter(parameter_in = Path))]
// pub scope: RuleScope,
// /// The kind of rule
// #[salvo(parameter(parameter_in = Path))]
// pub kind: RuleKind,
// /// The identifier for the rule.
// #[salvo(parameter(parameter_in = Path))]
// pub rule_id: String,
/// Whether the push rule is enabled or not.
pub enabled: bool,
}
// /// `GET /_matrix/client/*/pushrules/{scope}/{kind}/{rule_id}/enabled`
// ///
// /// This endpoint gets whether the specified push rule is enabled.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3pushrulesscopekindruleidenabled
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/pushrules/:scope/:kind/:rule_id/enabled",
// 1.1 => "/_matrix/client/v3/pushrules/:scope/:kind/:rule_id/enabled",
// }
// };
/// Request type for the `get_pushrule_enabled` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct RuleEnabledReqBody {
/// The scope to fetch a rule from.
#[salvo(parameter(parameter_in = Path))]
pub scope: RuleScope,
/// The kind of rule
#[salvo(parameter(parameter_in = Path))]
pub kind: RuleKind,
/// The identifier for the rule.
#[salvo(parameter(parameter_in = Path))]
pub rule_id: String,
}
/// Response type for the `get_pushrule_enabled` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct RuleEnabledResBody {
/// Whether the push rule is enabled or not.
pub enabled: bool,
}
impl RuleEnabledResBody {
/// Creates a new `Response` with the given enabled flag.
pub fn new(enabled: bool) -> Self {
Self { enabled }
}
}
// /// `DELETE /_matrix/client/*/pushrules/{scope}/{kind}/{rule_id}`
// ///
// /// This endpoint removes the push rule defined in the path.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#delete_matrixclientv3pushrulesscopekindruleid
// const METADATA: Metadata = metadata! {
// method: DELETE,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/pushrules/:scope/:kind/:rule_id",
// 1.1 => "/_matrix/client/v3/pushrules/:scope/:kind/:rule_id",
// }
// };
// /// Request type for the `delete_pushrule` endpoint.
// pub struct DeleteRuleReqBody {
// /// The scope to delete from.
// #[salvo(parameter(parameter_in = Path))]
// pub scope: RuleScope,
// /// The kind of rule
// #[salvo(parameter(parameter_in = Path))]
// pub kind: RuleKind,
// /// The identifier for the rule.
// #[salvo(parameter(parameter_in = Path))]
// pub rule_id: String,
// }
// /// `GET /_matrix/client/*/pushrules/global/`
// ///
// /// Retrieve all push rulesets in the global scope for this user.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3pushrules
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/pushrules/global/",
// 1.1 => "/_matrix/client/v3/pushrules/global/",
// }
// };
/// Response type for the `get_pushrules_global_scope` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct DeleteRuleResBody {
/// The global ruleset.
#[serde(flatten)]
pub global: Ruleset,
}
impl DeleteRuleResBody {
/// Creates a new `Response` with the given global ruleset.
pub fn new(global: Ruleset) -> Self {
Self { global }
}
}
// /// `GET /_matrix/client/*/pushrules/{scope}/{kind}/{rule_id}/actions`
// ///
// /// This endpoint get the actions for the specified push rule.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3pushrulesscopekindruleidactions
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/pushrules/:scope/:kind/:rule_id/actions",
// 1.1 => "/_matrix/client/v3/pushrules/:scope/:kind/:rule_id/actions",
// }
// };
// /// Request type for the `get_pushrule_actions` endpoint.
// pub struct RuleActionsReqBody {
// /// The scope to fetch a rule from.
// #[salvo(parameter(parameter_in = Path))]
// pub scope: RuleScope,
// /// The kind of rule
// #[salvo(parameter(parameter_in = Path))]
// pub kind: RuleKind,
// /// The identifier for the rule.
// #[salvo(parameter(parameter_in = Path))]
// pub rule_id: String,
// }
/// Response type for the `get_pushrule_actions` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct RuleActionsResBody {
/// The actions to perform for this rule.
pub actions: Vec<Action>,
}
impl RuleActionsResBody {
/// Creates a new `Response` with the given actions.
pub fn new(actions: Vec<Action>) -> Self {
Self { actions }
}
}
// /// `PUT /_matrix/client/*/pushrules/{scope}/{kind}/{rule_id}/actions`
// ///
// /// This endpoint allows clients to change the actions of a push rule. This can
// /// be used to change the actions of builtin rules.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#put_matrixclientv3pushrulesscopekindruleidactions
// const METADATA: Metadata = metadata! {
// method: PUT,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/pushrules/:scope/:kind/:rule_id/actions",
// 1.1 => "/_matrix/client/v3/pushrules/:scope/:kind/:rule_id/actions",
// }
// };
/// Request type for the `set_pushrule_actions` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct SetRuleActionsReqBody {
// /// The scope to fetch a rule from.
// #[salvo(parameter(parameter_in = Path))]
// pub scope: RuleScope,
// /// The kind of rule
// #[salvo(parameter(parameter_in = Path))]
// pub kind: RuleKind,
// /// The identifier for the rule.
// #[salvo(parameter(parameter_in = Path))]
// pub rule_id: String,
/// The actions to perform for this rule
pub actions: Vec<Action>,
}
| 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/client/push/pusher.rs | crates/core/src/client/push/pusher.rs | //! `GET /_matrix/client/*/pushers`
//!
//! Gets all currently active pushers for the authenticated user.
use js_option::JsOption;
use salvo::prelude::*;
use serde::{Deserialize, Serialize, de, ser::SerializeStruct};
use crate::{
push::{Pusher, PusherIds},
serde::{RawJsonValue, from_raw_json_value},
};
// `/v3/` ([spec])
//
// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3pushers
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/pushers",
// 1.1 => "/_matrix/client/v3/pushers",
// }
// };
/// Response type for the `get_pushers` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct PushersResBody {
/// An array containing the current pushers for the user.
pub pushers: Vec<Pusher>,
}
impl PushersResBody {
/// Creates a new `Response` with the given pushers.
pub fn new(pushers: Vec<Pusher>) -> Self {
Self { pushers }
}
}
// `POST /_matrix/client/*/pushers/set`
//
// This endpoint allows the creation, modification and deletion of pushers for
// this user ID. `/v3/` ([spec])
//
// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3pushersset
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/pushers/set",
// 1.1 => "/_matrix/client/v3/pushers/set",
// }
// };
/// Request type for the `set_pusher` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct SetPusherReqBody(pub PusherAction);
// impl Request {
// /// Creates a new `Request` for the given action.
// pub fn new(action: PusherAction) -> Self {
// Self { action }
// }
// /// Creates a new `Request` to create or update the given pusher.
// pub fn post(pusher: Pusher) -> Self {
// Self::new(PusherAction::Post(PusherPostData { pusher, append: false
// })) }
// /// Creates a new `Request` to delete the pusher identified by the given
// IDs. pub fn delete(ids: PusherIds) -> Self {
// Self::new(PusherAction::Delete(ids))
// }
// }
/// The action to take for the pusher.
#[derive(ToSchema, Clone, Debug)]
pub enum PusherAction {
/// Create or update the given pusher.
Post(PusherPostData),
/// Delete the pusher identified by the given IDs.
Delete(PusherIds),
}
impl Serialize for PusherAction {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
PusherAction::Post(pusher) => pusher.serialize(serializer),
PusherAction::Delete(ids) => {
let mut st = serializer.serialize_struct("PusherAction", 3)?;
st.serialize_field("pushkey", &ids.pushkey)?;
st.serialize_field("app_id", &ids.app_id)?;
st.serialize_field("kind", &None::<&str>)?;
st.end()
}
}
}
}
#[derive(Debug, Deserialize)]
struct PusherActionDeHelper {
kind: JsOption<String>,
}
impl<'de> Deserialize<'de> for PusherAction {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
let json = Box::<RawJsonValue>::deserialize(deserializer)?;
let PusherActionDeHelper { kind } = from_raw_json_value(&json)?;
match kind {
JsOption::Some(_) => Ok(Self::Post(from_raw_json_value(&json)?)),
JsOption::Null => Ok(Self::Delete(from_raw_json_value(&json)?)),
// This is unreachable because we don't use `#[serde(default)]` on the field.
JsOption::Undefined => Err(de::Error::missing_field("kind")),
}
}
}
/// Data necessary to create or update a pusher.
#[derive(ToSchema, Serialize, Clone, Debug)]
pub struct PusherPostData {
/// The pusher to configure.
#[serde(flatten)]
pub pusher: Pusher,
/// Controls if another pusher with the same pushkey and app id should be
/// created, if there are already others for other users.
///
/// Defaults to `false`. See the spec for more details.
#[serde(
skip_serializing_if = "crate::serde::is_default",
default = "default_false"
)]
pub append: bool,
}
#[derive(Debug, Deserialize)]
struct PusherPostDataDeHelper {
#[serde(default)]
append: bool,
}
impl<'de> Deserialize<'de> for PusherPostData {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
let json = Box::<RawJsonValue>::deserialize(deserializer)?;
let PusherPostDataDeHelper { append } = from_raw_json_value(&json)?;
let pusher = from_raw_json_value(&json)?;
Ok(Self { pusher, append })
}
}
| 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/client/discovery/auth_metadata.rs | crates/core/src/client/discovery/auth_metadata.rs | //! `GET /_matrix/client/*/auth_metadata`
//!
//! Get the metadata of the authorization server that is trusted by the homeserver.
use std::collections::BTreeSet;
use ::serde::Serialize;
use salvo::prelude::*;
use url::Url;
use crate::PrivOwnedStr;
use crate::serde::{RawJson, StringEnum};
mod serde;
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: None,
// history: {
// unstable => "/_matrix/client/unstable/org.matrix.msc2965/auth_metadata",
// 1.15 => "/_matrix/client/v1/auth_metadata",
// }
// };
/// Response type for the `client_well_known` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct AuthMetadtaResBody {
/// The authorization server metadata as defined in [RFC 8414].
///
/// [RFC 8414]: https://datatracker.ietf.org/doc/html/rfc8414
#[serde(flatten)]
#[salvo(schema(value_type = Object, additional_properties = true))]
pub metadata: RawJson<AuthorizationServerMetadata>,
}
impl AuthMetadtaResBody {
/// Creates a new `Response` with the given `HomeServerInfo`.
pub fn new(metadata: RawJson<AuthorizationServerMetadata>) -> Self {
Self { metadata }
}
}
/// Metadata describing the configuration of the authorization server.
///
/// While the metadata properties and their values are declared for OAuth 2.0 in [RFC 8414] and
/// other RFCs, this type only supports properties and values that are used for Matrix, as
/// specified in [MSC3861] and its dependencies.
///
/// This type is validated to have at least all the required values during deserialization. The
/// URLs are not validated during deserialization, to validate them use
/// [`AuthorizationServerMetadata::validate_urls()`] or
/// [`AuthorizationServerMetadata::insecure_validate_urls()`].
///
/// This type has no constructor, it should be sent as raw JSON directly.
///
/// [RFC 8414]: https://datatracker.ietf.org/doc/html/rfc8414
/// [MSC3861]: https://github.com/matrix-org/matrix-spec-proposals/pull/3861
#[derive(Debug, Clone, Serialize)]
pub struct AuthorizationServerMetadata {
/// The authorization server's issuer identifier.
///
/// This should be a URL with no query or fragment components.
pub issuer: Url,
/// URL of the authorization server's authorization endpoint ([RFC 6749]).
///
/// [RFC 6749]: https://datatracker.ietf.org/doc/html/rfc6749
pub authorization_endpoint: Url,
/// URL of the authorization server's token endpoint ([RFC 6749]).
///
/// [RFC 6749]: https://datatracker.ietf.org/doc/html/rfc6749
pub token_endpoint: Url,
/// URL of the authorization server's OAuth 2.0 Dynamic Client Registration endpoint
/// ([RFC 7591]).
///
/// [RFC 7591]: https://datatracker.ietf.org/doc/html/rfc7591
#[serde(skip_serializing_if = "Option::is_none")]
pub registration_endpoint: Option<Url>,
/// List of the OAuth 2.0 `response_type` values that this authorization server supports.
///
/// Those values are the same as those used with the `response_types` parameter defined by
/// OAuth 2.0 Dynamic Client Registration ([RFC 7591]).
///
/// This field must include [`ResponseType::Code`].
///
/// [RFC 7591]: https://datatracker.ietf.org/doc/html/rfc7591
pub response_types_supported: BTreeSet<ResponseType>,
/// List of the OAuth 2.0 `response_mode` values that this authorization server supports.
///
/// Those values are specified in [OAuth 2.0 Multiple Response Type Encoding Practices].
///
/// This field must include [`ResponseMode::Query`] and [`ResponseMode::Fragment`].
///
/// [OAuth 2.0 Multiple Response Type Encoding Practices]: https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html
pub response_modes_supported: BTreeSet<ResponseMode>,
/// List of the OAuth 2.0 `grant_type` values that this authorization server supports.
///
/// Those values are the same as those used with the `grant_types` parameter defined by
/// OAuth 2.0 Dynamic Client Registration ([RFC 7591]).
///
/// This field must include [`GrantType::AuthorizationCode`] and
/// [`GrantType::RefreshToken`].
///
/// [RFC 7591]: https://datatracker.ietf.org/doc/html/rfc7591
pub grant_types_supported: BTreeSet<GrantType>,
/// URL of the authorization server's OAuth 2.0 revocation endpoint ([RFC 7009]).
///
/// [RFC 7009]: https://datatracker.ietf.org/doc/html/rfc7009
pub revocation_endpoint: Url,
/// List of Proof Key for Code Exchange (PKCE) code challenge methods supported by this
/// authorization server ([RFC 7636]).
///
/// This field must include [`CodeChallengeMethod::S256`].
///
/// [RFC 7636]: https://datatracker.ietf.org/doc/html/rfc7636
pub code_challenge_methods_supported: BTreeSet<CodeChallengeMethod>,
/// URL where the user is able to access the account management capabilities of the
/// authorization server ([MSC4191]).
///
/// [MSC4191]: https://github.com/matrix-org/matrix-spec-proposals/pull/4191
#[cfg(feature = "unstable-msc4191")]
#[serde(skip_serializing_if = "Option::is_none")]
pub account_management_uri: Option<Url>,
/// List of actions that the account management URL supports ([MSC4191]).
///
/// [MSC4191]: https://github.com/matrix-org/matrix-spec-proposals/pull/4191
#[cfg(feature = "unstable-msc4191")]
#[serde(skip_serializing_if = "BTreeSet::is_empty")]
pub account_management_actions_supported: BTreeSet<AccountManagementAction>,
/// URL of the authorization server's device authorization endpoint ([RFC 8628]).
///
/// [RFC 8628]: https://datatracker.ietf.org/doc/html/rfc8628
#[cfg(feature = "unstable-msc4108")]
#[serde(skip_serializing_if = "Option::is_none")]
pub device_authorization_endpoint: Option<Url>,
/// The [`Prompt`] values supported by the authorization server ([Initiating User
/// Registration via OpenID Connect 1.0]).
///
/// [Initiating User Registration via OpenID Connect 1.0]: https://openid.net/specs/openid-connect-prompt-create-1_0.html
#[serde(skip_serializing_if = "Vec::is_empty")]
pub prompt_values_supported: Vec<Prompt>,
}
impl AuthorizationServerMetadata {
/// Strict validation of the URLs in this `AuthorizationServerMetadata`.
///
/// This checks that:
///
/// * The `issuer` is a valid URL using an `https` scheme and without a query or fragment.
///
/// * All the URLs use an `https` scheme.
pub fn validate_urls(&self) -> Result<(), AuthorizationServerMetadataUrlError> {
self.validate_urls_inner(false)
}
/// Weak validation the URLs `AuthorizationServerMetadata` are all absolute URLs.
///
/// This only checks that the `issuer` is a valid URL without a query or fragment.
///
/// In production, you should prefer [`AuthorizationServerMetadata`] that also check if the
/// URLs use an `https` scheme. This method is meant for development purposes, when
/// interacting with a local authorization server.
pub fn insecure_validate_urls(&self) -> Result<(), AuthorizationServerMetadataUrlError> {
self.validate_urls_inner(true)
}
/// Get an iterator over the URLs of this `AuthorizationServerMetadata`, except the
/// `issuer`.
fn validate_urls_inner(
&self,
insecure: bool,
) -> Result<(), AuthorizationServerMetadataUrlError> {
if self.issuer.query().is_some() || self.issuer.fragment().is_some() {
return Err(AuthorizationServerMetadataUrlError::IssuerHasQueryOrFragment);
}
if insecure {
// No more checks.
return Ok(());
}
let required_urls = &[
("issuer", &self.issuer),
("authorization_endpoint", &self.authorization_endpoint),
("token_endpoint", &self.token_endpoint),
("revocation_endpoint", &self.revocation_endpoint),
];
let optional_urls = &[
self.registration_endpoint
.as_ref()
.map(|string| ("registration_endpoint", string)),
#[cfg(feature = "unstable-msc4191")]
self.account_management_uri
.as_ref()
.map(|string| ("account_management_uri", string)),
#[cfg(feature = "unstable-msc4108")]
self.device_authorization_endpoint
.as_ref()
.map(|string| ("device_authorization_endpoint", string)),
];
for (field, url) in required_urls.iter().chain(optional_urls.iter().flatten()) {
if url.scheme() != "https" {
return Err(AuthorizationServerMetadataUrlError::NotHttpsScheme(field));
}
}
Ok(())
}
}
/// The method to use at the authorization endpoint.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(Clone, StringEnum)]
#[palpo_enum(rename_all = "lowercase")]
pub enum ResponseType {
/// Use the authorization code grant flow ([RFC 6749]).
///
/// [RFC 6749]: https://datatracker.ietf.org/doc/html/rfc6749
Code,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
/// The mechanism to be used for returning authorization response parameters from the
/// authorization endpoint.
///
/// The values are specified in [OAuth 2.0 Multiple Response Type Encoding Practices].
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
///
/// [OAuth 2.0 Multiple Response Type Encoding Practices]: https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html
#[derive(Clone, StringEnum)]
#[palpo_enum(rename_all = "lowercase")]
pub enum ResponseMode {
/// Authorization Response parameters are encoded in the fragment added to the
/// `redirect_uri` when redirecting back to the client.
Query,
/// Authorization Response parameters are encoded in the query string added to the
/// `redirect_uri` when redirecting back to the client.
Fragment,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
/// The grant type to use at the token endpoint.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(Clone, StringEnum)]
#[palpo_enum(rename_all = "snake_case")]
pub enum GrantType {
/// The authorization code grant type ([RFC 6749]).
///
/// [RFC 6749]: https://datatracker.ietf.org/doc/html/rfc6749
AuthorizationCode,
/// The refresh token grant type ([RFC 6749]).
///
/// [RFC 6749]: https://datatracker.ietf.org/doc/html/rfc6749
RefreshToken,
/// The device code grant type ([RFC 8628]).
///
/// [RFC 8628]: https://datatracker.ietf.org/doc/html/rfc8628
#[cfg(feature = "unstable-msc4108")]
#[palpo_enum(rename = "urn:ietf:params:oauth:grant-type:device_code")]
DeviceCode,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
/// The code challenge method to use at the authorization endpoint.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(Clone, StringEnum)]
pub enum CodeChallengeMethod {
/// Use a SHA-256, base64url-encoded code challenge ([RFC 7636]).
///
/// [RFC 7636]: https://datatracker.ietf.org/doc/html/rfc7636
S256,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
/// The action that the user wishes to do at the account management URL.
///
/// The values are specified in [MSC 4191].
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
///
/// [MSC 4191]: https://github.com/matrix-org/matrix-spec-proposals/pull/4191
#[cfg(feature = "unstable-msc4191")]
#[derive(Clone, StringEnum)]
pub enum AccountManagementAction {
/// The user wishes to view their profile (name, avatar, contact details).
///
/// [RFC 7636]: https://datatracker.ietf.org/doc/html/rfc7636
#[palpo_enum(rename = "org.matrix.profile")]
Profile,
/// The user wishes to view a list of their sessions.
#[palpo_enum(rename = "org.matrix.sessions_list")]
SessionsList,
/// The user wishes to view the details of a specific session.
#[palpo_enum(rename = "org.matrix.session_view")]
SessionView,
/// The user wishes to end/logout a specific session.
#[palpo_enum(rename = "org.matrix.session_end")]
SessionEnd,
/// The user wishes to deactivate their account.
#[palpo_enum(rename = "org.matrix.account_deactivate")]
AccountDeactivate,
/// The user wishes to reset their cross-signing keys.
#[palpo_enum(rename = "org.matrix.cross_signing_reset")]
CrossSigningReset,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
/// The possible errors when validating URLs of [`AuthorizationServerMetadata`].
#[derive(Debug, Clone, thiserror::Error)]
pub enum AuthorizationServerMetadataUrlError {
/// The URL of the field does not use the `https` scheme.
#[error("URL in `{0}` must use the `https` scheme")]
NotHttpsScheme(&'static str),
/// The `issuer` URL has a query or fragment component.
#[error("URL in `issuer` cannot have a query or fragment component")]
IssuerHasQueryOrFragment,
}
/// The desired user experience when using the authorization endpoint.
#[derive(Clone, StringEnum)]
#[palpo_enum(rename_all = "lowercase")]
pub enum Prompt {
/// The user wants to create a new account ([Initiating User Registration via OpenID
/// Connect 1.0]).
///
/// [Initiating User Registration via OpenID Connect 1.0]: https://openid.net/specs/openid-connect-prompt-create-1_0.html
Create,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
#[cfg(test)]
mod tests {
use serde_json::{Value as JsonValue, from_value as from_json_value, json};
use url::Url;
use super::AuthorizationServerMetadata;
/// A valid `AuthorizationServerMetadata` with all fields and values, as a JSON object.
pub(super) fn authorization_server_metadata_json() -> JsonValue {
json!({
"issuer": "https://server.local/",
"authorization_endpoint": "https://server.local/authorize",
"token_endpoint": "https://server.local/token",
"registration_endpoint": "https://server.local/register",
"response_types_supported": ["code"],
"response_modes_supported": ["query", "fragment"],
"grant_types_supported": ["authorization_code", "refresh_token"],
"revocation_endpoint": "https://server.local/revoke",
"code_challenge_methods_supported": ["S256"],
"account_management_uri": "https://server.local/account",
"account_management_actions_supported": [
"org.matrix.profile",
"org.matrix.sessions_list",
"org.matrix.session_view",
"org.matrix.session_end",
"org.matrix.account_deactivate",
"org.matrix.cross_signing_reset",
],
"device_authorization_endpoint": "https://server.local/device",
})
}
/// A valid `AuthorizationServerMetadata`, with valid URLs.
fn authorization_server_metadata() -> AuthorizationServerMetadata {
from_json_value(authorization_server_metadata_json()).unwrap()
}
#[test]
fn metadata_valid_urls() {
let metadata = authorization_server_metadata();
metadata.validate_urls().unwrap();
metadata.insecure_validate_urls().unwrap();
}
#[test]
fn metadata_invalid_or_insecure_issuer() {
let original_metadata = authorization_server_metadata();
// URL with query string.
let mut metadata = original_metadata.clone();
metadata.issuer = Url::parse("https://server.local/?session=1er45elp").unwrap();
metadata.validate_urls().unwrap_err();
metadata.insecure_validate_urls().unwrap_err();
// URL with fragment.
let mut metadata = original_metadata.clone();
metadata.issuer = Url::parse("https://server.local/#session").unwrap();
metadata.validate_urls().unwrap_err();
metadata.insecure_validate_urls().unwrap_err();
// Insecure URL.
let mut metadata = original_metadata;
metadata.issuer = Url::parse("http://server.local/").unwrap();
metadata.validate_urls().unwrap_err();
metadata.insecure_validate_urls().unwrap();
}
#[test]
fn metadata_insecure_urls() {
let original_metadata = authorization_server_metadata();
let mut metadata = original_metadata.clone();
metadata.authorization_endpoint = Url::parse("http://server.local/authorize").unwrap();
metadata.validate_urls().unwrap_err();
metadata.insecure_validate_urls().unwrap();
let mut metadata = original_metadata.clone();
metadata.token_endpoint = Url::parse("http://server.local/token").unwrap();
metadata.validate_urls().unwrap_err();
metadata.insecure_validate_urls().unwrap();
let mut metadata = original_metadata.clone();
metadata.registration_endpoint = Some(Url::parse("http://server.local/register").unwrap());
metadata.validate_urls().unwrap_err();
metadata.insecure_validate_urls().unwrap();
let mut metadata = original_metadata.clone();
metadata.revocation_endpoint = Url::parse("http://server.local/revoke").unwrap();
metadata.validate_urls().unwrap_err();
metadata.insecure_validate_urls().unwrap();
#[cfg(feature = "unstable-msc4191")]
{
let mut metadata = original_metadata.clone();
metadata.account_management_uri =
Some(Url::parse("http://server.local/account").unwrap());
metadata.validate_urls().unwrap_err();
metadata.insecure_validate_urls().unwrap();
}
#[cfg(feature = "unstable-msc4108")]
{
let mut metadata = original_metadata.clone();
metadata.device_authorization_endpoint =
Some(Url::parse("http://server.local/device").unwrap());
metadata.validate_urls().unwrap_err();
metadata.insecure_validate_urls().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/client/discovery/support.rs | crates/core/src/client/discovery/support.rs | //! `GET /.well-known/matrix/support` ([spec])
//!
//! [spec]: https://spec.matrix.org/latest/client-server-api/#getwell-knownmatrixsupport
//!
//! Get server admin contact and support page of a homeserver's domain.
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{OwnedUserId, PrivOwnedStr, serde::StringEnum};
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: None,
// history: {
// 1.10 => "/.well-known/matrix/support",
// }
// };
/// Response type for the `discover_support` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct SupportResBody {
/// Ways to contact the server administrator.
///
/// At least one of `contacts` or `support_page` is required. If only `contacts` is set, it
/// must contain at least one item.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub contacts: Vec<Contact>,
/// The URL of a page to give users help specific to the homeserver, like extra
/// login/registration steps.
///
/// At least one of `contacts` or `support_page` is required.
#[serde(skip_serializing_if = "Option::is_none")]
pub support_page: Option<String>,
}
impl SupportResBody {
/// Creates a new `Response` with the given contacts.
pub fn with_contacts(contacts: Vec<Contact>) -> Self {
Self {
contacts,
support_page: None,
}
}
/// Creates a new `Response` with the given support page.
pub fn with_support_page(support_page: String) -> Self {
Self {
contacts: Vec::new(),
support_page: Some(support_page),
}
}
}
/// A way to contact the server administrator.
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize)]
pub struct Contact {
/// An informal description of what the contact methods are used for.
pub role: ContactRole,
/// An email address to reach the administrator.
///
/// At least one of `matrix_id` or `email_address` is required.
#[serde(skip_serializing_if = "Option::is_none")]
pub email_address: Option<String>,
/// A Matrix User ID representing the administrator.
///
/// It could be an account registered on a different homeserver so the administrator can be
/// contacted when the homeserver is down.
///
/// At least one of `matrix_id` or `email_address` is required.
#[serde(skip_serializing_if = "Option::is_none")]
pub matrix_id: Option<OwnedUserId>,
}
impl Contact {
/// Creates a new `Contact` with the given role and email address.
pub fn with_email_address(role: ContactRole, email_address: String) -> Self {
Self {
role,
email_address: Some(email_address),
matrix_id: None,
}
}
/// Creates a new `Contact` with the given role and Matrix User ID.
pub fn with_matrix_id(role: ContactRole, matrix_id: OwnedUserId) -> Self {
Self {
role,
email_address: None,
matrix_id: Some(matrix_id),
}
}
}
/// An informal description of what the contact methods are used for.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[palpo_enum(rename_all(prefix = "m.role.", rule = "snake_case"))]
#[non_exhaustive]
pub enum ContactRole {
/// A catch-all role for any queries.
Admin,
/// A role intended for sensitive requests.
Security,
/// A role for moderation-related queries according to [MSC4121](https://github.com/matrix-org/matrix-spec-proposals/pull/4121).
///
/// The future prefix for this if accepted will be `m.role.moderator`
#[cfg(feature = "unstable-msc4121")]
#[palpo_enum(
rename = "support.feline.msc4121.role.moderator",
alias = "m.role.moderator"
)]
Moderator,
#[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/client/discovery/client.rs | crates/core/src/client/discovery/client.rs | //! `GET /.well-known/matrix/client` ([spec])
//!
//! [spec]: https://spec.matrix.org/latest/client-server-api/#getwell-knownmatrixclient
//!
//! Get discovery information about the domain.
use std::borrow::Cow;
use salvo::prelude::*;
#[cfg(feature = "unstable-msc4143")]
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
#[cfg(feature = "unstable-msc4143")]
use serde_json::Value as JsonValue;
use crate::serde::JsonObject;
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: None,
// history: {
// 1.0 => "/.well-known/matrix/client",
// }
// };
/// Response type for the `client_well_known` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct ClientResBody {
/// Information about the homeserver to connect to.
#[serde(rename = "m.homeserver")]
pub homeserver: HomeServerInfo,
/// Information about the identity server to connect to.
#[serde(
default,
rename = "m.identity_server",
skip_serializing_if = "Option::is_none"
)]
pub identity_server: Option<IdentityServerInfo>,
/// Information about the tile server to use to display location data.
#[cfg(feature = "unstable-msc3488")]
#[serde(
default,
rename = "org.matrix.msc3488.tile_server",
alias = "m.tile_server",
skip_serializing_if = "Option::is_none"
)]
pub tile_server: Option<TileServerInfo>,
/// A list of the available MatrixRTC foci, ordered by priority.
#[cfg(feature = "unstable-msc4143")]
#[serde(
rename = "org.matrix.msc4143.rtc_foci",
alias = "m.rtc_foci",
default,
skip_serializing_if = "Vec::is_empty"
)]
pub rtc_foci: Vec<RtcFocusInfo>,
}
impl ClientResBody {
/// Creates a new `Response` with the given `HomeServerInfo`.
pub fn new(homeserver: HomeServerInfo) -> Self {
Self {
homeserver,
identity_server: None,
#[cfg(feature = "unstable-msc3488")]
tile_server: None,
#[cfg(feature = "unstable-msc4143")]
rtc_foci: Default::default(),
}
}
}
/// Information about a discovered homeserver.
#[derive(ToSchema, Clone, Debug, Deserialize, Hash, Serialize)]
pub struct HomeServerInfo {
/// The base URL for the homeserver for client-server connections.
pub base_url: String,
}
impl HomeServerInfo {
/// Creates a new `HomeServerInfo` with the given `base_url`.
pub fn new(base_url: String) -> Self {
Self { base_url }
}
}
/// Information about a discovered identity server.
#[derive(ToSchema, Clone, Debug, Deserialize, Hash, Serialize)]
pub struct IdentityServerInfo {
/// The base URL for the identity server for client-server connections.
pub base_url: String,
}
impl IdentityServerInfo {
/// Creates an `IdentityServerInfo` with the given `base_url`.
pub fn new(base_url: String) -> Self {
Self { base_url }
}
}
/// Information about a discovered map tile server.
#[derive(ToSchema, Clone, Debug, Deserialize, Hash, Serialize)]
pub struct TileServerInfo {
/// The URL of a map tile server's `style.json` file.
///
/// See the [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/) for more details.
pub map_style_url: String,
}
impl TileServerInfo {
/// Creates a `TileServerInfo` with the given map style URL.
pub fn new(map_style_url: String) -> Self {
Self { map_style_url }
}
}
/// Information about a specific MatrixRTC focus.
#[cfg(feature = "unstable-msc4143")]
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(tag = "type")]
pub enum RtcFocusInfo {
/// A LiveKit RTC focus.
#[serde(rename = "livekit")]
LiveKit(LiveKitRtcFocusInfo),
/// A custom RTC focus.
#[doc(hidden)]
#[serde(untagged)]
_Custom(CustomRtcFocusInfo),
}
#[cfg(feature = "unstable-msc4143")]
impl RtcFocusInfo {
/// A constructor to create a custom RTC focus.
///
/// Prefer to use the public variants of `RtcFocusInfo` where possible; this constructor is
/// meant to be used for unsupported focus types only and does not allow setting arbitrary data
/// for supported ones.
///
/// # Errors
///
/// Returns an error if the `focus_type` is known and serialization of `data` to the
/// corresponding `RtcFocusInfo` variant fails.
pub fn new(focus_type: &str, data: JsonObject) -> serde_json::Result<Self> {
fn deserialize_variant<T: DeserializeOwned>(obj: JsonObject) -> serde_json::Result<T> {
serde_json::from_value(JsonValue::Object(obj))
}
Ok(match focus_type {
"livekit" => Self::LiveKit(deserialize_variant(data)?),
_ => Self::_Custom(CustomRtcFocusInfo {
focus_type: focus_type.to_owned(),
data,
}),
})
}
/// Creates a new `RtcFocusInfo::LiveKit`.
pub fn livekit(service_url: String) -> Self {
Self::LiveKit(LiveKitRtcFocusInfo { service_url })
}
/// Returns a reference to the focus type of this RTC focus.
pub fn focus_type(&self) -> &str {
match self {
Self::LiveKit(_) => "livekit",
Self::_Custom(custom) => &custom.focus_type,
}
}
/// Returns the associated data.
///
/// The returned JSON object won't contain the `focus_type` field, please use
/// [`.focus_type()`][Self::focus_type] to access that.
///
/// Prefer to use the public variants of `RtcFocusInfo` where possible; this method is meant to
/// be used for custom focus types only.
pub fn data(&self) -> Cow<'_, JsonObject> {
fn serialize<T: Serialize>(object: &T) -> JsonObject {
match serde_json::to_value(object).expect("rtc focus type serialization to succeed") {
JsonValue::Object(object) => object,
_ => panic!("all rtc focus types must serialize to objects"),
}
}
match self {
Self::LiveKit(info) => Cow::Owned(serialize(info)),
Self::_Custom(info) => Cow::Borrowed(&info.data),
}
}
}
/// Information about a LiveKit RTC focus.
#[cfg(feature = "unstable-msc4143")]
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct LiveKitRtcFocusInfo {
/// The URL for the LiveKit service.
#[serde(rename = "livekit_service_url")]
pub service_url: String,
}
/// Information about a custom RTC focus type.
#[doc(hidden)]
#[cfg(feature = "unstable-msc4143")]
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct CustomRtcFocusInfo {
/// The type of RTC focus.
#[serde(rename = "type")]
focus_type: String,
/// Remaining RTC focus data.
#[serde(flatten)]
data: JsonObject,
}
#[cfg(test)]
mod tests {
#[cfg(feature = "unstable-msc4143")]
use assert_matches2::assert_matches;
#[cfg(feature = "unstable-msc4143")]
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
#[cfg(feature = "unstable-msc4143")]
use super::RtcFocusInfo;
#[test]
#[cfg(feature = "unstable-msc4143")]
fn test_livekit_rtc_focus_deserialization() {
// Given the JSON for a LiveKit RTC focus.
let json = json!({
"type": "livekit",
"livekit_service_url": "https://livekit.example.com"
});
// When deserializing it into an RtcFocusInfo.
let focus: RtcFocusInfo = from_json_value(json).unwrap();
// Then it should be recognized as a LiveKit focus with the correct service URL.
assert_matches!(focus, RtcFocusInfo::LiveKit(info));
assert_eq!(info.service_url, "https://livekit.example.com");
}
#[test]
#[cfg(feature = "unstable-msc4143")]
fn test_livekit_rtc_focus_serialization() {
// Given a LiveKit RTC focus info.
let focus = RtcFocusInfo::livekit("https://livekit.example.com".to_owned());
// When serializing it to JSON.
let json = to_json_value(&focus).unwrap();
// Then it should match the expected JSON structure.
assert_eq!(
json,
json!({
"type": "livekit",
"livekit_service_url": "https://livekit.example.com"
})
);
}
#[test]
#[cfg(feature = "unstable-msc4143")]
fn test_custom_rtc_focus_serialization() {
// Given the JSON for a custom RTC focus type with additional fields.
let json = json!({
"type": "some-focus-type",
"additional-type-specific-field": "https://my_focus.domain",
"another-additional-type-specific-field": ["with", "Array", "type"]
});
// When deserializing it into an RtcFocusInfo.
let focus: RtcFocusInfo = from_json_value(json.clone()).unwrap();
// Then it should be recognized as a custom focus type, with all the additional fields
// included.
assert_eq!(focus.focus_type(), "some-focus-type");
let data = &focus.data();
assert_eq!(
data["additional-type-specific-field"],
"https://my_focus.domain"
);
let array_values: Vec<&str> = data["another-additional-type-specific-field"]
.as_array()
.unwrap()
.iter()
.map(|v| v.as_str().unwrap())
.collect();
assert_eq!(array_values, vec!["with", "Array", "type"]);
assert!(!data.contains_key("type"));
// When serializing it back to JSON.
let serialized = to_json_value(&focus).unwrap();
// Then it should match the original JSON.
assert_eq!(serialized, 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/client/discovery/versions.rs | crates/core/src/client/discovery/versions.rs | //! `GET /_matrix/client/*/capabilities`
//!
//! Get information about the server's supported feature set and other relevant
//! capabilities ([spec]).
//!
//! [spec]: https://spec.matrix.org/latest/client-server-api/#capabilities-negotiation
use std::collections::BTreeMap;
use salvo::prelude::*;
use serde::Serialize;
use crate::SupportedVersions;
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessTokenOptional,
// history: {
// 1.0 => "/_matrix/client/versions",
// }
// };
/// Response type for the `api_versions` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct VersionsResBody {
/// A list of Matrix client API protocol versions supported by the
/// homeserver.
pub versions: Vec<String>,
/// Experimental features supported by the server.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub unstable_features: BTreeMap<String, bool>,
}
impl VersionsResBody {
/// Creates a new `Response` with the given `versions`.
pub fn new(versions: Vec<String>) -> Self {
Self {
versions,
unstable_features: BTreeMap::new(),
}
}
/// Convert this `Response` into a [`SupportedVersions`] that can be used with
/// `OutgoingRequest::try_into_http_request()`.
///
/// Matrix versions that can't be parsed to a `MatrixVersion`, and features with the boolean
/// value set to `false` are discarded.
pub fn as_supported_versions(&self) -> SupportedVersions {
SupportedVersions::from_parts(&self.versions, &self.unstable_features)
}
}
| 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/client/discovery/capabilities.rs | crates/core/src/client/discovery/capabilities.rs | //! `GET /_matrix/client/*/capabilities`
//!
//! Get information about the server's supported feature set and other relevant capabilities
//! ([spec]).
//!
//! [spec]: https://spec.matrix.org/latest/client-server-api/#capabilities-negotiation
use std::{borrow::Cow, collections::BTreeMap};
use maplit::btreemap;
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json::{Value as JsonValue, from_value as from_json_value, to_value as to_json_value};
use crate::client::profile::ProfileFieldName;
use crate::{PrivOwnedStr, RoomVersionId, serde::StringEnum};
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3capabilities
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/capabilities",
// 1.1 => "/_matrix/client/v3/capabilities",
// }
// };
/// Response type for the `get_capabilities` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct CapabilitiesResBody {
/// The capabilities the server supports
pub capabilities: Capabilities,
}
impl CapabilitiesResBody {
/// Creates a new `Response` with the given capabilities.
pub fn new(capabilities: Capabilities) -> Self {
Self { capabilities }
}
}
/// Contains information about all the capabilities that the server supports.
#[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)]
#[allow(deprecated)]
pub struct Capabilities {
/// Capability to indicate if the user can change their password.
#[serde(rename = "m.change_password", default)]
pub change_password: ChangePasswordCapability,
/// The room versions the server supports.
#[serde(rename = "m.room_versions", default)]
pub room_versions: RoomVersionsCapability,
/// Capability to indicate if the user can change their display name.
#[serde(rename = "m.set_display_name", default)]
#[deprecated = "Since Matrix 1.16, prefer profile_fields if it is set."]
pub set_display_name: SetDisplayNameCapability,
/// Capability to indicate if the user can change their avatar.
#[serde(rename = "m.set_avatar_url", default)]
#[deprecated = "Since Matrix 1.16, prefer profile_fields if it is set."]
pub set_avatar_url: SetAvatarUrlCapability,
/// Capability to indicate if the user can change the third-party
/// identifiers associated with their account.
#[serde(rename = "m.3pid_changes", default)]
pub thirdparty_id_changes: ThirdPartyIdChangesCapability,
/// Capability to indicate if the user can set extended profile fields.
#[serde(
rename = "m.profile_fields",
alias = "uk.tcpip.msc4133.profile_fields",
skip_serializing_if = "Option::is_none"
)]
pub profile_fields: Option<ProfileFieldsCapability>,
/// Any other custom capabilities that the server supports outside of the
/// specification, labeled using the Java package naming convention and
/// stored as arbitrary JSON values.
#[serde(flatten)]
#[salvo(schema(skip))]
#[salvo(schema(value_type = Object, additional_properties = true))]
pub custom_capabilities: BTreeMap<String, JsonValue>,
}
impl Capabilities {
/// Creates empty `Capabilities`.
pub fn new() -> Self {
Default::default()
}
/// Returns the value of the given capability.
///
/// Prefer to use the public fields of `Capabilities` where possible; this
/// method is meant to be used for unsupported capabilities only.
pub fn get(&self, capability: &str) -> Option<Cow<'_, JsonValue>> {
fn serialize<T: Serialize>(cap: &T) -> JsonValue {
to_json_value(cap).expect("capability serialization to succeed")
}
match capability {
"m.change_password" => Some(Cow::Owned(serialize(&self.change_password))),
"m.room_versions" => Some(Cow::Owned(serialize(&self.room_versions))),
#[allow(deprecated)]
"m.set_displayname" => Some(Cow::Owned(serialize(&self.set_display_name))),
#[allow(deprecated)]
"m.set_avatar_url" => Some(Cow::Owned(serialize(&self.set_avatar_url))),
"m.3pid_changes" => Some(Cow::Owned(serialize(&self.thirdparty_id_changes))),
_ => self.custom_capabilities.get(capability).map(Cow::Borrowed),
}
}
/// Sets a capability to the given value.
///
/// Prefer to use the public fields of `Capabilities` where possible; this
/// method is meant to be used for unsupported capabilities only and
/// does not allow setting arbitrary data for supported ones.
pub fn set(&mut self, capability: &str, value: JsonValue) -> serde_json::Result<()> {
match capability {
"m.change_password" => self.change_password = from_json_value(value)?,
"m.room_versions" => self.room_versions = from_json_value(value)?,
#[allow(deprecated)]
"m.set_displayname" => self.set_display_name = from_json_value(value)?,
#[allow(deprecated)]
"m.set_avatar_url" => self.set_avatar_url = from_json_value(value)?,
"m.3pid_changes" => self.thirdparty_id_changes = from_json_value(value)?,
_ => {
self.custom_capabilities
.insert(capability.to_owned(), value);
}
}
Ok(())
}
}
/// Information about the m.change_password capability
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct ChangePasswordCapability {
/// `true` if the user can change their password, `false` otherwise.
pub enabled: bool,
}
impl ChangePasswordCapability {
/// Creates a new `ChangePasswordCapability` with the given enabled flag.
pub fn new(enabled: bool) -> Self {
Self { enabled }
}
/// Returns whether all fields have their default value.
pub fn is_default(&self) -> bool {
self.enabled
}
}
impl Default for ChangePasswordCapability {
fn default() -> Self {
Self { enabled: true }
}
}
/// Information about the m.room_versions capability
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct RoomVersionsCapability {
/// The default room version the server is using for new rooms.
pub default: RoomVersionId,
/// A detailed description of the room versions the server supports.
pub available: BTreeMap<RoomVersionId, RoomVersionStability>,
}
impl RoomVersionsCapability {
/// Creates a new `RoomVersionsCapability` with the given default room
/// version ID and room version descriptions.
pub fn new(
default: RoomVersionId,
available: BTreeMap<RoomVersionId, RoomVersionStability>,
) -> Self {
Self { default, available }
}
/// Returns whether all fields have their default value.
pub fn is_default(&self) -> bool {
self.default == RoomVersionId::V1
&& self.available.len() == 1
&& self
.available
.get(&RoomVersionId::V1)
.map(|stability| *stability == RoomVersionStability::Stable)
.unwrap_or(false)
}
}
impl Default for RoomVersionsCapability {
fn default() -> Self {
Self {
default: RoomVersionId::V1,
available: btreemap! { RoomVersionId::V1 => RoomVersionStability::Stable },
}
}
}
/// The stability of a room version.
#[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 RoomVersionStability {
/// Support for the given version is stable.
Stable,
/// Support for the given version is unstable.
Unstable,
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(PrivOwnedStr),
}
/// Information about the `m.set_display_name` capability
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
#[deprecated = "Since Matrix 1.16, prefer ProfileFieldsCapability instead."]
pub struct SetDisplayNameCapability {
/// `true` if the user can change their display name, `false` otherwise.
pub enabled: bool,
}
#[allow(deprecated)]
impl SetDisplayNameCapability {
/// Creates a new `SetDisplayNameCapability` with the given enabled flag.
pub fn new(enabled: bool) -> Self {
Self { enabled }
}
/// Returns whether all fields have their default value.
pub fn is_default(&self) -> bool {
self.enabled
}
}
#[allow(deprecated)]
impl Default for SetDisplayNameCapability {
fn default() -> Self {
Self { enabled: true }
}
}
/// Information about the `m.set_avatar_url` capability
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
#[deprecated = "Since Matrix 1.16, prefer ProfileFieldsCapability instead."]
pub struct SetAvatarUrlCapability {
/// `true` if the user can change their avatar, `false` otherwise.
pub enabled: bool,
}
#[allow(deprecated)]
impl SetAvatarUrlCapability {
/// Creates a new `SetAvatarUrlCapability` with the given enabled flag.
pub fn new(enabled: bool) -> Self {
Self { enabled }
}
/// Returns whether all fields have their default value.
pub fn is_default(&self) -> bool {
self.enabled
}
}
#[allow(deprecated)]
impl Default for SetAvatarUrlCapability {
fn default() -> Self {
Self { enabled: true }
}
}
/// Information about the `m.3pid_changes` capability
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct ThirdPartyIdChangesCapability {
/// `true` if the user can change the third-party identifiers associated
/// with their account, `false` otherwise.
pub enabled: bool,
}
impl ThirdPartyIdChangesCapability {
/// Creates a new `ThirdPartyIdChangesCapability` with the given enabled
/// flag.
pub fn new(enabled: bool) -> Self {
Self { enabled }
}
/// Returns whether all fields have their default value.
pub fn is_default(&self) -> bool {
self.enabled
}
}
impl Default for ThirdPartyIdChangesCapability {
fn default() -> Self {
Self { enabled: true }
}
}
/// Information about the `m.get_login_token` capability.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct GetLoginTokenCapability {
/// Whether the user can request a login token.
pub enabled: bool,
}
impl GetLoginTokenCapability {
/// Creates a new `GetLoginTokenCapability` with the given enabled flag.
pub fn new(enabled: bool) -> Self {
Self { enabled }
}
/// Returns whether all fields have their default value.
pub fn is_default(&self) -> bool {
!self.enabled
}
}
/// Information about the `m.profile_fields` capability.
#[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)]
pub struct ProfileFieldsCapability {
/// Whether the user can set extended profile fields.
pub enabled: bool,
/// The fields that can be set by the user.
#[serde(skip_serializing_if = "Option::is_none")]
pub allowed: Option<Vec<ProfileFieldName>>,
/// The fields that cannot be set by the user.
///
/// This list is ignored if `allowed` is provided.
#[serde(skip_serializing_if = "Option::is_none")]
pub disallowed: Option<Vec<ProfileFieldName>>,
}
impl ProfileFieldsCapability {
/// Creates a new `ProfileFieldsCapability` with the given enabled flag.
pub fn new(enabled: bool) -> Self {
Self {
enabled,
allowed: None,
disallowed: None,
}
}
/// Whether the server advertises that the field with the given name can be set.
pub fn can_set_field(&self, field: &ProfileFieldName) -> bool {
if !self.enabled {
return false;
}
if let Some(allowed) = &self.allowed {
allowed.contains(field)
} else if let Some(disallowed) = &self.disallowed {
!disallowed.contains(field)
} else {
// The default is that any field is allowed.
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/client/discovery/homeserver.rs | crates/core/src/client/discovery/homeserver.rs | //! `GET /.well-known/matrix/client` ([spec])
//!
//! [spec]: https://spec.matrix.org/latest/client-server-api/#getwell-knownmatrixclient
//!
//! Get discovery information about the domain.
#[cfg(feature = "unstable-msc4143")]
use std::borrow::Cow;
use crate::auth_scheme::NoAuthentication;
#[cfg(feature = "unstable-msc4143")]
use crate::serde::JsonObject;
#[cfg(feature = "unstable-msc4143")]
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
#[cfg(feature = "unstable-msc4143")]
use serde_json::Value as JsonValue;
use salvo::oapi::{ToParameters, ToSchema};
// metadata! {
// method: GET,
// rate_limited: false,
// authentication: NoAuthentication,
// path: "/.well-known/matrix/client",
// }
// /// Request type for the `client_well_known` endpoint.
// #[request(error = crate::Error)]
// #[derive(Default)]
// pub struct Request {}
/// Response type for the `client_well_known` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct HomeServerResBody {
/// Information about the homeserver to connect to.
#[serde(rename = "m.homeserver")]
pub homeserver: HomeserverInfo,
/// Information about the identity server to connect to.
#[serde(rename = "m.identity_server", skip_serializing_if = "Option::is_none")]
pub identity_server: Option<IdentityServerInfo>,
/// Information about the tile server to use to display location data.
#[cfg(feature = "unstable-msc3488")]
#[serde(
rename = "org.matrix.msc3488.tile_server",
alias = "m.tile_server",
skip_serializing_if = "Option::is_none"
)]
pub tile_server: Option<TileServerInfo>,
/// A list of the available MatrixRTC foci, ordered by priority.
#[cfg(feature = "unstable-msc4143")]
#[serde(
rename = "org.matrix.msc4143.rtc_foci",
alias = "m.rtc_foci",
default,
skip_serializing_if = "Vec::is_empty"
)]
pub rtc_foci: Vec<RtcFocusInfo>,
}
impl HomeServerResBody {
/// Creates a new `HomeServerResBody` with the given `HomeserverInfo`.
pub fn new(homeserver: HomeserverInfo) -> Self {
Self {
homeserver,
identity_server: None,
#[cfg(feature = "unstable-msc3488")]
tile_server: None,
#[cfg(feature = "unstable-msc4143")]
rtc_foci: Default::default(),
}
}
}
/// Information about a discovered homeserver.
#[derive(ToSchema, Clone, Debug, Deserialize, Hash, Serialize, PartialEq, Eq)]
pub struct HomeserverInfo {
/// The base URL for the homeserver for client-server connections.
pub base_url: String,
}
impl HomeserverInfo {
/// Creates a new `HomeserverInfo` with the given `base_url`.
pub fn new(base_url: String) -> Self {
Self { base_url }
}
}
/// Information about a discovered identity server.
#[derive(ToSchema, Clone, Debug, Deserialize, Hash, Serialize, PartialEq, Eq)]
pub struct IdentityServerInfo {
/// The base URL for the identity server for client-server connections.
pub base_url: String,
}
impl IdentityServerInfo {
/// Creates an `IdentityServerInfo` with the given `base_url`.
pub fn new(base_url: String) -> Self {
Self { base_url }
}
}
/// Information about a discovered map tile server.
#[cfg(feature = "unstable-msc3488")]
#[derive(ToSchema, Clone, Debug, Deserialize, Hash, Serialize, PartialEq, Eq)]
pub struct TileServerInfo {
/// The URL of a map tile server's `style.json` file.
///
/// See the [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/) for more details.
pub map_style_url: String,
}
#[cfg(feature = "unstable-msc3488")]
impl TileServerInfo {
/// Creates a `TileServerInfo` with the given map style URL.
pub fn new(map_style_url: String) -> Self {
Self { map_style_url }
}
}
/// Information about a specific MatrixRTC focus.
#[cfg(feature = "unstable-msc4143")]
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(tag = "type")]
pub enum RtcFocusInfo {
/// A LiveKit RTC focus.
#[serde(rename = "livekit")]
LiveKit(LiveKitRtcFocusInfo),
/// A custom RTC focus.
#[doc(hidden)]
#[serde(untagged)]
_Custom(CustomRtcFocusInfo),
}
#[cfg(feature = "unstable-msc4143")]
impl RtcFocusInfo {
/// A constructor to create a custom RTC focus.
///
/// Prefer to use the public variants of `RtcFocusInfo` where possible; this constructor is
/// meant to be used for unsupported focus types only and does not allow setting arbitrary data
/// for supported ones.
///
/// # Errors
///
/// Returns an error if the `focus_type` is known and serialization of `data` to the
/// corresponding `RtcFocusInfo` variant fails.
pub fn new(focus_type: &str, data: JsonObject) -> serde_json::Result<Self> {
fn deserialize_variant<T: DeserializeOwned>(obj: JsonObject) -> serde_json::Result<T> {
serde_json::from_value(JsonValue::Object(obj))
}
Ok(match focus_type {
"livekit" => Self::LiveKit(deserialize_variant(data)?),
_ => Self::_Custom(CustomRtcFocusInfo {
focus_type: focus_type.to_owned(),
data,
}),
})
}
/// Creates a new `RtcFocusInfo::LiveKit`.
pub fn livekit(service_url: String) -> Self {
Self::LiveKit(LiveKitRtcFocusInfo { service_url })
}
/// Returns a reference to the focus type of this RTC focus.
pub fn focus_type(&self) -> &str {
match self {
Self::LiveKit(_) => "livekit",
Self::_Custom(custom) => &custom.focus_type,
}
}
/// Returns the associated data.
///
/// The returned JSON object won't contain the `focus_type` field, please use
/// [`.focus_type()`][Self::focus_type] to access that.
///
/// Prefer to use the public variants of `RtcFocusInfo` where possible; this method is meant to
/// be used for custom focus types only.
pub fn data(&self) -> Cow<'_, JsonObject> {
fn serialize<T: Serialize>(object: &T) -> JsonObject {
match serde_json::to_value(object).expect("rtc focus type serialization to succeed") {
JsonValue::Object(object) => object,
_ => panic!("all rtc focus types must serialize to objects"),
}
}
match self {
Self::LiveKit(info) => Cow::Owned(serialize(info)),
Self::_Custom(info) => Cow::Borrowed(&info.data),
}
}
}
/// Information about a LiveKit RTC focus.
#[cfg(feature = "unstable-msc4143")]
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct LiveKitRtcFocusInfo {
/// The URL for the LiveKit service.
#[serde(rename = "livekit_service_url")]
pub service_url: String,
}
/// Information about a custom RTC focus type.
#[doc(hidden)]
#[cfg(feature = "unstable-msc4143")]
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct CustomRtcFocusInfo {
/// The type of RTC focus.
#[serde(rename = "type")]
focus_type: String,
/// Remaining RTC focus data.
#[serde(flatten)]
data: JsonObject,
}
#[cfg(test)]
mod tests {
#[cfg(feature = "unstable-msc4143")]
use assert_matches2::assert_matches;
#[cfg(feature = "unstable-msc4143")]
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
#[cfg(feature = "unstable-msc4143")]
use super::RtcFocusInfo;
#[test]
#[cfg(feature = "unstable-msc4143")]
fn test_livekit_rtc_focus_deserialization() {
// Given the JSON for a LiveKit RTC focus.
let json = json!({
"type": "livekit",
"livekit_service_url": "https://livekit.example.com"
});
// When deserializing it into an RtcFocusInfo.
let focus: RtcFocusInfo = from_json_value(json).unwrap();
// Then it should be recognized as a LiveKit focus with the correct service URL.
assert_matches!(focus, RtcFocusInfo::LiveKit(info));
assert_eq!(info.service_url, "https://livekit.example.com");
}
#[test]
#[cfg(feature = "unstable-msc4143")]
fn test_livekit_rtc_focus_serialization() {
// Given a LiveKit RTC focus info.
let focus = RtcFocusInfo::livekit("https://livekit.example.com".to_owned());
// When serializing it to JSON.
let json = to_json_value(&focus).unwrap();
// Then it should match the expected JSON structure.
assert_eq!(
json,
json!({
"type": "livekit",
"livekit_service_url": "https://livekit.example.com"
})
);
}
#[test]
#[cfg(feature = "unstable-msc4143")]
fn test_custom_rtc_focus_serialization() {
// Given the JSON for a custom RTC focus type with additional fields.
let json = json!({
"type": "some-focus-type",
"additional-type-specific-field": "https://my_focus.domain",
"another-additional-type-specific-field": ["with", "Array", "type"]
});
// When deserializing it into an RtcFocusInfo.
let focus: RtcFocusInfo = from_json_value(json.clone()).unwrap();
// Then it should be recognized as a custom focus type, with all the additional fields
// included.
assert_eq!(focus.focus_type(), "some-focus-type");
let data = &focus.data();
assert_eq!(
data["additional-type-specific-field"],
"https://my_focus.domain"
);
let array_values: Vec<&str> = data["another-additional-type-specific-field"]
.as_array()
.unwrap()
.iter()
.map(|v| v.as_str().unwrap())
.collect();
assert_eq!(array_values, vec!["with", "Array", "type"]);
assert!(!data.contains_key("type"));
// When serializing it back to JSON.
let serialized = to_json_value(&focus).unwrap();
// Then it should match the original JSON.
assert_eq!(serialized, 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/client/discovery/auth_metadata/serde.rs | crates/core/src/client/discovery/auth_metadata/serde.rs | use std::collections::BTreeSet;
use serde::{Deserialize, de};
use url::Url;
#[cfg(feature = "unstable-msc4191")]
use super::AccountManagementAction;
use super::{
AuthorizationServerMetadata, CodeChallengeMethod, GrantType, Prompt, ResponseMode, ResponseType,
};
impl<'de> Deserialize<'de> for AuthorizationServerMetadata {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let helper = AuthorizationServerMetadataDeHelper::deserialize(deserializer)?;
let AuthorizationServerMetadataDeHelper {
issuer,
authorization_endpoint,
token_endpoint,
registration_endpoint,
response_types_supported,
response_modes_supported,
grant_types_supported,
revocation_endpoint,
code_challenge_methods_supported,
#[cfg(feature = "unstable-msc4191")]
account_management_uri,
#[cfg(feature = "unstable-msc4191")]
account_management_actions_supported,
#[cfg(feature = "unstable-msc4108")]
device_authorization_endpoint,
prompt_values_supported,
} = helper;
// Require `code` in `response_types_supported`.
if !response_types_supported.contains(&ResponseType::Code) {
return Err(de::Error::custom(
"missing value `code` in `response_types_supported`",
));
}
// Require `query` and `fragment` in `response_modes_supported`.
if let Some(response_modes) = &response_modes_supported {
let query_found = response_modes.contains(&ResponseMode::Query);
let fragment_found = response_modes.contains(&ResponseMode::Fragment);
if !query_found && !fragment_found {
return Err(de::Error::custom(
"missing values `query` and `fragment` in `response_modes_supported`",
));
}
if !query_found {
return Err(de::Error::custom(
"missing value `query` in `response_modes_supported`",
));
}
if !fragment_found {
return Err(de::Error::custom(
"missing value `fragment` in `response_modes_supported`",
));
}
}
// If the field is missing, the default value is `["query", "fragment"]`, according to
// RFC8414.
let response_modes_supported = response_modes_supported
.unwrap_or_else(|| [ResponseMode::Query, ResponseMode::Fragment].into());
// Require `authorization_code` and `refresh_token` in `grant_types_supported`.
let authorization_code_found =
grant_types_supported.contains(&GrantType::AuthorizationCode);
let refresh_token_found = grant_types_supported.contains(&GrantType::RefreshToken);
if !authorization_code_found && !refresh_token_found {
return Err(de::Error::custom(
"missing values `authorization_code` and `refresh_token` in `grant_types_supported`",
));
}
if !authorization_code_found {
return Err(de::Error::custom(
"missing value `authorization_code` in `grant_types_supported`",
));
}
if !refresh_token_found {
return Err(de::Error::custom(
"missing value `refresh_token` in `grant_types_supported`",
));
}
// Require `S256` in `code_challenge_methods_supported`.
if !code_challenge_methods_supported.contains(&CodeChallengeMethod::S256) {
return Err(de::Error::custom(
"missing value `S256` in `code_challenge_methods_supported`",
));
}
Ok(AuthorizationServerMetadata {
issuer,
authorization_endpoint,
token_endpoint,
registration_endpoint,
response_types_supported,
response_modes_supported,
grant_types_supported,
revocation_endpoint,
code_challenge_methods_supported,
#[cfg(feature = "unstable-msc4191")]
account_management_uri,
#[cfg(feature = "unstable-msc4191")]
account_management_actions_supported,
#[cfg(feature = "unstable-msc4108")]
device_authorization_endpoint,
prompt_values_supported,
})
}
}
#[derive(Deserialize)]
struct AuthorizationServerMetadataDeHelper {
issuer: Url,
authorization_endpoint: Url,
token_endpoint: Url,
registration_endpoint: Option<Url>,
response_types_supported: BTreeSet<ResponseType>,
response_modes_supported: Option<BTreeSet<ResponseMode>>,
grant_types_supported: BTreeSet<GrantType>,
revocation_endpoint: Url,
code_challenge_methods_supported: BTreeSet<CodeChallengeMethod>,
#[cfg(feature = "unstable-msc4191")]
account_management_uri: Option<Url>,
#[cfg(feature = "unstable-msc4191")]
#[serde(default)]
account_management_actions_supported: BTreeSet<AccountManagementAction>,
#[cfg(feature = "unstable-msc4108")]
device_authorization_endpoint: Option<Url>,
#[serde(default)]
prompt_values_supported: Vec<Prompt>,
}
#[cfg(test)]
mod tests {
use as_variant::as_variant;
use serde_json::{Value as JsonValue, from_value as from_json_value, value::Map as JsonMap};
use url::Url;
#[cfg(feature = "unstable-msc4191")]
use crate::client::discovery::auth_metadata::AccountManagementAction;
use crate::client::discovery::auth_metadata::{
AuthorizationServerMetadata, CodeChallengeMethod, GrantType, ResponseMode, ResponseType,
tests::authorization_server_metadata_json,
};
/// A valid `AuthorizationServerMetadata` with all fields and values, as a JSON object.
fn authorization_server_metadata_object() -> JsonMap<String, JsonValue> {
as_variant!(authorization_server_metadata_json(), JsonValue::Object).unwrap()
}
/// Get a mutable reference to the array value with the given key in the given object.
///
/// Panics if the property doesn't exist or is not an array.
fn get_mut_array<'a>(
object: &'a mut JsonMap<String, JsonValue>,
key: &str,
) -> &'a mut Vec<JsonValue> {
object.get_mut(key).unwrap().as_array_mut().unwrap()
}
#[test]
fn metadata_all_fields() {
let metadata_object = authorization_server_metadata_object();
let metadata =
from_json_value::<AuthorizationServerMetadata>(metadata_object.into()).unwrap();
assert_eq!(metadata.issuer.as_str(), "https://server.local/");
assert_eq!(
metadata.authorization_endpoint.as_str(),
"https://server.local/authorize"
);
assert_eq!(
metadata.token_endpoint.as_str(),
"https://server.local/token"
);
assert_eq!(
metadata.registration_endpoint.as_ref().map(Url::as_str),
Some("https://server.local/register")
);
assert_eq!(metadata.response_types_supported.len(), 1);
assert!(
metadata
.response_types_supported
.contains(&ResponseType::Code)
);
assert_eq!(metadata.response_modes_supported.len(), 2);
assert!(
metadata
.response_modes_supported
.contains(&ResponseMode::Query)
);
assert!(
metadata
.response_modes_supported
.contains(&ResponseMode::Fragment)
);
assert_eq!(metadata.grant_types_supported.len(), 2);
assert!(
metadata
.grant_types_supported
.contains(&GrantType::AuthorizationCode)
);
assert!(
metadata
.grant_types_supported
.contains(&GrantType::RefreshToken)
);
assert_eq!(
metadata.revocation_endpoint.as_str(),
"https://server.local/revoke"
);
assert_eq!(metadata.code_challenge_methods_supported.len(), 1);
assert!(
metadata
.code_challenge_methods_supported
.contains(&CodeChallengeMethod::S256)
);
#[cfg(feature = "unstable-msc4191")]
{
assert_eq!(
metadata.account_management_uri.as_ref().map(Url::as_str),
Some("https://server.local/account")
);
assert_eq!(metadata.account_management_actions_supported.len(), 6);
assert!(
metadata
.account_management_actions_supported
.contains(&AccountManagementAction::Profile)
);
assert!(
metadata
.account_management_actions_supported
.contains(&AccountManagementAction::SessionsList)
);
assert!(
metadata
.account_management_actions_supported
.contains(&AccountManagementAction::SessionView)
);
assert!(
metadata
.account_management_actions_supported
.contains(&AccountManagementAction::SessionEnd)
);
assert!(
metadata
.account_management_actions_supported
.contains(&AccountManagementAction::AccountDeactivate)
);
assert!(
metadata
.account_management_actions_supported
.contains(&AccountManagementAction::CrossSigningReset)
);
}
#[cfg(feature = "unstable-msc4108")]
assert_eq!(
metadata
.device_authorization_endpoint
.as_ref()
.map(Url::as_str),
Some("https://server.local/device")
);
}
#[test]
fn metadata_no_optional_fields() {
let mut metadata_object = authorization_server_metadata_object();
assert!(metadata_object.remove("registration_endpoint").is_some());
assert!(metadata_object.remove("response_modes_supported").is_some());
assert!(metadata_object.remove("account_management_uri").is_some());
assert!(
metadata_object
.remove("account_management_actions_supported")
.is_some()
);
assert!(
metadata_object
.remove("device_authorization_endpoint")
.is_some()
);
let metadata =
from_json_value::<AuthorizationServerMetadata>(metadata_object.into()).unwrap();
assert_eq!(metadata.issuer.as_str(), "https://server.local/");
assert_eq!(
metadata.authorization_endpoint.as_str(),
"https://server.local/authorize"
);
assert_eq!(
metadata.token_endpoint.as_str(),
"https://server.local/token"
);
assert_eq!(metadata.registration_endpoint, None);
assert_eq!(metadata.response_types_supported.len(), 1);
assert!(
metadata
.response_types_supported
.contains(&ResponseType::Code)
);
assert_eq!(metadata.response_modes_supported.len(), 2);
assert!(
metadata
.response_modes_supported
.contains(&ResponseMode::Query)
);
assert!(
metadata
.response_modes_supported
.contains(&ResponseMode::Fragment)
);
assert_eq!(metadata.grant_types_supported.len(), 2);
assert!(
metadata
.grant_types_supported
.contains(&GrantType::AuthorizationCode)
);
assert!(
metadata
.grant_types_supported
.contains(&GrantType::RefreshToken)
);
assert_eq!(
metadata.revocation_endpoint.as_str(),
"https://server.local/revoke"
);
assert_eq!(metadata.code_challenge_methods_supported.len(), 1);
assert!(
metadata
.code_challenge_methods_supported
.contains(&CodeChallengeMethod::S256)
);
#[cfg(feature = "unstable-msc4191")]
{
assert_eq!(metadata.account_management_uri, None);
assert_eq!(metadata.account_management_actions_supported.len(), 0);
}
#[cfg(feature = "unstable-msc4108")]
assert_eq!(metadata.device_authorization_endpoint, None);
}
#[test]
fn metadata_additional_values() {
let mut metadata_object = authorization_server_metadata_object();
get_mut_array(&mut metadata_object, "response_types_supported").push("custom".into());
get_mut_array(&mut metadata_object, "response_modes_supported").push("custom".into());
get_mut_array(&mut metadata_object, "grant_types_supported").push("custom".into());
get_mut_array(&mut metadata_object, "code_challenge_methods_supported")
.push("custom".into());
get_mut_array(&mut metadata_object, "account_management_actions_supported")
.push("custom".into());
let metadata =
from_json_value::<AuthorizationServerMetadata>(metadata_object.into()).unwrap();
assert_eq!(metadata.issuer.as_str(), "https://server.local/");
assert_eq!(
metadata.authorization_endpoint.as_str(),
"https://server.local/authorize"
);
assert_eq!(
metadata.token_endpoint.as_str(),
"https://server.local/token"
);
assert_eq!(
metadata.registration_endpoint.as_ref().map(Url::as_str),
Some("https://server.local/register")
);
assert_eq!(metadata.response_types_supported.len(), 2);
assert!(
metadata
.response_types_supported
.contains(&ResponseType::Code)
);
assert!(
metadata
.response_types_supported
.contains(&ResponseType::from("custom"))
);
assert_eq!(metadata.response_modes_supported.len(), 3);
assert!(
metadata
.response_modes_supported
.contains(&ResponseMode::Query)
);
assert!(
metadata
.response_modes_supported
.contains(&ResponseMode::Fragment)
);
assert!(
metadata
.response_modes_supported
.contains(&ResponseMode::from("custom"))
);
assert_eq!(metadata.grant_types_supported.len(), 3);
assert!(
metadata
.grant_types_supported
.contains(&GrantType::AuthorizationCode)
);
assert!(
metadata
.grant_types_supported
.contains(&GrantType::RefreshToken)
);
assert!(
metadata
.grant_types_supported
.contains(&GrantType::from("custom"))
);
assert_eq!(
metadata.revocation_endpoint.as_str(),
"https://server.local/revoke"
);
assert_eq!(metadata.code_challenge_methods_supported.len(), 2);
assert!(
metadata
.code_challenge_methods_supported
.contains(&CodeChallengeMethod::S256)
);
assert!(
metadata
.code_challenge_methods_supported
.contains(&CodeChallengeMethod::from("custom"))
);
#[cfg(feature = "unstable-msc4191")]
{
assert_eq!(
metadata.account_management_uri.as_ref().map(Url::as_str),
Some("https://server.local/account")
);
assert_eq!(metadata.account_management_actions_supported.len(), 7);
assert!(
metadata
.account_management_actions_supported
.contains(&AccountManagementAction::Profile)
);
assert!(
metadata
.account_management_actions_supported
.contains(&AccountManagementAction::SessionsList)
);
assert!(
metadata
.account_management_actions_supported
.contains(&AccountManagementAction::SessionView)
);
assert!(
metadata
.account_management_actions_supported
.contains(&AccountManagementAction::SessionEnd)
);
assert!(
metadata
.account_management_actions_supported
.contains(&AccountManagementAction::AccountDeactivate)
);
assert!(
metadata
.account_management_actions_supported
.contains(&AccountManagementAction::CrossSigningReset)
);
assert!(
metadata
.account_management_actions_supported
.contains(&AccountManagementAction::from("custom"))
);
}
#[cfg(feature = "unstable-msc4108")]
assert_eq!(
metadata
.device_authorization_endpoint
.as_ref()
.map(Url::as_str),
Some("https://server.local/device")
);
}
#[test]
fn metadata_missing_required_fields() {
let original_metadata_object = authorization_server_metadata_object();
let mut metadata_object = original_metadata_object.clone();
assert!(metadata_object.remove("issuer").is_some());
from_json_value::<AuthorizationServerMetadata>(metadata_object.into()).unwrap_err();
let mut metadata_object = original_metadata_object.clone();
assert!(metadata_object.remove("authorization_endpoint").is_some());
from_json_value::<AuthorizationServerMetadata>(metadata_object.into()).unwrap_err();
let mut metadata_object = original_metadata_object.clone();
assert!(metadata_object.remove("token_endpoint").is_some());
from_json_value::<AuthorizationServerMetadata>(metadata_object.into()).unwrap_err();
let mut metadata_object = original_metadata_object.clone();
assert!(metadata_object.remove("response_types_supported").is_some());
from_json_value::<AuthorizationServerMetadata>(metadata_object.into()).unwrap_err();
let mut metadata_object = original_metadata_object.clone();
assert!(metadata_object.remove("grant_types_supported").is_some());
from_json_value::<AuthorizationServerMetadata>(metadata_object.into()).unwrap_err();
let mut metadata_object = original_metadata_object.clone();
assert!(metadata_object.remove("revocation_endpoint").is_some());
from_json_value::<AuthorizationServerMetadata>(metadata_object.into()).unwrap_err();
let mut metadata_object = original_metadata_object;
assert!(
metadata_object
.remove("code_challenge_methods_supported")
.is_some()
);
from_json_value::<AuthorizationServerMetadata>(metadata_object.into()).unwrap_err();
}
#[test]
fn metadata_missing_required_values() {
let original_metadata_object = authorization_server_metadata_object();
let mut metadata_object = original_metadata_object.clone();
get_mut_array(&mut metadata_object, "response_types_supported").clear();
from_json_value::<AuthorizationServerMetadata>(metadata_object.into()).unwrap_err();
let mut metadata_object = original_metadata_object.clone();
get_mut_array(&mut metadata_object, "response_modes_supported").clear();
from_json_value::<AuthorizationServerMetadata>(metadata_object.into()).unwrap_err();
let mut metadata_object = original_metadata_object.clone();
get_mut_array(&mut metadata_object, "response_modes_supported").remove(0);
from_json_value::<AuthorizationServerMetadata>(metadata_object.into()).unwrap_err();
let mut metadata_object = original_metadata_object.clone();
get_mut_array(&mut metadata_object, "response_modes_supported").remove(1);
from_json_value::<AuthorizationServerMetadata>(metadata_object.into()).unwrap_err();
let mut metadata_object = original_metadata_object.clone();
get_mut_array(&mut metadata_object, "grant_types_supported").clear();
from_json_value::<AuthorizationServerMetadata>(metadata_object.into()).unwrap_err();
let mut metadata_object = original_metadata_object.clone();
get_mut_array(&mut metadata_object, "grant_types_supported").remove(0);
from_json_value::<AuthorizationServerMetadata>(metadata_object.into()).unwrap_err();
let mut metadata_object = original_metadata_object.clone();
get_mut_array(&mut metadata_object, "grant_types_supported").remove(1);
from_json_value::<AuthorizationServerMetadata>(metadata_object.into()).unwrap_err();
let mut metadata_object = original_metadata_object;
get_mut_array(&mut metadata_object, "code_challenge_methods_supported").clear();
from_json_value::<AuthorizationServerMetadata>(metadata_object.into()).unwrap_err();
}
}
| 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.