Improve mime detection

This commit is contained in:
Gregory 2020-06-10 15:08:39 -04:00
parent 66bcde83f4
commit 63bc4697c7
No known key found for this signature in database
GPG key ID: 2E44FAEEDC94B1E2

View file

@ -26,16 +26,38 @@ impl TryFrom<&str> for MimeType {
}
}
fn read_mb(path: &Path) -> Result<(std::fs::Metadata, Vec<u8>)> {
let metadata = std::fs::metadata(path)?;
let data = if metadata.len() <= 1024 {
std::fs::read(path)?
} else {
use std::io::prelude::*;
let mut buffer = Vec::with_capacity(1024);
let reader = std::io::BufReader::new(std::fs::File::open(path)?);
reader.take(1024).read_exact(&mut buffer)?;
buffer
};
Ok((metadata, data))
}
impl TryFrom<&Path> for MimeType {
type Error = Error;
fn try_from(path: &Path) -> Result<Self> {
let guess = SHARED_MIME_DB.guess_mime_type().path(path).guess();
let guess = guess.mime_type().clone();
let file_name = path.file_name().unwrap_or_default().to_string_lossy();
if guess == mime::APPLICATION_OCTET_STREAM {
Err(Error::Ambiguous(path.to_string_lossy().into()))
} else {
Ok(Self(guess))
match &*SHARED_MIME_DB.get_mime_types_from_file_name(&file_name) {
[t, ..] if t == &mime::APPLICATION_OCTET_STREAM => Ok(Self({
let (meta, data) = read_mb(path)?;
SHARED_MIME_DB
.guess_mime_type()
.metadata(meta)
.data(&data)
.guess()
.mime_type()
.clone()
})),
[other, ..] => Ok(Self(other.clone())),
_ => Err(Error::Ambiguous(path.to_string_lossy().into())),
}
}
}