init
This commit is contained in:
commit
8dd8bc8033
8 changed files with 2223 additions and 0 deletions
57
src/proxy.rs
Normal file
57
src/proxy.rs
Normal file
|
@ -0,0 +1,57 @@
|
|||
use std::path::PathBuf;
|
||||
|
||||
use actix_web::{HttpRequest, HttpResponse};
|
||||
|
||||
pub struct ProxyMirror {
|
||||
mirrors: Vec<String>,
|
||||
data_dir: String,
|
||||
}
|
||||
|
||||
impl ProxyMirror {
|
||||
pub fn new(mirrors: Vec<String>, data_dir: &str) -> Self {
|
||||
Self {
|
||||
mirrors,
|
||||
data_dir: data_dir.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
|
||||
if p.exists() {
|
||||
// todo : refresh caches
|
||||
return Some(
|
||||
actix_files::NamedFile::open_async(&p)
|
||||
.await
|
||||
.ok()?
|
||||
.into_response(req),
|
||||
);
|
||||
}
|
||||
|
||||
for mirror in &self.mirrors {
|
||||
let url = format!("{mirror}{path}");
|
||||
let res = self.get_url(&url, &p).await;
|
||||
if let Some(res) = res {
|
||||
if res.status().is_success() {
|
||||
return Some(res);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub async fn get_url(&self, path: &str, save: &PathBuf) -> Option<HttpResponse> {
|
||||
println!("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();
|
||||
let mut http_response = HttpResponse::build(
|
||||
actix_web::http::StatusCode::from_u16(status_code.as_u16()).unwrap(),
|
||||
);
|
||||
let http_response = http_response.body(body_bytes);
|
||||
Some(http_response)
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue