aboutsummaryrefslogtreecommitdiff
path: root/src/content.rs
blob: ba1a4600b459cd137e900f30d8d434cf1e6309de (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
extern crate reqwest;
extern crate serde_json;
extern crate cursive;

use cursive::Cursive;
use cursive::views::Dialog;
use serde_json::Value;
use reqwest::Response;

pub fn query_url_gen(title: &str) -> String {

    title.replace(" ", "%20");

    // query config
    let mut url = String::from("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("titles=");
    url.push_str(title);
    url.push_str("&");
    url.push_str("explaintext=1");

    url
}

pub fn search_url_gen(search: &str) -> String {
    // /w/api.php?action=opensearch&format=json&search=dota%202&limit=5;

    search.replace(" ", "%20");

    let mut url = String::from("https://en.wikipedia.org");
    url.push_str("/w/api.php?");
    url.push_str("action=opensearch&");
    url.push_str("format=json&");
    url.push_str("search=");
    url.push_str(search);
    url.push_str("&");
    url.push_str("limit=5");

    url

}

pub fn get_extract(title: &str) -> Result<String, reqwest::Error> {
    let url = query_url_gen(title);
    let res = reqwest::get(&url[..])?;

    let mut v: Value = match serde_json::from_str(&res.text()?) {
        Ok(x) => x,
        Err(x) => panic!("Failed to parse json\nReceived error {}", x),
    };
    let pageid = &v["query"]["pageids"][0];
    let pageid_str = match pageid {
        Value::String(id) => id,
        _ => panic!("wut"),
    };

    match &v["query"]["pages"][pageid_str]["extract"] {
        Value::String(extract) => {

            // format to plain text
            extract.replace("\\\\", "\\");
            Ok(format!("{}", extract))
        }
        // ignore non strings
        _ => Ok(format!(""))
    }
}

pub fn get_title(title: &str, mut res: Response) -> String {
    let mut v: Value = serde_json::from_str(&res.text().unwrap())
        .unwrap_or_else( |e| {
            panic!("Recieved error {:?}", e);
        } );
    format!("{}", &v["query"]["normalized"][0]["to"])
}

pub fn get_search_results(search: &str) -> Result<Vec<String>, reqwest::Error> {

    let url = search_url_gen(search);
    let res = reqwest::get(&url[..])?;
    let mut v: Value = serde_json::from_str(&res.text().unwrap())
        .unwrap_or_else( |e| {
            panic!("Recieved error {:?}", e);
        } );

    let mut results: Vec<String> = vec![];
    for item in v[1].as_array().unwrap() {
        match item {
            Value::String(x) => results.push(x.to_string()),
            // ignore non strings
            _ => (),
        }
    }
    Ok(results)
}

pub fn pop_error(s: &mut Cursive, msg: String) {
    s.add_layer(Dialog::text(format!("{}", msg))
                .title("Error")
                .button("Ok", |s| s.quit()));
}

pub fn handler(e: reqwest::Error) -> String {
    let msg: String = String::new();
    if e.is_http() {
        match e.url() {
            None => msg = format!("No URL given"),
            Some(url) => msg = format!("Problem making request to: {}", url),
        }
    }
    // Inspect the internal error and output it
    if e.is_serialization() {
        let serde_error = match e.get_ref() {
            Some(err) => err,
        };
        msg.push(format!("\nproblem parsing information {}", serde_error));
    }

    if e.is_redirect() {
        msg.push(format!("server redirecting too many times or making loop"));
    }

    msg
}