diff --git a/src/proxy.rs b/src/proxy.rs index 4aa6e5b..8fc4d16 100644 --- a/src/proxy.rs +++ b/src/proxy.rs @@ -68,36 +68,55 @@ impl Mirror { let p = std::path::Path::new(&path[1..]); let p = std::path::Path::new(&self.data_dir).join(p); + // check if cache should be used if !self.no_cache.is_match(path) { Self::create_cache_dir(p.parent().unwrap()); - if p.exists() { - // todo : refresh caches + // use cache if present + if let Some(resp) = self.fetch_cache(&p, req).await { 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(resp); + } + } + + // fetch from network, if no response (offline) then use cache + if let Some(resp) = self.fetch_network(path, &p).await { + Some(resp) + } else { + log::info!("Returning {path} from cache"); + self.fetch_cache(&p, req).await + } + } + + pub async fn fetch_cache(&self, p: &PathBuf, req: &HttpRequest) -> Option { + if p.exists() { + // todo : refresh caches + if p.is_dir() { return Some( - actix_files::NamedFile::open_async(&p) + actix_files::NamedFile::open_async(p.join("index")) .await .ok()? .into_response(req), ); } + return Some( + actix_files::NamedFile::open_async(&p) + .await + .ok()? + .into_response(req), + ); } + None + } + pub async fn fetch_network(&self, path: &str, local: &PathBuf) -> Option { let mut mirrors = self.mirrors.clone(); mirrors.shuffle(&mut rand::thread_rng()); log::info!("Fetching {path} from mirrors"); for mirror in mirrors { let url = format!("{mirror}{path}"); - let response = self.get_url(&url, &p).await; + let response = self.get_url(&url, local).await; if let Some(res) = response { if res.status().is_success() { return Some(res);