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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
//! # IPLocate
//!
//! [IPLocate.io] is an internet service for finding data associated with Internet Protocol (IP)
//! addresses, such as city, country, approximate location, timezone, and more.
//!
//! Before starting to use their service, take a look at their [terms of service].
//!
//! The `iplocate` crate provides a wrapper for IPLocate API, and it can be handled with ease!
//!
//! ```
//! # extern crate iplocate;
//! # fn main() -> iplocate::Result<()> {
//! let ip = "8.8.8.8".parse().unwrap();
//! let result = iplocate::lookup(ip)?;
//! if let Some(ref country) = &result.geo_ip.country {
//!     println!("The IP address {} comes from the {}.", ip, country);
//! } else {
//!     println!("The IP address {} does not belong to any country.", ip);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! [IPLocate.io]: https://www.iplocate.io/
//! [Terms of Service]: https://www.iplocate.io/legal
extern crate chrono;
extern crate reqwest;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;

use chrono::format::ParseResult;
use chrono::offset::Utc;
use chrono::DateTime;
use std::fmt::{self, Display, Formatter};
use std::net::IpAddr;
use std::str::FromStr;

/// An alias for [`reqwest::Result`] in which it will result in error in case of a failed HTTP
/// request.
///
/// [`reqwest::Result`]: https://docs.rs/reqwest/0.9/reqwest/type.Result.html
pub type Result<T> = reqwest::Result<T>;

/// The main URL where it will request data from.
const API_REQUEST_URL: &str = "https://www.iplocate.io/api/lookup";

/// Looks up information for an IP address and returns an [`IpLocate`] on success.
///
/// [`IpLocate`]: struct.IpLocate.html
pub fn lookup(ip: IpAddr) -> Result<IpLocate> {
    Lookup::new(ip).lookup()
}

/// This type allows customization of `lookup` function.
pub struct Lookup<'a> {
    /// The IP address to be analyzed.
    ip: IpAddr,
    /// The response's format.
    format: Option<Format>,
    /// The IPLocate API's key.
    apikey: Option<&'a str>,
    /// The JSONP callback.
    callback: Option<&'a str>,
}

impl<'a> Lookup<'a> {
    /// Constructs a new `Lookup`.
    pub fn new(ip: IpAddr) -> Self {
        Lookup {
            ip,
            format: None,
            apikey: None,
            callback: None,
        }
    }

    /// Sets the response's format.
    pub fn format(&mut self, value: Format) -> &mut Self {
        self.format = Some(value);
        self
    }

    /// Sets the IPLocate API's key.
    pub fn apikey(&mut self, value: &'a str) -> &mut Self {
        self.apikey = Some(value);
        self
    }

    /// Sets the JSONP callback.
    pub fn callback(&mut self, value: &'a str) -> &mut Self {
        self.callback = Some(value);
        self
    }

    /// Requests for data without deserializing its content. Returns a [`String`] on success.
    ///
    /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
    pub fn raw_lookup(&self) -> Result<String> {
        self.request()?.text()
    }

    /// Requests for data and deserializes its content. Returns an [`IpLocate`] on success.
    ///
    /// By default, this method sets `self.format` to be JSON type and `self.callback` to be
    /// empty. Otherwise, it would panic at runtime.
    ///
    /// [`IpLocate`]: struct.IpLocate.html
    pub fn lookup(&self) -> reqwest::Result<IpLocate> {
        let mut lookup = Lookup { ..*self };

        // Ensures that the format is of JSON type.
        if lookup.format.is_some() {
            lookup.format(Format::Json);
        }
        // Ensures that the callback has no value.
        if lookup.callback.is_some() {
            lookup.callback = None;
        }

        let mut response = lookup.request()?;

        let rate_limit = RateLimit::from(&response);

        let geo_ip: GeoIp = response.json()?;

        Ok(IpLocate { rate_limit, geo_ip })
    }

    /// Make a request to the IPLocate API, looking up information for a given IP address.
    fn request(&self) -> Result<reqwest::Response> {
        let mut url = self
            .format
            .and_then(|format| Some(format!("{}/{}.{}", API_REQUEST_URL, self.ip, format)))
            .or(Some(format!("{}/{}", API_REQUEST_URL, self.ip)))
            .unwrap()
            .parse::<reqwest::Url>()
            .unwrap();

        if let Some(callback) = self.callback {
            url.set_query(Some(&format!("callback={}", callback)));
        }

        let mut request = reqwest::Request::new(reqwest::Method::GET, url);

        if let Some(apikey) = self.apikey {
            let headers = request.headers_mut();

            headers.insert("x-api-key", apikey.parse().unwrap());
        }

        Ok(reqwest::Client::new().execute(request)?)
    }
}

/// The format of the data to be returned upon request from the IPLocate API.
#[derive(Clone, Copy)]
pub enum Format {
    Json,
    Xml,
    Yaml,
    Csv,
}

impl Display for Format {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        let format = match *self {
            Format::Json => "json",
            Format::Xml => "xml",
            Format::Yaml => "yaml",
            Format::Csv => "csv",
        };

        f.write_str(format)
    }
}

/// The preferred return type of a request.
#[derive(Debug)]
pub struct IpLocate {
    pub rate_limit: RateLimit,
    pub geo_ip: GeoIp,
}

impl IpLocate {
    /// Constructs a new `Lookup`.
    pub fn new<'a>(ip: IpAddr) -> Lookup<'a> {
        Lookup::new(ip)
    }
}

/// This type contains all the data associated with IPLocate API's rate limits.
#[derive(Debug)]
pub struct RateLimit {
    /// The number of requests you can make daily.
    pub limit: i32,
    /// The remaining number of requests that you can make on the same day.
    pub remaining: i32,
    /// The time that will reset the remaining number of requests back to the IPLocate API's rate
    /// limit.
    pub reset: DateTime<Utc>,
}

impl<'a> From<&'a reqwest::Response> for RateLimit {
    fn from(response: &'a reqwest::Response) -> Self {
        let limit: i32;
        let remaining: i32;
        let reset: DateTime<Utc>;

        let headers = response.headers();

        let get_header = |name: &str| -> Option<&str> {
            headers
                .get(name)
                .and_then(|value| Some(value.to_str().unwrap()))
        };

        limit = get_header("x-ratelimit-limit")
            .and_then(|limit| limit.parse::<i32>().ok())
            .unwrap();
        remaining = get_header("x-ratelimit-remaining")
            .and_then(|remaining| remaining.parse::<i32>().ok())
            .unwrap();
        reset = get_header("x-ratelimit-reset")
            .and_then(|reset| from_raw_custom_datetime(reset).ok())
            .unwrap();

        RateLimit {
            limit,
            remaining,
            reset,
        }
    }
}

/// This type contains all the data related to a specific IP address.
#[derive(Debug, Serialize, Deserialize)]
pub struct GeoIp {
    pub ip: String,
    pub country: Option<String>,
    pub country_code: Option<String>,
    pub city: Option<String>,
    pub continent: Option<String>,
    pub latitude: Option<f64>,
    pub longitude: Option<f64>,
    pub time_zone: Option<String>,
    pub postal_code: Option<String>,
    pub org: Option<String>,
    pub asn: Option<String>,
    pub subdivision: Option<String>,
    pub subdivision2: Option<String>,
}

#[doc(hidden)]
fn from_raw_custom_datetime(s: &str) -> ParseResult<DateTime<Utc>> {
    let s = &s.split(' ').collect::<Vec<_>>();
    let s = format!("{}T{}{}", s[0], s[1], s[2]);
    chrono::DateTime::from_str(&s)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_from_raw_custom_datetime() {
        assert_eq!(
            Ok(DateTime::from_str("2018-09-21T00:00:00+00:00").unwrap()),
            from_raw_custom_datetime("2018-09-21 00:00:00 +0000"),
        );
    }
}