uhh... yikes

This commit is contained in:
Zynh Ludwig 2024-08-28 17:53:13 -07:00
parent 5fbef7f8bf
commit f7e068d562
6 changed files with 667 additions and 647 deletions

1124
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -8,24 +8,41 @@ edition = "2021"
[dependencies]
async-bincode = { version = "0.7.0", features = ["tokio"] }
async-trait = "0.1.72"
async_zip = { version = "0.0.13", features = ["deflate", "tokio", "tokio-fs", "async-compression"] }
axum = { version = "0.6.12", features = ["multipart", "http2", "headers", "macros", "original-uri"] }
async-trait = "0.1.81"
async_zip = { version = "0.0.17", features = [
"deflate",
"tokio",
"tokio-fs",
"async-compression",
] }
http-body-util = "0.1.2"
axum = { version = "0.7.5", features = [
"multipart",
"http2",
"macros",
"original-uri",
] }
axum-extra = { version = "0.9.0", features = ["typed-header"] }
bincode = "1.3.3"
chrono = { version = "0.4.24", features = ["serde"] }
futures = "0.3.28"
headers = "0.3.8"
leptos = { version = "0.4.6", features = ["ssr", "nightly", "tracing", "default-tls"] }
leptos_meta = { version = "0.4.6", features = ["ssr"] }
leptos_router = { version = "0.4.6", features = ["ssr"] }
headers = "0.4.0"
leptos = { version = "0.6.1", features = [
"ssr",
"nightly",
"tracing",
"default-tls",
] }
leptos_meta = { version = "0.6.1", features = ["ssr"] }
leptos_router = { version = "0.6.1", features = ["ssr"] }
rand = { version = "0.8.5", features = ["small_rng"] }
reqwest = { version = "0.11.18", features = ["json", "native-tls", "blocking"] }
reqwest = { version = "0.12.7", features = ["json", "native-tls", "blocking"] }
sanitize-filename-reader-friendly = "2.2.1"
serde = { version = "1.0.160", features = ["serde_derive", "derive"] }
serde_derive = "1.0.160"
tokio = { version = "1.27.0", features = ["full"] }
tokio-util = { version = "0.7.7", features = ["io"] }
tower = { version = "0.4.13", features = ["util"] }
tower-http = { version = "0.4.0", features = ["fs", "trace", "limit"] }
tower = { version = "0.5.0", features = ["util"] }
tower-http = { version = "0.5.0", features = ["fs", "trace", "limit"] }
tracing = "0.1.37"
tracing-subscriber = { version = "0.3.16", features = ["env-filter"] }

View file

@ -1,7 +1,5 @@
use crate::state::AppState;
use super::error;
use serde::Serialize;
use tokio::io::AsyncReadExt;
@ -17,7 +15,7 @@ where
let mut records_cache = tokio::fs::File::create(".cache/data").await.unwrap();
let mut buf: Vec<u8> = Vec::with_capacity(200);
bincode::serialize_into(&mut buf, records).map_err(|err| error::io_other(&err.to_string()))?;
bincode::serialize_into(&mut buf, records).map_err(io::Error::other)?;
let bytes_written = tokio::io::copy(&mut buf.as_slice(), &mut records_cache).await?;

View file

@ -1,19 +1,18 @@
use async_zip::{tokio::write::ZipFileWriter, Compression, ZipEntryBuilder};
use axum::{
body::StreamBody,
extract::{ConnectInfo, DefaultBodyLimit, Multipart, State},
http::{Request, Response, StatusCode},
body::Body,
extract::{ConnectInfo, DefaultBodyLimit, Multipart, Request, State},
http::{HeaderMap, Response, StatusCode},
middleware::{self, Next},
response::{Html, IntoResponse, Redirect},
routing::{get, post},
Json, Router, TypedHeader,
Json, Router,
};
use axum_extra::TypedHeader;
use futures::TryStreamExt;
use headers::HeaderMap;
use leptos::IntoView;
use nyazoom_headers::ForwardedFor;
use sanitize_filename_reader_friendly::sanitize;
@ -105,8 +104,11 @@ async fn main() -> io::Result<()> {
// Server creation
let addr = SocketAddr::from(([0, 0, 0, 0], 3000));
tracing::debug!("listening on http://{}/", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service_with_connect_info::<SocketAddr>())
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
axum::serve(
listener,
app.into_make_service_with_connect_info::<SocketAddr>(),
)
.await
.unwrap();
@ -133,9 +135,12 @@ async fn remaining(
async fn welcome() -> impl IntoResponse {
let cat_fact = views::get_cat_fact().await;
Html(leptos::ssr::render_to_string(move |cx| {
leptos::view! { cx, <Welcome fact=cat_fact /> }
}))
Html(
leptos::ssr::render_to_string(move || {
leptos::view! { <Welcome fact=cat_fact /> }
})
.to_string(),
)
}
async fn records(State(state): State<AppState>) -> impl IntoResponse {
@ -146,13 +151,14 @@ async fn records(State(state): State<AppState>) -> impl IntoResponse {
// this behind some kind of authentication
async fn records_links(State(state): State<AppState>) -> impl IntoResponse {
let records = state.records.lock().await.clone();
Html(leptos::ssr::render_to_string(move |cx| {
leptos::view! { cx,
Html(
leptos::ssr::render_to_string(move || {
leptos::view! {
<HtmxPage>
<div class="form-wrapper">
<div class="column-container">
<ul>
{records.keys().map(|key| leptos::view! { cx,
{records.keys().map(|key| leptos::view! {
<li class="link-wrapper">
<a href="/link/{key}">{key}</a>
<button style="margin-left: 1em;"
@ -167,7 +173,9 @@ async fn records_links(State(state): State<AppState>) -> impl IntoResponse {
</div>
</HtmxPage>
}
}))
})
.to_string(),
)
}
async fn link(
@ -182,12 +190,15 @@ async fn link(
.filter(|record| record.can_be_downloaded())
{
if record.can_be_downloaded() {
return Ok(Html(leptos::ssr::render_to_string({
return Ok(Html(
leptos::ssr::render_to_string({
let record = record.clone();
|cx| {
leptos::view! { cx, <DownloadLinkPage id=id record=record /> }
|| {
leptos::view! { <DownloadLinkPage id=id record=record /> }
}
})));
})
.into(),
));
}
}
}
@ -195,7 +206,7 @@ async fn link(
// TODO: This....
state.remove_record(&id).await.unwrap();
Err(Redirect::to(&format!("/404.html")))
Err(Redirect::to("/404.html"))
}
async fn link_delete(
@ -210,11 +221,11 @@ async fn link_delete(
Ok(Html("".to_string()))
}
async fn log_source<B>(
async fn log_source(
ConnectInfo(addr): ConnectInfo<SocketAddr>,
forwarded_for: Option<TypedHeader<ForwardedFor>>,
req: Request<B>,
next: Next<B>,
req: Request,
next: Next,
) -> impl IntoResponse {
tracing::info!("{} : {:?}", addr, forwarded_for);
@ -229,7 +240,7 @@ async fn upload_to_zip(
let cache_name = util::get_random_name(10);
let archive_path = Path::new(".cache/serve").join(&format!("{}.zip", &cache_name));
let archive_path = Path::new(".cache/serve").join(format!("{}.zip", &cache_name));
tracing::debug!("Zipping: {:?}", &archive_path);
@ -247,7 +258,7 @@ async fn upload_to_zip(
tracing::debug!("Downloading to Zip: {file_name:?}");
let stream = field;
let body_with_io_error = stream.map_err(|err| io::Error::new(io::ErrorKind::Other, err));
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, Compression::Deflate);
@ -283,9 +294,12 @@ async fn upload_to_zip(
.status(200)
.header("Content-Type", "text/html")
.header("HX-Push-Url", format!("/link/{}", &id))
.body(leptos::ssr::render_to_string(|cx| {
leptos::view! { cx, <LinkView id record /> }
}))
.body(
leptos::ssr::render_to_string(|| {
leptos::view! { <LinkView id record /> }
})
.into(),
)
.unwrap();
Ok(response)
@ -317,9 +331,8 @@ async fn download(
return Ok(axum::response::Response::builder()
.header("Content-Type", "application/zip")
.body(StreamBody::new(ReaderStream::new(file)))
.unwrap()
.into_response());
.body(Body::from_stream(ReaderStream::new(file)))
.unwrap());
} else {
records.remove_record(&id).await.unwrap()
}

View file

@ -66,12 +66,12 @@ impl AppState {
#[async_trait]
pub trait AsyncRemoveRecord {
async fn remove_record(&mut self, id: &String) -> Result<(), std::io::Error>;
async fn remove_record(&mut self, id: &str) -> Result<(), std::io::Error>;
}
#[async_trait]
impl AsyncRemoveRecord for AppState {
async fn remove_record(&mut self, id: &String) -> Result<(), std::io::Error> {
async fn remove_record(&mut self, id: &str) -> Result<(), std::io::Error> {
let mut records = self.records.lock().await;
records.remove_record(id).await
}
@ -79,12 +79,12 @@ impl AsyncRemoveRecord for AppState {
#[async_trait]
impl AsyncRemoveRecord for HashMap<String, UploadRecord> {
async fn remove_record(&mut self, id: &String) -> Result<(), std::io::Error> {
match self.entry(id.clone()) {
async fn remove_record(&mut self, id: &str) -> Result<(), std::io::Error> {
match self.entry(id.to_string()) {
Entry::Occupied(entry) => {
tokio::fs::remove_file(&entry.get().file).await?;
entry.remove_entry();
cache::write_to_cache(&self).await?;
cache::write_to_cache(self).await?;
Ok(())
}

View file

@ -1,5 +1,5 @@
use futures::TryFutureExt;
use leptos::{component, view, Children, IntoView, Scope};
use leptos::{component, view, Children, IntoView};
use serde::Deserialize;
use crate::state::UploadRecord;
@ -20,8 +20,8 @@ pub async fn get_cat_fact() -> String {
// {https://api.thecatapi.com/v1/images/search?size=small&format=src}
// {https://cataas.com/cat?width=250&height=250}
#[component]
pub fn Welcome(cx: Scope, fact: String) -> impl IntoView {
view! { cx,
pub fn Welcome(fact: String) -> impl IntoView {
view! {
<HtmxPage>
<div class="form-wrapper">
<WelcomeView fact />
@ -31,9 +31,8 @@ pub fn Welcome(cx: Scope, fact: String) -> impl IntoView {
}
#[component]
pub fn WelcomeView(cx: Scope, fact: String) -> impl IntoView {
pub fn WelcomeView(fact: String) -> impl IntoView {
view! {
cx,
<form id="form" hx-swap="outerHTML" hx-post="/upload" hx-encoding="multipart/form-data" class="column-container">
<div class="cat-img-wrapper">
<img class="cat-img" src="https://api.thecatapi.com/v1/images/search?size=small&format=src" />
@ -52,8 +51,8 @@ pub fn WelcomeView(cx: Scope, fact: String) -> impl IntoView {
// <link href="../dist/css/link.css" rel="stylesheet" />
// #TODO: Handle pushing cleaner
#[component]
pub fn DownloadLinkPage(cx: Scope, id: String, record: UploadRecord) -> impl IntoView {
view! { cx,
pub fn DownloadLinkPage(id: String, record: UploadRecord) -> impl IntoView {
view! {
<HtmxPage>
<div class="form-wrapper">
<LinkView id record />
@ -63,8 +62,8 @@ pub fn DownloadLinkPage(cx: Scope, id: String, record: UploadRecord) -> impl Int
}
#[component]
pub fn HtmxPage(cx: Scope, children: Children) -> impl IntoView {
view! { cx,
pub fn HtmxPage(children: Children) -> impl IntoView {
view! {
<head>
<title>Nyazoom</title>
<meta charset="UTF-8" />
@ -78,17 +77,16 @@ pub fn HtmxPage(cx: Scope, children: Children) -> impl IntoView {
<body>
<h1>NyaZoom<sup>2</sup></h1>
{children(cx)}
{children()}
</body>
}
}
#[component]
pub fn LinkView(cx: Scope, id: String, record: UploadRecord) -> impl IntoView {
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! {
cx,
<div class="column-container">
<div class="link-wrapper">
<a id="link" href="/download/{id}">Download Now!</a>