use serde_json::{Map, Value};
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Exif(Map<String, Value>);
impl Exif {
pub fn get(&self, query: &str) -> Option<&Value> {
let mut parts = query.split('.');
let mut value = self.0.get(parts.next()?)?;
for part in parts {
value = value.get(part)?;
}
Some(value)
}
pub fn all(&self) -> &Map<String, Value> {
&self.0
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn orientation(&self) -> Option<u64> {
self.get("IFD0.Orientation").and_then(Value::as_u64)
}
pub(crate) fn set_orientation(&mut self, orientation: u64) {
for section in self.0.values_mut() {
if let Some(tags) = section.as_object_mut()
&& tags.contains_key("Orientation")
{
tags.insert("Orientation".to_owned(), Value::from(orientation));
}
}
}
pub(crate) fn read(bytes: &[u8]) -> Exif {
let Ok(data) = exif::Reader::new().read_from_container(&mut std::io::Cursor::new(bytes)) else {
return Exif::default();
};
let mut sections = Map::new();
for field in data.fields() {
let section = match field.tag.context() {
exif::Context::Tiff if field.ifd_num == exif::In::PRIMARY => "IFD0",
exif::Context::Tiff => "THUMBNAIL",
exif::Context::Exif => "EXIF",
exif::Context::Gps => "GPS",
exif::Context::Interop => "INTEROP",
_ => continue,
};
let value = match &field.value {
exif::Value::Ascii(values) => Value::from(
values
.first()
.map(|v| String::from_utf8_lossy(v).into_owned())
.unwrap_or_default(),
),
exif::Value::Byte(values) if values.len() == 1 => Value::from(values[0]),
exif::Value::Short(values) if values.len() == 1 => Value::from(values[0]),
exif::Value::Long(values) if values.len() == 1 => Value::from(values[0]),
exif::Value::SShort(values) if values.len() == 1 => Value::from(values[0]),
exif::Value::SLong(values) if values.len() == 1 => Value::from(values[0]),
exif::Value::Rational(values) if values.len() == 1 => {
Value::from(format!("{}/{}", values[0].num, values[0].denom))
}
_ => Value::from(field.display_value().to_string()),
};
sections
.entry(section.to_owned())
.or_insert_with(|| Value::Object(Map::new()))
.as_object_mut()
.map(|tags| tags.insert(field.tag.to_string(), value));
}
Exif(sections)
}
}