use super::Run;
use crate::drive::{self, DriveAuthorization};
use crate::error::Result;
#[derive(Debug, Clone, PartialEq)]
pub(super) enum Kept {
Video {
captions: usize,
},
Photo,
}
impl Kept {
pub(super) fn captioned_video(&self) -> bool {
matches!(self, Kept::Video { captions } if *captions > 0)
}
}
pub(super) async fn keep(run: &Run, repository: u64, prefix: &str) -> Result<Vec<Kept>> {
let folder = format!("termite/repositories/{repository}/media/");
let mut files = Vec::new();
for name in drive::list(&run.key, &folder, None).await? {
if name.ends_with('/') {
continue;
}
let mut file = drive::pull(DriveAuthorization::Path {
authorization: run.key.clone(),
path: format!("{folder}{name}"),
group: None,
})
.await?;
let bytes = file.download(false, None).await?;
run.file(
&format!("{prefix}{name}"),
&file.content_type,
bytes.clone(),
)
.await?;
files.push((name, bytes));
}
Ok(kept(&files))
}
fn kept(files: &[(String, Vec<u8>)]) -> Vec<Kept> {
let named = |wanted: &str| files.iter().find(|(name, _)| name == wanted);
files
.iter()
.filter_map(|(name, _)| {
let (base, extension) = name.rsplit_once('.')?;
match extension.to_ascii_lowercase().as_str() {
"mp4" => Some(Kept::Video {
captions: named(&format!("{base}.vtt"))
.map_or(0, |(_, vtt)| cues(&String::from_utf8_lossy(vtt))),
}),
"jpg" | "jpeg" | "png" => Some(Kept::Photo),
_ => None,
}
})
.collect()
}
fn cues(vtt: &str) -> usize {
vtt.lines().filter(|line| line.contains("-->")).count()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn finds_videos_with_their_captions_and_photos() {
let vtt = "WEBVTT\n\n00:00.000 --> 00:02.500\nOpening a terminal\n\n00:02.500 --> 00:06.000\nThe tests pass\n";
let files: Vec<(String, Vec<u8>)> = [
("1.mp4", b"video".to_vec()),
("1.vtt", vtt.as_bytes().to_vec()),
("2.mp4", b"video".to_vec()),
("3.jpg", b"photo".to_vec()),
("notes.txt", b"text".to_vec()),
]
.into_iter()
.map(|(name, bytes)| (name.to_string(), bytes))
.collect();
let kept = kept(&files);
assert_eq!(
kept,
[
Kept::Video { captions: 2 },
Kept::Video { captions: 0 },
Kept::Photo
]
);
assert!(kept[0].captioned_video());
assert!(!kept[1].captioned_video() && !kept[2].captioned_video());
}
}