diff --git a/src/utils/misc.rs b/src/utils/misc.rs index c9678be..dacfd8b 100644 --- a/src/utils/misc.rs +++ b/src/utils/misc.rs @@ -1,4 +1,4 @@ -use std::{fs, path::Path}; +use std::{fs, os::unix::fs::MetadataExt, path::Path}; use actix_web::{ http::header::{self, ContentType, TryIntoHeaderValue}, @@ -7,6 +7,7 @@ use actix_web::{ }; use base64::{engine::general_purpose, Engine}; use cached::proc_macro::cached; +use mime_guess::mime; use reqwest::Client; use crate::config::FileConfiguration; @@ -63,14 +64,28 @@ pub fn read_file(filename: FilePath, expected_file: MType) -> Option { #[cached(time = 600)] fn reader(filename: FilePath, expected_file: MType) -> Option { let as_str = filename.to_string(); - Path::new(&as_str) - .extension() - .and_then(|ext| match ext.to_str().unwrap() { - "pdf" => fs::read(&as_str).map_or(None, |bytes| Some(read_pdf(bytes))), + let path = Path::new(&as_str); + + if let Ok(metadata) = path.metadata() { + // Taille maximale : 30M + if metadata.size() > 30 * 1000 * 1000 { + return None; + } + } + + path.extension().and_then(|ext| { + match mime_guess::from_ext(ext.to_str().unwrap_or_default()).first_or_text_plain() { + mime if mime == mime::APPLICATION_PDF => { + fs::read(&as_str).map_or(None, |bytes| Some(read_pdf(bytes))) + } + mime if mime.type_() == mime::IMAGE => { + fs::read(&as_str).map_or(None, |bytes| Some(read_img(bytes, &mime))) + } _ => fs::read_to_string(&as_str).map_or(None, |text| { Some(read_md(&filename, &text, expected_file, None, true)) }), - }) + } + }) } fn read_pdf(data: Vec) -> File { @@ -80,13 +95,23 @@ fn read_pdf(data: Vec) -> File { metadata: Metadata::default(), content: format!( r#""# + >"#, + mime::APPLICATION_PDF ), } } +fn read_img(data: Vec, mime: &mime::Mime) -> File { + let image = general_purpose::STANDARD.encode(data); + + File { + metadata: Metadata::default(), + content: format!(""), + } +} + /// Remove the first character of a string pub fn remove_first_letter(s: &str) -> &str { s.chars().next().map(|c| &s[c.len_utf8()..]).unwrap()