geolocate 0.2.2

A CLI for geolocation data providers
Documentation
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
#![allow(dead_code)]
#![allow(unused_imports)]

pub mod location {

  use clap::Parser;
  use confy::ConfyError;
  use reqwest::Url;
  use serde::{Deserialize, Serialize};
  use serde_json::{from_str, to_string_pretty, Map, Value};
  use std::{
    collections::HashMap,
    error::Error,
    fmt::{Debug, Display},
    io::Write,
    net::Ipv4Addr,
    process::{exit, Command, Stdio},
  };

  const IP2LOCATION: &str = "IP2LOCATION";
  const IPGEOLOCATION: &str = "IPGEOLOCATION";
  const DEFAULT: &str = "DEFAULT";
  const GEOLOCATE: &str = "GEOLOCATE";

  #[derive(Parser, Debug)]
  #[clap(name = "Geolocate")]
  #[clap(version = "0.1.0")]
  #[clap(author = "Nagy Botond")]
  #[clap(about = "Fetches geolocation data", long_about = None)]
  pub struct Args {
    /// The IP you want to fetch geolocation data about
    #[clap(short = 'i', long = "ip")]
    pub ip: Option<String>,

    /// File containing a list of IP addresses
    #[clap(short = 'f', long = "file")]
    pub file: Option<String>,

    /// Your API key from `https://ipgeolocation.io` or `https://ip2location.io`
    #[clap(short = 'k', long = "key")]
    pub api_key: Option<String>,

    /// Either `ip2location` or `ipgeolocation`
    /// Lets geolocate know which API to hit
    #[clap(short = 'n', long = "name")]
    pub name: Option<String>,

    #[clap(short = 'd', long = "default")]
    pub default: Option<String>,
  }

  /// Configuration struct to hold API key names and values in a HashMap
  #[derive(Serialize, Deserialize, Debug)]
  #[serde(transparent)]
  pub struct APIKeys(HashMap<String, String>);

  impl Default for APIKeys {
    fn default() -> Self {
      Self(HashMap::from([
        (IP2LOCATION.to_string(), "".to_string()),
        (IPGEOLOCATION.to_string(), "".to_string()),
        (DEFAULT.to_string(), "".to_string()),
      ]))
    }
  }

  trait ProviderConfig {
    // Load the configuration file for usage
    fn load_config(&self) -> Result<APIKeys, ConfyError> {
      let config = confy::load(GEOLOCATE)?;
      Ok(config)
    }
  }

  /// Branches to take according to which CLI arguments we're given
  #[derive(Debug)]
  pub enum LocationFrom {
    KeyAndProvider(Ipv4Addr, String, String),
    KeyOnly(Ipv4Addr, String),
    ProviderOnly(Ipv4Addr, String),
    Nothing(Ipv4Addr),
    DefaultOnly(Ipv4Addr, String),
  }

  impl ProviderConfig for LocationFrom {}

  impl LocationFrom {
    /// Fetch geolocation data
    pub fn fetch(&self) -> Result<(), Box<dyn Error>> {
      let url = match self.build_url().ok_or("URL is invalid") {
        Ok(url) => url,
        Err(err) => return Err(err.into()),
      };

      // let mut jq = Command::new("jq")
      //   .stdin(Stdio::piped())
      //   .stderr(Stdio::piped())
      //   .stdout(Stdio::piped())
      //   .spawn()?;

      match reqwest::blocking::get(url)?.text() {
        Ok(response) => {
          let serialized: Map<String, Value> = from_str(&response).expect("Failed to parse JSON");

          println!(
            "{}",
            to_string_pretty(&serialized).expect("Failed to prettify JSON")
          );

          Ok(())
        }

        Err(err) => {
          eprintln!("{err}");
          Ok(())
        }
      }
    }

    /// Build the URL that `fetch` will use
    fn build_url(&self) -> Option<String> {
      use LocationFrom::*;

      let mut config = self.load_config().expect("Failed to load config file");

      match self {
        // Both key and provider are known, build url normally
        KeyAndProvider(ip_address, api_key, provider_name) => {
          let url = self.format_url(&ip_address, &api_key, &provider_name)?;

          Some(url)
        }

        // Only key is known, look up provider based on key on the config file
        KeyOnly(ip_address, api_key) => {
          let provider_name = config
            .0
            .iter()
            // if the value of the `api_key` in the HashMap matches the value held by the enum
            // then return the provider that matches it
            .find_map(|(provider, _api_key)| {
              if api_key == _api_key.as_str() {
                Some(provider)
              } else {
                None
              }
            })?;

          let url = self.format_url(&ip_address, &api_key, &provider_name)?;

          Some(url)
        }

        // Only provider is known, look up api_key based on provider in config file
        ProviderOnly(ip_address, provider_name) => {
          let api_key = config.0.get(provider_name)?;
          let url = self.format_url(&ip_address, &api_key, &provider_name)?;

          Some(url)
        }

        // Nothing was given, default was found
        Nothing(ip_address) => {
          if let Some((_, default_provider_name)) = config.0.get_key_value(DEFAULT) {
            let default_api_key = config.0.get(default_provider_name)?;

            if default_provider_name == IP2LOCATION {
              let url = self.format_url(ip_address, &default_api_key, &default_provider_name)?;

              Some(url)
            } else if default_provider_name == IPGEOLOCATION {
              let url = self.format_url(ip_address, &default_api_key, &default_provider_name)?;

              Some(url)
            } else {
              None
            }
          } else {
            None
          }
        }

        DefaultOnly(ip_address, default) => {
          config
            .0
            .entry(DEFAULT.to_string())
            .and_modify(|entry_value| {
              *entry_value = default.to_string();
            });

          confy::store(GEOLOCATE, &config).ok()?;

          let default_provider_name = config.0.get(DEFAULT)?;
          let default_api_key = config.0.get(default_provider_name)?;

          let url = self.format_url(ip_address, default_api_key, default_provider_name)?;

          Some(url)
        }
      }
    }

    /// Format the url corresponding to the provider name
    fn format_url(
      &self,
      ip_address: &Ipv4Addr,
      api_key: &str,
      provider_name: &str,
    ) -> Option<String> {
      match provider_name {
        IPGEOLOCATION => Some(format!(
          "https://api.ipgeolocation.io/ipgeo?apiKey={api_key}&ip={ip_address}"
        )),

        IP2LOCATION => Some(format!(
          "https://api.ip2location.io/?ip={ip_address}&key={api_key}"
        )),

        // Default value
        _ => None,
      }
    }
  }

  #[derive(Debug)]
  pub struct ProviderNameValidationError;

  impl Display for ProviderNameValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
      write!(f, "-n | --name has to be `ip2location` or `ipgeolocation")
    }
  }

  impl std::error::Error for ProviderNameValidationError {}

  #[derive(Debug)]
  pub struct DefaultFieldValidationError;

  impl Display for DefaultFieldValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
      write!(
        f,
        "-d | --default has to be `ip2location` or `ipgeolocation"
      )
    }
  }

  impl std::error::Error for DefaultFieldValidationError {}

  /// Struct to collect the cli args
  #[derive(Debug)]
  pub struct Geolocation {
    ip_address: Option<Ipv4Addr>,
    provider_name: Option<String>,
    api_key: Option<String>,
    file: Option<String>,
    default: Option<String>,
  }

  /// The default provider is `https://ip2location.io`
  /// The default ip address is `localhost` but only to comply with the Ipv4Addr type
  /// Fetch will check for it and will refuse to execute the query
  impl Default for Geolocation {
    fn default() -> Self {
      Self {
        ip_address: Some("127.0.0.1".parse::<Ipv4Addr>().unwrap()),
        provider_name: Some("ip2location".to_string()),
        api_key: Some("".to_string()),
        file: Some("".to_string()),
        default: Some(IP2LOCATION.to_string()),
      }
    }
  }

  impl ProviderConfig for Geolocation {}

  impl Geolocation {
    /// Build a `Geolocation` struct from the cli arguments
    /// If the IP address is invalid, throw
    pub fn from(
      ip_address: Option<String>,
      provider_name: Option<String>,
      api_key: Option<String>,
      file: Option<String>,
      default: Option<String>,
    ) -> Result<Self, String> {
      if ip_address.is_none()
        && provider_name.is_none()
        && api_key.is_none()
        && file.is_none()
        && default.is_some()
      {
        let mut config = confy::load::<APIKeys>(GEOLOCATE).expect("Failed to load config file");

        config
          .0
          .entry(DEFAULT.to_string())
          .and_modify(|entry_value| {
            let _default = default.clone().unwrap().to_uppercase();

            if *entry_value != _default {
              *entry_value = _default;
              println!("Default overwritten to: {}", entry_value.to_lowercase());
            } else {
              println!("Default was already set to {}", entry_value.to_lowercase());
              exit(0)
            };
          });

        confy::store(GEOLOCATE, &config).expect("Failed to save config file");

        exit(0)
      }

      let valid_ip: Option<Ipv4Addr>;
      if ip_address.is_some() {
        valid_ip = ip_address
          .map(|value| value.parse::<Ipv4Addr>())
          .expect("Failed to parse IP address.")
          .ok();
      } else {
        println!("Some options would be nice");
        println!("Pass -h for help");
        exit(0)
      }

      let geolocation = Self {
        ip_address: valid_ip,
        // converting here to uppercase means I don't have to anywhere else
        // and the user feels no difference
        provider_name: provider_name.map(|val| val.to_uppercase()),
        api_key,
        file,
        default: default.map(|val| val.to_uppercase()),
      }
      .validate_provider()
      .map_err(|err| format!("{err}"))?
      .validate_default()
      .map_err(|err| format!("{err}"))?;

      Ok(geolocation)
    }

    /// Convert the struct to a `LocationFrom` enum by consuming it.
    /// The enum's variants hold the necessary data to make the API call
    /// to the respective service
    pub fn with(self) -> LocationFrom {
      if self.api_key.is_some() && self.provider_name.is_some() {
        // unwrap is fine because we know for sure there's gonna be a value
        // let provider_name_from_config = config.0.get(provider_cloned.unwrap().as_str());

        // Error out it failed to write config file for now
        self
          .store_provider_in_config(self.provider_name.clone())
          .expect("Failed to write to configuration file");

        LocationFrom::KeyAndProvider(
          self.ip_address.unwrap(),
          self.api_key.unwrap(),
          self.provider_name.unwrap(),
        )
      } else if self.api_key.is_some() && self.provider_name.is_none() {
        LocationFrom::KeyOnly(self.ip_address.unwrap(), self.api_key.unwrap())
      } else if self.api_key.is_none() && self.provider_name.is_some() {
        LocationFrom::ProviderOnly(self.ip_address.unwrap(), self.provider_name.unwrap())
      } else if self.default.is_some() {
        // store the default value in the config
        // when on the `-d` is passed on the cli
        // hit the default service
        // self
        //   .store_default_in_config(self.default.clone())
        //   .expect("Failed to write to configuration file");

        LocationFrom::DefaultOnly(self.ip_address.unwrap(), self.default.unwrap())
      } else {
        LocationFrom::Nothing(self.ip_address.unwrap())
      }
    }

    /// Validate the provider name by consuming self
    /// Return a ValidationError if it doesn't match
    fn validate_provider(self) -> Result<Self, ProviderNameValidationError> {
      match self.provider_name.as_deref() {
        Some(IP2LOCATION) | Some(IPGEOLOCATION) => Ok(Self { ..self }),
        None => Ok(Self {
          provider_name: None,
          ..self
        }),
        _ => Err(ProviderNameValidationError),
      }
    }

    /// Constrain the `default` field to `ip2location` or `ipgeolocation`
    fn validate_default(self) -> Result<Self, DefaultFieldValidationError> {
      match self.default.as_deref() {
        Some(IP2LOCATION) => Ok(Self {
          default: Some(IP2LOCATION.to_string()),
          ..self
        }),

        Some(IPGEOLOCATION) => Ok(Self {
          default: Some(IPGEOLOCATION.to_string()),
          ..self
        }),

        None => {
          let config = self.load_config().expect("Failed to read config file");
          let default = config.0.get(DEFAULT);
          Ok(Self {
            default: Some(default.unwrap().to_string()),
            ..self
          })
        }

        _ => Err(DefaultFieldValidationError),
      }
    }

    /// Stores the API keys into a config file and updates them if they change
    fn store_provider_in_config(&self, provider_name: Option<String>) -> Result<(), ConfyError> {
      let mut config = self.load_config()?;

      // if the string `ip2location` is provided with -n
      // then get it's matching api_key from the config file
      // on each run, it's different from the last api_key
      // then update it
      match provider_name {
        Some(provider) => match provider.as_str() {
          IP2LOCATION => config
            .0
            .entry(IP2LOCATION.to_string())
            .and_modify(|entry_value| {
              if let Some(api_key) = self.api_key.clone() {
                if api_key != *entry_value {
                  *entry_value = api_key;
                }
              }
            }),

          // same as above just for the string `ipgeolocation`
          IPGEOLOCATION => config
            .0
            .entry(IPGEOLOCATION.to_string())
            .and_modify(|entry_value| {
              if let Some(api_key) = self.api_key.clone() {
                if api_key != *entry_value {
                  *entry_value = api_key;
                }
              }
            }),

          // any other providers will go here
          _ => {
            return Ok(());
          }
        },

        // None is fine, no update's to do
        None => return Ok(()),
      };

      confy::store(GEOLOCATE, config)?;
      Ok(())
    }

    /// Store the value of default in the config file
    fn store_default_in_config(&self, default: Option<String>) -> Result<(), ConfyError> {
      let mut config = self.load_config()?;

      match default.as_deref() {
        Some(IP2LOCATION) => {
          config
            .0
            .entry(DEFAULT.to_string())
            .and_modify(|entry_value| *entry_value = IP2LOCATION.to_string())
            .or_insert(IP2LOCATION.to_string());

          confy::store(GEOLOCATE, config)?;

          Ok(())
        }

        Some(IPGEOLOCATION) => {
          config
            .0
            .entry(DEFAULT.to_string())
            .and_modify(|entry_value| *entry_value = IPGEOLOCATION.to_string())
            .or_insert(IPGEOLOCATION.to_string());

          confy::store(GEOLOCATE, config)?;

          Ok(())
        }
        _ => unimplemented!(),
      }
    }
  }
}