From 2388e2c2cee3af7d2c7f8ec0547bd33024c6a3aa Mon Sep 17 00:00:00 2001 From: neri Date: Wed, 10 Mar 2021 00:02:02 +0100 Subject: [PATCH] decide when to show embedded text based on mime type of file --- src/main.rs | 29 +++++++++++++++++------------ template/view.html | 2 +- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/src/main.rs b/src/main.rs index 483ccdc..8c43a36 100644 --- a/src/main.rs +++ b/src/main.rs @@ -153,7 +153,7 @@ async fn download( config: web::Data, ) -> Result { let id = req.match_info().query("id"); - let mut rows = sqlx::query("SELECT file_id, file_name, kind from files WHERE file_id = $1") + let mut rows = sqlx::query("SELECT file_id, file_name from files WHERE file_id = $1") .bind(id) .fetch(db.as_ref()); let row: PgRow = rows @@ -164,11 +164,12 @@ async fn download( let file_id: String = row.get("file_id"); let file_name: String = row.get("file_name"); - let kind: String = row.get("kind"); let mut path = config.files_dir.clone(); path.push(&file_id); - if kind == FileKind::TEXT.to_string() && !req.query_string().contains("raw") { + let download = req.query_string().contains("dl"); + let (content_type, mut content_disposition) = get_content_types(&path, &file_name); + if content_type.type_() == mime::TEXT && !download { let content = fs::read_to_string(path).await.map_err(|_| { error::ErrorInternalServerError("this file should be here but could not be found") })?; @@ -177,7 +178,9 @@ async fn download( let response = HttpResponse::Ok().content_type("text/html").body(view_html); Ok(response) } else { - let (content_type, content_disposition) = get_content_types(&path, &file_name); + if download { + content_disposition.disposition = DispositionType::Attachment; + } let file = NamedFile::open(path) .map_err(|_| { error::ErrorInternalServerError("this file should be here but could not be found") @@ -200,8 +203,16 @@ fn get_content_types(path: &Path, filename: &str) -> (Mime, ContentDisposition) _ => DispositionType::Attachment, }; - let mut parameters = vec![DispositionParam::Filename(filename.to_owned())]; + let cd = ContentDisposition { + disposition, + parameters: get_disposition_params(filename), + }; + (ct, cd) +} + +fn get_disposition_params(filename: &str) -> Vec { + let mut parameters = vec![DispositionParam::Filename(filename.to_owned())]; if !filename.is_ascii() { parameters.push(DispositionParam::FilenameExt(ExtendedValue { charset: Charset::Ext(String::from("UTF-8")), @@ -209,13 +220,7 @@ fn get_content_types(path: &Path, filename: &str) -> (Mime, ContentDisposition) value: filename.to_owned().into_bytes(), })) } - - let cd = ContentDisposition { - disposition, - parameters, - }; - - (ct, cd) + parameters } async fn not_found() -> Result { diff --git a/template/view.html b/template/view.html index dfeb3a6..24aaf78 100644 --- a/template/view.html +++ b/template/view.html @@ -13,7 +13,7 @@ {text}
- herunterladen + herunterladen