use std::{error::Error, fs, io::Write, path::PathBuf};
use base64::{Engine, engine::general_purpose};
use bt_logger::{get_error, log_error};
use sha3::{Digest, Sha3_512};
use crate::folder_manager::get_local_usr_data_path;
pub struct BTCache{
folder_path: PathBuf,
}
impl BTCache {
pub fn new(app_folder_name: Option<&str>) -> Result<Self, Box<dyn Error>>{
let local_path = get_local_usr_data_path(app_folder_name, Some("cache"), true)?;
Ok(
Self { folder_path: PathBuf::from(local_path) }
)
}
fn get_hash_string_base64(input: &str) -> String {
let mut hasher = Sha3_512::new();
hasher.update(input.as_bytes());
let result = hasher.finalize();
general_purpose::URL_SAFE_NO_PAD.encode(result)
}
fn download_file(url: &str, int_file_path: &PathBuf) -> Result<(), Box<dyn Error>>{
let download_response = reqwest::blocking::get(url)?;
let bytes = download_response.bytes()?;
let mut file = fs::File::create(int_file_path)?;
file.write_all(&bytes)?;
Ok(())
}
pub fn get_local_file_path(&self, url: &str) -> Result<String,Box<dyn Error>> {
let int_file_path = self.folder_path.join(Self::get_hash_string_base64(url));
let path_check = int_file_path.try_exists();
if path_check.is_err() {
log_error!("get_local_file_path","Issue finding file '{:?}' trying downloading again",int_file_path);
Self::download_file(url, &int_file_path)?;
}else{
if !path_check.unwrap(){
Self::download_file(url, &int_file_path)?;
}
}
if let Some(full_path) = int_file_path.to_str(){
return Ok(full_path.to_owned())
}else{
return Err(get_error!("get_local_file_path","Unable to retrieve cached file path. Invalid Unicode Path").into())
}
}
pub fn get_file_data_base64(&self, url: &str) -> Result<String,Box<dyn Error>> {
let full_file_path = self.get_local_file_path(url)?;
let file_data_bytes = fs::read(full_file_path)?;
Ok(general_purpose::STANDARD.encode(file_data_bytes))
}
}
#[cfg(test)]
mod bt_cache_tests {
use super::*;
const FILE_URL: &str = "https://avatars.githubusercontent.com/u/188628667?v=4";
#[test]
fn test_get_file_path_success() {
let local_cache = BTCache::new(Some("bt_cache")).unwrap();
let p = local_cache.get_local_file_path(FILE_URL).unwrap();
assert_eq!(p,"/home/super/.local/share/bt_cache/cache/Pe2MEfGkJXVt54yoLZ2ziRh9v4fGIJcRWQE98MtwcYTSNgJyE4ec6lZ4tSdolTCN9SA-wVrhmtP-8HJ-7jVWGg");
}
#[test]
fn test_get_file_data_success() {
let local_cache = BTCache::new(Some("bt_cache")).unwrap();
let p = local_cache.get_file_data_base64(FILE_URL);
assert!(p.is_ok());
}
}