feat: functional frontend for uploading api

This commit is contained in:
kossLAN 2025-03-01 21:39:56 -05:00
parent 7f8d940ef5
commit c423174110
Signed by: kossLAN
SSH key fingerprint: SHA256:bdV0x+wdQHGJ6LgmstH3KV8OpWY+OOFmJcPcB0wQPV8
6 changed files with 580 additions and 38 deletions

View file

@ -4,15 +4,11 @@ Essentially tinyupload is a personal cdn, that you can host yourself. Why? mostl
## Motivation
I made this to solve a problem I have with discord, by using a vencord plugin eventually I'll be able to just upload directly to my instance of tinyupload and get past Discord's low 10mb upload limit, without having to pay $10/month to do so.
My free solution to getting by discord's absurdly low upload limit, a tiny cdn.
## RoadMap
- [ ] Server Side Encryption
- [ ] Vencord Plugin
- [ ] Config File
- [ ] Config File (Maybe)
*and probably many others*
## Acknowledgements
This was really my first fully fledged project in rust, which was made a lot easier from the help of [outfoxxed](https://github.com/outfoxxed), check out some of the stuff he does.

298
pages/home.html Normal file
View file

@ -0,0 +1,298 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{title}}</title>
<link rel="stylesheet" href="/static/common.css">
<style>
/* Home-specific styles */
.upload-form {
display: flex;
flex-direction: column;
gap: 1.5rem;
}
.file-input-container {
position: relative;
border: 2px dashed var(--primary-color);
border-radius: 8px;
padding: 2rem;
text-align: center;
cursor: pointer;
transition: all 0.3s ease;
}
.file-input-container:hover {
border-color: var(--accent-color);
background-color: rgba(79, 195, 247, 0.05);
}
.file-input-container.drag-over {
border-color: var(--accent-color);
background-color: rgba(79, 195, 247, 0.1);
}
.file-input-label {
display: block;
font-weight: 500;
margin-bottom: 0.5rem;
color: var(--secondary-color);
}
.file-input {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
cursor: pointer;
}
.file-name {
margin-top: 1rem;
font-size: 0.9rem;
color: var(--secondary-color);
word-break: break-all;
}
.result-container {
display: none;
margin-top: 2rem;
padding: 1.5rem;
background-color: #e8f5e9;
border-radius: 8px;
border-left: 4px solid var(--success-color);
}
.result-title {
color: var(--success-color);
margin-top: 0;
margin-bottom: 1rem;
}
.file-link {
display: block;
padding: 0.8rem;
color: blue;
background-color: white;
border: 1px solid #ddd;
border-radius: 4px;
word-break: break-all;
margin-bottom: 1rem;
font-family: monospace;
}
.copy-btn {
background-color: var(--secondary-color);
color: white;
border: none;
border-radius: 5px;
padding: 0.5rem 1rem;
font-size: 0.9rem;
cursor: pointer;
transition: background-color 0.3s ease;
width: auto;
}
async fn css_file() -> impl IntoResponse {
// Create headers with content type for CSS
let mut headers = HeaderMap::new();
headers.insert(header::CONTENT_TYPE, "text/css".parse().unwrap());
// Return the CSS content with appropriate headers
(headers, include_str!("../static/common.css"))
}
.copy-btn:hover {
background-color: var(--primary-color);
}
.loading {
display: none;
margin: 1rem auto;
border: 4px solid rgba(0, 0, 0, 0.1);
border-top: 4px solid var(--primary-color);
border-radius: 50%;
width: 30px;
height: 30px;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.error-message {
display: none;
color: #f44336;
background-color: #ffebee;
padding: 1rem;
border-radius: 5px;
margin-top: 1rem;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<h1>{{title}}</h1>
<form id="uploadForm" class="upload-form" enctype="multipart/form-data">
<div id="fileInputContainer" class="file-input-container">
<span class="file-input-label">Drag & drop a file here or click to browse</span>
<input type="file" id="fileInput" name="file" class="file-input" required>
<div id="fileName" class="file-name"></div>
</div>
<button type="submit" id="uploadBtn" class="upload-btn" disabled>Upload</button>
<div id="loading" class="loading"></div>
<div id="errorMessage" class="error-message"></div>
</form>
<div id="resultContainer" class="result-container">
<h3 class="result-title">Upload Successful!</h3>
<div id="fileLink" class="file-link"></div>
<button id="copyBtn" class="copy-btn">Copy Link</button>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const form = document.getElementById('uploadForm');
const fileInput = document.getElementById('fileInput');
const fileInputContainer = document.getElementById('fileInputContainer');
const fileName = document.getElementById('fileName');
const uploadBtn = document.getElementById('uploadBtn');
const loading = document.getElementById('loading');
const resultContainer = document.getElementById('resultContainer');
const fileLink = document.getElementById('fileLink');
const copyBtn = document.getElementById('copyBtn');
const errorMessage = document.getElementById('errorMessage');
// File input change handler
fileInput.addEventListener('change', function() {
if (this.files.length > 0) {
fileName.textContent = this.files[0].name;
uploadBtn.disabled = false;
} else {
fileName.textContent = '';
uploadBtn.disabled = true;
}
});
// Drag and drop handlers
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
fileInputContainer.addEventListener(eventName, preventDefaults, false);
});
function preventDefaults(e) {
e.preventDefault();
e.stopPropagation();
}
['dragenter', 'dragover'].forEach(eventName => {
fileInputContainer.addEventListener(eventName, highlight, false);
});
['dragleave', 'drop'].forEach(eventName => {
fileInputContainer.addEventListener(eventName, unhighlight, false);
});
function highlight() {
fileInputContainer.classList.add('drag-over');
}
function unhighlight() {
fileInputContainer.classList.remove('drag-over');
}
fileInputContainer.addEventListener('drop', handleDrop, false);
function handleDrop(e) {
const dt = e.dataTransfer;
const files = dt.files;
if (files.length > 0) {
fileInput.files = files;
fileName.textContent = files[0].name;
uploadBtn.disabled = false;
}
}
// Form submission
form.addEventListener('submit', function(e) {
e.preventDefault();
if (!fileInput.files.length) {
return;
}
// Hide any previous error
errorMessage.style.display = 'none';
// Show loading spinner
loading.style.display = 'block';
uploadBtn.disabled = true;
const formData = new FormData();
formData.append('file', fileInput.files[0]);
fetch('/upload', {
method: 'POST',
body: formData
})
.then(response => {
if (!response.ok) {
throw new Error('Upload failed. Please try again.');
}
return response.text();
})
.then(data => {
// Hide loading spinner
loading.style.display = 'none';
// Show result
fileLink.textContent = data;
resultContainer.style.display = 'block';
// Reset form
form.reset();
fileName.textContent = '';
uploadBtn.disabled = true;
})
.catch(error => {
// Hide loading spinner
loading.style.display = 'none';
// Show error message
errorMessage.textContent = error.message;
errorMessage.style.display = 'block';
// Re-enable upload button
uploadBtn.disabled = false;
});
});
// Copy link button
copyBtn.addEventListener('click', function() {
const tempInput = document.createElement('input');
document.body.appendChild(tempInput);
tempInput.value = fileLink.textContent;
tempInput.select();
document.execCommand('copy');
document.body.removeChild(tempInput);
// Change button text temporarily
const originalText = this.textContent;
this.textContent = 'Copied!';
setTimeout(() => {
this.textContent = originalText;
}, 2000);
});
});
</script>
</body>
</html>

22
pages/login.html Normal file
View file

@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{title}} - Login</title>
<link rel="stylesheet" href="/static/common.css">
</head>
<body>
<div class="container">
<h1>{{title}} login</h1>
<form action="/login" method="post">
<div class="form-group">
<label for="key">Enter Access Key:</label>
<input type="password" id="key" name="key" required autofocus>
</div>
<button type="submit">Login</button>
<div id="error" class="error"></div>
</form>
</div>
</body>
</html>

97
pages/static/common.css Normal file
View file

@ -0,0 +1,97 @@
:root {
--primary-color: lightblue;
--secondary-color: lightgrey;
--accent-color: #4fc3f7;
--background-color: #2A2E32;
--text-color: white;
--success-color: #4caf50;
--container-bg: #40464C;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: var(--background-color);
color: var(--text-color);
line-height: 1.6;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
}
.container {
width: 90%;
max-width: 600px;
background-color: var(--container-bg);
border-radius: 10px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
padding: 2rem;
margin: 2rem 0;
text-align: center;
}
h1 {
color: var(--primary-color);
margin-bottom: 1.5rem;
}
button {
background-color: var(--primary-color);
color: white;
border: none;
border-radius: 5px;
padding: 0.8rem 1.5rem;
font-size: 1rem;
font-weight: 500;
cursor: pointer;
transition: background-color 0.3s ease;
width: 100%;
}
button:hover {
background-color: var(--secondary-color);
}
button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
.form-group {
margin-bottom: 1.5rem;
}
label {
display: block;
font-weight: 500;
margin-bottom: 0.5rem;
color: var(--secondary-color);
text-align: left;
}
input {
width: 100%;
padding: 0.8rem;
border: 2px solid var(--secondary-color);
border-radius: 5px;
background-color: rgba(255, 255, 255, 0.1);
color: var(--text-color);
font-size: 1rem;
box-sizing: border-box;
}
input:focus {
border-color: var(--accent-color);
outline: none;
}
.error {
color: #f44336;
text-align: center;
margin-top: 1rem;
font-size: 0.9rem;
}

View file

@ -18,6 +18,10 @@ struct Cli {
#[arg(short, long, default_value = "0.0.0.0:1337")]
address: String,
/// The title displayed in the frontend of tinyupload.
#[arg(short, long, default_value = "tinyupload")]
title: String,
// The upload limit in Mb.
#[arg(short, long, default_value_t = 100)]
upload_size: usize,
@ -43,7 +47,7 @@ async fn main() {
Commands::Serve {} => {
println!("Starting server on {}", cli.address);
let db = database::init(cli.database_url).await.unwrap();
server::init(db, cli.files_path, cli.upload_size, cli.address).await;
server::init(db, cli.files_path, cli.upload_size, cli.address, cli.title).await;
}
Commands::Generate {} => {

View file

@ -2,12 +2,13 @@ use crate::database;
use axum::{
body::Body,
extract::{DefaultBodyLimit, Multipart, Path, State},
extract::{DefaultBodyLimit, Form, Multipart, Path, State},
http::{
header::{self, HeaderMap},
StatusCode,
Request, StatusCode,
},
response::{IntoResponse, Response},
middleware::{self, Next},
response::{Html, IntoResponse, Redirect, Response},
routing::{get, post},
Router,
};
@ -24,6 +25,7 @@ use tokio::io::{AsyncReadExt, AsyncSeekExt};
struct AppState {
db: SqlitePool,
files_path: String,
title: String,
}
#[derive(Deserialize)]
@ -31,25 +33,120 @@ struct Media {
urlpath: String,
}
pub async fn init(db: SqlitePool, files_path: String, upload_size: usize, address: String) {
// Initialize the state
let state = AppState { db, files_path };
#[derive(Deserialize)]
struct LoginForm {
key: String,
}
const AUTH_COOKIE: &str = "auth_token";
pub async fn init(
db: SqlitePool,
files_path: String,
upload_size: usize,
address: String,
title: String,
) {
let state = AppState {
db,
files_path,
title,
};
// Initialize tracing
tracing_subscriber::fmt::init();
// Build our application with a route
let app = Router::new()
// Testing serving a file
.route("/:urlpath", get(stream))
.route("/", get(home))
.route("/login", get(login_page).post(process_login))
.route("/static/common.css", get(css_file))
.route("/file/:urlpath", get(stream))
.route("/upload", post(upload))
.with_state(state)
.layer(DefaultBodyLimit::max(1024 * 1024 * upload_size));
.layer(middleware::from_fn_with_state(
state.clone(),
auth_middleware,
))
.layer(DefaultBodyLimit::max(1024 * 1024 * upload_size))
.with_state(state);
let listener = tokio::net::TcpListener::bind(address).await.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn home(State(state): State<AppState>) -> impl IntoResponse {
let html = include_str!("../pages/home.html").replace("{{title}}", &state.title);
Html(html)
}
async fn login_page(State(state): State<AppState>) -> impl IntoResponse {
let html = include_str!("../pages/login.html").replace("{{title}}", &state.title);
Html(html)
}
async fn css_file() -> impl IntoResponse {
let mut headers = HeaderMap::new();
headers.insert(header::CONTENT_TYPE, "text/css".parse().unwrap());
(headers, include_str!("../pages/static/common.css"))
}
async fn process_login(
State(state): State<AppState>,
Form(form): Form<LoginForm>,
) -> impl IntoResponse {
if database::check_key(&state.db, form.key.clone())
.await
.unwrap_or(false)
{
let mut response = Redirect::to("/").into_response();
let cookie = format!(
"{}={}; Path=/; HttpOnly; Max-Age=604800",
AUTH_COOKIE, form.key
);
response.headers_mut().insert(
header::SET_COOKIE,
header::HeaderValue::from_str(&cookie).unwrap(),
);
response
} else {
Redirect::to("/login").into_response()
}
}
async fn auth_middleware(
State(state): State<AppState>,
request: Request<Body>,
next: Next,
) -> Response {
let path = request.uri().path();
let allowed_paths = ["/login", "/upload", "/static/common.css"];
if allowed_paths.contains(&path) || path.starts_with("/file/") {
return next.run(request).await;
}
let cookie_value = request
.headers()
.get(header::COOKIE)
.and_then(|_| get_cookie_value(request.headers(), AUTH_COOKIE));
let is_authenticated = match cookie_value {
Some(value) => match database::check_key(&state.db, value).await {
Ok(is_valid) => is_valid,
Err(_) => false,
},
None => false,
};
// Allow other requests if user is authenticated
if is_authenticated {
next.run(request).await
} else {
Redirect::to("/login").into_response()
}
}
// TODO: This only really works for video's right now, need to put some checks in for other file types
async fn stream(
State(state): State<AppState>,
Path(Media { urlpath }): Path<Media>,
@ -153,25 +250,33 @@ fn parse_range_header(h: &str, len: u64) -> Option<(u64, u64)> {
}
// Everything below is for uploading functionality
async fn upload(
State(state): State<AppState>,
headers: HeaderMap,
mut multipart: Multipart,
) -> Response {
// Create a response builder
let mut response_builder = Response::builder();
// Add CORS headers
response_builder = response_builder.header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*");
// Key validation
let key = headers
let scheme = headers
.get("x-forwarded-proto")
.and_then(|h| h.to_str().ok())
.unwrap_or("http");
let host = headers
.get(header::HOST)
.and_then(|h| h.to_str().ok())
.unwrap_or("localhost:1337");
// Key validation, check cookie if it, otherwise fall back to API key header (for API uploads)
let key = get_cookie_value(&headers, AUTH_COOKIE).unwrap_or_else(|| {
headers
.get("x-api-key")
.unwrap_or(&"None".parse().unwrap())
.to_str()
.unwrap()
.into();
.and_then(|v| v.to_str().ok())
.unwrap_or("None")
.to_string()
});
if !database::check_key(&state.db, key).await.unwrap_or(false) {
println!("Attempt to upload without a valid key.");
@ -183,17 +288,16 @@ async fn upload(
// Processing the multipart form data
while let Some(field) = multipart.next_field().await.unwrap_or(None) {
let (name, ext) = parse_filename(field.name().unwrap());
let (name, ext) = (name.to_string(), ext.unwrap_or("").to_string());
let field_name = field.name().unwrap_or("file").to_string();
let original_filename = field.file_name().unwrap_or("unnamed_file").to_string();
let (_, ext) = parse_filename(&original_filename);
let (name, ext) = (field_name, ext.unwrap_or("").to_string());
let data = match field.bytes().await {
Ok(data) => data,
Err(e) => {
println!(
"Error reading field data: {:?}
(Chances are that the upload size is not enough)",
e
);
println!("Error reading field data: {:?}", e);
continue;
}
};
@ -201,6 +305,8 @@ async fn upload(
// Hash file name
let mut s = DefaultHasher::new();
name.hash(&mut s);
original_filename.hash(&mut s);
data.hash(&mut s);
let hash = s.finish();
let full_path = format!("{}/{}", state.files_path, hash);
@ -223,7 +329,11 @@ async fn upload(
println!("New file uploaded to {}", full_path);
}
Err(e) => {
println!("Error writing to file: {:?}", e);
println!(
"Error writing to file:
{:?}",
e
);
continue;
}
};
@ -251,7 +361,7 @@ async fn upload(
.unwrap();
// The file name doesn't matter here we just spoof it
let rel_path = format!("{}.{}", hash, ext);
let rel_path = format!("{}://{}/file/{}.{}", scheme, host, hash, ext);
return response_builder
.status(StatusCode::OK)
.body(axum::body::Body::from(rel_path))
@ -264,6 +374,21 @@ async fn upload(
.unwrap()
}
fn get_cookie_value(headers: &HeaderMap, name: &str) -> Option<String> {
let cookies = headers.get(header::COOKIE)?;
let cookies_str = cookies.to_str().ok()?;
cookies_str.split(';').map(|s| s.trim()).find_map(|cookie| {
let mut parts = cookie.split('=');
let cookie_name = parts.next()?;
if cookie_name == name {
parts.next().map(|value| value.to_string())
} else {
None
}
})
}
fn generate_etag(path: &str) -> String {
let modified_secs = Utc::now().timestamp();