You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
80 lines
1.9 KiB
80 lines
1.9 KiB
use crate::{ |
|
MASTER_SERVER, |
|
MASTER_PORT, |
|
contracts::*, |
|
}; |
|
use reqwest::{ |
|
Client, |
|
Url, |
|
Response, |
|
RequestBuilder |
|
}; |
|
|
|
|
|
pub struct ClientHandler { |
|
base_url: Url, |
|
client: Client, |
|
cli_info: ClientInfo, |
|
password: Option<String> |
|
} |
|
|
|
impl ClientHandler { |
|
pub fn new() -> Self { |
|
Self { |
|
client: Client::new(), |
|
cli_info: ClientInfo::gather(), |
|
base_url: Url::parse( |
|
&format!("http://{}:{}", MASTER_SERVER, MASTER_PORT) |
|
).unwrap(), |
|
password: None |
|
} |
|
} |
|
|
|
pub fn new_pwd(password: String) -> Self { |
|
let mut instance = Self::new(); |
|
instance.password = Some(password); |
|
instance |
|
} |
|
|
|
fn set_pwd(&self, rb: RequestBuilder) -> RequestBuilder { |
|
match &self.password { |
|
Some(p) => rb.bearer_auth(p), |
|
None => rb |
|
} |
|
} |
|
|
|
fn build_get(&self, url: &str) -> RequestBuilder { |
|
let rb = self.client.get(self.base_url.join(url).unwrap()); |
|
self.set_pwd(rb) |
|
} |
|
|
|
fn build_post(&self, url: &str) -> RequestBuilder { |
|
let rb = self.client.post(self.base_url.join(url).unwrap()); |
|
self.set_pwd(rb) |
|
} |
|
|
|
pub async fn init(&self) -> RawMsg { |
|
let response: Response = self.build_post("/new") |
|
.json(&self.cli_info.as_message()) |
|
.send() |
|
.await |
|
.unwrap(); |
|
let msg = response |
|
.json::<Message<RawMsg>>() |
|
.await |
|
.unwrap(); |
|
msg.into_item().into_owned() |
|
} |
|
|
|
pub async fn list(&self) -> Vec<ClientInfo> { |
|
let response: Response = self.build_get("/ls") |
|
.send() |
|
.await |
|
.unwrap(); |
|
let msg = response |
|
.json::<Message<Vec<ClientInfo>>>() |
|
.await |
|
.unwrap(); |
|
msg.into_item().into_owned() |
|
} |
|
}
|
|
|