rust-sdk: Cleanup the docs and fix the examples up.

master
Damir Jelić 2020-03-02 11:31:03 +01:00
parent de154e272a
commit c41d3873b6
4 changed files with 98 additions and 44 deletions

View File

@ -35,6 +35,6 @@ cjson = { version = "0.1.0", optional = true }
[dev-dependencies] [dev-dependencies]
tokio = { version = "0.2.11", features = ["full"] } tokio = { version = "0.2.11", features = ["full"] }
async-std = { version = "1.5.0", features = ["attributes"] } async-std = { version = "1.5.0", features = ["unstable", "attributes"] }
url = "2.1.1" url = "2.1.1"
mockito = "0.23.3" mockito = "0.23.3"

View File

@ -67,10 +67,9 @@ pub struct AsyncClient {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # use matrix_sdk::AsyncClientConfig;
/// // To pass all the request through mitmproxy set the proxy and disable SSL /// // To pass all the request through mitmproxy set the proxy and disable SSL
/// // verification /// // verification
/// use matrix_sdk::AsyncClientConfig;
///
/// let client_config = AsyncClientConfig::new() /// let client_config = AsyncClientConfig::new()
/// .proxy("http://localhost:8080") /// .proxy("http://localhost:8080")
/// .unwrap() /// .unwrap()
@ -265,7 +264,17 @@ impl AsyncClient {
/// received. /// received.
/// ///
/// # Examples /// # Examples
/// ```noexecute /// ```
/// # use matrix_sdk::events::{
/// # collections::all::RoomEvent,
/// # room::message::{MessageEvent, MessageEventContent, TextMessageEventContent},
/// # EventResult,
/// # };
/// # use matrix_sdk::Room;
/// # use std::sync::{Arc, RwLock};
/// # use matrix_sdk::AsyncClient;
/// # use url::Url;
///
/// async fn async_cb(room: Arc<RwLock<Room>>, event: Arc<EventResult<RoomEvent>>) { /// async fn async_cb(room: Arc<RwLock<Room>>, event: Arc<EventResult<RoomEvent>>) {
/// let room = room.read().unwrap(); /// let room = room.read().unwrap();
/// let event = if let EventResult::Ok(event) = &*event { /// let event = if let EventResult::Ok(event) = &*event {
@ -287,10 +296,14 @@ impl AsyncClient {
/// ); /// );
/// } /// }
/// } /// }
/// # fn main() -> Result<(), matrix_sdk::Error> {
/// let homeserver = Url::parse("http://localhost:8080")?;
///
/// let mut client = AsyncClient::new(homeserver, None)?;
/// ///
/// async fn main(client: AsyncClient) {
/// client.add_event_callback(async_cb); /// client.add_event_callback(async_cb);
/// } /// # Ok(())
/// # }
/// ``` /// ```
pub fn add_event_callback<C: 'static>( pub fn add_event_callback<C: 'static>(
&mut self, &mut self,
@ -309,9 +322,11 @@ impl AsyncClient {
/// ///
/// # Arguments /// # Arguments
/// ///
/// `user` - The user that should be logged in to the homeserver. /// * `user` - The user that should be logged in to the homeserver.
/// `password` - The password of the user. ///
/// `device_id` - A unique id that will be associated with this session. If /// * `password` - The password of the user.
///
/// * `device_id` - A unique id that will be associated with this session. If
/// not given the homeserver will create one. Can be an exising /// not given the homeserver will create one. Can be an exising
/// device_id from a previous login call. Note that this should be done /// device_id from a previous login call. Note that this should be done
/// only if the client also holds the encryption keys for this devcie. /// only if the client also holds the encryption keys for this devcie.
@ -408,6 +423,7 @@ impl AsyncClient {
/// ///
/// * `sync_settings` - Settings for the sync call. Note that those settings /// * `sync_settings` - Settings for the sync call. Note that those settings
/// will be only used for the first sync call. /// will be only used for the first sync call.
///
/// * `callback` - A callback that will be called every time a successful /// * `callback` - A callback that will be called every time a successful
/// response has been fetched from the server. /// response has been fetched from the server.
/// ///
@ -417,16 +433,35 @@ impl AsyncClient {
/// the interesting events through a mpsc channel to another thread e.g. a /// the interesting events through a mpsc channel to another thread e.g. a
/// UI thread. /// UI thread.
/// ///
/// ```noexecute /// ```compile_fail,E0658
/// # use matrix_sdk::events::{
/// # collections::all::RoomEvent,
/// # room::message::{MessageEvent, MessageEventContent, TextMessageEventContent},
/// # EventResult,
/// # };
/// # use matrix_sdk::Room;
/// # use std::sync::{Arc, RwLock};
/// # use matrix_sdk::{AsyncClient, SyncSettings};
/// # use url::Url;
/// # use futures::executor::block_on;
/// # block_on(async {
/// # let homeserver = Url::parse("http://localhost:8080").unwrap();
/// # let mut client = AsyncClient::new(homeserver, None).unwrap();
///
/// use async_std::sync::channel;
///
/// let (tx, rx) = channel(100);
///
/// let sync_channel = &tx;
/// let sync_settings = SyncSettings::new()
/// .timeout(30_000)
/// .unwrap();
///
/// client /// client
/// .sync_forever(sync_settings, async move |response| { /// .sync_forever(sync_settings, async move |response| {
/// let channel = sync_channel; /// let channel = sync_channel;
///
/// for (room_id, room) in response.rooms.join { /// for (room_id, room) in response.rooms.join {
/// for event in room.state.events {
/// if let EventResult::Ok(e) = event {
/// channel.send(e).await;
/// }
/// }
/// for event in room.timeline.events { /// for event in room.timeline.events {
/// if let EventResult::Ok(e) = event { /// if let EventResult::Ok(e) = event {
/// channel.send(e).await; /// channel.send(e).await;
@ -435,6 +470,7 @@ impl AsyncClient {
/// } /// }
/// }) /// })
/// .await; /// .await;
/// })
/// ``` /// ```
pub async fn sync_forever<C>( pub async fn sync_forever<C>(
&mut self, &mut self,
@ -542,12 +578,13 @@ impl AsyncClient {
/// Send a room message to the homeserver. /// Send a room message to the homeserver.
/// ///
/// Returns the parsed response from the server.
///
/// # Arguments /// # Arguments
/// ///
/// `room_id` - The id of the room that should receive the message. /// * `room_id` - The id of the room that should receive the message.
/// `data` - The content of the message.
/// ///
/// Returns the parsed response from the server. /// * `data` - The content of the message.
pub async fn room_send( pub async fn room_send(
&mut self, &mut self,
room_id: &str, room_id: &str,

View File

@ -58,9 +58,11 @@ pub struct Room {
impl Room { impl Room {
/// Create a new room. /// Create a new room.
///
/// # Arguments /// # Arguments
/// ///
/// * `room_id` - The unique id of the room. /// * `room_id` - The unique id of the room.
///
/// * `own_user_id` - The mxid of our own user. /// * `own_user_id` - The mxid of our own user.
pub fn new(room_id: &str, own_user_id: &str) -> Self { pub fn new(room_id: &str, own_user_id: &str) -> Self {
Room { Room {
@ -137,11 +139,12 @@ impl Room {
} }
/// Receive a timeline event for this room and update the room state. /// Receive a timeline event for this room and update the room state.
/// # Arguments
///
/// `event` - The event of the room.
/// ///
/// Returns true if the joined member list changed, false otherwise. /// Returns true if the joined member list changed, false otherwise.
///
/// # Arguments
///
/// * `event` - The event of the room.
pub fn receive_timeline_event(&mut self, event: &RoomEvent) -> bool { pub fn receive_timeline_event(&mut self, event: &RoomEvent) -> bool {
match event { match event {
RoomEvent::RoomMember(m) => self.handle_membership(m), RoomEvent::RoomMember(m) => self.handle_membership(m),
@ -150,11 +153,12 @@ impl Room {
} }
/// Receive a state event for this room and update the room state. /// Receive a state event for this room and update the room state.
/// # Arguments
///
/// `event` - The event of the room.
/// ///
/// Returns true if the joined member list changed, false otherwise. /// Returns true if the joined member list changed, false otherwise.
///
/// # Arguments
///
/// * `event` - The event of the room.
pub fn receive_state_event(&mut self, event: &StateEvent) -> bool { pub fn receive_state_event(&mut self, event: &StateEvent) -> bool {
match event { match event {
StateEvent::RoomMember(m) => self.handle_membership(m), StateEvent::RoomMember(m) => self.handle_membership(m),
@ -180,9 +184,10 @@ pub struct Client {
impl Client { impl Client {
/// Create a new client. /// Create a new client.
///
/// # Arguments /// # Arguments
/// ///
/// `session` - An optional session if the user already has one from a /// * `session` - An optional session if the user already has one from a
/// previous login call. /// previous login call.
pub fn new(session: Option<Session>) -> Self { pub fn new(session: Option<Session>) -> Self {
Client { Client {
@ -198,9 +203,10 @@ impl Client {
} }
/// Receive a login response and update the session of the client. /// Receive a login response and update the session of the client.
///
/// # Arguments /// # Arguments
/// ///
/// `response` - A successful login response that contains our access token /// * `response` - A successful login response that contains our access token
/// and device id. /// and device id.
pub fn receive_login_response(&mut self, response: &api::session::login::Response) { pub fn receive_login_response(&mut self, response: &api::session::login::Response) {
let session = Session { let session = Session {
@ -228,13 +234,14 @@ impl Client {
/// Receive a timeline event for a joined room and update the client state. /// Receive a timeline event for a joined room and update the client state.
/// ///
/// # Arguments
///
/// `room_id` - The unique id of the room the event belongs to.
/// `event` - The event that should be handled by the client.
///
/// Returns true if the membership list of the room changed, false /// Returns true if the membership list of the room changed, false
/// otherwise. /// otherwise.
///
/// # Arguments
///
/// * `room_id` - The unique id of the room the event belongs to.
///
/// * `event` - The event that should be handled by the client.
pub fn receive_joined_timeline_event( pub fn receive_joined_timeline_event(
&mut self, &mut self,
room_id: &str, room_id: &str,
@ -251,13 +258,14 @@ impl Client {
/// Receive a state event for a joined room and update the client state. /// Receive a state event for a joined room and update the client state.
/// ///
/// # Arguments
///
/// `room_id` - The unique id of the room the event belongs to.
/// `event` - The event that should be handled by the client.
///
/// Returns true if the membership list of the room changed, false /// Returns true if the membership list of the room changed, false
/// otherwise. /// otherwise.
///
/// # Arguments
///
/// * `room_id` - The unique id of the room the event belongs to.
///
/// * `event` - The event that should be handled by the client.
pub fn receive_joined_state_event(&mut self, room_id: &str, event: &StateEvent) -> bool { pub fn receive_joined_state_event(&mut self, room_id: &str, event: &StateEvent) -> bool {
let mut room = self.get_or_create_room(room_id).write().unwrap(); let mut room = self.get_or_create_room(room_id).write().unwrap();
room.receive_state_event(event) room.receive_state_event(event)
@ -267,7 +275,7 @@ impl Client {
/// ///
/// # Arguments /// # Arguments
/// ///
/// `response` - The response that we received after a successful sync. /// * `response` - The response that we received after a successful sync.
pub fn receive_sync_response(&mut self, response: &api::sync::sync_events::IncomingResponse) { pub fn receive_sync_response(&mut self, response: &api::sync::sync_events::IncomingResponse) {
self.sync_token = Some(response.next_batch.clone()); self.sync_token = Some(response.next_batch.clone());
} }

View File

@ -80,7 +80,7 @@ impl OlmMachine {
/// ///
/// # Arguments /// # Arguments
/// ///
/// `response` - The keys upload response of the request that the client /// * `response` - The keys upload response of the request that the client
/// performed. /// performed.
pub async fn receive_keys_upload_response(&mut self, response: &keys::upload_keys::Response) { pub async fn receive_keys_upload_response(&mut self, response: &keys::upload_keys::Response) {
self.account.shared = true; self.account.shared = true;
@ -186,7 +186,13 @@ impl OlmMachine {
Ok(one_time_key_map) Ok(one_time_key_map)
} }
/// Convert a JSON value to the canonical representation and sign the JSON string. /// Convert a JSON value to the canonical representation and sign the JSON
/// string.
///
/// # Arguments
///
/// * `json` - The value that should be converted into a canonical JSON
/// string.
fn sign_json(&self, json: &Value) -> String { fn sign_json(&self, json: &Value) -> String {
let canonical_json = cjson::to_string(json) let canonical_json = cjson::to_string(json)
.unwrap_or_else(|_| panic!(format!("Can't serialize {} to canonical JSON", json))); .unwrap_or_else(|_| panic!(format!("Can't serialize {} to canonical JSON", json)));
@ -198,16 +204,19 @@ impl OlmMachine {
/// The object must have a signatures key associated with an object of the /// The object must have a signatures key associated with an object of the
/// form `user_id: {key_id: signature}`. /// form `user_id: {key_id: signature}`.
/// ///
/// Returns Ok if the signature was successfully verified, otherwise an
/// SignatureError.
///
/// # Arguments /// # Arguments
/// ///
/// * `user_id` - The user who signed the JSON object. /// * `user_id` - The user who signed the JSON object.
///
/// * `device_id` - The device that signed the JSON object. /// * `device_id` - The device that signed the JSON object.
///
/// * `user_key` - The public ed25519 key which was used to sign the JSON /// * `user_key` - The public ed25519 key which was used to sign the JSON
/// object. /// object.
/// * `json` - The JSON object that should be verified.
/// ///
/// Returns Ok if the signature was successfully verified, otherwise an /// * `json` - The JSON object that should be verified.
/// SignatureError.
fn verify_json( fn verify_json(
&self, &self,
user_id: &str, user_id: &str,