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(&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<HttpResponse> {
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<HttpResponse> {
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);