beffroi-tools/crates/pptx-reporter/src/archive.rs

178 lines
6.0 KiB
Rust

use crate::{model::Settings, playback};
use anyhow::{Context, Result};
use roxmltree::Document;
use std::{
collections::{BTreeMap, BTreeSet},
fs::File,
io::Read,
path::Path,
};
use zip::ZipArchive;
pub const P: &str = "http://schemas.openxmlformats.org/presentationml/2006/main";
pub const R: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
pub const P14: &str = "http://schemas.microsoft.com/office/powerpoint/2010/main";
pub type Relationships = BTreeMap<String, (Option<String>, String)>;
#[derive(Default)]
pub struct Discovery {
pub videos: Vec<String>,
pub uses: BTreeMap<String, BTreeSet<usize>>,
pub settings: BTreeMap<String, Vec<Settings>>,
pub external: BTreeSet<usize>,
}
pub fn xml(zip: &mut ZipArchive<File>, name: &str) -> Option<String> {
let mut s = String::new();
// XML parts should be small; avoid unbounded reads of untrusted archives.
zip.by_name(name)
.ok()?
.take(16 * 1024 * 1024)
.read_to_string(&mut s)
.ok()?;
Document::parse(&s).ok()?;
Some(s)
}
pub fn normalize(base: &str, target: &str) -> String {
let target = target.split(['#', '?']).next().unwrap_or("");
let joined = if target.starts_with('/') {
target.to_owned()
} else {
format!("{}/{}", base.rsplit_once('/').map_or("", |v| v.0), target)
};
let mut parts = vec![];
for part in joined.split('/') {
match part {
"" | "." => {}
".." => {
parts.pop();
}
p => parts.push(p),
}
}
parts.join("/")
}
pub fn rels(zip: &mut ZipArchive<File>, source: &str) -> Relationships {
let (dir, base) = source.rsplit_once('/').unwrap_or(("", source));
let Some(s) = xml(zip, &format!("{dir}/_rels/{base}.rels")) else {
return BTreeMap::new();
};
let doc = Document::parse(&s).unwrap();
doc.descendants()
.filter(|n| n.tag_name().name() == "Relationship")
.filter_map(|n| {
let id = n.attribute("Id")?;
let target = if n
.attribute("TargetMode")
.is_some_and(|v| v.eq_ignore_ascii_case("external"))
{
None
} else {
Some(normalize(source, n.attribute("Target").unwrap_or("")))
};
Some((
id.into(),
(target, n.attribute("Type").unwrap_or("").into()),
))
})
.collect()
}
pub fn is_video(name: &str) -> bool {
let ext = name.rsplit('.').next().unwrap_or("").to_lowercase();
[
"mp4", "m4v", "mov", "avi", "wmv", "webm", "mpg", "mpeg", "mkv", "asf", "3gp", "ts",
]
.contains(&ext.as_str())
}
pub fn slides(zip: &mut ZipArchive<File>) -> Vec<String> {
let mapping = rels(zip, "ppt/presentation.xml");
if let Some(s) = xml(zip, "ppt/presentation.xml") {
let doc = Document::parse(&s).unwrap();
let ordered: Vec<_> = doc
.descendants()
.filter(|n| n.has_tag_name((P, "sldId")))
.filter_map(|n| {
mapping
.get(n.attribute((R, "id"))?)
.and_then(|v| v.0.clone())
})
.collect();
if !ordered.is_empty() {
return ordered;
}
}
let mut parts: Vec<_> = zip
.file_names()
.filter_map(|s| {
let num = s
.strip_prefix("ppt/slides/slide")?
.strip_suffix(".xml")?
.parse::<u64>()
.ok()?;
Some((num, s.to_string()))
})
.collect();
parts.sort();
parts.into_iter().map(|v| v.1).collect()
}
pub fn discover(zip: &mut ZipArchive<File>) -> Discovery {
let names: BTreeSet<_> = zip.file_names().map(str::to_owned).collect();
let videos: Vec<_> = names
.iter()
.filter(|s| s.starts_with("ppt/media/") && is_video(s))
.cloned()
.collect();
let mut out = Discovery {
videos,
..Default::default()
};
for (index, slide) in slides(zip).iter().enumerate() {
let index = index + 1;
let Some(s) = xml(zip, slide) else { continue };
let doc = Document::parse(&s).unwrap();
let mapping = rels(zip, slide);
for node in doc
.descendants()
.filter(|n| matches!(n.tag_name().name(), "videoFile" | "media"))
{
for attr in ["link", "embed"] {
let Some((target, kind)) = node.attribute((R, attr)).and_then(|id| mapping.get(id))
else {
continue;
};
if node.tag_name().name() == "media" && !kind.ends_with("/media") {
continue;
}
match target {
None => {
out.external.insert(index);
}
Some(target) if names.contains(target) && is_video(target) => {
out.uses.entry(target.clone()).or_default().insert(index);
}
_ => {}
}
}
}
for (part, settings) in playback::shape_settings(&doc, &mapping, &out.videos, index) {
let group = out.settings.entry(part).or_default();
if !group.contains(&settings) {
group.push(settings);
}
}
}
out
}
pub fn copy_media(zip: &mut ZipArchive<File>, part: &str, destination: &Path) -> Result<()> {
anyhow::ensure!(
!destination.is_symlink(),
"Refusing output symlink: {}",
destination.display()
);
let parent = destination.parent().context("No output parent")?;
std::fs::create_dir_all(parent)?;
// Never leave a partially extracted media file on failure.
let mut temporary = tempfile::NamedTempFile::new_in(parent)?;
std::io::copy(&mut zip.by_name(part)?, &mut temporary)?;
temporary.persist(destination).map_err(|e| e.error)?;
Ok(())
}