nitr_std/validate/media/
mod.rs1use mlua::{Lua, Table};
16
17mod dimensions;
18mod sniff;
19#[cfg(test)]
20mod tests;
21mod types;
22
23pub use dimensions::dimensions;
24pub use sniff::{detect, is_text, text_subtype_matches};
25pub use types::MEDIA_TYPES;
26
27use super::TypePattern;
28
29pub(crate) const UNKNOWN_TYPE: &str = "application/octet-stream";
32
33pub(crate) const EXECUTABLE_TYPE: &str = "application/x-executable";
35
36pub const SNIFF_BYTES: usize = 64 * 1024;
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum Family {
42 Image,
44 Vector,
46 Document,
48 Text,
50 Archive,
52 Audio,
54 Video,
56 Font,
58 Data,
60 Generic,
62}
63
64impl Family {
65 fn name(self) -> &'static str {
66 match self {
67 Self::Image => "image",
68 Self::Vector => "vector",
69 Self::Document => "document",
70 Self::Text => "text",
71 Self::Archive => "archive",
72 Self::Audio => "audio",
73 Self::Video => "video",
74 Self::Font => "font",
75 Self::Data => "data",
76 Self::Generic => "generic",
77 }
78 }
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum Tier {
84 Detected,
86 Text,
88 Header,
90}
91
92impl Tier {
93 fn name(self) -> &'static str {
94 match self {
95 Self::Detected => "detected",
96 Self::Text => "text",
97 Self::Header => "header",
98 }
99 }
100}
101
102#[derive(Debug)]
104pub struct MediaType {
105 pub name: &'static str,
107 pub extensions: &'static [&'static str],
109 pub family: Family,
111 pub tier: Tier,
113 pub short: &'static str,
115 dims: bool,
117}
118
119impl MediaType {
120 pub fn has_dimensions(&self) -> bool {
122 self.dims
123 }
124}
125
126impl PartialEq for MediaType {
128 fn eq(&self, other: &Self) -> bool {
129 self.name == other.name
130 }
131}
132
133impl Eq for MediaType {}
134
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137pub enum Detection {
138 Detected(&'static MediaType),
140 Text,
142 Executable,
144 Unknown,
146}
147
148pub fn is_active_content(name: &str) -> bool {
152 matches!(
153 name,
154 "image/svg+xml" | "text/html" | "application/xhtml+xml"
155 )
156}
157
158pub fn lookup(name: &str) -> Option<&'static MediaType> {
160 MEDIA_TYPES.iter().find(|m| m.name == name)
161}
162
163fn family_name(name: &str) -> &str {
165 name.split('/').next().unwrap_or(name)
166}
167
168pub(crate) fn extension_matches(media: &MediaType, ext: &str) -> bool {
170 media.extensions.contains(&ext)
171}
172
173pub fn executable_extension(ext: &str) -> bool {
175 types::SCRIPT_EXTENSIONS.contains(&ext)
176}
177
178pub(crate) fn describe_types(patterns: &[TypePattern]) -> String {
181 let families: Vec<&str> = patterns
184 .iter()
185 .filter_map(|p| match p {
186 TypePattern::Exact(name) => Some(family_name(name)),
187 _ => None,
188 })
189 .collect();
190 if families.len() > 1
191 && families.len() == patterns.len()
192 && families.iter().all(|f| *f == families[0])
193 {
194 let exts: Vec<&str> = patterns
195 .iter()
196 .filter_map(|p| match p {
197 TypePattern::Exact(name) => {
198 lookup(name).and_then(|m| m.extensions.first().copied())
199 }
200 _ => None,
201 })
202 .collect();
203 let family = families[0];
204 let article = if family.starts_with(['a', 'e', 'i', 'o', 'u']) {
205 "an"
206 } else {
207 "a"
208 };
209 return format!("{article} {family} ({})", exts.join(", "));
210 }
211 let mut parts = Vec::new();
212 for pattern in patterns {
213 parts.push(match pattern {
214 TypePattern::Any => "any file".to_string(),
215 TypePattern::Family(f) => {
216 let exts: Vec<&str> = MEDIA_TYPES
217 .iter()
218 .filter(|m| family_name(m.name) == f && !m.extensions.is_empty())
219 .map(|m| m.extensions[0])
220 .collect();
221 let article = if f.starts_with(['a', 'e', 'i', 'o', 'u']) {
222 "an"
223 } else {
224 "a"
225 };
226 if exts.is_empty() {
227 format!("{article} {f} file")
228 } else {
229 format!("{article} {f} ({})", exts.join(", "))
230 }
231 }
232 TypePattern::Exact(name) => lookup(name)
233 .map(|m| m.short.to_string())
234 .unwrap_or_else(|| name.clone()),
235 });
236 }
237 match parts.len() {
238 0 => "a file".into(),
239 1 => parts.remove(0),
240 _ => {
241 let last = parts.pop().unwrap_or_default();
242 format!("{} or {last}", parts.join(", "))
243 }
244 }
245}
246
247pub(crate) fn media_types_table(lua: &Lua) -> mlua::Result<Table> {
249 let out = lua.create_table()?;
250 for media in MEDIA_TYPES {
251 let entry = lua.create_table()?;
252 entry.set(
253 "extensions",
254 lua.create_sequence_from(media.extensions.iter().copied())?,
255 )?;
256 entry.set("family", media.family.name())?;
257 entry.set("tier", media.tier.name())?;
258 entry.set("dimensions", media.dims)?;
259 out.set(media.name, entry)?;
260 }
261 Ok(out)
262}