Add Api-Logic

- THIS COMMIT IS ONLY FOR DATA SAFETY PURPOSES
- Missing: corrent auth token generation
- clean format/ "use"
- will fix both in an upcoming commit
This commit is contained in:
CramMK
2020-01-14 09:40:22 +01:00
parent af876b3519
commit 49ceef2a7f
7 changed files with 319 additions and 91 deletions

27
examples/auth.rs Normal file
View File

@@ -0,0 +1,27 @@
use std::env;
use irssi_wire::net::wire_api::{
wire_client::WireClient,
auth::Config,
conversations::Conversations,
members::Members,
self_info::SelfInfo,
};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut client = WireClient::new(
env::var("EMAIL").unwrap(),
env::var("PW").unwrap(),
Config::Default,
);
let auth_response = client
.authentification()
.await
.unwrap();
dbg!(client);
Ok(())
}

View File

@@ -4,11 +4,9 @@ use hyper::{header, Body, Client, Method, Request};
use hyper_tls::HttpsConnector; use hyper_tls::HttpsConnector;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::net::wire_api::wire_client::{WireClient};
use crate::net::wire_api::error::ApiError; use crate::net::wire_api::error::ApiError;
const USER_AGENT: &str = "irssi";
const CONTENT_TYPE: &str = "application/json";
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ConnectionUrls { pub struct ConnectionUrls {
pub websocket: String, pub websocket: String,
@@ -35,8 +33,8 @@ impl Config {
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct LoginInfo { pub struct LoginInfo {
email: String, pub email: String,
password: String, pub password: String,
} }
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
@@ -53,51 +51,39 @@ impl AuthResponse {
} }
} }
pub struct WireClient { // TODO move auth here
login_info: LoginInfo,
pub client: Client<HttpsConnector<HttpConnector>>,
pub config: Config,
}
impl WireClient { impl WireClient {
pub fn new(email: String, password: String, config: Config) -> WireClient { pub async fn authentification(&mut self) -> Result<(), ApiError> {
let https_client = Client::builder().build::<_, hyper::Body>(HttpsConnector::new());
WireClient {
login_info: LoginInfo { email, password },
client: https_client,
config: config,
}
}
pub async fn authentification(&mut self) -> Result<AuthResponse, ApiError> {
let endpoint = [ let endpoint = [
self.config.fetch().rest_url, self.config.fetch().rest_url,
"/login?persist=true".to_string(), String::from("/login?persist=true")
] ].concat();
.concat();
let json = serde_json::to_string(&self.login_info).unwrap(); let json = serde_json::to_string(&self.login_info)
.unwrap();
let auth_request = Request::builder() let auth_request = Request::builder()
.method(Method::POST) .method(Method::POST)
.uri(endpoint) .uri(endpoint)
.header(header::CONTENT_TYPE, CONTENT_TYPE) .header(header::CONTENT_TYPE, "application/json")
.header(header::USER_AGENT, USER_AGENT) .header(header::USER_AGENT, &self.user_agent)
.body(Body::from(json)) .body(Body::from(json))
.unwrap(); .unwrap();
let auth_result = self let auth_response = self.client
.client
.request(auth_request) .request(auth_request)
.await .await
.map_err(|e| ApiError::HttpError(e))?; .map_err(|e| ApiError::HttpError(e))?;
let auth_body = hyper::body::aggregate(auth_result) let body = hyper::body::aggregate(auth_response)
.await .await
.map_err(|e| ApiError::HttpError(e))?; .map_err(|e| ApiError::HttpError(e))?;
let auth_response = serde_json::from_reader(auth_body.bytes()) let parsed_json = serde_json::from_reader(body.bytes())
.map_err(|e| ApiError::JsonParseError(Box::new(e)))?; .map_err(|e| ApiError::JsonParseError(Box::new(e)))?;
Ok(auth_response) self.auth_token = Some(parsed_json);
Ok(())
} }
} }

View File

@@ -4,11 +4,10 @@ use hyper::{header, Body, Client, Method, Request};
use hyper_tls::HttpsConnector; use hyper_tls::HttpsConnector;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::net::wire_api::auth::{AuthResponse, Config, WireClient}; use crate::net::wire_api::{
use crate::net::wire_api::error::ApiError; wire_client::WireClient,
auth::AuthResponse,
const CONTENT_TYPE: &str = "application/json"; error::ApiError};
const USER_AGENT: &str = "irssi";
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct Conversations { pub struct Conversations {
@@ -75,6 +74,8 @@ pub struct ServiceRef {
provider: String, provider: String,
} }
// TODO delete this
/*
impl WireClient { impl WireClient {
pub async fn fetch_conversations( pub async fn fetch_conversations(
&mut self, &mut self,
@@ -90,8 +91,8 @@ impl WireClient {
let fetch_request = Request::builder() let fetch_request = Request::builder()
.method(Method::GET) .method(Method::GET)
.uri(endpoint) .uri(endpoint)
.header(header::CONTENT_TYPE, CONTENT_TYPE) .header(header::CONTENT_TYPE, "application/json")
.header(header::USER_AGENT, USER_AGENT) .header(header::USER_AGENT, self.user_agent)
.header(header::AUTHORIZATION, auth_token) .header(header::AUTHORIZATION, auth_token)
.body(Body::empty()) .body(Body::empty())
.unwrap(); .unwrap();
@@ -112,3 +113,4 @@ impl WireClient {
Ok(fetch_response) Ok(fetch_response)
} }
} }
*/

View File

@@ -0,0 +1,19 @@
use serde::{Serialize, Deserialize};
use crate::net::wire_api::{error::ApiError};
#[derive(Serialize, Deserialize, Debug)]
pub struct Members {
user: Option<String>,
created_by: Option<String>,
legalhold_status: Option<String>,
created_at: Option<String>,
permissions: Option<Permissions>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Permissions {
copy: Option<u32>,
#[serde(rename = "self")]
self_: Option<u32>,
}

View File

@@ -1,3 +1,7 @@
pub mod auth;
pub mod conversations;
pub mod error; pub mod error;
pub mod wire_client;
pub mod auth;
pub mod self_info;
pub mod conversations;
pub mod members;

View File

@@ -0,0 +1,58 @@
use serde::{Serialize, Deserialize};
use crate::net::wire_api::wire_client::WireClient;
use crate::net::wire_api::error::ApiError;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SelfInfo {
email: Option<String>,
handle: Option<String>,
locale: Option<String>,
managed_by: Option<String>,
accent_id: Option<u32>,
picture: Option<Vec<u32>>,
name: Option<String>,
pub team: Option<String>,
id: Option<String>,
assests: Option<Vec<UserAssets>>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UserAssets {
size: Option<String>,
key: Option<String>,
r#type: Option<String>,
}
impl WireClient {
pub async fn fetch_self(&mut self) -> Result<(), ApiError> {
self.self_info = Some(self
.api_get(String::from("/self"))
.await
.unwrap());
Ok(())
}
pub async fn fetch_conversations(&mut self) -> Result<(), ApiError> {
self.conversations = Some(self
.api_get(String::from("/conversations?size=500"))
.await
.unwrap());
Ok(())
}
pub async fn fetch_members(&mut self) -> Result<(), ApiError>{
self.members = Some(self
.api_get(String::from(
[String::from("/teams/"),
self.self_info.clone().unwrap().team.unwrap(),
String::from("/members"),].concat()
))
.await
.unwrap());
Ok(())
}
}

View File

@@ -0,0 +1,132 @@
use hyper::body::Buf;
use hyper::{
client::connect::HttpConnector,
{header, Body, Client, Method, Request}};
use hyper_tls::HttpsConnector;
use crate::net::wire_api::error::ApiError;
use crate::net::wire_api::auth::{LoginInfo, AuthResponse, Config};
use crate::net::wire_api::{
self_info::SelfInfo,
conversations::Conversations,
members::Members,
};
#[derive(Debug)]
pub struct WireClient {
pub user_agent: String,
pub login_info: LoginInfo,
pub auth_token: Option<AuthResponse>,
pub client: Client<HttpsConnector<HttpConnector>>,
pub config: Config,
pub self_info: Option<SelfInfo>,
pub conversations: Option<Conversations>,
pub members: Option<Members>
}
impl WireClient {
pub fn new(email: String, password: String, config: Config) -> WireClient {
let https_client = Client::builder().build::<_, hyper::Body>(HttpsConnector::new());
WireClient {
user_agent: String::from("irssi"),
login_info: LoginInfo { email, password },
auth_token: None,
client: https_client,
config: config,
self_info: None,
conversations: None,
members: None,
}
}
pub async fn api_post<T>(
&mut self,
endpoint: String,
body_content: String) -> Result<T, ApiError>
where T: serde::de::DeserializeOwned {
let api_request = Request::builder()
.method(Method::POST)
.uri(endpoint)
.header(header::CONTENT_TYPE, "application/json")
.header(header::USER_AGENT, &self.user_agent)
.header(header::AUTHORIZATION, self.auth_token.as_ref().unwrap().token_string())
.body(Body::from(body_content))
.unwrap();
let api_response = self.client
.request(api_request)
.await
.map_err(|e| ApiError::HttpError(e))?;
let body = hyper::body::aggregate(api_response)
.await
.map_err(|e| ApiError::HttpError(e))?;
let parsed_json = serde_json::from_reader(body.bytes())
.map_err(|e| ApiError::JsonParseError(Box::new(e)))?;
Ok(parsed_json)
}
pub async fn api_get<T>(
&mut self,
endpoint: String) -> Result<T, ApiError>
where T: serde::de::DeserializeOwned {
let api_request = Request::builder()
.method(Method::GET)
.uri([self.config.fetch().rest_url, endpoint].concat())
.header(header::CONTENT_TYPE, "application/json")
.header(header::USER_AGENT, &self.user_agent)
.header(header::AUTHORIZATION, self.auth_token.as_ref().unwrap().token_string())
.body(Body::empty())
.unwrap();
let api_response = self.client
.request(api_request)
.await
.map_err(|e| ApiError::HttpError(e))?;
let body = hyper::body::aggregate(api_response)
.await.map_err(|e| ApiError::HttpError(e))?;
let parsed_json = serde_json::from_reader(body.bytes())
.map_err(|e| ApiError::JsonParseError(Box::new(e)))?;
Ok(parsed_json)
}
/*
// TODO delete this
pub async fn authentification(&mut self) -> Result<AuthResponse, ApiError> {
let endpoint = [
self.config.fetch().rest_url,
"/login?persist=true".to_string(),
]
.concat();
let json = serde_json::to_string(&self.login_info).unwrap();
let auth_request = Request::builder()
.method(Method::POST)
.uri(endpoint)
.header(header::CONTENT_TYPE, "application/json")
.header(header::USER_AGENT, self.user_agent)
.body(Body::from(json))
.unwrap();
let auth_result = self
.client
.request(auth_request)
.await
.map_err(|e| ApiError::HttpError(e))?;
let auth_body = hyper::body::aggregate(auth_result)
.await
.map_err(|e| ApiError::HttpError(e))?;
let auth_response = serde_json::from_reader(auth_body.bytes())
.map_err(|e| ApiError::JsonParseError(Box::new(e)))?;
Ok(auth_response)
}
*/
}