use std::path::Path;
use crate::detect::{Format, detect};
use crate::error::{Result, StryptError};
use crate::formats::{StripOptions, Stripped};
use crate::io::{AtomicWrite, Limits, Overwrite, Permissions, read_bounded};
use crate::registry::handler_for;
use crate::report::{InspectOptions, MetadataReport, StripReport};
pub fn inspect_bytes(data: &[u8], options: &InspectOptions) -> Result<MetadataReport> {
let format = detect(data)?;
handler(format)?.inspect(data, options)
}
pub fn strip_bytes(data: &[u8], options: &StripOptions) -> Result<Stripped> {
let format = detect(data)?;
let handler = handler(format)?;
let stripped = handler.strip(data, options)?;
let verified_format = detect(&stripped.bytes)?;
if verified_format != format {
return Err(StryptError::VerificationFailed {
format,
residual: 0,
});
}
let residual = handler
.inspect(&stripped.bytes, &InspectOptions::names_only())?
.findings
.len();
if residual > 0 {
return Err(StryptError::VerificationFailed { format, residual });
}
Ok(stripped)
}
pub fn inspect_file(
path: &Path,
limits: Limits,
options: &InspectOptions,
) -> Result<MetadataReport> {
let data = read_bounded(path, limits)?;
inspect_bytes(&data, options)
}
pub fn strip_file(
input: &Path,
output: &Path,
limits: Limits,
overwrite: Overwrite,
options: &StripOptions,
) -> Result<StripReport> {
let data = read_bounded(input, limits)?;
strip_bytes_to_file(&data, output, overwrite, options)
}
pub fn strip_bytes_to_file(
data: &[u8],
output: &Path,
overwrite: Overwrite,
options: &StripOptions,
) -> Result<StripReport> {
let stripped = strip_bytes(data, options)?;
let mut writer = AtomicWrite::begin(output, overwrite, Permissions::OwnerOnly)?;
writer.write_all(&stripped.bytes)?;
writer.commit()?;
Ok(stripped.report)
}
fn handler(format: Format) -> Result<&'static dyn crate::formats::MetadataHandler> {
handler_for(format).ok_or(StryptError::UnsupportedFormat {
format: match format {
Format::Jpeg
| Format::Png
| Format::Webp
| Format::Pdf
| Format::Tiff
| Format::Gif
| Format::Heif
| Format::Avif
| Format::Docx
| Format::Xlsx
| Format::Pptx
| Format::Odt
| Format::Ods
| Format::Odp
| Format::Svg
| Format::Jxl
| Format::Flac
| Format::Wav
| Format::Mp3
| Format::Ogg
| Format::Opus
| Format::OggFlac
| Format::Mp4
| Format::M4a => crate::error::UnsupportedKind::NotYetImplemented(format),
},
})
}