From 4e2cfcfac635daa9a95f2ea7bc86763a61b5574c Mon Sep 17 00:00:00 2001 From: Edward Shen Date: Sun, 16 Jan 2022 00:49:07 -0800 Subject: [PATCH] Add mime type guessing from file ext for web ui --- Cargo.lock | 1 + web/Cargo.toml | 1 + web/src/decrypt.rs | 20 +++++++++++++++++++- 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index e059d25..2036016 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1030,6 +1030,7 @@ dependencies = [ "gloo-console", "http", "js-sys", + "mime_guess", "omegaupload-common 0.1.0", "reqwasm", "serde", diff --git a/web/Cargo.toml b/web/Cargo.toml index 7d232fe..5fd6ca6 100644 --- a/web/Cargo.toml +++ b/web/Cargo.toml @@ -17,6 +17,7 @@ console_error_panic_hook = "0.1" gloo-console = "0.1" http = "0.2" js-sys = "0.3" +mime_guess = "2" reqwasm = "0.2" tree_magic_mini = { version = "3", features = ["with-gpl-data"] } serde = { version = "1.0", features = ["derive"] } diff --git a/web/src/decrypt.rs b/web/src/decrypt.rs index 41c91e7..608493e 100644 --- a/web/src/decrypt.rs +++ b/web/src/decrypt.rs @@ -55,10 +55,11 @@ pub fn decrypt( mut container: Vec, key: &Secret, maybe_password: Option>, + name_hint: Option<&str>, ) -> Result<(DecryptedData, MimeType), Error> { open_in_place(&mut container, key, maybe_password)?; - let mime_type = tree_magic_mini::from_u8(&container); + let mime_type = guess_mime_type(name_hint, &container); log!("[rs] Mime type:", mime_type); log!("[rs] Blob conversion started."); @@ -148,6 +149,23 @@ fn handle_gzip(blob: Arc, container: Vec) -> DecryptedData { } } +fn guess_mime_type(name_hint: Option<&str>, data: &[u8]) -> &'static str { + if let Some(name) = name_hint { + let guesses = mime_guess::from_path(name); + if let Some(mime_type) = guesses.first_raw() { + // Found at least one, but generally speaking this crate only + // uses authoritative sources (RFCs), so generally speaking + // there's only one association, and multiple are due to legacy + // support. As a result, we can probably just get the first one. + log!("[rs] Mime type inferred from extension."); + return mime_type; + } else { + log!("[rs] No mime type found for extension, falling back to introspection."); + } + } + tree_magic_mini::from_u8(&data) +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] enum ContentType { Text,