mnml/svt/src/main.rs
2019-09-10 16:44:36 +10:00

76 lines
2.0 KiB
Rust

extern crate reqwest;
extern crate rand;
extern crate ws;
use std::thread;
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use reqwest::header;
use std::iter;
use ws::{connect, CloseCode, Message, Handler, Sender, Result, Request, Response};
struct Bot {
out: Sender,
token: String,
}
impl Handler for Bot {
fn build_request(&mut self, url: &url::Url) -> Result<Request> {
let mut req = Request::from_url(url)?;
let headers = req.headers_mut();
headers.push(("x-auth-token".to_string(), Vec::from(self.token.clone())));
Ok(req)
}
fn on_open(&mut self, _: ws::Handshake) -> ws::Result<()> {
println!("websocket connected");
Ok(())
}
}
fn main() {
let mut rng = thread_rng();
let name: String = iter::repeat(()).map(|()| rng.sample(Alphanumeric)).take(12).collect();
let password: String = iter::repeat(()).map(|()| rng.sample(Alphanumeric)).take(12).collect();
let mut headers = header::HeaderMap::new();
headers.insert(header::CONTENT_TYPE, header::HeaderValue::from_static("application/json"));
let client = reqwest::Client::builder()
.cookie_store(true)
.default_headers(headers)
.build()
.unwrap();
let register_body = format!("{{ \"name\": {:?}, \"password\": {:?}, \"code\": \"grep842\" }}", name, password);
println!("{:?}", register_body);
let account = client.post("http://localhost/api/account/register")
.body(register_body)
.send()
.unwrap();
println!("{:?}", account.headers().get("set-cookie"));
// Client thread
let client = thread::Builder::new().name(name).spawn(move || {
connect("ws://localhost/api/ws", |out| {
let token_cookie = account.cookies()
.find(|c| c.name() == "x-auth-token")
.unwrap();
Bot {
out: out,
token: token_cookie.value().to_string(),
}
}).unwrap()
}).unwrap();
client.join().unwrap()
}