63个版本
0.28.1 | 2024年5月13日 |
---|---|
0.27.11 | 2023年11月27日 |
0.26.1 | 2022年5月4日 |
0.26.0 | 2022年2月19日 |
0.2.0 | 2016年12月21日 |
977 在 网络编程 中
2,021 每月下载量
用于 36 个包 (9 直接)
1MB
24K SLoC
ruma-events
Matrix规范中事件的可序列化类型,可以由客户端和服务器代码共享。
lib.rs
:
(De)序列化Matrix规范中事件的可序列化类型。这些类型由其他Ruma包使用。
Matrix中所有交换的数据都表示为事件。不同的事件类型代表不同的操作,如加入房间或发送消息。事件以简单的JSON结构存储和传输。虽然任何人都可以为自身目的创建新的事件类型,但Matrix规范定义了多个被视为协议核心的事件类型。本模块包含规范中定义的所有事件类型的Rust类型,以及用于扩展事件系统以支持自定义事件类型的工具。
核心事件类型
本模块包含Matrix规范中所有事件类型的Rust类型。为了更好地组织包,这些类型位于单独的模块中,其层次结构与事件类型的反向域名表示法相匹配。例如,m.room.message
事件位于 ruma::events::room::message::RoomMessageEvent
。每个类型的模块还包含该事件类型的 content
字段的Rust类型,以及事件的其他字段所需的任何其他支持类型。
扩展Ruma以支持自定义事件
在我们的示例中,我们将从一个简单的自定义状态事件开始。 ruma_event
指定状态事件的 type
和其 kind
。
use ruma_events::macros::EventContent;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
#[ruma_event(type = "org.example.event", kind = State, state_key_type = String)]
pub struct ExampleContent {
field: String,
}
这可以与事件结构一起使用,例如将其传递给ruma::api::client::state::send_state_event
的Request
。
作为一个更高级的例子,我们创建了一个反应消息事件。为此事件,我们将使用一个OriginalSyncMessageLikeEvent
结构,但任何OriginalMessageLikeEvent
结构都适用。
use ruma_common::OwnedEventId;
use ruma_events::{macros::EventContent, OriginalSyncMessageLikeEvent};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "rel_type")]
pub enum RelatesTo {
#[serde(rename = "m.annotation")]
Annotation {
/// The event this reaction relates to.
event_id: OwnedEventId,
/// The displayable content of the reaction.
key: String,
},
/// Since this event is not fully specified in the Matrix spec
/// it may change or types may be added, we are ready!
#[serde(rename = "m.whatever")]
Whatever,
}
/// The payload for our reaction event.
#[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
#[ruma_event(type = "m.reaction", kind = MessageLike)]
pub struct ReactionEventContent {
#[serde(rename = "m.relates_to")]
pub relates_to: RelatesTo,
}
let json = serde_json::json!({
"content": {
"m.relates_to": {
"event_id": "$xxxx-xxxx",
"key": "👍",
"rel_type": "m.annotation"
}
},
"event_id": "$xxxx-xxxx",
"origin_server_ts": 1,
"sender": "@someone:example.org",
"type": "m.reaction",
"unsigned": {
"age": 85
}
});
// The downside of this event is we cannot use it with event enums,
// but could be deserialized from a `Raw<_>` that has failed to deserialize.
assert!(matches!(
serde_json::from_value::<OriginalSyncMessageLikeEvent<ReactionEventContent>>(json),
Ok(OriginalSyncMessageLikeEvent {
content: ReactionEventContent {
relates_to: RelatesTo::Annotation { key, .. },
},
..
}) if key == "👍"
));
依赖项
~8–20MB
~300K SLoC