Skip to main content

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::{MatrixVersion, client::alias::get_alias},
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_cfg))]
99
100use std::{any::type_name, future::Future};
101
102#[doc(no_inline)]
103pub use ruma;
104use ruma::api::{
105    OutgoingRequest,
106    auth_scheme::{AuthScheme, SendAccessToken},
107    path_builder::PathBuilder,
108};
109use tracing::{Instrument, info_span};
110
111#[cfg(feature = "client-api")]
112mod client;
113mod error;
114pub mod http_client;
115
116#[cfg(feature = "client-api")]
117pub use self::client::{Client, ClientBuilder, SupportedPathBuilder, TokenMode};
118pub use self::{
119    error::Error,
120    http_client::{DefaultConstructibleHttpClient, HttpClient, HttpClientExt},
121};
122
123/// The error type for sending the request `R` with the http client `C`.
124pub type ResponseError<C, R> =
125    Error<<C as HttpClient>::Error, <R as OutgoingRequest>::EndpointError>;
126
127/// The result of sending the request `R` with the http client `C`.
128pub type ResponseResult<C, R> =
129    Result<<R as OutgoingRequest>::IncomingResponse, ResponseError<C, R>>;
130
131fn send_customized_request<'a, C, R, F>(
132    http_client: &'a C,
133    homeserver_url: &str,
134    send_access_token: SendAccessToken<'a>,
135    path_builder_input: <R::PathBuilder as PathBuilder>::Input<'_>,
136    request: R,
137    customize: F,
138) -> impl Future<Output = ResponseResult<C, R>> + Send + 'a + use<'a, C, R, F>
139where
140    C: HttpClient + ?Sized,
141    R: OutgoingRequest,
142    R::Authentication: AuthScheme<Input<'a> = SendAccessToken<'a>>,
143    F: FnOnce(&mut http::Request<C::RequestBody>) -> Result<(), ResponseError<C, R>>,
144{
145    let http_req =
146        info_span!("serialize_request", request_type = type_name::<R>()).in_scope(move || {
147            request
148                .try_into_http_request(homeserver_url, send_access_token, path_builder_input)
149                .map_err(ResponseError::<C, R>::from)
150                .and_then(|mut req| {
151                    customize(&mut req)?;
152                    Ok(req)
153                })
154        });
155
156    let send_span = info_span!(
157        "send_request",
158        request_type = type_name::<R>(),
159        http_client = type_name::<C>(),
160        homeserver_url,
161    );
162
163    async move {
164        let http_res = http_client
165            .send_http_request(http_req?)
166            .instrument(send_span)
167            .await
168            .map_err(Error::Response)?;
169
170        let res =
171            info_span!("deserialize_response", response_type = type_name::<R::IncomingResponse>())
172                .in_scope(move || ruma::api::IncomingResponse::try_from_http_response(http_res))?;
173
174        Ok(res)
175    }
176}