ruma_client/
lib.rs

1#![doc(html_favicon_url = "https://ruma.dev/favicon.ico")]
2#![doc(html_logo_url = "https://ruma.dev/images/logo.png")]
3//! A minimal [Matrix](https://matrix.org/) client library.
4//!
5//! # Usage
6//!
7//! Begin by creating a `Client`, selecting one of the type aliases from `ruma_client::http_client`
8//! for the generic parameter. For the client API, there are login and registration methods
9//! provided for the client (feature `client-api`):
10//!
11//! ```no_run
12//! # #[cfg(feature = "client-api")]
13//! # async {
14//! # type HttpClient = ruma_client::http_client::Dummy;
15//! let homeserver_url = "https://example.com".to_owned();
16//! let client =
17//!     ruma_client::Client::builder().homeserver_url(homeserver_url).build::<HttpClient>().await?;
18//!
19//! let session = client.log_in("@alice:example.com", "secret", None, None).await?;
20//!
21//! // You're now logged in! Write the session to a file if you want to restore it later.
22//! // Then start using the API!
23//! # Result::<(), ruma_client::Error<_, _>>::Ok(())
24//! # };
25//! ```
26//!
27//! You can also pass an existing access token to the `Client` constructor to restore a previous
28//! session rather than calling `log_in`. This can also be used to create a session for an
29//! application service that does not need to log in, but uses the access_token directly:
30//!
31//! ```no_run
32//! # #[cfg(feature = "client-api")]
33//! # async {
34//! # type HttpClient = ruma_client::http_client::Dummy;
35//! let homeserver_url = "https://example.com".to_owned();
36//! let client = ruma_client::Client::builder()
37//!     .homeserver_url(homeserver_url)
38//!     .access_token(Some("as_access_token".into()))
39//!     .build::<HttpClient>()
40//!     .await?;
41//!
42//! // make calls to the API
43//! # Result::<(), ruma_client::Error<_, _>>::Ok(())
44//! # };
45//! ```
46//!
47//! The `Client` type also provides methods for registering a new account if you don't already have
48//! one with the given homeserver.
49//!
50//! Beyond these basic convenience methods, `ruma-client` gives you access to the entire Matrix
51//! client-server API via the `request` method. You can pass it any of the `Request` types found in
52//! `ruma::api::*` and get back a corresponding response from the homeserver.
53//!
54//! For example:
55//!
56//! ```no_run
57//! # #[cfg(feature = "client-api")]
58//! # async {
59//! # type HttpClient = ruma_client::http_client::Dummy;
60//! # let homeserver_url = "https://example.com".to_owned();
61//! # let client = ruma_client::Client::builder()
62//! #     .homeserver_url(homeserver_url)
63//! #     .build::<HttpClient>()
64//! #     .await?;
65//!
66//! use ruma::{
67//!     api::{client::alias::get_alias, MatrixVersion},
68//!     owned_room_alias_id, room_id,
69//! };
70//!
71//! let alias = owned_room_alias_id!("#example_room:example.com");
72//! let response = client.send_request(get_alias::v3::Request::new(alias)).await?;
73//!
74//! assert_eq!(response.room_id, room_id!("!n8f893n9:example.com"));
75//! # Result::<(), ruma_client::Error<_, _>>::Ok(())
76//! # };
77//! ```
78//!
79//! # Crate features
80//!
81//! The following features activate http client types in the [`http_client`] module:
82//!
83//! * `hyper`
84//! * `hyper-native-tls`
85//! * `hyper-rustls`
86//! * `reqwest` – if you use the `reqwest` library already, activate this feature and configure the
87//!   TLS backend on `reqwest` directly. If you want to use `reqwest` but don't depend on it
88//!   already, use one of the sub-features instead. For details on the meaning of these, see
89//!   [reqwest's documentation](https://docs.rs/reqwest/0.11/reqwest/#optional-features):
90//!   * `reqwest-native-tls`
91//!   * `reqwest-native-tls-alpn`
92//!   * `reqwest-native-tls-vendored`
93//!   * `reqwest-rustls-manual-roots`
94//!   * `reqwest-rustls-webpki-roots`
95//!   * `reqwest-rustls-native-roots`
96
97#![warn(missing_docs)]
98#![cfg_attr(docsrs, feature(doc_auto_cfg))]
99
100use std::{any::type_name, future::Future};
101
102#[doc(no_inline)]
103pub use ruma;
104use ruma::{
105    api::{OutgoingRequest, SendAccessToken, SupportedVersions},
106    UserId,
107};
108use tracing::{info_span, Instrument};
109
110#[cfg(feature = "client-api")]
111mod client;
112mod error;
113pub mod http_client;
114
115#[cfg(feature = "client-api")]
116pub use self::client::{Client, ClientBuilder};
117pub use self::{
118    error::Error,
119    http_client::{DefaultConstructibleHttpClient, HttpClient, HttpClientExt},
120};
121
122/// The error type for sending the request `R` with the http client `C`.
123pub type ResponseError<C, R> =
124    Error<<C as HttpClient>::Error, <R as OutgoingRequest>::EndpointError>;
125
126/// The result of sending the request `R` with the http client `C`.
127pub type ResponseResult<C, R> =
128    Result<<R as OutgoingRequest>::IncomingResponse, ResponseError<C, R>>;
129
130fn send_customized_request<'a, C, R, F>(
131    http_client: &'a C,
132    homeserver_url: &str,
133    send_access_token: SendAccessToken<'_>,
134    for_versions: &SupportedVersions,
135    request: R,
136    customize: F,
137) -> impl Future<Output = ResponseResult<C, R>> + Send + 'a
138where
139    C: HttpClient + ?Sized,
140    R: OutgoingRequest,
141    F: FnOnce(&mut http::Request<C::RequestBody>) -> Result<(), ResponseError<C, R>>,
142{
143    let http_req =
144        info_span!("serialize_request", request_type = type_name::<R>()).in_scope(move || {
145            request
146                .try_into_http_request(homeserver_url, send_access_token, for_versions)
147                .map_err(ResponseError::<C, R>::from)
148                .and_then(|mut req| {
149                    customize(&mut req)?;
150                    Ok(req)
151                })
152        });
153
154    let send_span = info_span!(
155        "send_request",
156        request_type = type_name::<R>(),
157        http_client = type_name::<C>(),
158        homeserver_url,
159    );
160
161    async move {
162        let http_res = http_client
163            .send_http_request(http_req?)
164            .instrument(send_span)
165            .await
166            .map_err(Error::Response)?;
167
168        let res =
169            info_span!("deserialize_response", response_type = type_name::<R::IncomingResponse>())
170                .in_scope(move || ruma::api::IncomingResponse::try_from_http_response(http_res))?;
171
172        Ok(res)
173    }
174}
175
176fn add_user_id_to_query<C: HttpClient + ?Sized, R: OutgoingRequest>(
177    user_id: &UserId,
178) -> impl FnOnce(&mut http::Request<C::RequestBody>) -> Result<(), ResponseError<C, R>> + '_ {
179    use assign::assign;
180    use http::uri::Uri;
181
182    move |http_request| {
183        let extra_params = serde_html_form::to_string([("user_id", user_id)]).unwrap();
184        let uri = http_request.uri_mut();
185        let new_path_and_query = match uri.query() {
186            Some(params) => format!("{}?{params}&{extra_params}", uri.path()),
187            None => format!("{}?{extra_params}", uri.path()),
188        };
189        *uri = Uri::from_parts(assign!(uri.clone().into_parts(), {
190            path_and_query: Some(new_path_and_query.parse()?),
191        }))?;
192
193        Ok(())
194    }
195}