Ordering some files
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
use crate::ip_api::ip_location::IpLocation;
|
||||
|
||||
pub fn extract_coords_and_city(ip: &str) -> Result<IpLocation, ureq::Error> {
|
||||
let url = format!("http://ip-api.com/json/{}?fields=16592", ip);
|
||||
let body: serde_json::Value = ureq::get(&url).call()?.into_json()?;
|
||||
|
||||
let current_weather: IpLocation = serde_json::from_value(body).unwrap();
|
||||
Ok(current_weather)
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct IpLocation {
|
||||
pub lat: f64,
|
||||
pub lon: f64,
|
||||
pub city: String,
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
use std::{
|
||||
fs::{create_dir_all, File},
|
||||
io::{Read, Write},
|
||||
path::PathBuf,
|
||||
};
|
||||
|
||||
use crate::ip_api::ip_location::IpLocation;
|
||||
use directories::ProjectDirs;
|
||||
pub fn save_to_cache(ip: &str, data: &IpLocation) {
|
||||
let cache_dir = get_cache_dir();
|
||||
if cache_dir.is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut cache_dir = cache_dir.unwrap();
|
||||
cache_dir.push(format!("{}.{}", ip, "json"));
|
||||
|
||||
let json = serde_json::to_string(data);
|
||||
if json.is_err() {
|
||||
return;
|
||||
}
|
||||
let file = File::create(&cache_dir);
|
||||
if file.is_err() {
|
||||
return;
|
||||
}
|
||||
|
||||
let res = file.unwrap().write_all(json.unwrap().as_bytes());
|
||||
if res.is_err() {
|
||||
println!("[WARN] Error saving to cache IpLocation");
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_from_cache(ip: &str) -> Option<IpLocation> {
|
||||
let cache_dir = get_cache_dir();
|
||||
if cache_dir.is_none() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut cache_dir = cache_dir.unwrap();
|
||||
cache_dir.push(format!("{}.{}", ip, "json"));
|
||||
|
||||
if !is_in_cache(&cache_dir) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let file = File::open(&cache_dir);
|
||||
if file.is_err() {
|
||||
return None;
|
||||
}
|
||||
let mut content = String::new();
|
||||
let res = file.unwrap().read_to_string(&mut content);
|
||||
if res.is_err() {
|
||||
return None;
|
||||
}
|
||||
|
||||
if let Ok(ip_location) = serde_json::from_str(&content) {
|
||||
Some(ip_location)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn is_in_cache(path: &PathBuf) -> bool {
|
||||
path.is_file()
|
||||
}
|
||||
|
||||
fn get_cache_dir() -> Option<PathBuf> {
|
||||
let dir = ProjectDirs::from("com", "midefos", "open-meteo-cli");
|
||||
if dir.is_some() {
|
||||
let project_dir = dir.unwrap();
|
||||
|
||||
let cache_dir = project_dir.cache_dir();
|
||||
if !cache_dir.exists() {
|
||||
let res = create_dir_all(cache_dir);
|
||||
if res.is_err() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
Some(cache_dir.to_owned())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user