use anyhow::{bail, Context, Result};
use std::{
env, fs,
path::{Path, PathBuf},
process,
time::SystemTime,
};
pub const IMAGE_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "bmp", "gif", "webp"];
const EXTENSION_DISPLAY_PREFIX: &str = ".";
const FALLBACK_PARENT_DIR: &str = ".";
#[allow(dead_code)]
pub fn discover(directory: &Path, extension: &str) -> Result<Vec<PathBuf>> {
let wanted = extension.trim_start_matches(EXTENSION_DISPLAY_PREFIX);
let mut paths = Vec::new();
for entry in
fs::read_dir(directory).with_context(|| format!("reading {}", directory.display()))?
{
let path = entry?.path();
if path.is_file()
&& path
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case(wanted))
{
paths.push(path);
}
}
paths.sort();
Ok(paths)
}
pub fn companion_image(video: &Path) -> Result<PathBuf> {
let stem = video.file_stem().context("video has no file stem")?;
let parent = video
.parent()
.unwrap_or_else(|| Path::new(FALLBACK_PARENT_DIR));
for ext in IMAGE_EXTENSIONS {
let candidate = parent.join(stem).with_extension(ext);
if candidate.is_file() {
return Ok(candidate);
}
}
bail!(
"no image found for {} (tried: {})",
video.display(),
IMAGE_EXTENSIONS
.iter()
.map(|e| format!("{EXTENSION_DISPLAY_PREFIX}{e}"))
.collect::<Vec<_>>()
.join(", ")
)
}
pub fn has_stem_suffix(path: &Path, suffix: &str) -> bool {
path.file_stem()
.is_some_and(|stem| stem.to_string_lossy().ends_with(suffix))
}
pub fn canonical_discover(
directory: &Path,
extension: &str,
exclude_stem_suffix: Option<&str>,
) -> Result<Vec<PathBuf>> {
let wanted = extension.trim_start_matches(EXTENSION_DISPLAY_PREFIX);
let mut paths = Vec::new();
for entry in
fs::read_dir(directory).with_context(|| format!("reading {}", directory.display()))?
{
let path = entry?.path();
if !path.is_file() {
continue;
}
if !path
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case(wanted))
{
continue;
}
if let Some(suffix) = exclude_stem_suffix {
if has_stem_suffix(&path, suffix) {
continue;
}
}
if let Ok(canonical) = path.canonicalize() {
paths.push(canonical);
}
}
paths.sort();
Ok(paths)
}
pub fn queue_from_directory(
directory: &Path,
extension: &str,
exclude_stem_suffix: Option<&str>,
) -> Result<Vec<PathBuf>> {
canonical_discover(directory, extension, exclude_stem_suffix)
}
pub fn queue_from_entry(
entry: &Path,
extension: &str,
exclude_stem_suffix: Option<&str>,
) -> Result<Vec<PathBuf>> {
let parent = entry
.parent()
.with_context(|| format!("file has no parent: {}", entry.display()))?;
let canonical_entry = entry
.canonicalize()
.with_context(|| format!("file not found: {}", entry.display()))?;
let siblings = canonical_discover(parent, extension, exclude_stem_suffix)?;
let mut queue = Vec::with_capacity(siblings.len() + 1);
queue.push(canonical_entry.clone());
for path in siblings {
if path != canonical_entry {
queue.push(path);
}
}
Ok(queue)
}
#[allow(dead_code)]
pub fn has_extension(path: &Path, extension: &str) -> bool {
path.extension().is_some_and(|e| {
e.eq_ignore_ascii_case(extension.trim_start_matches(EXTENSION_DISPLAY_PREFIX))
})
}
pub fn temp_path(prefix: &str, suffix: &str) -> Result<PathBuf> {
let now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.context("system time before Unix epoch")?
.as_nanos();
let pid = process::id();
let filename = format!("{}{}_{}{}", prefix, pid, now, suffix);
Ok(env::temp_dir().join(filename))
}
pub fn output_path_for_video_with_image(video: &Path) -> Result<PathBuf> {
let dir = video.parent().context("video has no parent")?;
let stem = video
.file_stem()
.context("video has no stem")?
.to_string_lossy();
Ok(dir.join(format!("{stem}_with_image.mp4")))
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
#[test]
fn discovers_no_subdirectories() {
let dir = tempdir().unwrap();
fs::write(dir.path().join("a.TS"), "").unwrap();
fs::create_dir(dir.path().join("nested.ts")).unwrap();
assert_eq!(discover(dir.path(), "ts").unwrap().len(), 1);
}
#[test]
fn finds_priority_and_special_names() {
let dir = tempdir().unwrap();
let video = dir.path().join("a [x].video.mp4");
fs::write(&video, "").unwrap();
fs::write(dir.path().join("a [x].video.jpg"), "").unwrap();
assert!(companion_image(&video)
.unwrap()
.ends_with("a [x].video.jpg"));
}
}