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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
//! It's rate limited and HTTPS access is a [paid feature](http://ip-api.com/docs/pro).
//! If the rate limiter catches you going over the 150 requests per minute you will be banned by IP until you [unban yourself](http://ip-api.com/docs/unban).
//! You can also view overall usage [statistics here](http://ip-api.com/docs/statistics).
//!
//! This information is likely not exact. Take this data with a grain of salt.
//!
//! Example
//!
//!```rust,ignore
//!extern crate ip_api;
//!
//!use ip_api::GeoIp;
//!
//!let fb = match GeoIp::new("www.facebook.com", false) {
//!    Err(e) => {
//!        eprintln!("{}", e);
//!        return;
//!    },
//!    Ok(geo_ip) => geo_ip
//!};
//!
//!println!("{}", fb.country().unwrap());
//!```

extern crate hyper;
extern crate hyper_native_tls;
extern crate serde;
extern crate serde_json;

#[macro_use]
extern crate serde_derive;

use hyper::Client;
use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;
use serde_json::Value;
use std::io::Read;
use std::error::Error;

mod error;

pub use error::*;

/// Information about an IP address.
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct GeoIp {
    country: String,
    country_code: String,
    region: String,
    region_name: String,
    city: String,
    zip: String,
    lat: f32,
    lon: f32,
    timezone: String,
    isp: String,
    org: String,
    #[serde(rename = "as")]
    as_nn: String,
    mobile: bool,
    proxy: bool
}

impl GeoIp {
    /// Get information on an IP address or domain name.
    /// If no host is provided then it will return information on your current IP.
    pub fn new(host: Option<&str>, https: bool) -> Result<GeoIp, IpApiError> {
        let ssl = NativeTlsClient::new().unwrap();
        let connector = HttpsConnector::new(ssl);
        let client = Client::with_connector(connector);

        let url = format!(
            "{}://ip-api.com/json/{}?fields=258047",
            if https { "https" } else { "http" },
            host.unwrap_or("")
        );

        let mut response = match client.get(&url).send() {
            Err(e) => return Err(IpApiError::OtherError(format!("{}", e.description()))),
            Ok(res) => res,
        };

        let mut body = String::new();
        response.read_to_string(&mut body).unwrap();

        let json: Value = match serde_json::from_str(&body) {
            Err(_) => return Err(IpApiError::OtherError(
                format!("Error interpreting body as json; the body is: {}", body))),
            Ok(json) => json
        };

        match json.get("status") {
            Some(&Value::String(ref s)) => {
                match s.as_ref() {
                    "success" => (),
                    "fail" => {
                        match json.get("message") {
                            Some(&Value::String(ref s)) => {
                                match s.as_ref() {
                                    "private range" => return Err(IpApiError::PrivateRange),
                                    "reserved range" => return Err(IpApiError::ReservedRange),
                                    "invalid query" => return Err(IpApiError::InvalidQuery),
                                    "quota" => return Err(IpApiError::Quota),
                                    _ => return Err(unexpected_json(&body, "unknown error message"))
                                }
                            }
                            _ => return Err(unexpected_json(&body, "unexpected message type"))
                        }
                    }
                    _ => return Err(unexpected_json(&body, "invalid status value"))
                };
            }
            _ => return Err(unexpected_json(&body, "invalid status"))
        };

        match serde_json::from_value(json) {
            Err(_) => return Err(IpApiError::OtherError(
                format!("Error deserializing json to GeoIp; the body is: {}", body))),
            Ok(geo_ip) => Ok(geo_ip)
        }
    }

    /// Get the country. (e.g. "United States")
    pub fn country(&self) -> Option<String> {
        as_option(&self.country)
    }

    /// Get the country code. (e.g. "US")
    pub fn country_code(&self) -> Option<String> {
        as_option(&self.country_code)
    }

    /// Get the region. (e.g. "CA" or "10")
    pub fn region(&self) -> Option<String> {
        as_option(&self.region)
    }

    /// Get the region name. (e.g. "California")
    pub fn region_name(&self) -> Option<String> {
        as_option(&self.region_name)
    }

    /// Get the city. (e.g. "Mountain View")
    pub fn city(&self) -> Option<String> {
        as_option(&self.city)
    }

    /// Get the zip code. (e.g. "94043")
    pub fn zip_code(&self) -> Option<String> {
        as_option(&self.zip)
    }

    /// Get the location as a tuple of latitude and longitude.
    pub fn location(&self) -> Option<(f32, f32)> {
        if self.lat == 0.0 && self.lon == 0.0 {
            None
        } else {
            Some((self.lat, self.lon))
        }
    }

    /// Get the timezone. (e.g. "America/Los_Angeles")
    pub fn timezone(&self) -> Option<String> {
        as_option(&self.timezone)
    }

    /// Get the internet service provider. (e.g. "Google")
    pub fn isp(&self) -> Option<String> {
        as_option(&self.isp)
    }

    /// Get the organization. (e.g. "Google")
    pub fn organization(&self) -> Option<String> {
        as_option(&self.org)
    }

    /// Get the [autonomous system](https://en.wikipedia.org/wiki/Autonomous_system_(Internet)) number and name. (e.g. "AS15169 Google Inc.")
    pub fn as_nn(&self) -> Option<String> {
        as_option(&self.as_nn)
    }

    /// Get whether the IP is a cellular connection.
    pub fn is_mobile(&self) -> bool {
        self.mobile
    }

    /// Get whether the IP is a known proxy.
    pub fn is_proxy(&self) -> bool {
        self.proxy
    }
}

fn unexpected_json(body: &str, reason: &str) -> IpApiError {
    IpApiError::OtherError(format!("Unexpected response: {}; body is: {}", reason, body))
}

fn as_option(string: &String) -> Option<String> {
    if string.is_empty() {
        None
    } else {
        Some(string.clone())
    }
}