From e70bd1c35348e344015e5f718a8d70e134d3f5f3 Mon Sep 17 00:00:00 2001 From: Volkor <me@volkor.me> Date: Fri, 7 Jul 2023 23:04:39 +1000 Subject: [PATCH] run cargofmt --- src/db.rs | 9 +++- src/engine.rs | 2 +- src/handlers/list_files.rs | 2 +- src/handlers/mod.rs | 46 ++++++++++------- src/handlers/serve_file.rs | 101 ++++++++++++++++++++----------------- src/handlers/upload.rs | 9 ++-- 6 files changed, 95 insertions(+), 74 deletions(-) diff --git a/src/db.rs b/src/db.rs index f4d59d6..7499508 100644 --- a/src/db.rs +++ b/src/db.rs @@ -1,6 +1,6 @@ use sqlx::{sqlite::SqliteQueryResult, Pool, Sqlite}; -use tracing::debug; use std::{collections::HashMap, time::SystemTime}; +use tracing::debug; /// This struct represents a single file, with a few statistics about said file instance. pub struct FileMetric { @@ -88,7 +88,12 @@ pub async fn add_file( ) .execute(sqlconn) .await?; - tracing::debug!("[{}] Added {} ({}) to the database", &domain, &file, &mimetype); + tracing::debug!( + "[{}] Added {} ({}) to the database", + &domain, + &file, + &mimetype + ); Ok(result) // Will need to add another else if for expiry_override if added later. } diff --git a/src/engine.rs b/src/engine.rs index f77b7a7..378ed70 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -41,7 +41,7 @@ pub async fn generate_adminkey(sqlconn: &Pool<Sqlite>) -> String { .adminkey_size .try_into() .expect("Problem with converting adminkey_size to usize"); - + let adminkey = nanoid!(adminkey_size); let result = db::check_adminkey(sqlconn, &adminkey).await; if result.is_ok() { diff --git a/src/handlers/list_files.rs b/src/handlers/list_files.rs index 1821365..c144d52 100644 --- a/src/handlers/list_files.rs +++ b/src/handlers/list_files.rs @@ -49,7 +49,7 @@ pub async fn list_files(req: &mut Request, res: &mut Response) { } else { "background-color: #00ff100a;".to_string() }; - + // Add a new file to the rendered string html.push_str(&format!("<tr style='{}'><td><a href={}>{}</a></td><td data-sort='{}'>{}</td><td>{}</td><td>{}</td><td data-sort='{}'>{}</td></tr>", colour, diff --git a/src/handlers/mod.rs b/src/handlers/mod.rs index 0d11e99..fc369e8 100644 --- a/src/handlers/mod.rs +++ b/src/handlers/mod.rs @@ -1,4 +1,9 @@ -use std::{path::PathBuf, time::{Duration, SystemTime}, fs::{self, File}, io::Read}; +use std::{ + fs::{self, File}, + io::Read, + path::PathBuf, + time::{Duration, SystemTime}, +}; use chrono::{DateTime, Utc}; use chrono_humanize::Humanize; @@ -10,12 +15,13 @@ use salvo::{ writer::Text, Response, }; -use sqlx::{Error, sqlite::SqliteQueryResult}; +use sqlx::{sqlite::SqliteQueryResult, Error}; use tokio::{task, time}; use crate::{ db::{self, FileMetric}, - engine::{self, calculate_expiry, generate_adminkey}, CONFIG, COOKIE, SQLITE, + engine::{self, calculate_expiry, generate_adminkey}, + CONFIG, COOKIE, SQLITE, }; // Submodules for each request handler @@ -272,7 +278,9 @@ async fn check_file_exists(filename: &str, directory: &str) -> bool { /// It adds it back to the database, with stub information. pub async fn add_undeleted_file(filename: &str) -> Result<SqliteQueryResult, sqlx::Error> { // Grab a SQLITE pool - let sqlconn = SQLITE.get().expect("There was a problem grabbing a SQLite Pool"); + let sqlconn = SQLITE + .get() + .expect("There was a problem grabbing a SQLite Pool"); // Get the path for the file let path = PathBuf::from("files/").join(filename); @@ -286,7 +294,7 @@ pub async fn add_undeleted_file(filename: &str) -> Result<SqliteQueryResult, sql mime_file .read_exact(&mut buffer) .expect("Error reading file"); - + let mimetype = detect_mime_type(&buffer).unwrap_or("text/plain".to_string()); // Check the filesize @@ -298,8 +306,8 @@ pub async fn add_undeleted_file(filename: &str) -> Result<SqliteQueryResult, sql let adminkey = generate_adminkey(sqlconn).await; // Set accessed to now let accessed = SystemTime::now() - .duration_since(SystemTime::UNIX_EPOCH) - .unwrap(); + .duration_since(SystemTime::UNIX_EPOCH) + .unwrap(); // Set 'domain' to "legacy" // since this is just for fancy stats, it'll work well when we don't know where it was uploaded. @@ -307,15 +315,15 @@ pub async fn add_undeleted_file(filename: &str) -> Result<SqliteQueryResult, sql // Add the file to the database db::add_file( - sqlconn, - filename, - &mimetype, - expiry, - &adminkey, - accessed.as_secs() as i32, - filesize, - "127.0.0.1", - domain - ).await - -} \ No newline at end of file + sqlconn, + filename, + &mimetype, + expiry, + &adminkey, + accessed.as_secs() as i32, + filesize, + "127.0.0.1", + domain, + ) + .await +} diff --git a/src/handlers/serve_file.rs b/src/handlers/serve_file.rs index 6fcbb6f..ec482dd 100644 --- a/src/handlers/serve_file.rs +++ b/src/handlers/serve_file.rs @@ -1,18 +1,22 @@ use salvo::{ fs::NamedFile, + handler, http::HeaderValue, - hyper::{header::{self, HOST}, HeaderMap}, + hyper::{ + header::{self, HOST}, + HeaderMap, + }, prelude::StatusCode, writer::Text, - Request, Response, handler, + Request, Response, }; -use tracing::debug; use std::time::SystemTime; +use tracing::debug; use crate::{ db::{self, FileCheckResult}, engine, - handlers::{render_template, TemplateStruct, check_file_exists, add_undeleted_file}, + handlers::{add_undeleted_file, check_file_exists, render_template, TemplateStruct}, CONFIG, SQLITE, }; @@ -20,13 +24,15 @@ use crate::{ /// This function converts any unsafe mimetypes to text/plain, and should /always/ nicely render an error if something goes wrong. pub async fn render_file(req: &mut Request, res: &mut Response, headers: HeaderMap) { // Grab the filename for easy use later - let filename: String = req.param("file").expect("Failed to set the filename variable"); + let filename: String = req + .param("file") + .expect("Failed to set the filename variable"); tracing::info!("New File View: {:?}", &filename.to_string()); // Get a new sql pool thingy let sqlconn = SQLITE.get().expect("Failed to grab sqlite pool"); - + // Read the list of unsafe mimetypes from the config let mime_unsafe = &CONFIG.operations.unsafe_mimetype; @@ -65,45 +71,45 @@ pub async fn render_file(req: &mut Request, res: &mut Response, headers: HeaderM 0 }); - // Check if engine mode is set to 1, to recalculate the expiry based on views. - if CONFIG.operations.engine_mode == 1 { - // Recalculate expiry here - // Filesize is 0 since we don't need it for this engine mode. - engine::calculate_expiry(sqlconn, filename.clone(), 0).await; - } + // Check if engine mode is set to 1, to recalculate the expiry based on views. + if CONFIG.operations.engine_mode == 1 { + // Recalculate expiry here + // Filesize is 0 since we don't need it for this engine mode. + engine::calculate_expiry(sqlconn, filename.clone(), 0).await; + } - // Check if nginx sendfile is enabled, because we can skip this if it is. - if CONFIG.server.nginx_sendfile { - // Add the X-Accel-Redirect header, allowing for faster file serving. - // I was told to put a Path here, but I don't think it's really necessary, since it's converted to a HeaderValue anyway. - let xsend = HeaderValue::try_from(format!("/files/{}", &filename)).unwrap(); - res.add_header("X-Accel-Redirect", xsend, true).unwrap(); + // Check if nginx sendfile is enabled, because we can skip this if it is. + if CONFIG.server.nginx_sendfile { + // Add the X-Accel-Redirect header, allowing for faster file serving. + // I was told to put a Path here, but I don't think it's really necessary, since it's converted to a HeaderValue anyway. + let xsend = HeaderValue::try_from(format!("/files/{}", &filename)).unwrap(); + res.add_header("X-Accel-Redirect", xsend, true).unwrap(); - // Add the mimetype - res.add_header("Content-Type", mimetype, true).unwrap(); + // Add the mimetype + res.add_header("Content-Type", mimetype, true).unwrap(); - // Go through all the headers and print them out, just to check for now! - tracing::debug!("response headers: {:?}", res.headers()); + // Go through all the headers and print them out, just to check for now! + tracing::debug!("response headers: {:?}", res.headers()); - // https://github.com/salvo-rs/salvo/issues/233 - res.status_code(StatusCode::OK); - } else { - // If nginx sendfile is disabled, we need to render the file directly + // https://github.com/salvo-rs/salvo/issues/233 + res.status_code(StatusCode::OK); + } else { + // If nginx sendfile is disabled, we need to render the file directly - let filepath = "files/".to_string() + &filename.to_string(); - let file = NamedFile::open(&filepath).await.unwrap(); + let filepath = "files/".to_string() + &filename.to_string(); + let file = NamedFile::open(&filepath).await.unwrap(); - // Send the file to the response, and then send the response. - file.send(&headers, res).await; + // Send the file to the response, and then send the response. + file.send(&headers, res).await; - // Add the mimetype - res.add_header("Content-Type", mimetype, true).unwrap(); + // Add the mimetype + res.add_header("Content-Type", mimetype, true).unwrap(); - // Go through all the headers and print them out, just to check for now! - tracing::debug!("response headers: {:?}", res.headers()); + // Go through all the headers and print them out, just to check for now! + tracing::debug!("response headers: {:?}", res.headers()); - res.status_code(StatusCode::OK); - } + res.status_code(StatusCode::OK); + } } /// Rendering a 404 page, when there is no file. @@ -122,10 +128,10 @@ pub async fn render_404(res: &mut Response, upload_by_web: bool, headers: Header ), ..Default::default() }; - + let status_code = StatusCode::NOT_FOUND; render_template(res, &headers, template_filename, template, status_code).await; - }, + } false => { res.status_code(StatusCode::NOT_FOUND); res.render(Text::Json(r#"{"error": "FileNotFound"}"#)); @@ -133,7 +139,6 @@ pub async fn render_404(res: &mut Response, upload_by_web: bool, headers: Header } } - /// This handles serving files from disk, and all the tracking and handling too. /// This calls separate rendering functions depending on the status of the file. #[handler] @@ -142,7 +147,9 @@ pub async fn serve_file(req: &mut Request, res: &mut Response) { let sqlconn = SQLITE.get().expect("Failed to grab sqlite pool"); // Check if the filename exists in the DB - let filename: String = req.param("file").expect("Failed to set the filename variable"); + let filename: String = req + .param("file") + .expect("Failed to set the filename variable"); let check_filename = db::check_filename(sqlconn, &filename).await; // Returns true if the "source" field in the HTTP request's form data is "web", false otherwise or if an error occurs. @@ -169,21 +176,19 @@ pub async fn serve_file(req: &mut Request, res: &mut Response) { tracing::info!("Successfully added file back into the database"); // Now we can render the file! render_file(req, res, headers).await - }, + } Err(_) => { tracing::error!("Error while adding file back into the database"); // TODO: Refactor a nice error rendering function, were we just pass the errorcode, and message render_404(res, upload_by_web, headers).await - }, + } }; - - - }, + } // File doesn't exist in the filesystem :( false => { tracing::debug!("Double checked, file truly doesn't exist."); render_404(res, upload_by_web, headers).await - }, + } } } @@ -207,7 +212,9 @@ pub async fn serve_file(req: &mut Request, res: &mut Response) { render_template(res, &headers, template_filename, template, status_code).await; } else { res.status_code(StatusCode::INTERNAL_SERVER_ERROR); - res.render(Text::Json(r#"{"error": "InternalServerError - Couldn't find file that should exist."}"#)); + res.render(Text::Json( + r#"{"error": "InternalServerError - Couldn't find file that should exist."}"#, + )); } } diff --git a/src/handlers/upload.rs b/src/handlers/upload.rs index cd55bd2..a629b48 100644 --- a/src/handlers/upload.rs +++ b/src/handlers/upload.rs @@ -55,11 +55,12 @@ pub async fn upload(req: &mut Request, res: &mut Response) { let mut buffer = Vec::with_capacity(2048); // Load up 2048 bytes (There wasn't a decent answer on how much or little I should read) - mime_file.take(2048) - .read_to_end(&mut buffer).expect("couldn't read mimetype buffer"); - - tracing::trace!("read bytes for mime parsing: {:x?}", buffer); + mime_file + .take(2048) + .read_to_end(&mut buffer) + .expect("couldn't read mimetype buffer"); + tracing::trace!("read bytes for mime parsing: {:x?}", buffer); // Guess the mimetype let mimetype: &str = &detect_mime_type(&buffer).unwrap_or("text/plain".to_string()); -- GitLab