1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
//! Crate `ruma_client` is a [Matrix](https://matrix.org/) client library.

#![deny(missing_debug_implementations)]
#![deny(missing_docs)]
#![feature(try_from)]

extern crate futures;
extern crate http;
extern crate hyper;
#[cfg(feature = "tls")]
extern crate hyper_tls;
#[cfg(feature = "tls")]
extern crate native_tls;
extern crate ruma_api;
extern crate ruma_client_api;
extern crate ruma_identifiers;
extern crate serde_json;
extern crate serde_urlencoded;
extern crate url;

use std::cell::RefCell;
use std::convert::TryInto;
use std::rc::Rc;
use std::str::FromStr;

use futures::future::{Future, FutureFrom, IntoFuture};
use futures::stream::{self, Stream};
use hyper::{Client as HyperClient, Uri};
use hyper::client::HttpConnector;
use hyper::client::connect::Connect;
#[cfg(feature = "hyper-tls")]
use hyper_tls::HttpsConnector;
#[cfg(feature = "hyper-tls")]
use native_tls::Error as NativeTlsError;
use ruma_api::Endpoint;
use url::Url;

pub use error::Error;
pub use session::Session;

/// Matrix client-server API endpoints.
pub mod api;
mod error;
mod session;

/// A client for the Matrix client-server API.
#[derive(Debug)]
pub struct Client<C: Connect>(Rc<ClientData<C>>);

/// Data contained in Client's Rc
#[derive(Debug)]
pub struct ClientData<C>
where
    C: Connect,
{
    homeserver_url: Url,
    hyper: HyperClient<C>,
    session: RefCell<Option<Session>>,
}

impl Client<HttpConnector> {
    /// Creates a new client for making HTTP requests to the given homeserver.
    pub fn new(homeserver_url: Url, session: Option<Session>) -> Self {
        Client(Rc::new(ClientData {
            homeserver_url,
            hyper: HyperClient::builder().keep_alive(true).build_http(),
            session: RefCell::new(session),
        }))
    }
}

#[cfg(feature = "tls")]
impl Client<HttpsConnector<HttpConnector>> {
    /// Creates a new client for making HTTPS requests to the given homeserver.
    pub fn https(homeserver_url: Url, session: Option<Session>) -> Result<Self, NativeTlsError> {
        let connector = HttpsConnector::new(4)?;

        Ok(Client(Rc::new(ClientData {
            homeserver_url,
            hyper: {
                HyperClient::builder()
                    .keep_alive(true)
                    .build(connector)
            },
            session: RefCell::new(session),
        })))
    }
}

impl<C> Client<C>
where
    C: Connect + 'static,
{
    /// Creates a new client using the given `hyper::Client`.
    ///
    /// This allows the user to configure the details of HTTP as desired.
    pub fn custom(hyper_client: HyperClient<C>, homeserver_url: Url, session: Option<Session>) -> Self {
        Client(Rc::new(ClientData {
            homeserver_url,
            hyper: hyper_client,
            session: RefCell::new(session),
        }))
    }

    /// Log in with a username and password.
    ///
    /// In contrast to api::r0::session::login::call(), this method stores the
    /// session data returned by the endpoint in this client, instead of
    /// returning it.
    pub fn log_in(&self, user: String, password: String, device_id: Option<String>)
    -> impl Future<Item = Session, Error = Error> {
        use api::r0::session::login;

        let data = self.0.clone();

        login::call(self.clone(), login::Request {
            address: None,
            login_type: login::LoginType::Password,
            medium: None,
            device_id,
            password,
            user,
        }).map(move |response| {
            let session = Session::new(response.access_token, response.user_id);
            *data.session.borrow_mut() = Some(session.clone());

            session
        })
    }

    /// Register as a guest. In contrast to api::r0::account::register::call(),
    /// this method stores the session data returned by the endpoint in this
    /// client, instead of returning it.
    pub fn register_guest(&self) -> impl Future<Item = Session, Error = Error> {
        use api::r0::account::register;

        let data = self.0.clone();

        register::call(self.clone(), register::Request {
            auth: None,
            bind_email: None,
            device_id: None,
            initial_device_display_name: None,
            kind: Some(register::RegistrationKind::Guest),
            password: None,
            username: None,
        }).map(move |response| {
            let session = Session::new(response.access_token, response.user_id);
            *data.session.borrow_mut() = Some(session.clone());

            session
        })
    }

    /// Register as a new user on this server.
    ///
    /// In contrast to api::r0::account::register::call(), this method stores
    /// the session data returned by the endpoint in this client, instead of
    /// returning it.
    ///
    /// The username is the local part of the returned user_id. If it is
    /// omitted from this request, the server will generate one.
    pub fn register_user(
        &self,
        username: Option<String>,
        password: String,
    ) -> impl Future<Item = Session, Error = Error> {
        use api::r0::account::register;

        let data = self.0.clone();

        register::call(self.clone(), register::Request {
            auth: None,
            bind_email: None,
            device_id: None,
            initial_device_display_name: None,
            kind: Some(register::RegistrationKind::User),
            password: Some(password),
            username,
        }).map(move |response| {
            let session = Session::new(response.access_token, response.user_id);
            *data.session.borrow_mut() = Some(session.clone());

            session
        })
    }

    /// Convenience method that represents repeated calls to the sync_events endpoint as a stream.
    ///
    /// If the since parameter is None, the first Item might take a significant time to arrive and
    /// be deserialized, because it contains all events that have occured in the whole lifetime of
    /// the logged-in users account and are visible to them.
    pub fn sync(
        &self,
        filter: Option<api::r0::sync::sync_events::Filter>,
        since: Option<String>,
        set_presence: bool,
    ) -> impl Stream<Item = api::r0::sync::sync_events::Response, Error = Error> {
        use api::r0::sync::sync_events;

        let client = self.clone();
        let set_presence = if set_presence {
            None
        } else {
            Some(sync_events::SetPresence::Offline)
        };

        stream::unfold(since, move |since| {
            Some(
                sync_events::call(
                    client.clone(),
                    sync_events::Request {
                        filter: filter.clone(),
                        since,
                        full_state: None,
                        set_presence: set_presence.clone(),
                        timeout: None,
                    },
                ).map(|res| {
                    let next_batch_clone = res.next_batch.clone();
                    (res, Some(next_batch_clone))
                })
            )
        })
    }

    /// Makes a request to a Matrix API endpoint.
    pub(crate) fn request<E>(
        self,
        request: <E as Endpoint>::Request,
    ) -> impl Future<Item = E::Response, Error = Error>
    where
        E: Endpoint,
    {
        let data1 = self.0.clone();
        let data2 = self.0.clone();
        let mut url = self.0.homeserver_url.clone();

        request
            .try_into()
            .map_err(Error::from)
            .into_future()
            .and_then(move |hyper_request| {
                {
                    let uri = hyper_request.uri();

                    url.set_path(uri.path());
                    url.set_query(uri.query());

                    if E::METADATA.requires_authentication {
                        if let Some(ref session) = *data1.session.borrow() {
                            url.query_pairs_mut().append_pair("access_token", session.access_token());
                        } else {
                            return Err(Error::AuthenticationRequired);
                        }
                    }
                }

                Uri::from_str(url.as_ref())
                    .map(move |uri| (uri, hyper_request))
                    .map_err(Error::from)
            })
            .and_then(move |(uri, mut hyper_request)| {
                *hyper_request.uri_mut() = uri;

                data2.hyper
                    .request(hyper_request)
                    .map_err(Error::from)
            })
            .and_then(|hyper_response| {
                E::Response::future_from(hyper_response).map_err(Error::from)
            })
    }
}

impl<C: Connect> Clone for Client<C> {
    fn clone(&self) -> Client<C> {
        Client(self.0.clone())
    }
}