Replace hyper with reqwest (#7)

An old version of hyper was used before (0.8.0), in the process of updating to hyper 0.12.11, found this higher-level replacement/wrapper, reqwest 0.9.4 which is simpler to use than the latest hyper and serves the purpose of a simple HTTP client well

* Begin updating to hyper 0.12.11

https://github.com/iceiix/steven/issues/4#issuecomment-425759778

* Use type variables for hyper::Client

* Fix setting header syntax, Content-Type: application/json, 17->13

* Parse strings into URLs with url.parse::<hyper::Uri>().unwrap()

b20971cb4e/examples/client.rs (L25)

* Use hyper::Request::post() then client.request() since client.post() removed

* wait() on the ResponseFuture to get the Result

* try! to unwrap the Result

* status() is now a method

* Concatenate body chunks unwrap into bytes, then parse JSON from byte slice, instead of from_reader which didn't compile

* Replace send() with wait() on ResponseFuture

* Parse HeaderValue to u64

* Slices implement std::io::Read trait

* Read into_bytes() instead of read_to_end()

* Disable boxed logger for now to workaround 'expected function, found macro'

* Remove unnecessary mutability, warnings

* Hack to parse twice to avoid double move

* Use hyper-rustls pure Rust implementation for TLS for HTTPS in hyper

* Start converting to reqwest: add Protocol::Error and reqwest::Error conversion

* Use reqwest, replacing hyper, in protocol

* Convert resources to use reqwest instead of hyper

* Convert skin download to reqwest, instead of hyper

* Remove hyper

* Revert unnecessary variable name change req/body to reduce diff

* Revert unnecessary whitespace change to reduce diff, align indentation on .

* Fix authenticating to server, wrong method and join URL

* Update Cargo.lock
This commit is contained in:
iceiix 2018-10-27 17:03:34 -07:00 committed by GitHub
parent de6cd2044e
commit b17f296ab4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 791 additions and 119 deletions

808
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -13,7 +13,7 @@ opt-level = 1
sha-1 = "0.8.0"
sdl2 = "0.31.0"
byteorder = "1.2.6"
hyper = "0.8.0"
reqwest = "0.9.4"
serde = "1.0.79"
serde_json = "1.0.31"
flate2 = "1.0.2"

View File

@ -26,7 +26,7 @@ use render;
use format::{Component, TextComponent, Color};
const FILTERED_CRATES: &'static [&'static str] = &[
"hyper",
//"reqwest", // TODO: needed?
"mime",
];

View File

@ -24,7 +24,7 @@ extern crate byteorder;
extern crate serde_json;
extern crate openssl;
extern crate sha1;
extern crate hyper;
extern crate reqwest;
extern crate flate2;
extern crate rand;
extern crate hex;
@ -179,7 +179,8 @@ fn main() {
let proxy = console::ConsoleProxy::new(con.clone());
log::set_boxed_logger(Box::new(proxy)).unwrap();
// TODO: fix error[E0423]: expected function, found macro `log::set_boxed_logger`
//log::set_boxed_logger(Box::new(proxy)).unwrap();
log::set_max_level(log::LevelFilter::Trace);
info!("Starting steven");

View File

@ -16,7 +16,7 @@
use openssl::crypto::symm;
use serde_json;
use hyper;
use reqwest;
pub mod mojang;
@ -690,7 +690,7 @@ pub enum Error {
Disconnect(format::Component),
IOError(io::Error),
Json(serde_json::Error),
Hyper(hyper::Error),
Reqwest(reqwest::Error),
}
impl convert::From<io::Error> for Error {
@ -705,9 +705,9 @@ impl convert::From<serde_json::Error> for Error {
}
}
impl convert::From<hyper::Error> for Error {
fn from(e: hyper::Error) -> Error {
Error::Hyper(e)
impl convert::From<reqwest::Error> for Error {
fn from(e: reqwest::Error) -> Error {
Error::Reqwest(e)
}
}
@ -718,7 +718,7 @@ impl ::std::error::Error for Error {
Error::Disconnect(_) => "Disconnect",
Error::IOError(ref e) => e.description(),
Error::Json(ref e) => e.description(),
Error::Hyper(ref e) => e.description(),
Error::Reqwest(ref e) => e.description(),
}
}
}
@ -730,7 +730,7 @@ impl ::std::fmt::Display for Error {
Error::Disconnect(ref val) => write!(f, "{}", val),
Error::IOError(ref e) => e.fmt(f),
Error::Json(ref e) => e.fmt(f),
Error::Hyper(ref e) => e.fmt(f),
Error::Reqwest(ref e) => e.fmt(f),
}
}
}

View File

@ -14,7 +14,7 @@
use sha1::{self, Digest};
use serde_json;
use hyper;
use reqwest;
#[derive(Clone, Debug)]
pub struct Profile {
@ -40,11 +40,11 @@ impl Profile {
}});
let req = try!(serde_json::to_string(&req_msg));
let client = hyper::Client::new();
let res = try!(client.post(LOGIN_URL)
.body(&req)
.header(hyper::header::ContentType("application/json".parse().unwrap()))
.send());
let client = reqwest::Client::new();
let res = client.post(LOGIN_URL)
.header(reqwest::header::CONTENT_TYPE, "application/json")
.body(req)
.send()?;
let ret: serde_json::Value = try!(serde_json::from_reader(res));
if let Some(error) = ret.get("error").and_then(|v| v.as_str()) {
@ -68,18 +68,19 @@ impl Profile {
});
let req = try!(serde_json::to_string(&req_msg));
let client = hyper::Client::new();
let res = try!(client.post(VALIDATE_URL)
.body(&req)
.header(hyper::header::ContentType("application/json".parse().unwrap()))
.send());
let client = reqwest::Client::new();
let res = client.post(VALIDATE_URL)
.header(reqwest::header::CONTENT_TYPE, "application/json")
.body(req)
.send()?;
if res.status != hyper::status::StatusCode::NoContent {
if res.status() != reqwest::StatusCode::NO_CONTENT {
let req = try!(serde_json::to_string(&req_msg)); // TODO: fix parsing twice to avoid move
// Refresh needed
let res = try!(client.post(REFRESH_URL)
.body(&req)
.header(hyper::header::ContentType("application/json".parse().unwrap()))
.send());
let res = client.post(REFRESH_URL)
.header(reqwest::header::CONTENT_TYPE, "application/json")
.body(req)
.send()?;
let ret: serde_json::Value = try!(serde_json::from_reader(res));
if let Some(error) = ret.get("error").and_then(|v| v.as_str()) {
@ -126,13 +127,13 @@ impl Profile {
});
let join = serde_json::to_string(&join_msg).unwrap();
let client = hyper::Client::new();
let res = try!(client.post(JOIN_URL)
.body(&join)
.header(hyper::header::ContentType("application/json".parse().unwrap()))
.send());
let client = reqwest::Client::new();
let res = client.post(JOIN_URL)
.header(reqwest::header::CONTENT_TYPE, "application/json")
.body(join)
.send()?;
if res.status == hyper::status::StatusCode::NoContent {
if res.status() == reqwest::StatusCode::NO_CONTENT {
Ok(())
} else {
Err(super::Error::Err("Failed to auth with server".to_owned()))

View File

@ -837,8 +837,8 @@ impl TextureManager {
}
fn process_skins(recv: mpsc::Receiver<String>, reply: mpsc::Sender<(String, Option<image::DynamicImage>)>) {
use hyper;
let client = hyper::Client::new();
use reqwest;
let client = reqwest::Client::new();
loop {
let hash = match recv.recv() {
Ok(val) => val,
@ -856,7 +856,7 @@ impl TextureManager {
}
}
fn obtain_skin(client: &::hyper::Client, hash: &str) -> Result<image::DynamicImage, ::std::io::Error> {
fn obtain_skin(client: &::reqwest::Client, hash: &str) -> Result<image::DynamicImage, ::std::io::Error> {
use std::io::Read;
use std::fs;
use std::path::Path;
@ -871,14 +871,22 @@ impl TextureManager {
try!(file.read_to_end(&mut buf));
} else {
// Need to download it
let url = format!("http://textures.minecraft.net/texture/{}", hash);
let mut res = match client.get(&url).send() {
let url = &format!("http://textures.minecraft.net/texture/{}", hash);
let mut res = match client.get(url).send() {
Ok(val) => val,
Err(err) => {
return Err(Error::new(ErrorKind::ConnectionAborted, err));
}
};
try!(res.read_to_end(&mut buf));
let mut buf = vec![];
match res.read_to_end(&mut buf) {
Ok(_) => {},
Err(err) => {
// TODO: different error for failure to read?
return Err(Error::new(ErrorKind::InvalidData, err));
}
}
// Save to cache
let mut file = try!(fs::File::create(cache_path));
try!(file.write_all(&buf));

View File

@ -24,7 +24,7 @@ use std::collections::HashMap;
use std::hash::BuildHasherDefault;
use serde_json;
use hyper;
use reqwest;
use zip;
use types::hash::FNVHash;
@ -285,15 +285,15 @@ impl Manager {
self.vanilla_assets_chan = Some(recv);
}
thread::spawn(move || {
let client = hyper::Client::new();
let client = reqwest::Client::new();
if fs::metadata(&location).is_err(){
fs::create_dir_all(location.parent().unwrap()).unwrap();
let res = client.get(ASSET_INDEX_URL)
.send()
.unwrap();
let length = *res.headers.get::<hyper::header::ContentLength>().unwrap();
Self::add_task(&progress_info, "Downloading Asset Index", &*location.to_string_lossy(), *length);
let length = res.headers().get(reqwest::header::CONTENT_LENGTH).unwrap().to_str().unwrap().parse::<u64>().unwrap();
Self::add_task(&progress_info, "Downloading Asset Index", &*location.to_string_lossy(), length);
{
let mut file = fs::File::create(format!("index-{}.tmp", ASSET_VERSION)).unwrap();
let mut progress = ProgressRead {
@ -354,15 +354,15 @@ impl Manager {
let progress_info = self.vanilla_progress.clone();
thread::spawn(move || {
let client = hyper::Client::new();
let client = reqwest::Client::new();
let res = client.get(VANILLA_CLIENT_URL)
.send()
.unwrap();
let mut file = fs::File::create(format!("{}.tmp", RESOURCES_VERSION)).unwrap();
let length = *res.headers.get::<hyper::header::ContentLength>().unwrap();
let length = res.headers().get(reqwest::header::CONTENT_LENGTH).unwrap().to_str().unwrap().parse::<u64>().unwrap();
let task_file = format!("./resources-{}", RESOURCES_VERSION);
Self::add_task(&progress_info, "Downloading Core Assets", &task_file, *length);
Self::add_task(&progress_info, "Downloading Core Assets", &task_file, length);
{
let mut progress = ProgressRead {
read: res,