This commit is contained in:
JMARyA 2024-04-15 09:18:29 +02:00
parent ff9a0b8691
commit b0ce294ec8
Signed by: jmarya
GPG key ID: 901B2ADDF27C2263

View file

@ -68,36 +68,55 @@ impl Mirror {
let p = std::path::Path::new(&path[1..]); let p = std::path::Path::new(&path[1..]);
let p = std::path::Path::new(&self.data_dir).join(p); let p = std::path::Path::new(&self.data_dir).join(p);
// check if cache should be used
if !self.no_cache.is_match(path) { if !self.no_cache.is_match(path) {
Self::create_cache_dir(p.parent().unwrap()); Self::create_cache_dir(p.parent().unwrap());
if p.exists() { // use cache if present
// todo : refresh caches if let Some(resp) = self.fetch_cache(&p, req).await {
log::info!("Returning {path} from cache"); log::info!("Returning {path} from cache");
if p.is_dir() { return Some(resp);
return Some( }
actix_files::NamedFile::open_async(p.join("index")) }
.await
.ok()? // fetch from network, if no response (offline) then use cache
.into_response(req), 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<HttpResponse> {
if p.exists() {
// todo : refresh caches
if p.is_dir() {
return Some( return Some(
actix_files::NamedFile::open_async(&p) actix_files::NamedFile::open_async(p.join("index"))
.await .await
.ok()? .ok()?
.into_response(req), .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<HttpResponse> {
let mut mirrors = self.mirrors.clone(); let mut mirrors = self.mirrors.clone();
mirrors.shuffle(&mut rand::thread_rng()); mirrors.shuffle(&mut rand::thread_rng());
log::info!("Fetching {path} from mirrors"); log::info!("Fetching {path} from mirrors");
for mirror in mirrors { for mirror in mirrors {
let url = format!("{mirror}{path}"); 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 let Some(res) = response {
if res.status().is_success() { if res.status().is_success() {
return Some(res); return Some(res);