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
// requests.rs
//
// Copyright © 2018
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

use curl::easy::Easy;
use serde_json;
use std::str;

use Configuration;
use WikibaseError;

/// Make a request to a Wikibase.
///
/// Takes a url and returns a JSON result.
pub fn wikibase_request(url: &str, configuration: &Configuration)
    -> Result<serde_json::Value, WikibaseError> {
    let mut request = Easy::new();
    let mut json = Vec::new();

    match request.useragent(&configuration.user_agent()) {
        Ok(_) => {}
        Err(_) => return Err(WikibaseError::Configuration(
            "User-agent was not accepted by curl".to_string()))
    };

    match request.url(&url) {
        Ok(_) => {},
        Err(_) => return Err(WikibaseError::Request("Request failed".to_string()))
    };

    {
        let mut transfer = request.transfer();

        transfer.write_function(|data| {
            json.extend_from_slice(data);
            Ok(data.len())
        }).unwrap();

        match transfer.perform() {
            Ok(_) => {},
            Err(_) => return Err(WikibaseError::Request("Transfer failed".to_string()))
        };
    }

    let s = match str::from_utf8(&json[..]) {
        Ok(value) => value,
        Err(_) => return Err(WikibaseError::Request("UTF8 decode failed".to_string()))
    };
    let item_json: serde_json::Value = match serde_json::from_str(s) {
        Ok(value) => value,
        Err(_) => return Err(WikibaseError::Request("JSON parsing failed".to_string()))
    };

    Ok(item_json)
}