mirror of
https://github.com/chmln/handlr.git
synced 2025-03-28 06:45:56 +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 {
|
impl TryFrom<&Path> for MimeType {
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
fn try_from(path: &Path) -> Result<Self> {
|
fn try_from(path: &Path) -> Result<Self> {
|
||||||
let guess = SHARED_MIME_DB.guess_mime_type().path(path).guess();
|
let file_name = path.file_name().unwrap_or_default().to_string_lossy();
|
||||||
let guess = guess.mime_type().clone();
|
|
||||||
|
|
||||||
if guess == mime::APPLICATION_OCTET_STREAM {
|
match &*SHARED_MIME_DB.get_mime_types_from_file_name(&file_name) {
|
||||||
Err(Error::Ambiguous(path.to_string_lossy().into()))
|
[t, ..] if t == &mime::APPLICATION_OCTET_STREAM => Ok(Self({
|
||||||
} else {
|
let (meta, data) = read_mb(path)?;
|
||||||
Ok(Self(guess))
|
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…
Add table
Reference in a new issue