Compare commits
No commits in common. "1e2a00edf3cd37d8049da0fb26446bda04f03a0c" and "a7085d3334691981fffb0d38b42697b51f9e17d6" have entirely different histories.
1e2a00edf3
...
a7085d3334
3 changed files with 24 additions and 186 deletions
|
@ -28,7 +28,7 @@
|
|||
- [ ] 5.3.6.2 Third-party ID
|
||||
- [ ] 5.3.6.3 Phone number
|
||||
- [ ] 5.4 Login
|
||||
- [x] 5.4.1 ~~GET /_matrix/client/r0/login~~
|
||||
- [ ] 5.4.1 GET /_matrix/client/r0/login
|
||||
- [ ] 5.4.2 POST /_matrix/client/r0/login
|
||||
- [ ] 5.4.3 POST /_matrix/client/r0/logout
|
||||
- [ ] 5.4.4 POST /_matrix/client/r0/logout/all
|
||||
|
|
|
@ -1,25 +1,16 @@
|
|||
use crate::api::methods::{login::*, sync::SyncResponse};
|
||||
use crate::api::methods::sync::SyncResponse;
|
||||
use reqwest::{
|
||||
header::{HeaderMap, HeaderValue, CONTENT_TYPE, USER_AGENT},
|
||||
Client as reqwest_client, Response, StatusCode,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
error::Error,
|
||||
fmt,
|
||||
sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
},
|
||||
thread, time,
|
||||
};
|
||||
use std::{collections::HashMap, error::Error, fmt, time};
|
||||
use url::{ParseError, Url};
|
||||
|
||||
#[cfg(test)]
|
||||
use mockito;
|
||||
|
||||
const V2_API_PATH: &str = "/_matrix/client/r0";
|
||||
const SUPPORTED_VERSION: &str = "r0.5.0";
|
||||
|
||||
#[derive(Debug)]
|
||||
|
@ -80,18 +71,18 @@ pub struct SupportedSpecs {
|
|||
#[derive(Deserialize)]
|
||||
pub struct DiscoveryInformation {
|
||||
#[serde(rename = "m.homeserver")]
|
||||
pub homeserver: HomeserverInformation,
|
||||
pub identity_server: Option<IdentityServerInformation>,
|
||||
homeserver: HomeserverInformation,
|
||||
identity_server: Option<IdentityServerInformation>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct HomeserverInformation {
|
||||
pub base_url: String,
|
||||
base_url: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct IdentityServerInformation {
|
||||
pub base_url: String,
|
||||
base_url: String,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
|
@ -175,7 +166,7 @@ impl Client {
|
|||
&self,
|
||||
method: MatrixHTTPMethod,
|
||||
path: &str,
|
||||
content: Option<Value>,
|
||||
content: Option<String>,
|
||||
query_params: Option<HashMap<String, String>>,
|
||||
headers: Option<HeaderMap>,
|
||||
) -> Result<Response, Box<dyn std::error::Error>> {
|
||||
|
@ -184,7 +175,6 @@ impl Client {
|
|||
|
||||
#[cfg(test)]
|
||||
let url = &mockito::server_url();
|
||||
|
||||
#[cfg(not(test))]
|
||||
let url = &self.homeserver_url;
|
||||
|
||||
|
@ -216,7 +206,7 @@ impl Client {
|
|||
request = request.headers(headers).query(&query_params);
|
||||
|
||||
if let Some(content) = content {
|
||||
request = request.body(content.to_string());
|
||||
request = request.body(content);
|
||||
}
|
||||
|
||||
loop {
|
||||
|
@ -228,17 +218,16 @@ impl Client {
|
|||
if res.status().is_success() {
|
||||
return Ok(res);
|
||||
} else if res.status() == StatusCode::TOO_MANY_REQUESTS {
|
||||
let mut body: &Value = &res.json()?;
|
||||
let mut body: HashMap<String, String> = res.json()?;
|
||||
if let Some(value) = body.get("error") {
|
||||
body = value;
|
||||
body = serde_json::from_str(value)?;
|
||||
}
|
||||
|
||||
std::thread::sleep(time::Duration::from_millis(
|
||||
body.get("retry_after_ms").map_or_else(
|
||||
|| self.default_492_wait_ms,
|
||||
|v| v.as_u64().unwrap_or_else(|| self.default_492_wait_ms),
|
||||
),
|
||||
));
|
||||
if let Some(value) = body.get("retry_after_ms") {
|
||||
std::thread::sleep(time::Duration::from_millis(value.parse::<u64>()?));
|
||||
} else {
|
||||
std::thread::sleep(time::Duration::from_millis(self.default_492_wait_ms));
|
||||
}
|
||||
} else {
|
||||
return Err(Box::from(ResponseError {
|
||||
code: res.status(),
|
||||
|
@ -300,108 +289,6 @@ impl Client {
|
|||
}
|
||||
}
|
||||
|
||||
// Holds implementation for Section 5.4, Login
|
||||
impl Client {
|
||||
/// Implementation of [Section 5.4.1 **GET** `/_matrix/client/r0/login`](https://matrix.org/docs/spec/client_server/r0.5.0#get-matrix-client-r0-login).
|
||||
pub fn login_flows(&self) -> Result<ValidLoginFlows, Box<dyn Error>> {
|
||||
Ok(self
|
||||
.send(
|
||||
MatrixHTTPMethod::Get,
|
||||
"/_matrix/client/r0/login",
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)?
|
||||
.json()?)
|
||||
}
|
||||
|
||||
/// Implementation of password-based login for
|
||||
/// [5.4.2 **POST** `/_matrix/client/r0/login`](https://matrix.org/docs/spec/client_server/r0.5.0#post-matrix-client-r0-login)
|
||||
///
|
||||
/// If a specific device ID is specified, then the server will attempt to
|
||||
/// use it. If an existing device ID is used, then any previously assigned
|
||||
/// access tokens to that device ID may be invalidated. If the device ID
|
||||
/// does not exist, then it will be created. If none is provided, then the
|
||||
/// server will generate one.
|
||||
///
|
||||
/// You may specify a device display name if the provided device ID is not
|
||||
/// known. It is ignored if the device ID already exists.
|
||||
pub fn login_password(
|
||||
&self,
|
||||
identifier: IdentifierType,
|
||||
password: &str,
|
||||
device_id: Option<&str>,
|
||||
initial_device_display_name: Option<&str>,
|
||||
) -> Result<LoginResponse, Box<dyn Error>> {
|
||||
self.login(
|
||||
json!({
|
||||
"type": "m.login.password",
|
||||
"password": password,
|
||||
}),
|
||||
identifier,
|
||||
device_id,
|
||||
initial_device_display_name,
|
||||
)
|
||||
}
|
||||
|
||||
/// Implementation of token-based login for
|
||||
/// [5.4.2 **POST** `/_matrix/client/r0/login`](https://matrix.org/docs/spec/client_server/r0.5.0#post-matrix-client-r0-login)
|
||||
///
|
||||
/// If a specific device ID is specified, then the server will attempt to
|
||||
/// use it. If an existing device ID is used, then any previously assigned
|
||||
/// access tokens to that device ID may be invalidated. If the device ID
|
||||
/// does not exist, then it will be created. If none is provided, then the
|
||||
/// server will generate one.
|
||||
///
|
||||
/// You may specify a device display name if the provided device ID is not
|
||||
/// known. It is ignored if the device ID already exists.
|
||||
pub fn login_token(
|
||||
&self,
|
||||
identifier: IdentifierType,
|
||||
password: &str,
|
||||
device_id: Option<&str>,
|
||||
initial_device_display_name: Option<&str>,
|
||||
) -> Result<LoginResponse, Box<dyn Error>> {
|
||||
self.login(
|
||||
json!({
|
||||
"type": "m.login.token",
|
||||
"token": password,
|
||||
}),
|
||||
identifier,
|
||||
device_id,
|
||||
initial_device_display_name,
|
||||
)
|
||||
}
|
||||
|
||||
fn login(
|
||||
&self,
|
||||
body: Value,
|
||||
identifier: IdentifierType,
|
||||
device_id: Option<&str>,
|
||||
initial_device_display_name: Option<&str>,
|
||||
) -> Result<LoginResponse, Box<dyn Error>> {
|
||||
let mut body = body;
|
||||
body["identifier"] = json!(identifier);
|
||||
|
||||
if let Some(id) = device_id {
|
||||
body["device_id"] = json!(id);
|
||||
if let Some(display_name) = initial_device_display_name {
|
||||
body["initial_device_display_name"] = json!(display_name);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(self
|
||||
.send(
|
||||
MatrixHTTPMethod::Post,
|
||||
"/_matrix/client/r0/login",
|
||||
Some(body),
|
||||
None,
|
||||
None,
|
||||
)?
|
||||
.json()?)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
@ -453,43 +340,6 @@ mod tests {
|
|||
assert!(resp.unstable_features.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn send_handles_too_many_requests() {
|
||||
let _mock_version_check = mock("GET", "/_matrix/client/versions")
|
||||
.with_body(r#"{"versions": ["r0.5.0"]}"#)
|
||||
.create();
|
||||
|
||||
let _m2 = mock("GET", "/hello")
|
||||
.with_body(
|
||||
r#"{
|
||||
"errcode": "M_LIMIT_EXCEEDED",
|
||||
"error": "Too many requests",
|
||||
"retry_after_ms": 2000
|
||||
}"#,
|
||||
)
|
||||
.with_status(429)
|
||||
.create();
|
||||
|
||||
// Run request in separate thread. Once async lands use async/await
|
||||
thread::spawn(|| {
|
||||
let resp: Value = Client::new("http://dummy.website", None, None, None)
|
||||
.expect("failed to get valid client")
|
||||
.send(MatrixHTTPMethod::Get, "/hello", None, None, None)
|
||||
.expect("failed to unwrap Response")
|
||||
.json()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(dbg!(resp)["hello"], "world");
|
||||
});
|
||||
|
||||
// Override 429 response with valid response after initial request
|
||||
// returns a 429. This should really be done with a synchronization
|
||||
// primitive (e.g. condvar) but I don't know how to do that.
|
||||
thread::sleep(time::Duration::from_secs(1));
|
||||
let _m = mock("GET", "/hello")
|
||||
.with_body(r#"{"hello": "world"}"#)
|
||||
.create();
|
||||
}
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub struct ApiError {}
|
||||
|
|
|
@ -1,34 +1,22 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
|
||||
// 5.4.1 GET /_matrix/client/r0/login
|
||||
use serde::Deserialize;
|
||||
|
||||
/// Response for 5.4.1: GET /_matrix/client/r0/login
|
||||
#[derive(Deserialize)]
|
||||
pub struct ValidLoginFlows {
|
||||
pub flows: Option<LoginFlow>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct LoginFlow {
|
||||
pub r#type: Option<String>,
|
||||
}
|
||||
|
||||
// 5.4.2 POST /_matrix/client/r0/login
|
||||
/// Request helper for 5.4.2: POST /_matrix/client/r0/login
|
||||
pub struct LoginRequest {
|
||||
|
||||
/// Known identifier types for authentication methods. See [Section 5.3.6](https://matrix.org/docs/spec/client_server/r0.5.0#identifier-types)
|
||||
/// for more details.
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub enum IdentifierType {
|
||||
#[serde(rename = "m.id.user")]
|
||||
User,
|
||||
#[serde(rename = "m.id.thirdparty")]
|
||||
ThirdParty,
|
||||
#[serde(rename = "m.id.phone")]
|
||||
Phone
|
||||
}
|
||||
|
||||
|
||||
/// Response for a valid login from 5.4.2: POST /_matrix/client/r0/login
|
||||
#[derive(Deserialize)]
|
||||
/// Response object for a valid login from 5.4.2: POST /_matrix/client/r0/login
|
||||
pub struct LoginResponse {
|
||||
pub user_id: Option<String>,
|
||||
pub access_token: Option<String>,
|
||||
|
@ -37,5 +25,5 @@ pub struct LoginResponse {
|
|||
pub well_known: Option<DiscoveryInformation>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct DiscoveryInformation {}
|
||||
pub struct DiscoveryInformation {
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue