From dc2f7ecab0bb5938abc3fe217139011f9ba8570e Mon Sep 17 00:00:00 2001 From: neri Date: Tue, 22 Nov 2022 21:11:35 +0100 Subject: [PATCH] move multipart error handling into its module --- src/multipart.rs | 25 ++++++++++++++++++++++++- src/upload.rs | 18 +----------------- 2 files changed, 25 insertions(+), 18 deletions(-) diff --git a/src/multipart.rs b/src/multipart.rs index 4092b30..379da82 100644 --- a/src/multipart.rs +++ b/src/multipart.rs @@ -5,10 +5,14 @@ use futures_util::{StreamExt, TryStreamExt}; use mime::{Mime, APPLICATION_OCTET_STREAM, TEXT_PLAIN}; use std::{ cmp::{max, min}, + io::ErrorKind, path::Path, }; use time::{Duration, OffsetDateTime}; -use tokio::{fs::File, io::AsyncWriteExt}; +use tokio::{ + fs::{self, File}, + io::AsyncWriteExt, +}; const MAX_UPLOAD_DURATION: Duration = Duration::days(31); const DEFAULT_UPLOAD_DURATION: Duration = Duration::minutes(30); @@ -21,6 +25,25 @@ pub(crate) struct UploadConfig { } pub(crate) async fn parse_multipart( + payload: Multipart, + file_path: &Path, + config: &config::Config, +) -> Result { + match parse_multipart_inner(payload, file_path, config).await { + Ok(data) => Ok(data), + Err(err) => { + match fs::remove_file(file_path).await { + Err(err) if err.kind() != ErrorKind::NotFound => { + log::error!("could not remove file {:?}", err); + } + _ => {} + } + Err(err) + } + } +} + +pub(crate) async fn parse_multipart_inner( mut payload: Multipart, file_path: &Path, config: &config::Config, diff --git a/src/upload.rs b/src/upload.rs index ba14219..1d9813c 100644 --- a/src/upload.rs +++ b/src/upload.rs @@ -41,28 +41,12 @@ pub async fn upload( error::ErrorInternalServerError("could not create file") })?; - let parsed_multipart = multipart::parse_multipart(payload, &file_name, &config).await; let UploadConfig { original_name, content_type, valid_till, delete_on_download, - } = match parsed_multipart { - Ok(data) => data, - Err(err) => { - match fs::remove_file(file_name).await { - Ok(()) => {} - Err(err) if err.kind() == ErrorKind::NotFound => {} - Err(err) => { - log::error!("could not remove file {:?}", err); - return Err(error::ErrorInternalServerError( - "could not parse multipart; could not remove file", - )); - } - } - return Err(err); - } - }; + } = multipart::parse_multipart(payload, &file_name, &config).await?; let file_name = original_name.clone().unwrap_or_else(|| { format!(