cachebusting and templating

This commit is contained in:
xenofem 2022-05-26 14:43:03 -04:00
parent b90220da22
commit 4f9d46cc28
8 changed files with 214 additions and 206 deletions

View file

@ -6,9 +6,8 @@ mod zip;
use std::{fmt::Debug, path::PathBuf, str::FromStr};
use actix_files::NamedFile;
use actix_web::{
error::InternalError, get, http::StatusCode, middleware::Logger, post, web, App, HttpRequest,
error::InternalError, get, middleware::Logger, post, web, App, HttpRequest,
HttpResponse, HttpServer, Responder,
};
use actix_web_actors::ws;
@ -31,9 +30,9 @@ struct Config {
max_lifetime: u16,
upload_password: String,
storage_dir: PathBuf,
static_dir: PathBuf,
reverse_proxy: bool,
mnemonic_codes: bool,
cachebuster: String,
}
pub fn get_ip_addr(req: &HttpRequest, reverse_proxy: bool) -> String {
@ -51,14 +50,29 @@ pub fn log_auth_failure(ip_addr: &str) {
warn!("Incorrect authentication attempt from {}", ip_addr);
}
#[derive(Template)]
#[template(path = "index.html")]
struct IndexPage<'a> { cachebuster: &'a str }
#[get("/")]
async fn index(data: web::Data<AppState>) -> impl Responder {
HttpResponse::Ok().body(IndexPage { cachebuster: &data.config.cachebuster }.render().unwrap())
}
#[derive(Deserialize)]
struct DownloadRequest {
code: String,
download: Option<download::DownloadSelection>,
}
#[derive(Serialize, Template)]
#[derive(Template)]
#[template(path = "download.html")]
struct DownloadPage<'a> {
info: DownloadInfo,
cachebuster: &'a str,
}
#[derive(Serialize)]
struct DownloadInfo {
file: StoredFile,
code: String,
@ -105,11 +119,14 @@ async fn handle_download(
} else {
let offsets = info.contents.as_deref().map(zip::file_data_offsets);
Ok(HttpResponse::Ok().body(
DownloadInfo {
file: info,
code: code.clone(),
available: file.metadata().await?.len(),
offsets,
DownloadPage {
info: DownloadInfo {
file: info,
code: code.clone(),
available: file.metadata().await?.len(),
offsets,
},
cachebuster: &data.config.cachebuster,
}
.render()
.unwrap(),
@ -149,6 +166,10 @@ async fn download_info(
}))
}
#[derive(Template)]
#[template(path = "404.html")]
struct NotFoundPage<'a> { cachebuster: &'a str }
fn not_found<T>(req: HttpRequest, data: web::Data<AppState>, report: bool) -> actix_web::Result<T> {
if report {
let ip_addr = get_ip_addr(&req, data.config.reverse_proxy);
@ -156,9 +177,7 @@ fn not_found<T>(req: HttpRequest, data: web::Data<AppState>, report: bool) -> ac
}
Err(InternalError::from_response(
"Download not found",
NamedFile::open(data.config.static_dir.join("404.html"))?
.set_status_code(StatusCode::NOT_FOUND)
.into_response(&req),
HttpResponse::NotFound().body(NotFoundPage { cachebuster: &data.config.cachebuster }.render().unwrap()),
)
.into())
}
@ -258,6 +277,7 @@ async fn main() -> std::io::Result<()> {
env_or::<ByteSize>("TRANSBEAM_MAX_STORAGE_SIZE", ByteSize(64 * bytesize::GB)).as_u64();
let upload_password: String =
std::env::var("TRANSBEAM_UPLOAD_PASSWORD").expect("TRANSBEAM_UPLOAD_PASSWORD must be set!");
let cachebuster: String = env_or_else("TRANSBEAM_CACHEBUSTER", String::new);
let data = web::Data::new(AppState {
file_store: RwLock::new(FileStore::load(storage_dir.clone(), max_storage_size).await?),
@ -266,9 +286,9 @@ async fn main() -> std::io::Result<()> {
max_lifetime,
upload_password,
storage_dir,
static_dir: static_dir.clone(),
reverse_proxy,
mnemonic_codes,
cachebuster,
},
});
start_reaper(data.clone());
@ -281,12 +301,13 @@ async fn main() -> std::io::Result<()> {
} else {
Logger::default()
})
.service(index)
.service(handle_download)
.service(download_info)
.service(handle_upload)
.service(check_upload_password)
.service(upload_limits)
.service(actix_files::Files::new("/", static_dir.clone()).index_file("index.html"))
.service(actix_files::Files::new("/", static_dir.clone()))
});
if reverse_proxy {