matrix_sdk: Rename public room builder and client methods

Remove 'get' from get_public_rooms* methods.
Rename RoomSearchBuilder -> RoomListFilterBuilder.
Use u32 over UInt in builders and Into<String> for String.
Fix docs of public room methods and builders.
master
Devin R 2020-06-24 07:46:40 -04:00
parent 4dbe785bd7
commit 1016519bb6
3 changed files with 102 additions and 102 deletions

View File

@ -663,8 +663,7 @@ impl Client {
/// ///
/// # Examples /// # Examples
/// ```no_run /// ```no_run
/// use matrix_sdk::{Client, RoomSearchBuilder}; /// use matrix_sdk::Client;
/// # use matrix_sdk::api::r0::directory::get_public_rooms;
/// # use url::Url; /// # use url::Url;
/// # let homeserver = Url::parse("http://example.com").unwrap(); /// # let homeserver = Url::parse("http://example.com").unwrap();
/// # let limit = Some(10); /// # let limit = Some(10);
@ -674,14 +673,14 @@ impl Client {
/// let mut cli = Client::new(homeserver).unwrap(); /// let mut cli = Client::new(homeserver).unwrap();
/// # use futures::executor::block_on; /// # use futures::executor::block_on;
/// # block_on(async { /// # block_on(async {
/// assert!(cli.get_public_rooms( /// assert!(cli.public_rooms(
/// limit, /// limit,
/// since, /// since,
/// server /// server
/// ).await.is_ok()); /// ).await.is_ok());
/// # }); /// # });
/// ``` /// ```
pub async fn get_public_rooms( pub async fn public_rooms(
&self, &self,
limit: Option<u32>, limit: Option<u32>,
since: Option<&str>, since: Option<&str>,
@ -699,18 +698,18 @@ impl Client {
self.send(request).await self.send(request).await
} }
/// Search the homeserver's directory of public rooms filtered. /// Search the homeserver's directory of public rooms with a filter.
/// ///
/// Returns a `get_public_rooms_filtered::Response`, an empty response. /// Returns a `get_public_rooms_filtered::Response`, an empty response.
/// ///
/// # Arguments /// # Arguments
/// ///
/// * `room_search` - The easiest way to create this request is using the `RoomSearchBuilder`. /// * `room_search` - The easiest way to create this request is using the `RoomListFilterBuilder`.
/// ///
/// # Examples /// # Examples
/// ``` /// ```
/// # use std::convert::TryFrom; /// # use std::convert::TryFrom;
/// # use matrix_sdk::{Client, RoomSearchBuilder}; /// # use matrix_sdk::{Client, RoomListFilterBuilder};
/// # use matrix_sdk::api::r0::directory::get_public_rooms_filtered::{self, RoomNetwork, Filter}; /// # use matrix_sdk::api::r0::directory::get_public_rooms_filtered::{self, RoomNetwork, Filter};
/// # use url::Url; /// # use url::Url;
/// # let homeserver = Url::parse("http://example.com").unwrap(); /// # let homeserver = Url::parse("http://example.com").unwrap();
@ -720,16 +719,16 @@ impl Client {
/// let mut client = Client::new(homeserver).unwrap(); /// let mut client = Client::new(homeserver).unwrap();
/// ///
/// let generic_search_term = Some("matrix-rust-sdk".to_string()); /// let generic_search_term = Some("matrix-rust-sdk".to_string());
/// let mut builder = RoomSearchBuilder::new(); /// let mut builder = RoomListFilterBuilder::new();
/// builder /// builder
/// .filter(Filter { generic_search_term, }) /// .filter(Filter { generic_search_term, })
/// .since(last_sync_token) /// .since(last_sync_token)
/// .room_network(RoomNetwork::Matrix); /// .room_network(RoomNetwork::Matrix);
/// ///
/// client.get_public_rooms_filtered(builder).await.is_err(); /// client.public_rooms_filtered(builder).await.is_err();
/// # }) /// # })
/// ``` /// ```
pub async fn get_public_rooms_filtered<R: Into<get_public_rooms_filtered::Request>>( pub async fn public_rooms_filtered<R: Into<get_public_rooms_filtered::Request>>(
&self, &self,
room_search: R, room_search: R,
) -> Result<get_public_rooms_filtered::Response> { ) -> Result<get_public_rooms_filtered::Response> {
@ -797,12 +796,14 @@ impl Client {
/// # use matrix_sdk::js_int::UInt; /// # use matrix_sdk::js_int::UInt;
/// ///
/// # let homeserver = Url::parse("http://example.com").unwrap(); /// # let homeserver = Url::parse("http://example.com").unwrap();
/// let mut builder = MessagesRequestBuilder::new(); /// let mut builder = MessagesRequestBuilder::new(
/// builder.room_id(RoomId::try_from("!roomid:example.com").unwrap()) /// RoomId::try_from("!roomid:example.com").unwrap(),
/// .from("t47429-4392820_219380_26003_2265".to_string()) /// "t47429-4392820_219380_26003_2265".to_string(),
/// .to("t4357353_219380_26003_2265".to_string()) /// );
///
/// builder.to("t4357353_219380_26003_2265".to_string())
/// .direction(Direction::Backward) /// .direction(Direction::Backward)
/// .limit(UInt::new(10).unwrap()); /// .limit(10);
/// ///
/// let mut client = Client::new(homeserver).unwrap(); /// let mut client = Client::new(homeserver).unwrap();
/// # use futures::executor::block_on; /// # use futures::executor::block_on;
@ -1497,7 +1498,7 @@ mod test {
use crate::events::collections::all::RoomEvent; use crate::events::collections::all::RoomEvent;
use crate::events::room::message::TextMessageEventContent; use crate::events::room::message::TextMessageEventContent;
use crate::identifiers::{EventId, RoomId, RoomIdOrAliasId, UserId}; use crate::identifiers::{EventId, RoomId, RoomIdOrAliasId, UserId};
use crate::{RegistrationBuilder, RoomSearchBuilder}; use crate::{RegistrationBuilder, RoomListFilterBuilder};
use matrix_sdk_base::JsonStore; use matrix_sdk_base::JsonStore;
use matrix_sdk_test::{test_json, EventBuilder, EventsJson}; use matrix_sdk_test::{test_json, EventBuilder, EventsJson};
@ -1860,11 +1861,8 @@ mod test {
let client = Client::new(homeserver).unwrap(); let client = Client::new(homeserver).unwrap();
if let get_public_rooms::Response { chunk, .. } = client if let get_public_rooms::Response { chunk, .. } =
// .get_public_rooms(Some(10), None, Some(&mockito::server_url().to_string())) client.public_rooms(Some(10), None, None).await.unwrap()
.get_public_rooms(Some(10), None, None)
.await
.unwrap()
{ {
assert_eq!(chunk.len(), 1) assert_eq!(chunk.len(), 1)
} }
@ -1894,13 +1892,13 @@ mod test {
client.restore_login(session).await.unwrap(); client.restore_login(session).await.unwrap();
let generic_search_term = Some("cheese".to_string()); let generic_search_term = Some("cheese".to_string());
let mut request = RoomSearchBuilder::default(); let mut request = RoomListFilterBuilder::default();
request.filter(Filter { request.filter(Filter {
generic_search_term, generic_search_term,
}); });
if let get_public_rooms_filtered::Response { chunk, .. } = if let get_public_rooms_filtered::Response { chunk, .. } =
client.get_public_rooms_filtered(request).await.unwrap() client.public_rooms_filtered(request).await.unwrap()
{ {
assert_eq!(chunk.len(), 1) assert_eq!(chunk.len(), 1)
} }

View File

@ -53,7 +53,7 @@ mod request_builder;
pub use client::{Client, ClientConfig, SyncSettings}; pub use client::{Client, ClientConfig, SyncSettings};
pub use error::{Error, Result}; pub use error::{Error, Result};
pub use request_builder::{ pub use request_builder::{
MessagesRequestBuilder, RegistrationBuilder, RoomBuilder, RoomSearchBuilder, MessagesRequestBuilder, RegistrationBuilder, RoomBuilder, RoomListFilterBuilder,
}; };
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]

View File

@ -1,20 +1,22 @@
use crate::api; use std::convert::TryFrom;
use crate::events::room::power_levels::PowerLevelsEventContent;
use crate::events::EventJson; use matrix_sdk_common::{
use crate::identifiers::{DeviceId, RoomId, UserId}; api::r0::{
use api::r0::account::register; account::register::{self, RegistrationKind},
use api::r0::account::register::RegistrationKind; directory::get_public_rooms_filtered::{self, Filter, RoomNetwork},
use api::r0::directory::get_public_rooms_filtered::{self, Filter, RoomNetwork}; filter::RoomEventFilter,
use api::r0::filter::RoomEventFilter; membership::Invite3pid,
use api::r0::membership::Invite3pid; message::get_message_events::{self, Direction},
use api::r0::message::get_message_events::{self, Direction}; room::{
use api::r0::room::{
create_room::{self, CreationContent, InitialStateEvent, RoomPreset}, create_room::{self, CreationContent, InitialStateEvent, RoomPreset},
Visibility, Visibility,
},
uiaa::AuthData,
},
events::{room::power_levels::PowerLevelsEventContent, EventJson},
identifiers::{DeviceId, RoomId, UserId},
js_int::{uint, UInt},
}; };
use api::r0::uiaa::AuthData;
use crate::js_int::UInt;
/// A builder used to create rooms. /// A builder used to create rooms.
/// ///
@ -194,24 +196,28 @@ impl Into<create_room::Request> for RoomBuilder {
/// # let last_sync_token = "".to_string(); /// # let last_sync_token = "".to_string();
/// let mut client = Client::new(homeserver).unwrap(); /// let mut client = Client::new(homeserver).unwrap();
/// ///
/// let mut builder = MessagesRequestBuilder::new(); /// let mut builder = MessagesRequestBuilder::new(
/// builder.room_id(room_id) /// RoomId::try_from("!roomid:example.com").unwrap(),
/// .from(last_sync_token) /// "t47429-4392820_219380_26003_2265".to_string(),
/// .direction(Direction::Forward); /// );
///
/// builder.to("t4357353_219380_26003_2265".to_string())
/// .direction(Direction::Backward)
/// .limit(10);
/// ///
/// client.room_messages(builder).await.is_err(); /// client.room_messages(builder).await.is_err();
/// # }) /// # })
/// ``` /// ```
#[derive(Clone, Debug, Default)] #[derive(Clone, Debug)]
pub struct MessagesRequestBuilder { pub struct MessagesRequestBuilder {
/// The room to get events from. /// The room to get events from.
room_id: Option<RoomId>, room_id: RoomId,
/// The token to start returning events from. /// The token to start returning events from.
/// ///
/// This token can be obtained from a /// This token can be obtained from a
/// prev_batch token returned for each room by the sync API, or from a start or end token /// prev_batch token returned for each room by the sync API, or from a start or end token
/// returned by a previous request to this endpoint. /// returned by a previous request to this endpoint.
from: Option<String>, from: String,
/// The token to stop returning events at. /// The token to stop returning events at.
/// ///
/// This token can be obtained from a prev_batch /// This token can be obtained from a prev_batch
@ -223,38 +229,30 @@ pub struct MessagesRequestBuilder {
/// The maximum number of events to return. /// The maximum number of events to return.
/// ///
/// Default: 10. /// Default: 10.
limit: Option<UInt>, limit: Option<u32>,
/// A filter of the returned events with. /// A filter of the returned events with.
filter: Option<RoomEventFilter>, filter: Option<RoomEventFilter>,
} }
impl MessagesRequestBuilder { impl MessagesRequestBuilder {
/// Create a `MessagesRequestBuilder` builder to make a `get_message_events::Request`. /// Create a `MessagesRequestBuilder` builder to make a `get_message_events::Request`.
///
/// The `room_id` and `from`` fields **need to be set** to create the request. /// The `room_id` and `from`` fields **need to be set** to create the request.
pub fn new() -> Self { pub fn new(room_id: RoomId, from: String) -> Self {
Self::default() Self {
room_id,
from,
to: None,
direction: None,
limit: None,
filter: None,
} }
/// RoomId is required to create a `get_message_events::Request`.
pub fn room_id(&mut self, room_id: RoomId) -> &mut Self {
self.room_id = Some(room_id);
self
}
/// A `next_batch` token or `start` or `end` from a previous `get_message_events` request.
///
/// This is required to create a `get_message_events::Request`.
pub fn from(&mut self, from: String) -> &mut Self {
self.from = Some(from);
self
} }
/// A `next_batch` token or `start` or `end` from a previous `get_message_events` request. /// A `next_batch` token or `start` or `end` from a previous `get_message_events` request.
/// ///
/// This token signals when to stop receiving events. /// This token signals when to stop receiving events.
pub fn to(&mut self, to: String) -> &mut Self { pub fn to<S: Into<String>>(&mut self, to: S) -> &mut Self {
self.to = Some(to); self.to = Some(to.into());
self self
} }
@ -267,7 +265,9 @@ impl MessagesRequestBuilder {
} }
/// The maximum number of events to return. /// The maximum number of events to return.
pub fn limit(&mut self, limit: UInt) -> &mut Self { ///
/// The default is 10.
pub fn limit(&mut self, limit: u32) -> &mut Self {
self.limit = Some(limit); self.limit = Some(limit);
self self
} }
@ -282,11 +282,11 @@ impl MessagesRequestBuilder {
impl Into<get_message_events::Request> for MessagesRequestBuilder { impl Into<get_message_events::Request> for MessagesRequestBuilder {
fn into(self) -> get_message_events::Request { fn into(self) -> get_message_events::Request {
get_message_events::Request { get_message_events::Request {
room_id: self.room_id.expect("`room_id` and `from` need to be set"), room_id: self.room_id,
from: self.from.expect("`room_id` and `from` need to be set"), from: self.from,
to: self.to, to: self.to,
dir: self.direction.unwrap_or(Direction::Backward), dir: self.direction.unwrap_or(Direction::Backward),
limit: self.limit, limit: self.limit.map_or(Ok(uint!(10)), UInt::try_from).ok(),
filter: self.filter, filter: self.filter,
} }
} }
@ -325,8 +325,6 @@ pub struct RegistrationBuilder {
impl RegistrationBuilder { impl RegistrationBuilder {
/// Create a `RegistrationBuilder` builder to make a `register::Request`. /// Create a `RegistrationBuilder` builder to make a `register::Request`.
///
/// The `room_id` and `from`` fields **need to be set** to create the request.
pub fn new() -> Self { pub fn new() -> Self {
Self::default() Self::default()
} }
@ -335,16 +333,16 @@ impl RegistrationBuilder {
/// ///
/// May be empty for accounts that should not be able to log in again /// May be empty for accounts that should not be able to log in again
/// with a password, e.g., for guest or application service accounts. /// with a password, e.g., for guest or application service accounts.
pub fn password(&mut self, password: &str) -> &mut Self { pub fn password<S: Into<String>>(&mut self, password: S) -> &mut Self {
self.password = Some(password.to_string()); self.password = Some(password.into());
self self
} }
/// local part of the desired Matrix ID. /// local part of the desired Matrix ID.
/// ///
/// If omitted, the homeserver MUST generate a Matrix ID local part. /// If omitted, the homeserver MUST generate a Matrix ID local part.
pub fn username(&mut self, username: &str) -> &mut Self { pub fn username<S: Into<String>>(&mut self, username: S) -> &mut Self {
self.username = Some(username.to_string()); self.username = Some(username.into());
self self
} }
@ -352,16 +350,19 @@ impl RegistrationBuilder {
/// ///
/// If this does not correspond to a known client device, a new device will be created. /// If this does not correspond to a known client device, a new device will be created.
/// The server will auto-generate a device_id if this is not specified. /// The server will auto-generate a device_id if this is not specified.
pub fn device_id(&mut self, device_id: &str) -> &mut Self { pub fn device_id<S: Into<String>>(&mut self, device_id: S) -> &mut Self {
self.device_id = Some(device_id.to_string()); self.device_id = Some(device_id.into());
self self
} }
/// A display name to assign to the newly-created device. /// A display name to assign to the newly-created device.
/// ///
/// Ignored if `device_id` corresponds to a known device. /// Ignored if `device_id` corresponds to a known device.
pub fn initial_device_display_name(&mut self, initial_device_display_name: &str) -> &mut Self { pub fn initial_device_display_name<S: Into<String>>(
self.initial_device_display_name = Some(initial_device_display_name.to_string()); &mut self,
initial_device_display_name: S,
) -> &mut Self {
self.initial_device_display_name = Some(initial_device_display_name.into());
self self
} }
@ -406,12 +407,12 @@ impl Into<register::Request> for RegistrationBuilder {
} }
} }
/// Create a builder for making get_message_event requests. /// Create a builder for making get_public_rooms_filtered requests.
/// ///
/// # Examples /// # Examples
/// ``` /// ```
/// # use std::convert::TryFrom; /// # use std::convert::TryFrom;
/// # use matrix_sdk::{Client, RoomSearchBuilder}; /// # use matrix_sdk::{Client, RoomListFilterBuilder};
/// # use matrix_sdk::api::r0::directory::get_public_rooms_filtered::{self, RoomNetwork, Filter}; /// # use matrix_sdk::api::r0::directory::get_public_rooms_filtered::{self, RoomNetwork, Filter};
/// # use url::Url; /// # use url::Url;
/// # let homeserver = Url::parse("http://example.com").unwrap(); /// # let homeserver = Url::parse("http://example.com").unwrap();
@ -421,28 +422,26 @@ impl Into<register::Request> for RegistrationBuilder {
/// let mut client = Client::new(homeserver).unwrap(); /// let mut client = Client::new(homeserver).unwrap();
/// ///
/// let generic_search_term = Some("matrix-rust-sdk".to_string()); /// let generic_search_term = Some("matrix-rust-sdk".to_string());
/// let mut builder = RoomSearchBuilder::new(); /// let mut builder = RoomListFilterBuilder::new();
/// builder /// builder
/// .filter(Filter { generic_search_term, }) /// .filter(Filter { generic_search_term, })
/// .since(last_sync_token) /// .since(last_sync_token)
/// .room_network(RoomNetwork::Matrix); /// .room_network(RoomNetwork::Matrix);
/// ///
/// client.get_public_rooms_filtered(builder).await.is_err(); /// client.public_rooms_filtered(builder).await.is_err();
/// # }) /// # })
/// ``` /// ```
#[derive(Clone, Debug, Default)] #[derive(Clone, Debug, Default)]
pub struct RoomSearchBuilder { pub struct RoomListFilterBuilder {
server: Option<String>, server: Option<String>,
limit: Option<UInt>, limit: Option<u32>,
since: Option<String>, since: Option<String>,
filter: Option<Filter>, filter: Option<Filter>,
room_network: Option<RoomNetwork>, room_network: Option<RoomNetwork>,
} }
impl RoomSearchBuilder { impl RoomListFilterBuilder {
/// Create a `RoomSearchBuilder` builder to make a `get_message_events::Request`. /// Create a `RoomListFilterBuilder` builder to make a `get_message_events::Request`.
///
/// The `room_id` and `from`` fields **need to be set** to create the request.
pub fn new() -> Self { pub fn new() -> Self {
Self::default() Self::default()
} }
@ -450,20 +449,20 @@ impl RoomSearchBuilder {
/// The server to fetch the public room lists from. /// The server to fetch the public room lists from.
/// ///
/// `None` means the server this request is sent to. /// `None` means the server this request is sent to.
pub fn server(&mut self, server: String) -> &mut Self { pub fn server<S: Into<String>>(&mut self, server: S) -> &mut Self {
self.server = Some(server); self.server = Some(server.into());
self self
} }
/// Limit for the number of results to return. /// Limit for the number of results to return.
pub fn limit(&mut self, limit: UInt) -> &mut Self { pub fn limit(&mut self, limit: u32) -> &mut Self {
self.limit = Some(limit); self.limit = Some(limit);
self self
} }
/// Pagination token from a previous request. /// Pagination token from a previous request.
pub fn since(&mut self, since: String) -> &mut Self { pub fn since<S: Into<String>>(&mut self, since: S) -> &mut Self {
self.since = Some(since); self.since = Some(since.into());
self self
} }
@ -474,17 +473,19 @@ impl RoomSearchBuilder {
} }
/// Network to fetch the public room lists from. /// Network to fetch the public room lists from.
///
/// Defaults to the Matrix network.
pub fn room_network(&mut self, room_network: RoomNetwork) -> &mut Self { pub fn room_network(&mut self, room_network: RoomNetwork) -> &mut Self {
self.room_network = Some(room_network); self.room_network = Some(room_network);
self self
} }
} }
impl Into<get_public_rooms_filtered::Request> for RoomSearchBuilder { impl Into<get_public_rooms_filtered::Request> for RoomListFilterBuilder {
fn into(self) -> get_public_rooms_filtered::Request { fn into(self) -> get_public_rooms_filtered::Request {
get_public_rooms_filtered::Request { get_public_rooms_filtered::Request {
room_network: self.room_network.unwrap_or_default(), room_network: self.room_network.unwrap_or_default(),
limit: self.limit, limit: self.limit.map_or(Ok(uint!(0)), UInt::try_from).ok(),
server: self.server, server: self.server,
since: self.since, since: self.since,
filter: self.filter, filter: self.filter,
@ -570,13 +571,14 @@ mod test {
device_id: "DEVICEID".to_owned(), device_id: "DEVICEID".to_owned(),
}; };
let mut builder = MessagesRequestBuilder::new(); let mut builder = MessagesRequestBuilder::new(
RoomId::try_from("!roomid:example.com").unwrap(),
"t47429-4392820_219380_26003_2265".to_string(),
);
builder builder
.room_id(RoomId::try_from("!roomid:example.com").unwrap())
.from("t47429-4392820_219380_26003_2265".to_string())
.to("t4357353_219380_26003_2265".to_string()) .to("t4357353_219380_26003_2265".to_string())
.direction(Direction::Backward) .direction(Direction::Backward)
.limit(UInt::new(10).unwrap()) .limit(10)
.filter(RoomEventFilter { .filter(RoomEventFilter {
lazy_load_options: LazyLoadOptions::Enabled { lazy_load_options: LazyLoadOptions::Enabled {
include_redundant_members: false, include_redundant_members: false,