#![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 {
#[clap(short = 'i', long = "ip")]
pub ip: Option<String>,
#[clap(short = 'f', long = "file")]
pub file: Option<String>,
#[clap(short = 'k', long = "key")]
pub api_key: Option<String>,
#[clap(short = 'n', long = "name")]
pub name: Option<String>,
#[clap(short = 'd', long = "default")]
pub default: Option<String>,
}
#[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 {
fn load_config(&self) -> Result<APIKeys, ConfyError> {
let config = confy::load(GEOLOCATE)?;
Ok(config)
}
}
#[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 {
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()),
};
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(())
}
}
}
fn build_url(&self) -> Option<String> {
use LocationFrom::*;
let mut config = self.load_config().expect("Failed to load config file");
match self {
KeyAndProvider(ip_address, api_key, provider_name) => {
let url = self.format_url(&ip_address, &api_key, &provider_name)?;
Some(url)
}
KeyOnly(ip_address, api_key) => {
let provider_name = config
.0
.iter()
.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)
}
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(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)
}
}
}
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}"
)),
_ => 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 {}
#[derive(Debug)]
pub struct Geolocation {
ip_address: Option<Ipv4Addr>,
provider_name: Option<String>,
api_key: Option<String>,
file: Option<String>,
default: Option<String>,
}
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 {
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,
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)
}
pub fn with(self) -> LocationFrom {
if self.api_key.is_some() && self.provider_name.is_some() {
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() {
LocationFrom::DefaultOnly(self.ip_address.unwrap(), self.default.unwrap())
} else {
LocationFrom::Nothing(self.ip_address.unwrap())
}
}
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),
}
}
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),
}
}
fn store_provider_in_config(&self, provider_name: Option<String>) -> Result<(), ConfyError> {
let mut config = self.load_config()?;
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;
}
}
}),
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;
}
}
}),
_ => {
return Ok(());
}
},
None => return Ok(()),
};
confy::store(GEOLOCATE, config)?;
Ok(())
}
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!(),
}
}
}
}