cargo fmt

This commit is contained in:
nyyu 2018-06-09 09:07:41 +02:00
parent c3b986ad2d
commit ec0aedbdfc

View File

@ -1,33 +1,37 @@
#[macro_use] extern crate serde_derive;
#[macro_use] extern crate log;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate log;
extern crate reqwest;
extern crate serde;
#[macro_use] extern crate serde_json;
extern crate simple_logger;
extern crate select;
#[macro_use]
extern crate serde_json;
extern crate regex;
#[macro_use] extern crate lazy_static;
extern crate select;
extern crate simple_logger;
#[macro_use]
extern crate lazy_static;
extern crate winreg;
use std::collections::BTreeMap;
use std::{io, fs, thread, time};
use std::path::PathBuf;
use regex::Regex;
use reqwest::header::{Headers, UserAgent};
use select::document::Document;
use select::predicate::{Class, Name};
use regex::Regex;
use serde_json::Value;
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::{fs, io, thread, time};
use time::Duration;
use winreg::RegKey;
#[derive(Deserialize)]
struct Realm {
v: String
v: String,
}
#[derive(Deserialize)]
struct Champion {
data: BTreeMap<String, ChampInfo>
data: BTreeMap<String, ChampInfo>,
}
#[derive(Deserialize)]
@ -44,18 +48,25 @@ struct ItemSet {
mode: String,
priority: bool,
sortrank: u32,
blocks: Vec<Value>
blocks: Vec<Value>,
}
const USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0";
const USER_AGENT: &str =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0";
const LOL_CHAMPS_DIR: &str = ".\\champs";
const CONSUMABLES: [u32; 9] = [2003, 2004, 2055, 2031, 2032, 2033, 2138, 2140, 2139];
const TRINKETS: [u32; 3] = [3340, 3364, 3363];
const ITEM_TYPES: &'static [(&str, [&str; 2]); 4] = &[
("Most Frequent Starters", ["firstItems", "mostGames"]),
("Highest Win % Starters", ["firstItems", "highestWinPercent"]),
(
"Highest Win % Starters",
["firstItems", "highestWinPercent"],
),
("Most Frequent Core Build", ["items", "mostGames"]),
("Highest Win % Core Build", ["firstItems", "highestWinPercent"])
(
"Highest Win % Core Build",
["firstItems", "highestWinPercent"],
),
];
fn main() {
@ -65,7 +76,7 @@ fn main() {
let lol_champs_dir = match lol_champ_dir() {
Ok(x) => x,
Err(_e) => PathBuf::from(LOL_CHAMPS_DIR)
Err(_e) => PathBuf::from(LOL_CHAMPS_DIR),
};
let mut headers = Headers::new();
@ -74,12 +85,26 @@ fn main() {
let client = reqwest::Client::builder()
.default_headers(headers)
.timeout(Duration::from_secs(10))
.build().unwrap();
.build()
.unwrap();
let realm: Realm = client.get("https://ddragon.leagueoflegends.com/realms/euw.json").send().unwrap().json().unwrap();
let realm: Realm = client
.get("https://ddragon.leagueoflegends.com/realms/euw.json")
.send()
.unwrap()
.json()
.unwrap();
info!("LoL version: {}", realm.v);
let champion: Champion = client.get(&format!("https://ddragon.leagueoflegends.com/cdn/{}/data/en_US/champion.json", realm.v)).send().unwrap().json().unwrap();
let champion: Champion = client
.get(&format!(
"https://ddragon.leagueoflegends.com/cdn/{}/data/en_US/champion.json",
realm.v
))
.send()
.unwrap()
.json()
.unwrap();
info!("LoL numbers of champs: {}", champion.data.len());
let (champs, patch) = get_champs_with_positions_and_patch(&client);
@ -101,19 +126,48 @@ fn main() {
}
}
fn get_champs_with_positions_and_patch(client: &reqwest::Client) -> (BTreeMap<String, Vec<String>>, String) {
let page = client.get("https://champion.gg").send().unwrap().text().unwrap();
fn get_champs_with_positions_and_patch(
client: &reqwest::Client,
) -> (BTreeMap<String, Vec<String>>, String) {
let page = client
.get("https://champion.gg")
.send()
.unwrap()
.text()
.unwrap();
let document = Document::from(&*page);
let patch = document.find(Class("analysis-holder")).next().unwrap().find(Name("strong")).next().unwrap().text();
let patch = document
.find(Class("analysis-holder"))
.next()
.unwrap()
.find(Name("strong"))
.next()
.unwrap()
.text();
let mut champions = BTreeMap::new();
for node in document.find(Class("champ-height")) {
let id = node.find(Class("home-champion")).next().unwrap().attr("class").unwrap().split(' ').last().unwrap().to_string();
let id = node.find(Class("home-champion"))
.next()
.unwrap()
.attr("class")
.unwrap()
.split(' ')
.last()
.unwrap()
.to_string();
let positions = node.find(Name("a"))
.skip(1)
.map(|x| x.attr("href").unwrap().split('/').last().unwrap().to_string())
.collect();
.skip(1)
.map(|x| {
x.attr("href")
.unwrap()
.split('/')
.last()
.unwrap()
.to_string()
})
.collect();
champions.insert(id, positions);
}
@ -121,7 +175,13 @@ fn get_champs_with_positions_and_patch(client: &reqwest::Client) -> (BTreeMap<St
}
fn get_champ_data(id: &str, position: &str, client: &reqwest::Client) -> Option<Value> {
let mut req = client.get(&format!("https://champion.gg/champion/{}/{}?league=", id, position)).send().unwrap();
let mut req = client
.get(&format!(
"https://champion.gg/champion/{}/{}?league=",
id, position
))
.send()
.unwrap();
if req.status() == reqwest::StatusCode::Ok {
serde_json::from_str(&find_champ_data(&req.text().unwrap())).unwrap()
} else {
@ -152,27 +212,47 @@ fn write_item_set(id: &str, pos: &str, ver: &str, path: &PathBuf, client: &reqwe
match data {
Some(data) => {
let mut item_set = ItemSet {
title: format!("CGG {} {} - {:.2}%", pos, ver, data["stats"]["winRate"].as_f64().unwrap() * 100.),
title: format!(
"CGG {} {} - {:.2}%",
pos,
ver,
data["stats"]["winRate"].as_f64().unwrap() * 100.
),
type_: "custom".to_string(),
map: "any".to_string(),
mode: "any".to_string(),
priority: false,
sortrank: 0,
blocks: vec![]
blocks: vec![],
};
for (label, path) in ITEM_TYPES.iter() {
if !data[&path[0]].get(&path[1]).is_none() {
item_set.blocks.push(make_item_set(&data[&path[0]][&path[1]], label));
item_set
.blocks
.push(make_item_set(&data[&path[0]][&path[1]], label));
}
}
item_set.blocks.push(make_item_set_from_list(&CONSUMABLES.to_vec(), "Consumables | Frequent:", "mostGames", &data));
item_set.blocks.push(make_item_set_from_list(&TRINKETS.to_vec(), "Trinkets | Wins:", "highestWinPercent", &data));
item_set.blocks.push(make_item_set_from_list(
&CONSUMABLES.to_vec(),
"Consumables | Frequent:",
"mostGames",
&data,
));
item_set.blocks.push(make_item_set_from_list(
&TRINKETS.to_vec(),
"Trinkets | Wins:",
"highestWinPercent",
&data,
));
info!("Writing item set for {} at {}", id, pos);
fs::write(path.join(format!("CGG_{}_{}.json", id, pos)), serde_json::to_string_pretty(&item_set).unwrap()).unwrap();
},
fs::write(
path.join(format!("CGG_{}_{}.json", id, pos)),
serde_json::to_string_pretty(&item_set).unwrap(),
).unwrap();
}
None => {
error!("Can't get data for {} at {}", id, pos);
}
@ -190,5 +270,9 @@ fn lol_champ_dir() -> Result<PathBuf, io::Error> {
let hklm = RegKey::predef(winreg::enums::HKEY_LOCAL_MACHINE);
let node = hklm.open_subkey(r"SOFTWARE\WOW6432Node\Riot Games\RADS")?;
let dir: String = node.get_value("LocalRootFolder")?;
Ok(PathBuf::from(&dir).parent().unwrap().join("Config").join("Champions"))
Ok(PathBuf::from(&dir)
.parent()
.unwrap()
.join("Config")
.join("Champions"))
}