From 938423224b0cfed3d7a36494bdf56b62e186b1c1 Mon Sep 17 00:00:00 2001 From: NerdyPepper Date: Sun, 17 Jun 2018 08:25:43 +0530 Subject: Refactor into content.rs --- src/content.rs | 38 ++++++++++++++++++++++++++++++++++++++ src/main.rs | 28 ++++++++-------------------- 2 files changed, 46 insertions(+), 20 deletions(-) create mode 100644 src/content.rs (limited to 'src') diff --git a/src/content.rs b/src/content.rs new file mode 100644 index 0000000..36d4da6 --- /dev/null +++ b/src/content.rs @@ -0,0 +1,38 @@ +pub fn url_gen(title: &str) -> String { + +// /w/api.php?action=query&format=json&prop=extracts&titles=rust&explaintext=1 + title.replace(" ", "%20"); + + // query config + let url = "https://en.wikipedia.org"; + url.push_str("w/api.php?"); + url.push_str("action=query&"); + url.push_str("format=json&"); + url.push_str("prop=extracts&"); + url.push_str(format!("titles={}", title)); + url.push_str("explaintext=1"); +} + +pub fn get_extract(title: &str, red: Response) -> String { + let mut v: Value = serde_json::from_str(&res.text().unwrap()).unwrap(); + + // Fetch page and pageids of requested title(s) + let pageid = &v["query"]["pageids"][0]; + let pageid_str = match pageid { + Value::String(id) => id, + _ => panic!("wut"), + }; + + if pageid_str == "-1" { + String::from("No such page") + } else { + format!("{}", &v["query"]["pages"][pageid_str]["extract"]) + } +} + +pub fn get_title(title: &str, res: Response) -> String { + let mut v: Value = serde_json::from_str(&res.text().unwrap()).unwrap_or_else( |e| { + panic!("Recieved invalid json"); + } ); + format!("{}", &v["query"]["normalized"][0]["to"]) +} diff --git a/src/main.rs b/src/main.rs index 951c94c..1573cdb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,33 +3,21 @@ extern crate serde_json; use serde_json::Value; -fn main() { - println!("{}", get_extract("scale")); -} +pub mod content; -fn get_extract(title: &str) -> String { +fn main() { let url = format!("https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&list=&meta=&indexpageids=1&continue=%7C%7Cimageinfo&titles={}&exlimit=20&explaintext=1&exsectionformat=plain", title); let res = reqwest::get(&url); match res { - Ok(mut res) => { + Ok(res) => { if res.status().is_success() { - let mut v: Value = serde_json::from_str(&res.text().unwrap()).unwrap(); - - // Fetch page and pageids of requested title(s) - let pageid = &v["query"]["pageids"][0]; - let pageid_str = match pageid { - Value::String(id) => id, - _ => panic!("wut"), - }; - - format!("{:#}", &v["query"]["pages"][pageid_str]["extract"]) - } else { - format!("Error while parsing url.\nRecieved {}", res.status()) + content::get_extract("") } - }, - Err(_) => { - format!("Failed to parse URL") + } + + Err(_) { + panic!("Oh no!"); } } } -- cgit v1.2.3