use tokio_util::io::ReaderStream; use axum::{ body::Body, extract::{ConnectInfo, Request, State}, http::{HeaderMap, StatusCode}, middleware::{self, Next}, response::{Html, IntoResponse, Redirect}, routing::get, Json, Router, }; use axum_extra::TypedHeader; use tower_http::{services::ServeDir, trace::TraceLayer}; use std::{io, net::SocketAddr}; mod router { pub mod upload; } mod cache; mod state; mod util; mod views; use util::{headers::ForwardedFor, logging, ssr, sweeper}; use router::*; use state::*; use views::*; use upload::get_upload_router; #[tokio::main] async fn main() -> io::Result<()> { logging::init_tracing(); // uses create_dir_all to create both .cache and serve inside it in one go util::make_dir(".cache/serve").await?; let state = cache::fetch_cache().await; sweeper::spawn(state.clone()); // Records views let record_router = Router::new() .route("/", get(records)) .route("/links", get(records_links)); // Link pages let link_router = Router::new() .route("/:id", get(link).delete(link_delete)) .route("/:id/remaining", get(remaining)); // Router Setup let app = Router::new() .route("/", get(welcome)) .route("/download/:id", get(download)) .nest("/upload", get_upload_router()) .nest("/records", record_router) .nest("/link", link_router) .with_state(state) .fallback_service(ServeDir::new("dist")) .layer(TraceLayer::new_for_http()) .layer(middleware::from_fn(log_source)); serve(app).await; Ok(()) } async fn remaining( State(state): State, axum::extract::Path(id): axum::extract::Path, ) -> impl IntoResponse { let records = state.records.lock().await; if let Some(record) = records.get(&id) { let downloads_remaining = record.downloads_remaining(); let plural = if downloads_remaining > 1 { "s" } else { "" }; let out = format!( "You have {} download{} remaining!", downloads_remaining, plural ); Html(out) } else { Html("?".to_string()) } } async fn welcome() -> impl IntoResponse { let cat_fact = views::get_cat_fact().await; Html(ssr::render(move || { leptos::view! { } })) } async fn records(State(state): State) -> impl IntoResponse { Json(state.records.lock().await.clone()) } // This function is to remain ugly until that time in which I properly hide // this behind some kind of authentication async fn records_links(State(state): State) -> impl IntoResponse { let records = state.records.lock().await.clone(); Html(ssr::render(move || { leptos::view! {
    {records .keys() .map(|key| { leptos::view! { } }) .collect::>()}
} })) } async fn link( axum::extract::Path(id): axum::extract::Path, State(mut state): State, ) -> Result, Redirect> { { let mut records = state.records.lock().await; if let Some(record) = records .get_mut(&id) .filter(|record| record.can_be_downloaded()) { return Ok(Html(ssr::render({ let record = record.clone(); || { leptos::view! { } } }))); } } // TODO: This.... state.remove_record(&id).await.unwrap(); Err(Redirect::to("/404.html")) } async fn link_delete( axum::extract::Path(id): axum::extract::Path, State(mut state): State, ) -> Result, (StatusCode, String)> { state .remove_record(&id) .await .map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()))?; Ok(Html("".to_string())) } async fn log_source( ConnectInfo(addr): ConnectInfo, forwarded_for: Option>, req: Request, next: Next, ) -> impl IntoResponse { tracing::info!("{} : {:?}", addr, forwarded_for); next.run(req).await } async fn download( axum::extract::Path(id): axum::extract::Path, headers: HeaderMap, State(state): State, ) -> Result { { let mut records = state.records.lock().await; if headers.get("hx-request").is_some() { return Ok(axum::http::Response::builder() .header("HX-Redirect", format!("/download/{id}")) .status(204) .body("".to_owned()) .unwrap() .into_response()); } if let Some(record) = records .get_mut(&id) .filter(|record| record.can_be_downloaded()) { record.downloads += 1; let file = tokio::fs::File::open(&record.file).await.unwrap(); return Ok(axum::response::Response::builder() .header("Content-Type", "application/zip") .body(Body::from_stream(ReaderStream::new(file))) .unwrap()); } else { records.remove_record(&id).await.unwrap() } } Ok(Redirect::to("/404.html").into_response()) } async fn serve(app: Router) { // // Server creation let addr = SocketAddr::from(([0, 0, 0, 0], 3000)); let listener = tokio::net::TcpListener::bind(&addr).await.unwrap(); axum::serve( listener, app.into_make_service_with_connect_info::(), ) .await .unwrap(); tracing::debug!("listening on http://{}/", addr); }