aboutsummaryrefslogtreecommitdiff
path: root/src/content.rs
blob: ed1d8c55c1a99169eb8a6756dc3c1bf70b9af811 (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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
extern crate cursive;
extern crate regex;
extern crate reqwest;
extern crate serde_json;
extern crate urlencoding;

use self::regex::Regex;
use cursive::theme::Effect;
use cursive::utils::markup::StyledString;
use cursive::views::Dialog;
use cursive::Cursive;
use reqwest::Url;
use serde_json::Value;
use CONFIGURATION;

pub fn query_url_gen(title: &str) -> Url {
    Url::parse_with_params(
        &(CONFIGURATION.wiki_url.clone() + "/w/api.php"),
        &[
            ("action", "query"),
            ("format", "json"),
            ("prop", "extracts|links"),
            ("indexpageids", "1"),
            ("titles", &urlencoding::encode(&title.replace(" ", "_"))),
            ("redirects", "1"),
            ("pllimit", "100"),
            ("explaintext", "1"),
        ],
    ).unwrap()
}

pub fn search_url_gen(search: &str) -> Url {
    Url::parse_with_params(
        &(CONFIGURATION.wiki_url.clone() + "/w/api.php"),
        &[
            ("action", "opensearch"),
            ("format", "json"),
            ("search", &urlencoding::encode(search)),
            ("limit", "20"),
        ],
    ).unwrap()
}

pub fn get_extract(v: &Value) -> Result<String, reqwest::Error> {
    let pageid = &v["query"]["pageids"][0];
    let pageid_str = match pageid {
        Value::String(id) => id,
        _ => "-1",
    };

    match &v["query"]["pages"][pageid_str]["extract"] {
        Value::String(extract) => {
            // format to plain text
            let extract = extract.replace("\\\\", "\\");

            Ok(extract.to_string())
        }
        // ignore non strings
        _ => Ok("This page does not exist anymore".to_string()),
    }
}

pub fn extract_formatter(extract: &str) -> StyledString {
    let mut formatted = StyledString::new();

    let heading = Regex::new(r"^== (?P<d>.*) ==$").unwrap();
    let subheading = Regex::new(r"^=== (?P<d>.*) ===$").unwrap();
    let subsubheading = Regex::new(r"^==== (?P<d>.*) ====$").unwrap();

    for line in extract.lines() {
        if heading.is_match(line) {
            formatted.append(StyledString::styled(
                heading.replace(line, "$d"),
                Effect::Bold,
            ));
        } else if subheading.is_match(line) {
            formatted.append(StyledString::styled(
                subheading.replace(line, "$d"),
                Effect::Italic,
            ));
        } else if subsubheading.is_match(line) {
            formatted.append(StyledString::styled(
                subsubheading.replace(line, "$d"),
                Effect::Underline,
            ));
        } else {
            formatted.append(StyledString::plain(line));
        }

        formatted.append(StyledString::plain("\n"))
    }

    formatted
}

pub fn get_search_results(search: &str) -> Result<Vec<String>, reqwest::Error> {
    let url = search_url_gen(search);
    let mut res = reqwest::get(&url[..])?;
    let v: Value = serde_json::from_str(&res.text()?).unwrap_or_else(|e| {
        panic!("Recieved error {:?}", e);
    });

    let mut results: Vec<String> = vec![];
    for item in v[1].as_array().unwrap() {
        if let Value::String(x) = item {
            results.push(x.to_string())
        }
    }
    Ok(results)
}

pub fn get_links(v: &Value) -> Result<Vec<String>, reqwest::Error> {
    let pageid = &v["query"]["pageids"][0];
    let pageid_str = match pageid {
        Value::String(id) => id,
        _ => panic!("wut"),
    };

    let mut links = vec![];
    match &v["query"]["pages"][pageid_str]["links"] {
        Value::Array(arr) => {
            for item in arr {
                match item["title"] {
                    Value::String(ref title) => links.push(title.to_string()),
                    _ => links.push(String::from("lol")),
                }
            }
        }
        _ => links.push(String::from("lol")),
    };

    Ok(links)
}

pub fn pop_error(s: &mut Cursive, msg: &str) {
    s.add_layer(Dialog::text(msg.to_string()).button("Ok", |s| s.quit()));
}

pub fn handler(e: &reqwest::Error) -> String {
    let mut msg: String = String::new();
    if e.is_http() {
        match e.url() {
            None => msg.push_str(&"No URL given"),
            Some(url) => msg.push_str(&format!("Problem making request to: {}", url)),
        }
    }

    if e.is_redirect() {
        msg.push_str(&"server redirecting too many times or making loop");
    }

    msg
}