events: Add support for the m.reaction event type

This commit is contained in:
Damir Jelić 2020-11-10 13:26:30 +01:00
parent cf7d4b40e1
commit 71a8d9d6ce
3 changed files with 69 additions and 0 deletions

View File

@ -36,6 +36,7 @@ event_enum! {
"m.call.invite",
"m.call.hangup",
"m.call.candidates",
"m.reaction",
"m.room.encrypted",
"m.room.message",
"m.room.message.feedback",

View File

@ -170,6 +170,7 @@ pub mod pdu;
pub mod policy;
pub mod presence;
pub mod push_rules;
pub mod reaction;
pub mod receipt;
pub mod room;
pub mod room_key;

View File

@ -0,0 +1,67 @@
//! Types for the *m.reaction* event.
use std::convert::TryFrom;
use crate::{
room::relationships::{Annotation, RelatesToJsonRepr, RelationJsonRepr},
MessageEvent,
};
use ruma_events_macros::MessageEventContent;
use ruma_identifiers::EventId;
use serde::{Deserialize, Serialize};
/// A reaction to another event.
pub type ReactionEvent = MessageEvent<ReactionEventContent>;
/// The payload for a `ReactionEvent`.
#[derive(Clone, Debug, Deserialize, Serialize, MessageEventContent)]
#[ruma_event(type = "m.reaction")]
pub struct ReactionEventContent {
/// Information about the related event.
#[serde(rename = "m.relates_to")]
pub relation: Relation,
}
/// The relation that contains info which event the reaction is applying to.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(try_from = "RelatesToJsonRepr", into = "RelatesToJsonRepr")]
pub struct Relation {
/// The event that is being reacted to.
pub event_id: EventId,
/// A string that holds the emoji reaction.
pub emoji: String,
}
impl From<Relation> for RelatesToJsonRepr {
fn from(relation: Relation) -> Self {
RelatesToJsonRepr::Relation(RelationJsonRepr::Annotation(Annotation {
event_id: relation.event_id,
key: relation.emoji,
}))
}
}
impl TryFrom<RelatesToJsonRepr> for Relation {
type Error = &'static str;
fn try_from(value: RelatesToJsonRepr) -> Result<Self, Self::Error> {
if let RelatesToJsonRepr::Relation(RelationJsonRepr::Annotation(a)) = value {
Ok(Relation { event_id: a.event_id, emoji: a.key })
} else {
Err("Expected a relation with a rel_type of `annotation`")
}
}
}
impl ReactionEventContent {
/// Create a new reaction.
///
/// # Arguments
///
/// * `event_id` - The id of the event we are reacting to.
/// * `emoji` - The emoji that indicates the reaction that is being applied.
pub fn new(event_id: EventId, emoji: String) -> Self {
ReactionEventContent { relation: Relation { event_id, emoji } }
}
}