ruma_client/client/
builder.rs1use std::sync::{Arc, Mutex};
2
3use ruma::api::{
4 client::discovery::get_supported_versions, MatrixVersion, SendAccessToken, SupportedVersions,
5};
6
7use super::{Client, ClientData};
8use crate::{DefaultConstructibleHttpClient, Error, HttpClient, HttpClientExt};
9
10pub struct ClientBuilder {
14 homeserver_url: Option<String>,
15 access_token: Option<String>,
16 supported_matrix_versions: Option<SupportedVersions>,
17}
18
19impl ClientBuilder {
20 pub(super) fn new() -> Self {
21 Self { homeserver_url: None, access_token: None, supported_matrix_versions: None }
22 }
23
24 pub fn homeserver_url(self, url: String) -> Self {
29 Self { homeserver_url: Some(url), ..self }
30 }
31
32 pub fn access_token(self, access_token: Option<String>) -> Self {
34 Self { access_token, ..self }
35 }
36
37 pub fn supported_matrix_versions(self, versions: SupportedVersions) -> Self {
43 Self { supported_matrix_versions: Some(versions), ..self }
44 }
45
46 pub async fn build<C>(self) -> Result<Client<C>, Error<C::Error, ruma::api::client::Error>>
53 where
54 C: DefaultConstructibleHttpClient,
55 {
56 self.http_client(C::default()).await
57 }
58
59 pub async fn http_client<C>(
65 self,
66 http_client: C,
67 ) -> Result<Client<C>, Error<C::Error, ruma::api::client::Error>>
68 where
69 C: HttpClient,
70 {
71 let homeserver_url = self
72 .homeserver_url
73 .expect("homeserver URL has to be set prior to calling .build() or .http_client()");
74
75 let supported_matrix_versions = match self.supported_matrix_versions {
76 Some(versions) => versions,
77 None => http_client
78 .send_matrix_request(
79 &homeserver_url,
80 SendAccessToken::None,
81 &SupportedVersions {
82 versions: [MatrixVersion::V1_0].into(),
83 features: Default::default(),
84 },
85 get_supported_versions::Request::new(),
86 )
87 .await?
88 .as_supported_versions(),
89 };
90
91 Ok(Client(Arc::new(ClientData {
92 homeserver_url,
93 http_client,
94 access_token: Mutex::new(self.access_token),
95 supported_matrix_versions,
96 })))
97 }
98}