fix cache dir problem

This commit is contained in:
JMARyA 2024-04-10 11:20:23 +02:00
parent 5d7afb2304
commit dfabf7bf8f
Signed by: jmarya
GPG key ID: 901B2ADDF27C2263

View file

@ -1,4 +1,4 @@
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use actix_web::{HttpRequest, HttpResponse};
@ -17,17 +17,39 @@ impl ProxyMirror {
}
}
pub fn create_cache_dir(dir: &Path) {
if dir.is_file() {
let tmp_file_path = dir.with_extension("tmp");
std::fs::rename(dir, &tmp_file_path).expect("Failed to rename file");
std::fs::create_dir_all(dir).expect("Failed to create directory");
let index_file_path = dir.join("index");
std::fs::rename(&tmp_file_path, index_file_path)
.expect("Failed to move file into directory");
} else {
std::fs::create_dir_all(dir).unwrap();
}
}
pub async fn get(&self, path: &str, req: &HttpRequest) -> Option<HttpResponse> {
let p = std::path::Path::new(&path[1..]);
let p = std::path::Path::new(&self.data_dir).join(p);
// todo : fix file dir problem
if !self.no_cache.is_match(path) {
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
Self::create_cache_dir(p.parent().unwrap());
if p.exists() {
// todo : refresh caches
log::info!("Returning {path} from cache");
if p.is_dir() {
return Some(
actix_files::NamedFile::open_async(p.join("index"))
.await
.ok()?
.into_response(req),
);
}
return Some(
actix_files::NamedFile::open_async(&p)
.await
@ -51,11 +73,13 @@ impl ProxyMirror {
}
pub async fn get_url(&self, path: &str, save: &PathBuf) -> Option<HttpResponse> {
println!("Fetching {path}");
log::info!("Fetching {path}");
let response = reqwest::get(path).await.unwrap();
let status_code = response.status();
let body_bytes = response.bytes().await.ok()?;
if status_code.is_success() {
std::fs::write(save, &body_bytes).unwrap();
}
let mut http_response = HttpResponse::build(
actix_web::http::StatusCode::from_u16(status_code.as_u16()).unwrap(),
);