forked from neri/datatrash
refactor: fix clippy warnings
This commit is contained in:
parent
7664ba3ec9
commit
756d4b67a0
|
@ -1,6 +1,7 @@
|
||||||
use std::env;
|
use std::env;
|
||||||
|
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
use std::str::FromStr;
|
||||||
use time::ext::NumericalDuration;
|
use time::ext::NumericalDuration;
|
||||||
use time::Duration;
|
use time::Duration;
|
||||||
use tokio::fs;
|
use tokio::fs;
|
||||||
|
@ -25,7 +26,7 @@ pub struct NoAuthLimits {
|
||||||
pub large_file_size: u64,
|
pub large_file_size: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_config() -> Config {
|
pub async fn from_env() -> Config {
|
||||||
let max_file_size = env::var("UPLOAD_MAX_BYTES")
|
let max_file_size = env::var("UPLOAD_MAX_BYTES")
|
||||||
.ok()
|
.ok()
|
||||||
.and_then(|variable| variable.parse().ok())
|
.and_then(|variable| variable.parse().ok())
|
||||||
|
@ -68,15 +69,15 @@ pub async fn get_config() -> Config {
|
||||||
fn get_no_auth_limits() -> Option<NoAuthLimits> {
|
fn get_no_auth_limits() -> Option<NoAuthLimits> {
|
||||||
match (
|
match (
|
||||||
env::var("AUTH_PASSWORD").ok(),
|
env::var("AUTH_PASSWORD").ok(),
|
||||||
env_number("NO_AUTH_MAX_TIME"),
|
env_number::<i64>("NO_AUTH_MAX_TIME"),
|
||||||
env_number("NO_AUTH_LARGE_FILE_MAX_TIME"),
|
env_number::<i64>("NO_AUTH_LARGE_FILE_MAX_TIME"),
|
||||||
env_number("NO_AUTH_LARGE_FILE_SIZE"),
|
env_number("NO_AUTH_LARGE_FILE_SIZE"),
|
||||||
) {
|
) {
|
||||||
(Some(auth_password), Some(max_time), Some(large_file_max_time), Some(large_file_size)) => {
|
(Some(auth_password), Some(max_time), Some(large_file_max_time), Some(large_file_size)) => {
|
||||||
Some(NoAuthLimits {
|
Some(NoAuthLimits {
|
||||||
auth_password,
|
auth_password,
|
||||||
max_time: (max_time as i64).seconds(),
|
max_time: max_time.seconds(),
|
||||||
large_file_max_time: (large_file_max_time as i64).seconds(),
|
large_file_max_time: large_file_max_time.seconds(),
|
||||||
large_file_size,
|
large_file_size,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -87,6 +88,6 @@ fn get_no_auth_limits() -> Option<NoAuthLimits> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn env_number(variable: &str) -> Option<u64> {
|
fn env_number<T: FromStr>(variable: &str) -> Option<T> {
|
||||||
env::var(variable).ok().and_then(|n| n.parse::<u64>().ok())
|
env::var(variable).ok().and_then(|n| n.parse::<T>().ok())
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,7 +2,7 @@ use sqlx::postgres::{PgPool, PgPoolOptions};
|
||||||
use std::env;
|
use std::env;
|
||||||
use time::ext::NumericalStdDuration;
|
use time::ext::NumericalStdDuration;
|
||||||
|
|
||||||
pub async fn setup_db() -> PgPool {
|
pub async fn setup() -> PgPool {
|
||||||
let conn_url = &get_db_url();
|
let conn_url = &get_db_url();
|
||||||
log::info!("Using Connection string {}", conn_url);
|
log::info!("Using Connection string {}", conn_url);
|
||||||
|
|
||||||
|
|
|
@ -42,8 +42,8 @@ pub async fn download(
|
||||||
|
|
||||||
let mime = Mime::from_str(&content_type).unwrap_or(APPLICATION_OCTET_STREAM);
|
let mime = Mime::from_str(&content_type).unwrap_or(APPLICATION_OCTET_STREAM);
|
||||||
let mut response = match get_view_type(&req, &mime, &path, delete).await {
|
let mut response = match get_view_type(&req, &mime, &path, delete).await {
|
||||||
ViewType::Raw => build_file_response(false, &file_name, path, mime, &req).await,
|
ViewType::Raw => build_file_response(false, &file_name, path, mime, &req),
|
||||||
ViewType::Download => build_file_response(true, &file_name, path, mime, &req).await,
|
ViewType::Download => build_file_response(true, &file_name, path, mime, &req),
|
||||||
ViewType::Html => build_text_response(&path).await,
|
ViewType::Html => build_text_response(&path).await,
|
||||||
}?;
|
}?;
|
||||||
|
|
||||||
|
@ -141,7 +141,7 @@ async fn build_text_response(path: &Path) -> Result<HttpResponse, Error> {
|
||||||
.body(html))
|
.body(html))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn build_file_response(
|
fn build_file_response(
|
||||||
download: bool,
|
download: bool,
|
||||||
file_name: &str,
|
file_name: &str,
|
||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
|
@ -196,7 +196,7 @@ fn get_disposition_params(filename: &str) -> Vec<DispositionParam> {
|
||||||
charset: Charset::Ext(String::from("UTF-8")),
|
charset: Charset::Ext(String::from("UTF-8")),
|
||||||
language_tag: None,
|
language_tag: None,
|
||||||
value: filename.to_owned().into_bytes(),
|
value: filename.to_owned().into_bytes(),
|
||||||
}))
|
}));
|
||||||
}
|
}
|
||||||
parameters
|
parameters
|
||||||
}
|
}
|
||||||
|
@ -204,7 +204,8 @@ fn get_disposition_params(filename: &str) -> Vec<DispositionParam> {
|
||||||
fn insert_cache_headers(response: &mut HttpResponse, valid_till: OffsetDateTime) {
|
fn insert_cache_headers(response: &mut HttpResponse, valid_till: OffsetDateTime) {
|
||||||
if response.status().is_success() {
|
if response.status().is_success() {
|
||||||
let valid_duration = valid_till - OffsetDateTime::now_utc();
|
let valid_duration = valid_till - OffsetDateTime::now_utc();
|
||||||
let valid_cache_seconds = valid_duration.whole_seconds().clamp(0, u32::MAX as i64) as u32;
|
let valid_cache_seconds =
|
||||||
|
valid_duration.whole_seconds().clamp(0, i64::from(u32::MAX)) as u32;
|
||||||
response.headers_mut().insert(
|
response.headers_mut().insert(
|
||||||
CACHE_CONTROL,
|
CACHE_CONTROL,
|
||||||
CacheControl(vec![
|
CacheControl(vec![
|
||||||
|
|
|
@ -37,8 +37,8 @@ async fn not_found() -> Result<HttpResponse, Error> {
|
||||||
async fn main() -> std::io::Result<()> {
|
async fn main() -> std::io::Result<()> {
|
||||||
env_logger::Builder::from_env(Env::default().default_filter_or("info,sqlx=warn")).init();
|
env_logger::Builder::from_env(Env::default().default_filter_or("info,sqlx=warn")).init();
|
||||||
|
|
||||||
let pool: PgPool = db::setup_db().await;
|
let pool: PgPool = db::setup().await;
|
||||||
let config = config::get_config().await;
|
let config = config::from_env().await;
|
||||||
let (sender, receiver) = channel(8);
|
let (sender, receiver) = channel(8);
|
||||||
|
|
||||||
log::info!("omnomnom");
|
log::info!("omnomnom");
|
||||||
|
|
|
@ -15,16 +15,16 @@ lazy_static! {
|
||||||
fn load_mime_aliases() -> HashMap<Mime, Mime> {
|
fn load_mime_aliases() -> HashMap<Mime, Mime> {
|
||||||
tree_magic_db::aliases()
|
tree_magic_db::aliases()
|
||||||
.lines()
|
.lines()
|
||||||
.flat_map(|line| line.split_once(' '))
|
.filter_map(|line| line.split_once(' '))
|
||||||
.flat_map(|(alias, mime)| Some((Mime::from_str(alias).ok()?, Mime::from_str(mime).ok()?)))
|
.filter_map(|(alias, mime)| Some((Mime::from_str(alias).ok()?, Mime::from_str(mime).ok()?)))
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn load_mime_parent_relations() -> Vec<(Mime, Mime)> {
|
fn load_mime_parent_relations() -> Vec<(Mime, Mime)> {
|
||||||
tree_magic_db::subclasses()
|
tree_magic_db::subclasses()
|
||||||
.lines()
|
.lines()
|
||||||
.flat_map(|line| line.split_once(' '))
|
.filter_map(|line| line.split_once(' '))
|
||||||
.flat_map(|(child, parent)| {
|
.filter_map(|(child, parent)| {
|
||||||
Some((Mime::from_str(child).ok()?, Mime::from_str(parent).ok()?))
|
Some((Mime::from_str(child).ok()?, Mime::from_str(parent).ok()?))
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
|
@ -34,11 +34,9 @@ fn load_mime_extensions() -> HashMap<Mime, &'static str> {
|
||||||
include_str!("../mime.types")
|
include_str!("../mime.types")
|
||||||
.lines()
|
.lines()
|
||||||
.filter(|line| !line.is_empty() && !line.starts_with('#'))
|
.filter(|line| !line.is_empty() && !line.starts_with('#'))
|
||||||
.map(|line| line.split_whitespace())
|
.map(str::split_whitespace)
|
||||||
.flat_map(|mut elements| Some((Mime::from_str(elements.next()?).ok()?, elements.next()?)))
|
.filter_map(|mut elements| Some((Mime::from_str(elements.next()?).ok()?, elements.next()?)))
|
||||||
.flat_map(|(mime, extension)| {
|
.map(|(mime, extension)| (ALIASES.get(&mime).cloned().unwrap_or(mime), extension))
|
||||||
Some((ALIASES.get(&mime).unwrap_or(&mime).clone(), extension))
|
|
||||||
})
|
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -32,16 +32,15 @@ pub(crate) async fn parse_multipart(
|
||||||
let mut password = None;
|
let mut password = None;
|
||||||
let mut size = 0;
|
let mut size = 0;
|
||||||
|
|
||||||
while let Ok(Some(field)) = payload.try_next().await {
|
while let Ok(Some(mut field)) = payload.try_next().await {
|
||||||
let name = get_field_name(&field)?;
|
let name = get_field_name(&field)?.to_owned();
|
||||||
let name = name.as_str();
|
match name.as_str() {
|
||||||
match name {
|
|
||||||
"keep_for" => {
|
"keep_for" => {
|
||||||
keep_for_seconds = Some(parse_string(name, field).await?);
|
keep_for_seconds = Some(parse_string(&name, &mut field).await?);
|
||||||
}
|
}
|
||||||
"file" => {
|
"file" => {
|
||||||
let (mime, uploaded_name) = get_file_metadata(&field);
|
let (mime, uploaded_name) = get_file_metadata(&field);
|
||||||
if uploaded_name == None || uploaded_name.as_deref() == Some("") {
|
if uploaded_name.is_none() || uploaded_name.as_deref() == Some("") {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
original_name = uploaded_name;
|
original_name = uploaded_name;
|
||||||
|
@ -62,10 +61,10 @@ pub(crate) async fn parse_multipart(
|
||||||
content_type = Some(get_content_type(&first_bytes));
|
content_type = Some(get_content_type(&first_bytes));
|
||||||
}
|
}
|
||||||
"delete_on_download" => {
|
"delete_on_download" => {
|
||||||
delete_on_download = parse_string(name, field).await? != "false";
|
delete_on_download = parse_string(&name, &mut field).await? != "false";
|
||||||
}
|
}
|
||||||
"password" => {
|
"password" => {
|
||||||
password = Some(parse_string(name, field).await?);
|
password = Some(parse_string(&name, &mut field).await?);
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
};
|
};
|
||||||
|
@ -77,8 +76,7 @@ pub(crate) async fn parse_multipart(
|
||||||
.map(|k| k.parse())
|
.map(|k| k.parse())
|
||||||
.transpose()
|
.transpose()
|
||||||
.map_err(|e| error::ErrorBadRequest(format!("field keep_for is not a number: {e}")))?
|
.map_err(|e| error::ErrorBadRequest(format!("field keep_for is not a number: {e}")))?
|
||||||
.map(Duration::seconds)
|
.map_or(DEFAULT_UPLOAD_DURATION, Duration::seconds);
|
||||||
.unwrap_or(DEFAULT_UPLOAD_DURATION);
|
|
||||||
let valid_till = OffsetDateTime::now_utc() + keep_for;
|
let valid_till = OffsetDateTime::now_utc() + keep_for;
|
||||||
|
|
||||||
let upload_config = UploadConfig {
|
let upload_config = UploadConfig {
|
||||||
|
@ -88,7 +86,7 @@ pub(crate) async fn parse_multipart(
|
||||||
delete_on_download,
|
delete_on_download,
|
||||||
};
|
};
|
||||||
|
|
||||||
check_requirements(&upload_config, size, password, &keep_for, config)?;
|
check_requirements(&upload_config, size, &password, &keep_for, config)?;
|
||||||
|
|
||||||
Ok(upload_config)
|
Ok(upload_config)
|
||||||
}
|
}
|
||||||
|
@ -96,7 +94,7 @@ pub(crate) async fn parse_multipart(
|
||||||
fn check_requirements(
|
fn check_requirements(
|
||||||
upload_config: &UploadConfig,
|
upload_config: &UploadConfig,
|
||||||
size: u64,
|
size: u64,
|
||||||
password: Option<String>,
|
password: &Option<String>,
|
||||||
keep_for: &Duration,
|
keep_for: &Duration,
|
||||||
config: &config::Config,
|
config: &config::Config,
|
||||||
) -> Result<(), error::Error> {
|
) -> Result<(), error::Error> {
|
||||||
|
@ -127,21 +125,23 @@ fn check_requirements(
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_field_name(field: &Field) -> Result<String, error::Error> {
|
fn get_field_name(field: &Field) -> Result<&str, error::Error> {
|
||||||
Ok(field
|
Ok(field
|
||||||
.content_disposition()
|
.content_disposition()
|
||||||
.get_name()
|
.get_name()
|
||||||
.map(|s| s.to_owned())
|
|
||||||
.ok_or(error::ParseError::Incomplete)?)
|
.ok_or(error::ParseError::Incomplete)?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn parse_string(name: &str, field: actix_multipart::Field) -> Result<String, error::Error> {
|
async fn parse_string(
|
||||||
|
name: &str,
|
||||||
|
field: &mut actix_multipart::Field,
|
||||||
|
) -> Result<String, error::Error> {
|
||||||
let data = read_content(field).await?;
|
let data = read_content(field).await?;
|
||||||
String::from_utf8(data)
|
String::from_utf8(data)
|
||||||
.map_err(|_| error::ErrorBadRequest(format!("could not parse field {name} as utf-8")))
|
.map_err(|_| error::ErrorBadRequest(format!("could not parse field {name} as utf-8")))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn read_content(mut field: actix_multipart::Field) -> Result<Vec<u8>, error::Error> {
|
async fn read_content(field: &mut actix_multipart::Field) -> Result<Vec<u8>, error::Error> {
|
||||||
let mut data = Vec::new();
|
let mut data = Vec::new();
|
||||||
while let Some(chunk) = field.try_next().await.map_err(error::ErrorBadRequest)? {
|
while let Some(chunk) = field.try_next().await.map_err(error::ErrorBadRequest)? {
|
||||||
data.extend(chunk);
|
data.extend(chunk);
|
||||||
|
|
|
@ -52,7 +52,7 @@ fn build_index_html(config: &Config) -> String {
|
||||||
.replace("{max_size_snippet}", MAX_SIZE_SNIPPET_HTML.trim_end())
|
.replace("{max_size_snippet}", MAX_SIZE_SNIPPET_HTML.trim_end())
|
||||||
.replace("{max_size}", &render_file_size(max_file_size));
|
.replace("{max_size}", &render_file_size(max_file_size));
|
||||||
} else {
|
} else {
|
||||||
html = html.replace("{max_size_snippet}", "")
|
html = html.replace("{max_size_snippet}", "");
|
||||||
};
|
};
|
||||||
html
|
html
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue