Compare commits
4 Commits
9caf7b78fe
...
2acdcc6d2f
Author | SHA1 | Date |
---|---|---|
Zynh Ludwig | 2acdcc6d2f | |
Zynh Ludwig | e58b966319 | |
Zynh Ludwig | b7bcd9c5f1 | |
Zynh Ludwig | ea7dee4dfd |
242
src/main.rs
242
src/main.rs
|
@ -1,34 +1,24 @@
|
|||
use async_zip::{tokio::write::ZipFileWriter, Compression, ZipEntryBuilder};
|
||||
|
||||
use futures::TryStreamExt;
|
||||
use tokio_util::{
|
||||
compat::FuturesAsyncWriteCompatExt,
|
||||
io::{ReaderStream, StreamReader},
|
||||
};
|
||||
|
||||
use axum::{
|
||||
body::Body,
|
||||
extract::{ConnectInfo, DefaultBodyLimit, Multipart, Request, State},
|
||||
http::{HeaderMap, Response, StatusCode},
|
||||
extract::{ConnectInfo, Request},
|
||||
middleware::{self, Next},
|
||||
response::{Html, IntoResponse, Redirect},
|
||||
routing::{get, post},
|
||||
Json, Router,
|
||||
response::{Html, IntoResponse},
|
||||
routing::get,
|
||||
Router,
|
||||
};
|
||||
use axum_extra::TypedHeader;
|
||||
use tower_http::{limit::RequestBodyLimitLayer, services::ServeDir, trace::TraceLayer};
|
||||
use tower_http::{services::ServeDir, trace::TraceLayer};
|
||||
|
||||
use sanitize_filename_reader_friendly::sanitize;
|
||||
|
||||
use std::{io, net::SocketAddr, path::Path};
|
||||
use std::{io, net::SocketAddr};
|
||||
|
||||
mod cache;
|
||||
mod router;
|
||||
mod state;
|
||||
mod util;
|
||||
mod views;
|
||||
|
||||
use util::{headers::ForwardedFor, logging, ssr, sweeper};
|
||||
|
||||
use router::*;
|
||||
use state::*;
|
||||
use views::*;
|
||||
|
||||
|
@ -46,16 +36,10 @@ async fn main() -> io::Result<()> {
|
|||
// Router Setup
|
||||
let app = Router::new()
|
||||
.route("/", get(welcome))
|
||||
.route("/upload", post(upload_to_zip))
|
||||
.route("/records", get(records))
|
||||
.route("/records/links", get(records_links))
|
||||
.route("/download/:id", get(download))
|
||||
.route("/link/:id", get(link).delete(link_delete))
|
||||
.route("/link/:id/remaining", get(remaining))
|
||||
.layer(DefaultBodyLimit::disable())
|
||||
.layer(RequestBodyLimitLayer::new(
|
||||
10 * 1024 * 1024 * 1024, // 10GiB
|
||||
))
|
||||
.nest("/download", get_download_router())
|
||||
.nest("/upload", get_upload_router())
|
||||
.nest("/records", get_records_router())
|
||||
.nest("/link", get_link_router())
|
||||
.with_state(state)
|
||||
.fallback_service(ServeDir::new("dist"))
|
||||
.layer(TraceLayer::new_for_http())
|
||||
|
@ -66,24 +50,6 @@ async fn main() -> io::Result<()> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
async fn remaining(
|
||||
State(state): State<AppState>,
|
||||
axum::extract::Path(id): axum::extract::Path<String>,
|
||||
) -> 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 || {
|
||||
|
@ -91,84 +57,6 @@ async fn welcome() -> impl IntoResponse {
|
|||
}))
|
||||
}
|
||||
|
||||
async fn records(State(state): State<AppState>) -> 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<AppState>) -> impl IntoResponse {
|
||||
let records = state.records.lock().await.clone();
|
||||
Html(ssr::render(move || {
|
||||
leptos::view! {
|
||||
<HtmxPage>
|
||||
<div class="form-wrapper">
|
||||
<div class="column-container">
|
||||
<ul>
|
||||
{records
|
||||
.keys()
|
||||
.map(|key| {
|
||||
leptos::view! {
|
||||
<li class="link-wrapper">
|
||||
<a href="/link/{key}">{key}</a>
|
||||
<button
|
||||
style="margin-left: 1em;"
|
||||
hx-target="closest .link-wrapper"
|
||||
hx-swap="outerHTML"
|
||||
hx-delete="/link/{key}"
|
||||
>
|
||||
X
|
||||
</button>
|
||||
</li>
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</HtmxPage>
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
async fn link(
|
||||
axum::extract::Path(id): axum::extract::Path<String>,
|
||||
State(mut state): State<AppState>,
|
||||
) -> Result<Html<String>, 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! { <DownloadLinkPage id=id record=record /> }
|
||||
}
|
||||
})));
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: This....
|
||||
state.remove_record(&id).await.unwrap();
|
||||
|
||||
Err(Redirect::to("/404.html"))
|
||||
}
|
||||
|
||||
async fn link_delete(
|
||||
axum::extract::Path(id): axum::extract::Path<String>,
|
||||
State(mut state): State<AppState>,
|
||||
) -> Result<Html<String>, (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<SocketAddr>,
|
||||
forwarded_for: Option<TypedHeader<ForwardedFor>>,
|
||||
|
@ -180,112 +68,6 @@ async fn log_source(
|
|||
next.run(req).await
|
||||
}
|
||||
|
||||
async fn upload_to_zip(
|
||||
State(state): State<AppState>,
|
||||
mut body: Multipart,
|
||||
) -> Result<Response<String>, (StatusCode, String)> {
|
||||
tracing::debug!("{:?}", *state.records.lock().await);
|
||||
|
||||
let cache_name = util::get_random_name(10);
|
||||
|
||||
let archive_path = Path::new(".cache/serve").join(format!("{}.zip", &cache_name));
|
||||
|
||||
tracing::debug!("Zipping: {:?}", &archive_path);
|
||||
|
||||
let mut archive = tokio::fs::File::create(&archive_path)
|
||||
.await
|
||||
.map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()))?;
|
||||
let mut writer = ZipFileWriter::with_tokio(&mut archive);
|
||||
|
||||
while let Some(field) = body.next_field().await.unwrap() {
|
||||
let file_name = match field.file_name() {
|
||||
Some(file_name) => sanitize(file_name),
|
||||
_ => continue,
|
||||
};
|
||||
|
||||
tracing::debug!("Downloading to Zip: {file_name:?}");
|
||||
|
||||
let stream = field;
|
||||
let body_with_io_error = stream.map_err(io::Error::other);
|
||||
let mut body_reader = StreamReader::new(body_with_io_error);
|
||||
|
||||
let builder = ZipEntryBuilder::new(file_name.into(), Compression::Deflate);
|
||||
let mut entry_writer = writer
|
||||
.write_entry_stream(builder)
|
||||
.await
|
||||
.unwrap()
|
||||
.compat_write();
|
||||
|
||||
tokio::io::copy(&mut body_reader, &mut entry_writer)
|
||||
.await
|
||||
.map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()))?;
|
||||
|
||||
entry_writer
|
||||
.into_inner()
|
||||
.close()
|
||||
.await
|
||||
.map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()))?;
|
||||
}
|
||||
|
||||
let mut records = state.records.lock().await;
|
||||
let record = UploadRecord::new(archive_path);
|
||||
records.insert(cache_name.clone(), record.clone());
|
||||
|
||||
cache::write_to_cache(&records)
|
||||
.await
|
||||
.map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()))?;
|
||||
|
||||
writer.close().await.unwrap();
|
||||
|
||||
let id = cache_name;
|
||||
let response = Response::builder()
|
||||
.status(200)
|
||||
.header("Content-Type", "text/html")
|
||||
.header("HX-Push-Url", format!("/link/{}", &id))
|
||||
.body(ssr::render(|| {
|
||||
leptos::view! { <LinkView id record /> }
|
||||
}))
|
||||
.unwrap();
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn download(
|
||||
axum::extract::Path(id): axum::extract::Path<String>,
|
||||
headers: HeaderMap,
|
||||
State(state): State<AppState>,
|
||||
) -> Result<axum::response::Response, (StatusCode, String)> {
|
||||
{
|
||||
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));
|
||||
|
|
|
@ -0,0 +1,52 @@
|
|||
use axum::{
|
||||
body::Body,
|
||||
extract::State,
|
||||
http::HeaderMap,
|
||||
response::{IntoResponse, Redirect},
|
||||
routing::get,
|
||||
Router,
|
||||
};
|
||||
use reqwest::StatusCode;
|
||||
use tokio_util::io::ReaderStream;
|
||||
|
||||
use crate::{AppState, AsyncRemoveRecord};
|
||||
|
||||
pub fn get_download_router() -> Router<AppState> {
|
||||
Router::new().route("/:id", get(download))
|
||||
}
|
||||
|
||||
async fn download(
|
||||
axum::extract::Path(id): axum::extract::Path<String>,
|
||||
headers: HeaderMap,
|
||||
State(state): State<AppState>,
|
||||
) -> Result<axum::response::Response, (StatusCode, String)> {
|
||||
{
|
||||
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())
|
||||
}
|
|
@ -0,0 +1,76 @@
|
|||
use axum::{
|
||||
extract::State,
|
||||
response::{Html, IntoResponse, Redirect},
|
||||
routing::get,
|
||||
Router,
|
||||
};
|
||||
use reqwest::StatusCode;
|
||||
|
||||
use crate::{util::ssr, AppState, AsyncRemoveRecord, DownloadLinkPage};
|
||||
|
||||
pub fn get_link_router() -> Router<AppState> {
|
||||
// Link pages
|
||||
Router::new()
|
||||
.route("/:id", get(link).delete(link_delete))
|
||||
.route("/:id/remaining", get(remaining))
|
||||
}
|
||||
|
||||
async fn link(
|
||||
axum::extract::Path(id): axum::extract::Path<String>,
|
||||
State(mut state): State<AppState>,
|
||||
) -> Result<Html<String>, 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! { <DownloadLinkPage id=id record=record /> }
|
||||
}
|
||||
})));
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: This....
|
||||
state.remove_record(&id).await.unwrap();
|
||||
|
||||
Err(Redirect::to("/404.html"))
|
||||
}
|
||||
|
||||
async fn link_delete(
|
||||
axum::extract::Path(id): axum::extract::Path<String>,
|
||||
State(mut state): State<AppState>,
|
||||
) -> Result<Html<String>, (StatusCode, String)> {
|
||||
state
|
||||
.remove_record(&id)
|
||||
.await
|
||||
.map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()))?;
|
||||
|
||||
Ok(Html("".to_string()))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_remaining_text(downloads_remaining: u8) -> String {
|
||||
let plural = if downloads_remaining > 1 { "s" } else { "" };
|
||||
format!(
|
||||
"You have {} download{} remaining!",
|
||||
downloads_remaining, plural
|
||||
)
|
||||
}
|
||||
|
||||
async fn remaining(
|
||||
State(state): State<AppState>,
|
||||
axum::extract::Path(id): axum::extract::Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
let records = state.records.lock().await;
|
||||
if let Some(record) = records.get(&id) {
|
||||
let downloads_remaining = record.downloads_remaining();
|
||||
Html(get_remaining_text(downloads_remaining))
|
||||
} else {
|
||||
Html("?".to_string())
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
pub mod download;
|
||||
pub mod link;
|
||||
pub mod records;
|
||||
pub mod upload;
|
||||
|
||||
pub use download::get_download_router;
|
||||
pub use link::get_link_router;
|
||||
pub use records::get_records_router;
|
||||
pub use upload::get_upload_router;
|
|
@ -0,0 +1,55 @@
|
|||
use axum::{
|
||||
extract::State,
|
||||
response::{Html, IntoResponse},
|
||||
routing::get,
|
||||
Json, Router,
|
||||
};
|
||||
|
||||
use crate::{util::ssr, AppState, HtmxPage};
|
||||
|
||||
pub fn get_records_router() -> Router<AppState> {
|
||||
// Records views
|
||||
Router::new()
|
||||
.route("/", get(records))
|
||||
.route("/links", get(records_links))
|
||||
}
|
||||
|
||||
pub(crate) async fn records(State(state): State<AppState>) -> 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
|
||||
pub async fn records_links(State(state): State<AppState>) -> impl IntoResponse {
|
||||
let records = state.records.lock().await.clone();
|
||||
Html(ssr::render(move || {
|
||||
leptos::view! {
|
||||
<HtmxPage>
|
||||
<div class="form-wrapper">
|
||||
<div class="column-container">
|
||||
<ul>
|
||||
{records
|
||||
.keys()
|
||||
.map(|key| {
|
||||
leptos::view! {
|
||||
<li class="link-wrapper">
|
||||
<a href="/link/{key}">{key}</a>
|
||||
<button
|
||||
style="margin-left: 1em;"
|
||||
hx-target="closest .link-wrapper"
|
||||
hx-swap="outerHTML"
|
||||
hx-delete="/link/{key}"
|
||||
>
|
||||
X
|
||||
</button>
|
||||
</li>
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</HtmxPage>
|
||||
}
|
||||
}))
|
||||
}
|
|
@ -0,0 +1,101 @@
|
|||
use std::path::Path;
|
||||
|
||||
use async_zip::{base::write::ZipFileWriter, Compression, ZipEntryBuilder};
|
||||
use axum::{
|
||||
extract::{DefaultBodyLimit, Multipart, State},
|
||||
http::Response,
|
||||
routing::post,
|
||||
Router,
|
||||
};
|
||||
use futures::TryStreamExt;
|
||||
use reqwest::StatusCode;
|
||||
use sanitize_filename_reader_friendly::sanitize;
|
||||
use tokio::io;
|
||||
use tokio_util::{compat::FuturesAsyncWriteCompatExt, io::StreamReader};
|
||||
use tower_http::limit::RequestBodyLimitLayer;
|
||||
|
||||
use crate::{
|
||||
cache,
|
||||
util::{self, ssr},
|
||||
AppState, LinkView, UploadRecord,
|
||||
};
|
||||
|
||||
pub fn get_upload_router() -> Router<AppState> {
|
||||
// Upload needs a subrouter to increase the body limit
|
||||
Router::new()
|
||||
.route("/", post(upload_to_zip))
|
||||
.layer(DefaultBodyLimit::disable())
|
||||
.layer(RequestBodyLimitLayer::new(
|
||||
10 * 1024 * 1024 * 1024, // 10GiB
|
||||
))
|
||||
}
|
||||
|
||||
async fn upload_to_zip(
|
||||
State(state): State<AppState>,
|
||||
mut body: Multipart,
|
||||
) -> Result<Response<String>, (StatusCode, String)> {
|
||||
tracing::debug!("{:?}", *state.records.lock().await);
|
||||
|
||||
let cache_name = util::get_random_name(10);
|
||||
|
||||
let archive_path = Path::new(".cache/serve").join(format!("{}.zip", &cache_name));
|
||||
|
||||
tracing::debug!("Zipping: {:?}", &archive_path);
|
||||
|
||||
let mut archive = tokio::fs::File::create(&archive_path)
|
||||
.await
|
||||
.map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()))?;
|
||||
let mut writer = ZipFileWriter::with_tokio(&mut archive);
|
||||
|
||||
while let Some(field) = body.next_field().await.unwrap() {
|
||||
let file_name = match field.file_name() {
|
||||
Some(file_name) => sanitize(file_name),
|
||||
_ => continue,
|
||||
};
|
||||
|
||||
tracing::debug!("Downloading to Zip: {file_name:?}");
|
||||
|
||||
let stream = field;
|
||||
let body_with_io_error = stream.map_err(io::Error::other);
|
||||
let mut body_reader = StreamReader::new(body_with_io_error);
|
||||
|
||||
let builder = ZipEntryBuilder::new(file_name.into(), Compression::Deflate);
|
||||
let mut entry_writer = writer
|
||||
.write_entry_stream(builder)
|
||||
.await
|
||||
.unwrap()
|
||||
.compat_write();
|
||||
|
||||
tokio::io::copy(&mut body_reader, &mut entry_writer)
|
||||
.await
|
||||
.map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()))?;
|
||||
|
||||
entry_writer
|
||||
.into_inner()
|
||||
.close()
|
||||
.await
|
||||
.map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()))?;
|
||||
}
|
||||
|
||||
let mut records = state.records.lock().await;
|
||||
let record = UploadRecord::new(archive_path);
|
||||
records.insert(cache_name.clone(), record.clone());
|
||||
|
||||
cache::write_to_cache(&records)
|
||||
.await
|
||||
.map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()))?;
|
||||
|
||||
writer.close().await.unwrap();
|
||||
|
||||
let id = cache_name;
|
||||
let response = Response::builder()
|
||||
.status(200)
|
||||
.header("Content-Type", "text/html")
|
||||
.header("HX-Push-Url", format!("/link/{}", &id))
|
||||
.body(ssr::render(|| {
|
||||
leptos::view! { <LinkView id record /> }
|
||||
}))
|
||||
.unwrap();
|
||||
|
||||
Ok(response)
|
||||
}
|
|
@ -1,5 +1,6 @@
|
|||
use leptos::{component, view, IntoView};
|
||||
|
||||
use crate::link::get_remaining_text;
|
||||
use crate::state::UploadRecord;
|
||||
use crate::HtmxPage;
|
||||
|
||||
|
@ -19,7 +20,6 @@ pub fn DownloadLinkPage(id: String, record: UploadRecord) -> impl IntoView {
|
|||
#[component]
|
||||
pub fn LinkView(id: String, record: UploadRecord) -> impl IntoView {
|
||||
let downloads_remaining = record.max_downloads - record.downloads;
|
||||
let plural = if downloads_remaining > 1 { "s" } else { "" };
|
||||
view! {
|
||||
<div class="column-container">
|
||||
<div class="link-wrapper">
|
||||
|
@ -33,11 +33,7 @@ pub fn LinkView(id: String, record: UploadRecord) -> impl IntoView {
|
|||
hx-get="/link/{id}/remaining"
|
||||
hx-trigger="click from:#link delay:0.2s, every 10s"
|
||||
>
|
||||
You have
|
||||
{record.downloads_remaining()}
|
||||
download
|
||||
{plural}
|
||||
remaining!
|
||||
{get_remaining_text(downloads_remaining)}
|
||||
</div>
|
||||
<button class="return-button" onclick="clipboard()">
|
||||
Copy to Clipboard
|
||||
|
|
Loading…
Reference in New Issue