sdk_base: Remove room_id as argument from all Room methods

Remove room_id paramater from some client methods. Make CreationContent
two methods of RoomBuilder. Add docs for MessageWrapper.
master
Devin R 2020-07-03 15:29:10 -04:00
parent 2338d3e8fd
commit dcc3d6e755
7 changed files with 57 additions and 57 deletions

View File

@ -773,7 +773,7 @@ impl Client {
/// ///
/// # let homeserver = Url::parse("http://example.com").unwrap(); /// # let homeserver = Url::parse("http://example.com").unwrap();
/// let mut builder = RoomBuilder::default(); /// let mut builder = RoomBuilder::default();
/// builder.creation_content(false, None) /// builder.federate(false)
/// .initial_state(vec![]) /// .initial_state(vec![])
/// .visibility(Visibility::Public) /// .visibility(Visibility::Public)
/// .name("name") /// .name("name")

View File

@ -32,7 +32,7 @@ use matrix_sdk_common::{
/// # let mut rt = tokio::runtime::Runtime::new().unwrap(); /// # let mut rt = tokio::runtime::Runtime::new().unwrap();
/// # rt.block_on(async { /// # rt.block_on(async {
/// let mut builder = RoomBuilder::default(); /// let mut builder = RoomBuilder::default();
/// builder.creation_content(false, None) /// builder.federate(false)
/// .initial_state(vec![]) /// .initial_state(vec![])
/// .visibility(Visibility::Public) /// .visibility(Visibility::Public)
/// .name("name") /// .name("name")
@ -43,7 +43,8 @@ use matrix_sdk_common::{
/// ``` /// ```
#[derive(Clone, Debug, Default)] #[derive(Clone, Debug, Default)]
pub struct RoomBuilder { pub struct RoomBuilder {
creation_content: Option<CreationContent>, previous_room: Option<PreviousRoom>,
federate: bool,
initial_state: Vec<InitialStateEvent>, initial_state: Vec<InitialStateEvent>,
invite: Vec<UserId>, invite: Vec<UserId>,
invite_3pid: Vec<Invite3pid>, invite_3pid: Vec<Invite3pid>,
@ -60,21 +61,27 @@ pub struct RoomBuilder {
impl RoomBuilder { impl RoomBuilder {
/// Returns an empty `RoomBuilder` for creating rooms. /// Returns an empty `RoomBuilder` for creating rooms.
pub fn new() -> Self { pub fn new() -> Self {
Self::default() Self {
// we can't send false as a default as it will overwrite the true default.
federate: true,
..Default::default()
}
} }
/// Set the `CreationContent`. /// A reference to the room this room replaces, if the previous room was upgraded.
/// ///
/// Weather users on other servers can join this room. /// Note: this is used to create the `CreationContent`.
pub fn creation_content( pub fn previous_room(&mut self, previous_room: PreviousRoom) -> &mut Self {
&mut self, self.previous_room = Some(previous_room);
federate: bool, self
predecessor: Option<PreviousRoom>, }
) -> &mut Self {
self.creation_content = Some(CreationContent { /// Whether users on other servers can join this room.
federate, ///
predecessor, /// Defaults to `true` if key does not exist.
}); /// Note: this is used to create the `CreationContent`.
pub fn federate(&mut self, federate: bool) -> &mut Self {
self.federate = federate;
self self
} }
@ -156,8 +163,12 @@ impl RoomBuilder {
impl Into<create_room::Request> for RoomBuilder { impl Into<create_room::Request> for RoomBuilder {
fn into(self) -> create_room::Request { fn into(self) -> create_room::Request {
let creation_content = Some(CreationContent {
federate: self.federate,
predecessor: self.previous_room,
});
create_room::Request { create_room::Request {
creation_content: self.creation_content, creation_content,
initial_state: self.initial_state, initial_state: self.initial_state,
invite: self.invite, invite: self.invite,
invite_3pid: self.invite_3pid, invite_3pid: self.invite_3pid,
@ -270,6 +281,7 @@ impl Into<get_message_events::Request> for MessagesRequestBuilder {
from: self.from, from: self.from,
to: self.to, to: self.to,
dir: self.direction.unwrap_or(Direction::Backward), dir: self.direction.unwrap_or(Direction::Backward),
// Will our default overwrite the normal default
limit: self.limit.map(UInt::from).unwrap_or_default(), limit: self.limit.map(UInt::from).unwrap_or_default(),
filter: self.filter, filter: self.filter,
} }
@ -509,7 +521,7 @@ mod test {
let mut builder = RoomBuilder::new(); let mut builder = RoomBuilder::new();
builder builder
.creation_content(false, None) .federate(false)
.initial_state(vec![]) .initial_state(vec![])
.visibility(Visibility::Public) .visibility(Visibility::Public)
.name("room_name") .name("room_name")

View File

@ -743,7 +743,7 @@ impl BaseClient {
let mut room = room_lock.write().await; let mut room = room_lock.write().await;
if let AnyRoomEventStub::State(AnyStateEventStub::RoomMember(mem_event)) = &mut e { if let AnyRoomEventStub::State(AnyStateEventStub::RoomMember(mem_event)) = &mut e {
let changed = room.handle_membership(mem_event, room_id); let changed = room.handle_membership(mem_event);
// The memberlist of the room changed, invalidate the group session // The memberlist of the room changed, invalidate the group session
// of the room. // of the room.
@ -754,7 +754,7 @@ impl BaseClient {
Ok(changed) Ok(changed)
} else { } else {
Ok(room.receive_timeline_event(&e, room_id)) Ok(room.receive_timeline_event(&e))
} }
} }
_ => Ok(false), _ => Ok(false),
@ -780,7 +780,7 @@ impl BaseClient {
let mut room = room_lock.write().await; let mut room = room_lock.write().await;
if let AnyStateEventStub::RoomMember(e) = event { if let AnyStateEventStub::RoomMember(e) = event {
let changed = room.handle_membership(e, room_id); let changed = room.handle_membership(e);
// The memberlist of the room changed, invalidate the group session // The memberlist of the room changed, invalidate the group session
// of the room. // of the room.
@ -791,7 +791,7 @@ impl BaseClient {
Ok(changed) Ok(changed)
} else { } else {
Ok(room.receive_state_event(event, room_id)) Ok(room.receive_state_event(event))
} }
} }
@ -834,7 +834,7 @@ impl BaseClient {
Ok(e) => { Ok(e) => {
let room_lock = self.get_or_create_left_room(room_id).await?; let room_lock = self.get_or_create_left_room(room_id).await?;
let mut room = room_lock.write().await; let mut room = room_lock.write().await;
Ok(room.receive_timeline_event(&e, room_id)) Ok(room.receive_timeline_event(&e))
} }
_ => Ok(false), _ => Ok(false),
} }
@ -857,7 +857,7 @@ impl BaseClient {
) -> Result<bool> { ) -> Result<bool> {
let room_lock = self.get_or_create_left_room(room_id).await?; let room_lock = self.get_or_create_left_room(room_id).await?;
let mut room = room_lock.write().await; let mut room = room_lock.write().await;
Ok(room.receive_state_event(event, room_id)) Ok(room.receive_state_event(event))
} }
/// Receive a presence event from a sync response and updates the client state. /// Receive a presence event from a sync response and updates the client state.
@ -906,11 +906,7 @@ impl BaseClient {
/// * `room_id` - The unique id of the room the event belongs to. /// * `room_id` - The unique id of the room the event belongs to.
/// ///
/// * `event` - The presence event for a specified room member. /// * `event` - The presence event for a specified room member.
pub async fn receive_ephemeral_event( pub async fn receive_ephemeral_event(&self, event: &AnyEphemeralRoomEventStub) -> bool {
&self,
_room_id: &RoomId,
event: &AnyEphemeralRoomEventStub,
) -> bool {
match &event { match &event {
AnyEphemeralRoomEventStub::FullyRead(_) => {} AnyEphemeralRoomEventStub::FullyRead(_) => {}
AnyEphemeralRoomEventStub::Receipt(_) => {} AnyEphemeralRoomEventStub::Receipt(_) => {}
@ -1093,7 +1089,7 @@ impl BaseClient {
if let Ok(e) = ephemeral.deserialize() { if let Ok(e) = ephemeral.deserialize() {
// FIXME: receive_* and emit_* methods shouldn't be called in parallel. We // FIXME: receive_* and emit_* methods shouldn't be called in parallel. We
// should only pass events to receive_* methods and then let *them* emit. // should only pass events to receive_* methods and then let *them* emit.
if self.receive_ephemeral_event(&room_id, &e).await { if self.receive_ephemeral_event(&e).await {
updated = true; updated = true;
} }

View File

@ -13,12 +13,17 @@ use serde::{de, ser, Serialize};
const MESSAGE_QUEUE_CAP: usize = 35; const MESSAGE_QUEUE_CAP: usize = 35;
/// A queue that holds the 10 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)]
pub struct MessageQueue { pub struct MessageQueue {
msgs: Vec<MessageWrapper>, msgs: Vec<MessageWrapper>,
} }
/// A wrapper for `ruma_events::AnyMessageEventStub` that allows implementation of
/// Eq, Ord and the Partial versions of the traits.
///
/// `MessageWrapper` also implements Deref and DerefMut so accessing the events contents
/// are simplified.
#[derive(Clone, Debug, Serialize)] #[derive(Clone, Debug, Serialize)]
pub struct MessageWrapper(pub AnyMessageEventStub); pub struct MessageWrapper(pub AnyMessageEventStub);

View File

@ -360,8 +360,8 @@ impl Room {
} }
} }
fn add_member(&mut self, event: &StateEventStub<MemberEventContent>, room_id: &RoomId) -> bool { fn add_member(&mut self, event: &StateEventStub<MemberEventContent>) -> bool {
let new_member = RoomMember::new(event, room_id); let new_member = RoomMember::new(event, &self.room_id);
if self.joined_members.contains_key(&new_member.user_id) if self.joined_members.contains_key(&new_member.user_id)
|| self.invited_members.contains_key(&new_member.user_id) || self.invited_members.contains_key(&new_member.user_id)
@ -396,12 +396,8 @@ impl Room {
/// Process the member event of a leaving user. /// Process the member event of a leaving user.
/// ///
/// Returns true if this made a change to the room's state, false otherwise. /// Returns true if this made a change to the room's state, false otherwise.
fn remove_member( fn remove_member(&mut self, event: &StateEventStub<MemberEventContent>) -> bool {
&mut self, let leaving_member = RoomMember::new(event, &self.room_id);
event: &StateEventStub<MemberEventContent>,
room_id: &RoomId,
) -> bool {
let leaving_member = RoomMember::new(event, room_id);
// Perform display name disambiguations, if necessary. // Perform display name disambiguations, if necessary.
let disambiguations = let disambiguations =
@ -587,19 +583,15 @@ impl Room {
/// Handle a room.member updating the room state if necessary. /// Handle a room.member updating the room state if necessary.
/// ///
/// Returns true if the joined member list changed, false otherwise. /// Returns true if the joined member list changed, false otherwise.
pub fn handle_membership( pub fn handle_membership(&mut self, event: &StateEventStub<MemberEventContent>) -> bool {
&mut self,
event: &StateEventStub<MemberEventContent>,
room_id: &RoomId,
) -> bool {
use MembershipChange::*; use MembershipChange::*;
// TODO: This would not be handled correctly as all the MemberEvents have the `prev_content` // TODO: This would not be handled correctly as all the MemberEvents have the `prev_content`
// inside of `unsigned` field. // inside of `unsigned` field.
match event.membership_change() { match event.membership_change() {
Invited | Joined => self.add_member(event, room_id), Invited | Joined => self.add_member(event),
Kicked | Banned | KickedAndBanned | InvitationRejected | Left => { Kicked | Banned | KickedAndBanned | InvitationRejected | Left => {
self.remove_member(event, room_id) self.remove_member(event)
} }
ProfileChanged { .. } => { ProfileChanged { .. } => {
let user_id = if let Ok(id) = UserId::try_from(event.state_key.as_str()) { let user_id = if let Ok(id) = UserId::try_from(event.state_key.as_str()) {
@ -640,7 +632,6 @@ impl Room {
.iter_mut() .iter_mut()
.find(|msg| &event.redacts == msg.event_id()) .find(|msg| &event.redacts == msg.event_id())
{ {
// TODO make msg an enum or use AnyMessageEventStub enum to represent
*msg = MessageWrapper(AnyMessageEventStub::RoomRedaction(event.clone())); *msg = MessageWrapper(AnyMessageEventStub::RoomRedaction(event.clone()));
true true
} else { } else {
@ -734,11 +725,11 @@ impl Room {
/// # Arguments /// # Arguments
/// ///
/// * `event` - The event of the room. /// * `event` - The event of the room.
pub fn receive_timeline_event(&mut self, event: &AnyRoomEventStub, room_id: &RoomId) -> bool { pub fn receive_timeline_event(&mut self, event: &AnyRoomEventStub) -> bool {
match &event { match &event {
AnyRoomEventStub::State(event) => match &event { AnyRoomEventStub::State(event) => match &event {
// update to the current members of the room // update to the current members of the room
AnyStateEventStub::RoomMember(event) => self.handle_membership(&event, room_id), AnyStateEventStub::RoomMember(event) => self.handle_membership(&event),
// finds all events related to the name of the room for later use // finds all events related to the name of the room for later use
AnyStateEventStub::RoomName(event) => self.handle_room_name(&event), AnyStateEventStub::RoomName(event) => self.handle_room_name(&event),
AnyStateEventStub::RoomCanonicalAlias(event) => self.handle_canonical(&event), AnyStateEventStub::RoomCanonicalAlias(event) => self.handle_canonical(&event),
@ -768,10 +759,10 @@ impl Room {
/// # Arguments /// # Arguments
/// ///
/// * `event` - The event of the room. /// * `event` - The event of the room.
pub fn receive_state_event(&mut self, event: &AnyStateEventStub, room_id: &RoomId) -> bool { pub fn receive_state_event(&mut self, event: &AnyStateEventStub) -> bool {
match event { match event {
// update to the current members of the room // update to the current members of the room
AnyStateEventStub::RoomMember(member) => self.handle_membership(member, room_id), AnyStateEventStub::RoomMember(member) => self.handle_membership(member),
// finds all events related to the name of the room for later use // finds all events related to the name of the room for later use
AnyStateEventStub::RoomName(name) => self.handle_room_name(name), AnyStateEventStub::RoomName(name) => self.handle_room_name(name),
AnyStateEventStub::RoomCanonicalAlias(c_alias) => self.handle_canonical(c_alias), AnyStateEventStub::RoomCanonicalAlias(c_alias) => self.handle_canonical(c_alias),

View File

@ -938,7 +938,6 @@ impl OlmMachine {
.ok_or(EventError::MissingSigningKey)?; .ok_or(EventError::MissingSigningKey)?;
Ok(( Ok((
// FIXME EventJson<Any*Event> fails to deserialize still?
EventJson::from(serde_json::from_value::<AnyToDeviceEvent>(decrypted_json)?), EventJson::from(serde_json::from_value::<AnyToDeviceEvent>(decrypted_json)?),
signing_key.to_owned(), signing_key.to_owned(),
)) ))
@ -999,7 +998,7 @@ impl OlmMachine {
.await? .await?
{ {
// Some events may have sensitive data e.g. private keys, while we // Some events may have sensitive data e.g. private keys, while we
// wan't to notify our users that a private key was received we // want to notify our users that a private key was received we
// don't want them to be able to do silly things with it. Handling // don't want them to be able to do silly things with it. Handling
// events modifies them and returns a modified one, so replace it // events modifies them and returns a modified one, so replace it
// here if we get one. // here if we get one.

View File

@ -6,8 +6,8 @@ use http::Response;
use matrix_sdk_common::api::r0::sync::sync_events::Response as SyncResponse; use matrix_sdk_common::api::r0::sync::sync_events::Response as SyncResponse;
use matrix_sdk_common::events::{ use matrix_sdk_common::events::{
presence::PresenceEvent, AnyBasicEvent, AnyEphemeralRoomEventContent, AnyRoomEventStub, presence::PresenceEvent, AnyBasicEvent, AnyEphemeralRoomEventStub, AnyRoomEventStub,
AnyStateEventStub, EphemeralRoomEventStub, AnyStateEventStub,
}; };
use matrix_sdk_common::identifiers::RoomId; use matrix_sdk_common::identifiers::RoomId;
use serde_json::Value as JsonValue; use serde_json::Value as JsonValue;
@ -16,9 +16,6 @@ pub use matrix_sdk_test_macros::async_test;
pub mod test_json; pub mod test_json;
/// Static `serde_json::Value`s
type AnyEphemeralRoomEventStub = EphemeralRoomEventStub<AnyEphemeralRoomEventContent>;
/// Embedded event files /// Embedded event files
#[derive(Debug)] #[derive(Debug)]
pub enum EventsJson { pub enum EventsJson {