From dfabf7bf8f7f3bf7b1bdba83ee366770d219c4a5 Mon Sep 17 00:00:00 2001 From: JMARyA Date: Wed, 10 Apr 2024 11:20:23 +0200 Subject: [PATCH] fix cache dir problem --- src/proxy.rs | 34 +++++++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/src/proxy.rs b/src/proxy.rs index b4dc64e..f402948 100644 --- a/src/proxy.rs +++ b/src/proxy.rs @@ -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 { 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 { - 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()?; - std::fs::write(save, &body_bytes).unwrap(); + 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(), );