use mlua::{Lua, Table};
mod dimensions;
mod sniff;
#[cfg(test)]
mod tests;
mod types;
pub use dimensions::dimensions;
pub use sniff::{detect, is_text, text_subtype_matches};
pub use types::MEDIA_TYPES;
use super::TypePattern;
pub(crate) const UNKNOWN_TYPE: &str = "application/octet-stream";
pub(crate) const EXECUTABLE_TYPE: &str = "application/x-executable";
pub const SNIFF_BYTES: usize = 64 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Family {
Image,
Vector,
Document,
Text,
Archive,
Audio,
Video,
Font,
Data,
Generic,
}
impl Family {
fn name(self) -> &'static str {
match self {
Self::Image => "image",
Self::Vector => "vector",
Self::Document => "document",
Self::Text => "text",
Self::Archive => "archive",
Self::Audio => "audio",
Self::Video => "video",
Self::Font => "font",
Self::Data => "data",
Self::Generic => "generic",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tier {
Detected,
Text,
Header,
}
impl Tier {
fn name(self) -> &'static str {
match self {
Self::Detected => "detected",
Self::Text => "text",
Self::Header => "header",
}
}
}
#[derive(Debug)]
pub struct MediaType {
pub name: &'static str,
pub extensions: &'static [&'static str],
pub family: Family,
pub tier: Tier,
pub short: &'static str,
dims: bool,
}
impl MediaType {
pub fn has_dimensions(&self) -> bool {
self.dims
}
}
impl PartialEq for MediaType {
fn eq(&self, other: &Self) -> bool {
self.name == other.name
}
}
impl Eq for MediaType {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Detection {
Detected(&'static MediaType),
Text,
Executable,
Unknown,
}
pub fn is_active_content(name: &str) -> bool {
matches!(
name,
"image/svg+xml" | "text/html" | "application/xhtml+xml"
)
}
pub fn lookup(name: &str) -> Option<&'static MediaType> {
MEDIA_TYPES.iter().find(|m| m.name == name)
}
fn family_name(name: &str) -> &str {
name.split('/').next().unwrap_or(name)
}
pub(crate) fn extension_matches(media: &MediaType, ext: &str) -> bool {
media.extensions.contains(&ext)
}
pub fn executable_extension(ext: &str) -> bool {
types::SCRIPT_EXTENSIONS.contains(&ext)
}
pub(crate) fn describe_types(patterns: &[TypePattern]) -> String {
let families: Vec<&str> = patterns
.iter()
.filter_map(|p| match p {
TypePattern::Exact(name) => Some(family_name(name)),
_ => None,
})
.collect();
if families.len() > 1
&& families.len() == patterns.len()
&& families.iter().all(|f| *f == families[0])
{
let exts: Vec<&str> = patterns
.iter()
.filter_map(|p| match p {
TypePattern::Exact(name) => {
lookup(name).and_then(|m| m.extensions.first().copied())
}
_ => None,
})
.collect();
let family = families[0];
let article = if family.starts_with(['a', 'e', 'i', 'o', 'u']) {
"an"
} else {
"a"
};
return format!("{article} {family} ({})", exts.join(", "));
}
let mut parts = Vec::new();
for pattern in patterns {
parts.push(match pattern {
TypePattern::Any => "any file".to_string(),
TypePattern::Family(f) => {
let exts: Vec<&str> = MEDIA_TYPES
.iter()
.filter(|m| family_name(m.name) == f && !m.extensions.is_empty())
.map(|m| m.extensions[0])
.collect();
let article = if f.starts_with(['a', 'e', 'i', 'o', 'u']) {
"an"
} else {
"a"
};
if exts.is_empty() {
format!("{article} {f} file")
} else {
format!("{article} {f} ({})", exts.join(", "))
}
}
TypePattern::Exact(name) => lookup(name)
.map(|m| m.short.to_string())
.unwrap_or_else(|| name.clone()),
});
}
match parts.len() {
0 => "a file".into(),
1 => parts.remove(0),
_ => {
let last = parts.pop().unwrap_or_default();
format!("{} or {last}", parts.join(", "))
}
}
}
pub(crate) fn media_types_table(lua: &Lua) -> mlua::Result<Table> {
let out = lua.create_table()?;
for media in MEDIA_TYPES {
let entry = lua.create_table()?;
entry.set(
"extensions",
lua.create_sequence_from(media.extensions.iter().copied())?,
)?;
entry.set("family", media.family.name())?;
entry.set("tier", media.tier.name())?;
entry.set("dimensions", media.dims)?;
out.set(media.name, entry)?;
}
Ok(out)
}