mirror of
https://github.com/chmln/handlr.git
synced 2024-11-14 21:49:27 +01:00
Improve mime detection
This commit is contained in:
parent
66bcde83f4
commit
63bc4697c7
1 changed files with 28 additions and 6 deletions
|
@ -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())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue