Files
open-meteo-cli/src/ip_api/ip_location_cache.rs
T
midefos 1affcb9d1a
ci/woodpecker/push/woodpecker Pipeline was successful
Correct stdout, updating lib and some clippy clean
2023-07-30 18:13:42 +02:00

82 lines
1.8 KiB
Rust

use std::{
fs::{create_dir_all, File},
io::{Read, Write},
path::{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: &Path) -> bool {
path.is_file()
}
fn get_cache_dir() -> Option<PathBuf> {
let dir = ProjectDirs::from("com", "midefos", "open-meteo-cli");
if let Some(project_dir) = &dir {
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
}
}