Remove FullOrRedacted use ruma::AnyPossiblyRedacted event enum

master
Devin R 2020-07-17 21:06:51 -04:00
parent 807435c043
commit e4f94cbfec
6 changed files with 62 additions and 122 deletions

View File

@ -14,16 +14,16 @@ repos:
types: [file, rust] types: [file, rust]
entry: cargo fmt -- --check entry: cargo fmt -- --check
# - id: clippy - id: clippy
# name: clippy name: clippy
# language: system language: system
# types: [file, rust] types: [file, rust]
# entry: cargo clippy --all-targets --all entry: cargo clippy --all-targets --all
# pass_filenames: false pass_filenames: false
# - id: test - id: test
# name: test name: test
# language: system language: system
# files: '\.rs$' files: '\.rs$'
# entry: cargo test --lib entry: cargo test --lib
# pass_filenames: false pass_filenames: false

View File

@ -41,7 +41,7 @@ pub use matrix_sdk_base::Error as BaseError;
pub use matrix_sdk_base::JsonStore; pub use matrix_sdk_base::JsonStore;
pub use matrix_sdk_base::{CustomOrRawEvent, EventEmitter, Room, Session, SyncRoom}; pub use matrix_sdk_base::{CustomOrRawEvent, EventEmitter, Room, Session, SyncRoom};
#[cfg(feature = "messages")] #[cfg(feature = "messages")]
pub use matrix_sdk_base::{FullOrRedactedEvent, MessageQueue, MessageWrapper}; pub use matrix_sdk_base::{MessageQueue, MessageWrapper, PossiblyRedactedExt};
pub use matrix_sdk_base::{RoomState, StateStore}; pub use matrix_sdk_base::{RoomState, StateStore};
pub use matrix_sdk_common::*; pub use matrix_sdk_common::*;
pub use reqwest::header::InvalidHeaderValue; pub use reqwest::header::InvalidHeaderValue;

View File

@ -55,7 +55,7 @@ pub use matrix_sdk_crypto::{Device, TrustState};
#[cfg(feature = "messages")] #[cfg(feature = "messages")]
#[cfg_attr(docsrs, doc(cfg(feature = "messages")))] #[cfg_attr(docsrs, doc(cfg(feature = "messages")))]
pub use models::{FullOrRedactedEvent, MessageQueue, MessageWrapper}; pub use models::{MessageQueue, MessageWrapper, PossiblyRedactedExt};
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
pub use state::JsonStore; pub use state::JsonStore;

View File

@ -11,34 +11,34 @@ use std::{
}; };
use matrix_sdk_common::identifiers::EventId; use matrix_sdk_common::identifiers::EventId;
use serde::{de, ser, Deserialize, Serialize}; use serde::{de, ser, Serialize};
use crate::events::{AnyRedactedSyncMessageEvent, AnySyncMessageEvent}; use crate::events::AnyPossiblyRedactedSyncMessageEvent;
/// Represents either a redacted event or a non-redacted event. /// Exposes some of the field access methods found in the event held by
/// `AnyPossiblyRedacted*` enums.
/// ///
/// Note: ruma may create types that solve this. /// This is just an extension trait to aid the ease of use of certain event enums.
#[derive(Clone, Debug, Deserialize, Serialize)] pub trait PossiblyRedactedExt {
pub enum FullOrRedactedEvent { /// Access the redacted or full events `event_id` field.
/// A non-redacted event. fn event_id(&self) -> &EventId;
Full(AnySyncMessageEvent), /// Access the redacted or full events `origin_server_ts` field.
/// An event that has been redacted. fn origin_server_ts(&self) -> &SystemTime;
Redacted(AnyRedactedSyncMessageEvent),
} }
impl FullOrRedactedEvent { impl PossiblyRedactedExt for AnyPossiblyRedactedSyncMessageEvent {
/// Access the underlying events `event_id`. /// Access the underlying events `event_id`.
pub fn event_id(&self) -> &EventId { fn event_id(&self) -> &EventId {
match self { match self {
Self::Full(e) => e.event_id(), Self::Regular(e) => e.event_id(),
Self::Redacted(e) => e.event_id(), Self::Redacted(e) => e.event_id(),
} }
} }
/// Access the underlying events `origin_server_ts`. /// Access the underlying events `origin_server_ts`.
pub fn origin_server_ts(&self) -> &SystemTime { fn origin_server_ts(&self) -> &SystemTime {
match self { match self {
Self::Full(e) => e.origin_server_ts(), Self::Regular(e) => e.origin_server_ts(),
Self::Redacted(e) => e.origin_server_ts(), Self::Redacted(e) => e.origin_server_ts(),
} }
} }
@ -46,7 +46,7 @@ impl FullOrRedactedEvent {
const MESSAGE_QUEUE_CAP: usize = 35; const MESSAGE_QUEUE_CAP: usize = 35;
pub type SyncMessageEvent = FullOrRedactedEvent; pub type SyncMessageEvent = AnyPossiblyRedactedSyncMessageEvent;
/// A queue that holds the 35 most recent messages received from the server. /// A queue that holds the 35 most recent messages received from the server.
#[derive(Clone, Debug, Default)] #[derive(Clone, Debug, Default)]
@ -206,17 +206,18 @@ pub(crate) mod ser_deser {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::*;
use std::collections::HashMap; use std::collections::HashMap;
use std::convert::TryFrom; use std::convert::TryFrom;
use matrix_sdk_common::{
events::{AnyPossiblyRedactedSyncMessageEvent, AnySyncMessageEvent},
identifiers::{RoomId, UserId},
};
use matrix_sdk_test::test_json;
#[cfg(target_arch = "wasm32")] #[cfg(target_arch = "wasm32")]
use wasm_bindgen_test::*; use wasm_bindgen_test::*;
use matrix_sdk_test::test_json; use super::*;
use crate::identifiers::{RoomId, UserId};
use crate::Room; use crate::Room;
#[test] #[test]
@ -227,7 +228,7 @@ mod test {
let mut room = Room::new(&id, &user); let mut room = Room::new(&id, &user);
let json: &serde_json::Value = &test_json::MESSAGE_TEXT; let json: &serde_json::Value = &test_json::MESSAGE_TEXT;
let msg = FullOrRedactedEvent::Full( let msg = AnyPossiblyRedactedSyncMessageEvent::Regular(
serde_json::from_value::<AnySyncMessageEvent>(json.clone()).unwrap(), serde_json::from_value::<AnySyncMessageEvent>(json.clone()).unwrap(),
); );
@ -274,7 +275,7 @@ mod test {
let mut room = Room::new(&id, &user); let mut room = Room::new(&id, &user);
let json: &serde_json::Value = &test_json::MESSAGE_TEXT; let json: &serde_json::Value = &test_json::MESSAGE_TEXT;
let msg = FullOrRedactedEvent::Full( let msg = AnyPossiblyRedactedSyncMessageEvent::Regular(
serde_json::from_value::<AnySyncMessageEvent>(json.clone()).unwrap(), serde_json::from_value::<AnySyncMessageEvent>(json.clone()).unwrap(),
); );

View File

@ -6,6 +6,6 @@ mod room_member;
#[cfg(feature = "messages")] #[cfg(feature = "messages")]
#[cfg_attr(docsrs, doc(cfg(feature = "messages")))] #[cfg_attr(docsrs, doc(cfg(feature = "messages")))]
pub use message::{FullOrRedactedEvent, MessageQueue, MessageWrapper}; pub use message::{MessageQueue, MessageWrapper, PossiblyRedactedExt};
pub use room::{Room, RoomName}; pub use room::{Room, RoomName};
pub use room_member::RoomMember; pub use room_member::RoomMember;

View File

@ -22,7 +22,7 @@ use serde::{Deserialize, Serialize};
use tracing::{debug, error, trace}; use tracing::{debug, error, trace};
#[cfg(feature = "messages")] #[cfg(feature = "messages")]
use super::message::{FullOrRedactedEvent, MessageQueue}; use super::message::MessageQueue;
use super::RoomMember; use super::RoomMember;
use crate::api::r0::sync::sync_events::{RoomSummary, UnreadNotificationsCount}; use crate::api::r0::sync::sync_events::{RoomSummary, UnreadNotificationsCount};
use crate::events::{ use crate::events::{
@ -42,30 +42,13 @@ use crate::events::{
#[cfg(feature = "messages")] #[cfg(feature = "messages")]
use crate::events::{ use crate::events::{
room::redaction::{RedactionEvent, SyncRedactionEvent}, room::redaction::SyncRedactionEvent, AnyPossiblyRedactedSyncMessageEvent, AnySyncMessageEvent,
AnySyncMessageEvent,
}; };
use crate::identifiers::{RoomAliasId, RoomId, UserId}; use crate::identifiers::{RoomAliasId, RoomId, UserId};
use crate::js_int::{int, uint, Int, UInt}; use crate::js_int::{int, uint, Int, UInt};
#[cfg(feature = "messages")]
fn redaction_event_from_redaction_stub(
event: SyncRedactionEvent,
room_id: RoomId,
) -> RedactionEvent {
RedactionEvent {
content: event.content,
redacts: event.redacts,
event_id: event.event_id,
unsigned: event.unsigned,
sender: event.sender,
origin_server_ts: event.origin_server_ts,
room_id,
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
/// `RoomName` allows the calculation of a text room name. /// `RoomName` allows the calculation of a text room name.
pub struct RoomName { pub struct RoomName {
@ -674,7 +657,8 @@ impl Room {
#[cfg(feature = "messages")] #[cfg(feature = "messages")]
#[cfg_attr(docsrs, doc(cfg(feature = "messages")))] #[cfg_attr(docsrs, doc(cfg(feature = "messages")))]
pub fn handle_message(&mut self, event: &AnySyncMessageEvent) -> bool { pub fn handle_message(&mut self, event: &AnySyncMessageEvent) -> bool {
self.messages.push(FullOrRedactedEvent::Full(event.clone())) self.messages
.push(AnyPossiblyRedactedSyncMessageEvent::Regular(event.clone()))
} }
/// Handle a room.redaction event and update the `MessageQueue`. /// Handle a room.redaction event and update the `MessageQueue`.
@ -686,68 +670,23 @@ impl Room {
#[cfg(feature = "messages")] #[cfg(feature = "messages")]
#[cfg_attr(docsrs, doc(cfg(feature = "messages")))] #[cfg_attr(docsrs, doc(cfg(feature = "messages")))]
pub fn handle_redaction(&mut self, redacted_event: &SyncRedactionEvent) -> bool { pub fn handle_redaction(&mut self, redacted_event: &SyncRedactionEvent) -> bool {
use matrix_sdk_common::events::{ use crate::identifiers::RoomVersionId;
AnyRedactedSyncMessageEvent, EventJson, RedactedSyncMessageEvent, SyncMessageEvent, use crate::models::message::PossiblyRedactedExt;
};
if let Some(msg) = self if let Some(msg) = self
.messages .messages
.iter_mut() .iter_mut()
.find(|msg| &redacted_event.redacts == msg.event_id()) .find(|msg| &redacted_event.redacts == msg.event_id())
{ {
match msg.deref_mut() { match msg.deref_mut() {
FullOrRedactedEvent::Full(event) => match event { AnyPossiblyRedactedSyncMessageEvent::Regular(event) => {
AnySyncMessageEvent::RoomMessage(event) => { msg.0 = AnyPossiblyRedactedSyncMessageEvent::Redacted(
let SyncMessageEvent { event
content, .clone()
event_id, .redact(redacted_event.clone(), RoomVersionId::version_6()),
sender, );
origin_server_ts, }
mut unsigned, AnyPossiblyRedactedSyncMessageEvent::Redacted(_) => return false,
} = event.clone();
unsigned.redacted_because =
Some(EventJson::from(redaction_event_from_redaction_stub(
redacted_event.clone(),
self.room_id.clone(),
)));
let redacted = content.redact();
msg.0 = FullOrRedactedEvent::Redacted(
AnyRedactedSyncMessageEvent::RoomMessage(RedactedSyncMessageEvent {
content: redacted,
event_id,
origin_server_ts,
sender,
unsigned,
}),
)
}
AnySyncMessageEvent::Sticker(event) => {
let SyncMessageEvent {
content,
event_id,
sender,
origin_server_ts,
mut unsigned,
} = event.clone();
unsigned.redacted_because =
Some(EventJson::from(redaction_event_from_redaction_stub(
redacted_event.clone(),
self.room_id.clone(),
)));
let redacted = content.redact();
msg.0 = FullOrRedactedEvent::Redacted(AnyRedactedSyncMessageEvent::Sticker(
RedactedSyncMessageEvent {
content: redacted,
event_id,
origin_server_ts,
sender,
unsigned,
},
))
}
// TODO handle the rest of the message events
_ => {}
},
FullOrRedactedEvent::Redacted(_) => return false,
} }
true true
} else { } else {
@ -1141,7 +1080,7 @@ impl Describe for MembershipChange {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::*; use super::*;
use crate::events::{room::encryption::EncryptionEventContent, EventJson, UnsignedData}; use crate::events::{room::encryption::EncryptionEventContent, EventJson, Unsigned};
use crate::identifiers::{EventId, UserId}; use crate::identifiers::{EventId, UserId};
use crate::{BaseClient, Session}; use crate::{BaseClient, Session};
use matrix_sdk_test::{async_test, sync_response, EventBuilder, EventsJson, SyncResponseFile}; use matrix_sdk_test::{async_test, sync_response, EventBuilder, EventsJson, SyncResponseFile};
@ -1714,7 +1653,7 @@ mod test {
for room in client.joined_rooms().read().await.values() { for room in client.joined_rooms().read().await.values() {
let queue = &room.read().await.messages; let queue = &room.read().await.messages;
if let crate::models::message::FullOrRedactedEvent::Redacted( if let crate::events::AnyPossiblyRedactedSyncMessageEvent::Redacted(
crate::events::AnyRedactedSyncMessageEvent::RoomMessage(event), crate::events::AnyRedactedSyncMessageEvent::RoomMessage(event),
) = &queue.msgs[0].deref() ) = &queue.msgs[0].deref()
{ {
@ -1746,17 +1685,17 @@ mod test {
client.restore_login(session).await.unwrap(); client.restore_login(session).await.unwrap();
client.receive_sync_response(&mut response).await.unwrap(); client.receive_sync_response(&mut response).await.unwrap();
let mut content = EncryptionEventContent::new(Algorithm::MegolmV1AesSha2);
content.rotation_period_ms = Some(100_000u32.into());
content.rotation_period_msgs = Some(100u32.into());
let event = SyncStateEvent { let event = SyncStateEvent {
event_id: EventId::try_from("$h29iv0s8:example.com").unwrap(), event_id: EventId::try_from("$h29iv0s8:example.com").unwrap(),
origin_server_ts: SystemTime::now(), origin_server_ts: SystemTime::now(),
sender: user_id, sender: user_id,
state_key: "".into(), state_key: "".into(),
unsigned: UnsignedData::default(), unsigned: Unsigned::default(),
content: EncryptionEventContent { content,
algorithm: Algorithm::MegolmV1AesSha2,
rotation_period_ms: Some(100_000u32.into()),
rotation_period_msgs: Some(100u32.into()),
},
prev_content: None, prev_content: None,
}; };