use std::collections::BTreeSet;
use js_int::uint;
use ruma_common::{
MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId, UserId,
};
use ruma_events::TimelineEventType;
use serde::{Deserialize, Serialize};
use serde_json::value::{RawValue as RawJsonValue, to_raw_value as to_raw_json_value};
use crate::Event;
#[derive(Clone, Debug, Deserialize)]
pub struct Pdu {
pub event_id: OwnedEventId,
pub room_id: Option<OwnedRoomId>,
pub sender: OwnedUserId,
pub origin_server_ts: MilliSecondsSinceUnixEpoch,
#[serde(rename = "type")]
pub event_type: TimelineEventType,
pub state_key: Option<String>,
pub content: Box<RawJsonValue>,
pub prev_events: BTreeSet<OwnedEventId>,
pub auth_events: BTreeSet<OwnedEventId>,
pub redacts: Option<OwnedEventId>,
pub rejected: bool,
}
impl Pdu {
pub fn with_minimal_fields<T>(
event_id: OwnedEventId,
sender: OwnedUserId,
event_type: TimelineEventType,
content: T,
) -> Self
where
T: Serialize,
{
let content =
to_raw_json_value(&content).expect("PDU content should serialize successfully");
Self {
event_id,
room_id: None,
sender,
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(0)),
event_type,
state_key: None,
content,
prev_events: BTreeSet::new(),
auth_events: BTreeSet::new(),
redacts: None,
rejected: false,
}
}
pub fn with_minimal_state_fields<T>(
event_id: OwnedEventId,
sender: OwnedUserId,
event_type: TimelineEventType,
state_key: String,
content: T,
) -> Self
where
T: Serialize,
{
let mut pdu = Self::with_minimal_fields(event_id, sender, event_type, content);
pdu.state_key = Some(state_key);
pdu
}
pub fn set_content<T>(&mut self, content: T)
where
T: Serialize,
{
self.content =
to_raw_json_value(&content).expect("PDU content should serialize successfully");
}
}
impl Event for Pdu {
type Id = OwnedEventId;
fn event_id(&self) -> &Self::Id {
&self.event_id
}
fn room_id(&self) -> Option<&RoomId> {
self.room_id.as_deref()
}
fn sender(&self) -> &UserId {
&self.sender
}
fn event_type(&self) -> &TimelineEventType {
&self.event_type
}
fn content(&self) -> &RawJsonValue {
&self.content
}
fn origin_server_ts(&self) -> MilliSecondsSinceUnixEpoch {
self.origin_server_ts
}
fn state_key(&self) -> Option<&str> {
self.state_key.as_deref()
}
fn prev_events(&self) -> Box<dyn DoubleEndedIterator<Item = &Self::Id> + '_> {
Box::new(self.prev_events.iter())
}
fn auth_events(&self) -> Box<dyn DoubleEndedIterator<Item = &Self::Id> + '_> {
Box::new(self.auth_events.iter())
}
fn redacts(&self) -> Option<&Self::Id> {
self.redacts.as_ref()
}
fn rejected(&self) -> bool {
self.rejected
}
}