use clap::{CommandFactory, Parser};
use confy::ConfyError;
use serde::de::value;
use std::convert::TryInto;
use std::error::Error;
use std::net::AddrParseError;
use std::{net::Ipv4Addr, process::exit};
use super::config::APIKeys;
use super::constants::{DEFAULT, GEOLOCATE, IP2LOCATION, IPGEOLOCATION};
use super::errors::{BuildError, DefaultFieldValidationError, ProviderNameValidationError};
#[derive(Parser, Debug)]
#[clap(name = "Geolocate")]
#[clap(version)]
#[clap(author)]
#[clap(about, long_about = None)]
pub struct Args {
#[clap(short = 'i', long = "ip")]
ip: Option<String>,
#[clap(short = 'k', long = "key")]
api_key: Option<String>,
#[clap(short = 'n', long = "name")]
name: Option<String>,
#[clap(short = 'd', long = "default")]
default: Option<String>,
}
pub fn construct_url() -> Result<String, Box<dyn std::error::Error>> {
let args = Args::parse();
let geolocation = Geolocation::new()
.default(args.default)?
.ip_address(args.ip)?
.api_key(args.api_key)
.provider_name(args.name)?
.check()?
.build_url()?;
Ok(geolocation)
}
#[derive(Debug)]
pub struct Geolocation {
ip_address: Option<Ipv4Addr>,
provider_name: Option<String>,
api_key: Option<String>,
default: Option<String>,
}
impl Default for Geolocation {
fn default() -> Self {
Self {
ip_address: None,
provider_name: Some(IP2LOCATION.to_string()),
api_key: None,
default: Some(IP2LOCATION.to_string()),
}
}
}
impl Geolocation {
pub fn new() -> Self {
Self {
..Default::default()
}
}
pub fn ip_address(&mut self, ip_address: Option<String>) -> Result<&mut Self, AddrParseError> {
match ip_address {
Some(value) => {
let valid_ip_address = value
.parse::<Ipv4Addr>()
.expect("IP address is in an invalid format");
self.ip_address = Some(valid_ip_address);
Ok(self)
}
None => {
self.ip_address = None;
Ok(self)
}
}
}
pub fn provider_name(
&mut self,
provider_name: Option<String>,
) -> Result<&mut Self, ProviderNameValidationError> {
self.provider_name = provider_name.and_then(|value| {
let _value = value.to_uppercase();
if _value == IPGEOLOCATION || _value == IP2LOCATION {
Some(_value)
} else {
None
}
});
Ok(self)
}
pub fn api_key(&mut self, api_key: Option<String>) -> &mut Self {
self.api_key = api_key;
self
}
pub fn default(
&mut self,
default: Option<String>,
) -> Result<&mut Self, DefaultFieldValidationError> {
let _default = default.as_deref();
if _default == Some(&IP2LOCATION.to_lowercase())
|| _default == Some(&IPGEOLOCATION.to_lowercase())
{
()
} else if _default.is_none() {
return Ok(self);
} else {
return Err(DefaultFieldValidationError);
}
let mut config = confy::load::<APIKeys>(GEOLOCATE)
.expect("Failed to read config file when checking `default` parameter");
self.default = Some(
default
.and_then(|value| {
let _value = value.to_uppercase();
if _value == IP2LOCATION || _value == IPGEOLOCATION {
config.0.insert(DEFAULT.to_string(), _value.to_owned());
confy::store(GEOLOCATE, APIKeys(config.0.clone()))
.expect("Failed to write to configuration file while parsing `default`");
Some(_value)
} else {
None
}
})
.get_or_insert_with(|| {
config
.0
.get(DEFAULT)
.and(Some(IP2LOCATION.to_string()))
.unwrap()
})
.to_owned(),
);
Ok(self)
}
pub fn check(&mut self) -> Result<&mut Self, Box<dyn std::error::Error>> {
let config = confy::load::<APIKeys>(GEOLOCATE)?;
let has_at_least_one = config
.0
.values()
.find(|value| if value.is_empty() { false } else { true });
if has_at_least_one.is_none() {
return Err("You have to have at least one provider saved in your config".into());
}
Ok(self)
}
pub fn build_url(&mut self) -> Result<String, Box<dyn std::error::Error>> {
let mut cmd = Args::command();
if self.ip_address.is_none() {
cmd.print_help()?;
return Err(BuildError.into());
}
if self.provider_name.is_some() && self.ip_address.is_some() {
let config = confy::load::<APIKeys>(GEOLOCATE)?;
let api_key = config
.0
.get(&self.provider_name.clone().unwrap().to_uppercase())
.unwrap();
match self.provider_name.clone().unwrap().as_str() {
IP2LOCATION => {
return Ok(format!(
"https://api.ip2location.io/?ip={}&key={}",
self.ip_address.unwrap(),
api_key
))
}
IPGEOLOCATION => {
return Ok(format!(
"https://api.ipgeolocation.io/ipgeo?apiKey={}&ip={}",
api_key,
self.ip_address.unwrap()
))
}
_ => todo!(),
}
} else if self.api_key.is_none() && self.ip_address.is_some() {
let config = confy::load::<APIKeys>(GEOLOCATE)?;
let default_provider_name = config.0.get(DEFAULT).unwrap();
let default_api_key = config.0.get(default_provider_name).unwrap();
match default_provider_name.as_str() {
IP2LOCATION => {
return Ok(format!(
"https://api.ip2location.io/?ip={}&key={}",
self.ip_address.unwrap(),
default_api_key
));
}
IPGEOLOCATION => {
return Ok(format!(
"https://api.ipgeolocation.io/ipgeo?apiKey={}&ip={}",
default_api_key,
self.ip_address.unwrap()
))
}
_ => return Err("Default provider name does not exist".into()),
}
}
let ip_address = self.ip_address.unwrap();
let api_key = self.api_key.as_ref().unwrap();
match self.provider_name.as_deref() {
Some(value) if value.to_uppercase() == IP2LOCATION => Ok(format!(
"https://api.ip2location.io/?ip={}&key={}",
&api_key, &ip_address
)),
Some(value) if value.to_uppercase() == IPGEOLOCATION => Ok(format!(
"https://api.ipgeolocation.io/ipgeo?apiKey={}&ip={}",
&ip_address, &api_key
)),
Some(_) => return Err(BuildError.into()),
None => {
let config =
confy::load::<APIKeys>(GEOLOCATE).expect("Failed to read config file when building url");
let default_provider_name = config.0.get(DEFAULT).unwrap();
let default_api_key = config.0.get(default_provider_name).unwrap();
if default_provider_name == IP2LOCATION {
Ok(format!(
"https://api.ip2location.io/?ip={}&key={}",
&ip_address, &default_api_key
))
} else if default_provider_name == IPGEOLOCATION {
Ok(format!(
"https://api.ipgeolocation.io/ipgeo?apiKey={}&ip={}",
&ip_address, &default_api_key
))
} else {
Err(BuildError.into())
}
}
}
}
}