Compare commits
23 Commits
96819d2437
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| d44c4da72f | |||
| 48d92f6b67 | |||
| 318ce583ea | |||
| 3a61e15449 | |||
| c46ae525fc | |||
| e16d899c14 | |||
| e06d2419e5 | |||
| 4b1cf6c491 | |||
| 70174e9e49 | |||
| b2ef1d3d3d | |||
| 708e44053e | |||
| 37b4e1b4b2 | |||
| 4ba8e3e3ee | |||
| 872c1096a6 | |||
| 7da8639881 | |||
| d4c94a5a3a | |||
| db29d662c6 | |||
| d00d49135a | |||
| 18108b5d44 | |||
| 8af62e313b | |||
| 334d2a5e53 | |||
| 6a52f3c5b1 | |||
| 0714ae6f2f |
468
Cargo.lock
generated
468
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -9,7 +9,7 @@ edition = "2018"
|
||||
[dependencies]
|
||||
failure = "0.1"
|
||||
glob = "0.3"
|
||||
human_format = { git ="https://github.com/wathiede/human-format-rs" }
|
||||
human_format = "1.1.0"
|
||||
humantime = "1"
|
||||
lazy_static = "1.4"
|
||||
log = "0.4"
|
||||
|
||||
164
src/lib.rs
164
src/lib.rs
@@ -1,32 +1,24 @@
|
||||
use std::cmp::Ordering;
|
||||
use std::collections::HashMap;
|
||||
use std::env;
|
||||
use std::ffi::OsStr;
|
||||
use std::fmt;
|
||||
use std::fmt::Display;
|
||||
use std::fmt::Formatter;
|
||||
use std::fs::File;
|
||||
use std::io::BufReader;
|
||||
use std::io::BufWriter;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::str::FromStr;
|
||||
use std::{
|
||||
cmp::Ordering,
|
||||
collections::{HashMap, HashSet},
|
||||
env,
|
||||
ffi::OsStr,
|
||||
fmt,
|
||||
fmt::{Display, Formatter},
|
||||
fs::File,
|
||||
io::{BufReader, BufWriter},
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
str::FromStr,
|
||||
};
|
||||
|
||||
use failure::bail;
|
||||
use failure::Error;
|
||||
use failure::ResultExt;
|
||||
use failure::{bail, Error, ResultExt};
|
||||
use glob::glob;
|
||||
use lazy_static::lazy_static;
|
||||
use log::error;
|
||||
use log::info;
|
||||
use rayon::iter::ParallelBridge;
|
||||
use rayon::prelude::ParallelIterator;
|
||||
use log::{error, info};
|
||||
use rayon::{iter::ParallelBridge, prelude::ParallelIterator};
|
||||
use regex::Regex;
|
||||
use serde::de;
|
||||
use serde::de::Deserializer;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use serde::{de, de::Deserializer, Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
const FULL_METADATA_FILENAME: &str = "metadata.json";
|
||||
@@ -160,8 +152,8 @@ enum Stream {
|
||||
},
|
||||
#[serde(rename = "subtitle")]
|
||||
Subtitle {
|
||||
codec_name: String,
|
||||
codec_long_name: String,
|
||||
codec_name: Option<String>,
|
||||
codec_long_name: Option<String>,
|
||||
tags: Option<Tags>,
|
||||
},
|
||||
#[serde(rename = "attachment")]
|
||||
@@ -217,8 +209,8 @@ pub struct AudioFormat {
|
||||
|
||||
#[derive(Clone, Deserialize, Debug, PartialEq, Serialize)]
|
||||
pub struct SubtitleFormat {
|
||||
short_name: String,
|
||||
long_name: String,
|
||||
short_name: Option<String>,
|
||||
long_name: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
title: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
@@ -279,7 +271,7 @@ pub struct MetadataFile {
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
pub struct MovieLibrary {
|
||||
root: String,
|
||||
pub root: String,
|
||||
}
|
||||
|
||||
fn json_metadata_for_path<P: AsRef<Path> + AsRef<OsStr>>(path: P) -> Result<String, Error> {
|
||||
@@ -296,7 +288,7 @@ fn json_metadata_for_path<P: AsRef<Path> + AsRef<OsStr>>(path: P) -> Result<Stri
|
||||
])
|
||||
.arg(Path::new("./").join(path));
|
||||
info!(target: "json", "cmd {:?}", cmd);
|
||||
let output = cmd.output()?;
|
||||
let output = cmd.output().context(format!("failed to run {:?}", cmd))?;
|
||||
if output.status.success() {
|
||||
return Ok(String::from_utf8(output.stdout)?);
|
||||
}
|
||||
@@ -319,6 +311,30 @@ pub struct Movie {
|
||||
}
|
||||
|
||||
impl Movie {
|
||||
fn max_pixel_count(&self) -> Option<usize> {
|
||||
if self.files.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(self.files.iter().fold(usize::min_value(), |acc, (_, cmd)| {
|
||||
let min = cmd.video.iter().fold(usize::min_value(), |acc, v| {
|
||||
std::cmp::max(acc, v.width * v.height)
|
||||
});
|
||||
std::cmp::max(acc, min)
|
||||
}))
|
||||
}
|
||||
}
|
||||
fn min_pixel_count(&self) -> Option<usize> {
|
||||
if self.files.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(self.files.iter().fold(usize::max_value(), |acc, (_, cmd)| {
|
||||
let min = cmd.video.iter().fold(usize::max_value(), |acc, v| {
|
||||
std::cmp::min(acc, v.width * v.height)
|
||||
});
|
||||
std::cmp::min(acc, min)
|
||||
}))
|
||||
}
|
||||
}
|
||||
fn min_bit_rate(&self) -> Option<usize> {
|
||||
if self.files.is_empty() {
|
||||
None
|
||||
@@ -328,17 +344,6 @@ impl Movie {
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
fn min_resolution(&self) -> Option<Resolution> {
|
||||
if self.files.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(self.files.iter().fold(
|
||||
Resolution(usize::max_value(), usize::max_value()),
|
||||
|acc, (_, cmd)| std::cmp::min(acc, cmd.largest_dimension().unwrap()),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Movie {
|
||||
@@ -364,19 +369,28 @@ pub struct Movies {
|
||||
|
||||
impl Movies {
|
||||
/// Find all movies with multiple copies. The returned vec contains a tuple of (Movie to keep,
|
||||
/// One or more Movies to remove). The highest bit rate movie is kept.
|
||||
/// One or more Movies to remove). The highest resolution movie is kept.
|
||||
/// Movies with differing years are considered distinct movies.
|
||||
/// If there is a yearless movie and one or more movies with a year exist, then the yearless
|
||||
/// movie will be removed
|
||||
pub fn duplicate_candidates(&self) -> Vec<(&Movie, Vec<&Movie>)> {
|
||||
lazy_static! {
|
||||
static ref MULTIPLE_SPACES: Regex = Regex::new(r"\s+").unwrap();
|
||||
}
|
||||
let date_re = Regex::new(r"\(\d{4}\)$").unwrap();
|
||||
let mut movie_counter = HashMap::new();
|
||||
let mut movies_without_date_counter = HashMap::new();
|
||||
for m in &self.movies {
|
||||
let (path, _cmd) = m.files.first().unwrap();
|
||||
let parent = clean_path_parent(path)
|
||||
.to_string_lossy()
|
||||
.to_ascii_lowercase()
|
||||
let parent = MULTIPLE_SPACES
|
||||
.replace_all(
|
||||
&clean_path_parent(path)
|
||||
.to_string_lossy()
|
||||
.to_ascii_lowercase()
|
||||
.replace("-", " ")
|
||||
.replace("'", " "),
|
||||
" ",
|
||||
)
|
||||
.to_string();
|
||||
if date_re.is_match(&parent) {
|
||||
movie_counter.entry(parent).or_insert(Vec::new()).push(m);
|
||||
@@ -396,23 +410,15 @@ impl Movies {
|
||||
}
|
||||
}
|
||||
|
||||
for (parent, mut movies) in movie_counter.into_iter() {
|
||||
for (_parent, mut movies) in movie_counter.into_iter() {
|
||||
if movies.len() > 1 {
|
||||
// Sort, lowest bit_rate movie first
|
||||
movies.sort_by(|a, b| a.min_bit_rate().cmp(&b.min_bit_rate()));
|
||||
// Sort, lowest resolution movie first
|
||||
movies.sort_by(|a, b| a.max_pixel_count().cmp(&b.max_pixel_count()));
|
||||
// Flip order, we care about the largest.
|
||||
movies.reverse();
|
||||
// Take the largest image, return the rest for removal.
|
||||
let tuple = (movies.remove(0), movies);
|
||||
dupes.push(tuple);
|
||||
} else {
|
||||
/*
|
||||
let dateless_parent = if date_re.is_match(&parent) {
|
||||
parent[..parent.len() - 7].to_string()
|
||||
} else {
|
||||
parent.to_string()
|
||||
};
|
||||
*/
|
||||
}
|
||||
}
|
||||
// Sort to make this function deterministic.
|
||||
@@ -425,14 +431,6 @@ impl Movies {
|
||||
.partial_cmp(&b_keep.files.first().unwrap().0)
|
||||
.unwrap()
|
||||
});
|
||||
for d in &dupes {
|
||||
let (biggest, deletes) = d;
|
||||
eprintln!("biggest: {}", biggest);
|
||||
for (i, delete) in deletes.iter().enumerate() {
|
||||
eprintln!("{}. delete: {}", i + 1, delete);
|
||||
}
|
||||
}
|
||||
|
||||
dupes
|
||||
}
|
||||
}
|
||||
@@ -548,8 +546,8 @@ impl MovieLibrary {
|
||||
} = s
|
||||
{
|
||||
Some(SubtitleFormat {
|
||||
short_name: codec_name.to_string(),
|
||||
long_name: codec_long_name.to_string(),
|
||||
short_name: codec_name.clone(),
|
||||
long_name: codec_long_name.clone(),
|
||||
title: tags.as_ref().and_then(|t| t.title()),
|
||||
language: tags.as_ref().and_then(|t| t.language()),
|
||||
})
|
||||
@@ -643,11 +641,17 @@ impl MovieLibrary {
|
||||
Some((path.to_string_lossy().into_owned(), json))
|
||||
}
|
||||
Err(e) => {
|
||||
error!("{}", e);
|
||||
error!("Failed to open {}: {}", path.to_string_lossy(), e);
|
||||
None
|
||||
}
|
||||
}
|
||||
})
|
||||
.inspect(|(path, json)| {
|
||||
if let Err(err) = serde_json::from_str::<Metadata>(&json) {
|
||||
error!("Can't parse metadata for {}: {}", path, err);
|
||||
error!("{}", json);
|
||||
}
|
||||
})
|
||||
.map(|(path, json)| (path, serde_json::from_str::<Value>(&json).unwrap()))
|
||||
.collect();
|
||||
let new_videos = metadata.keys().cloned().collect();
|
||||
@@ -686,7 +690,7 @@ impl MovieLibrary {
|
||||
Ok(movies_from_paths_compact_metadata(p_cmd))
|
||||
}
|
||||
|
||||
pub fn videos(&self) -> Result<(HashMap<String, CompactMetadata>), Error> {
|
||||
pub fn videos(&self) -> Result<HashMap<String, CompactMetadata>, Error> {
|
||||
let path = Path::new(&self.root).join(COMPACT_METADATA_FILENAME);
|
||||
let f = File::open(&path).context(format!("open {}", path.display()))?;
|
||||
let r = BufReader::new(f);
|
||||
@@ -694,6 +698,28 @@ impl MovieLibrary {
|
||||
Ok(serde_json::from_reader(r)
|
||||
.context(format!("serde_json::from_reader {}", path.display()))?)
|
||||
}
|
||||
|
||||
pub fn empty_dirs(&self) -> Result<Vec<String>, Error> {
|
||||
let mut all_dirs = HashSet::new();
|
||||
let root_len = self.root.len() + 1; // +1 for trailing slash
|
||||
for de in Path::new(&self.root).read_dir()? {
|
||||
let de = de?;
|
||||
if de.metadata()?.is_dir() {
|
||||
let path = de.path().to_string_lossy().to_string();
|
||||
all_dirs.insert(path[root_len..].to_string());
|
||||
}
|
||||
}
|
||||
for path in self.videos()?.keys() {
|
||||
let dir = match path.find("/") {
|
||||
Some(idx) => path[..idx].to_string(),
|
||||
None => path.to_string(),
|
||||
};
|
||||
all_dirs.remove(&dir);
|
||||
}
|
||||
let mut empty_dirs: Vec<_> = all_dirs.into_iter().collect();
|
||||
empty_dirs.sort();
|
||||
Ok(empty_dirs)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
56
src/main.rs
56
src/main.rs
@@ -1,10 +1,6 @@
|
||||
use std::collections::HashMap;
|
||||
use std::error::Error;
|
||||
use std::io::Write;
|
||||
use std::time::Duration;
|
||||
use std::{collections::HashMap, error::Error, io::Write, path::Path, time::Duration};
|
||||
|
||||
use human_format::Formatter;
|
||||
use human_format::Scales;
|
||||
use human_format::{Formatter, Scales};
|
||||
use humantime;
|
||||
use lazy_static::lazy_static;
|
||||
use log::info;
|
||||
@@ -12,12 +8,10 @@ use regex::Regex;
|
||||
use structopt::StructOpt;
|
||||
use tabwriter::TabWriter;
|
||||
|
||||
use superdeduper::clean_path_parent;
|
||||
use superdeduper::CompactMetadata;
|
||||
use superdeduper::MovieLibrary;
|
||||
use superdeduper::{clean_path_parent, CompactMetadata, MovieLibrary};
|
||||
|
||||
const MOVIE_DIR: &str = "/home/wathiede/Movies";
|
||||
const TO_BE_REMOVED_DIR: &str = "/storage/media/to-be-deleted/";
|
||||
const TO_BE_REMOVED_DIR: &str = "/home/wathiede/to-be-deleted/";
|
||||
|
||||
lazy_static! {
|
||||
static ref CLEAN_TITLE_CHARS: Regex = Regex::new("[^ 0-9[:alpha:]]").unwrap();
|
||||
@@ -68,8 +62,12 @@ fn print_dupes(lib: &MovieLibrary) {
|
||||
println!();
|
||||
}
|
||||
delete_paths.sort();
|
||||
let root = Path::new(&lib.root);
|
||||
for path in &delete_paths {
|
||||
println!(r#"mv "{}" /storage/media/to-be-deleted/"#, path);
|
||||
println!(r#"rm "{}""#, root.join(path).to_string_lossy(),);
|
||||
}
|
||||
if delete_paths.len() > 0 {
|
||||
println!("superdeduper update-compact-metadata && superdeduper empty-dirs")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,7 +143,7 @@ fn print_videos(videos: &HashMap<String, CompactMetadata>, filter: Option<&Regex
|
||||
humantime::Duration::from(Duration::from_secs(md.duration as u64)),
|
||||
&name[MOVIE_DIR.len() + 1..]
|
||||
);
|
||||
println!("mv '{}' '{}'", name, TO_BE_REMOVED_DIR);
|
||||
println!("rm '{}'", name);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,6 +169,8 @@ enum Command {
|
||||
about = "Write full metadata files and update compact file on changes"
|
||||
)]
|
||||
UpdateAndCompactMetadata,
|
||||
#[structopt(about = "Print directories with no movie files in them")]
|
||||
EmptyDirs,
|
||||
}
|
||||
|
||||
#[derive(StructOpt)]
|
||||
@@ -179,6 +179,13 @@ enum Command {
|
||||
about = "Tool for pruning extra videos in collection"
|
||||
)]
|
||||
struct SuperDeduper {
|
||||
#[structopt(
|
||||
short = "r",
|
||||
long = "root",
|
||||
help = "Root directory to store files.",
|
||||
default_value = MOVIE_DIR,
|
||||
)]
|
||||
root: String,
|
||||
#[structopt(
|
||||
short = "v",
|
||||
help = "Sets the level of verbosity",
|
||||
@@ -206,14 +213,14 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
|
||||
match app.cmd {
|
||||
Command::Samples => {
|
||||
let lib = MovieLibrary::new(MOVIE_DIR);
|
||||
let lib = MovieLibrary::new(app.root);
|
||||
let videos = lib.videos()?;
|
||||
|
||||
let samples_re = Regex::new(r"(?i).*sample.*").unwrap();
|
||||
print_videos(&videos, Some(&samples_re));
|
||||
}
|
||||
Command::Groups => {
|
||||
let lib = MovieLibrary::new(MOVIE_DIR);
|
||||
let lib = MovieLibrary::new(app.root);
|
||||
let videos = lib.videos()?;
|
||||
|
||||
let mut video_groups: HashMap<String, Vec<(String, CompactMetadata)>> = HashMap::new();
|
||||
@@ -226,28 +233,39 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
print_video_groups(&video_groups);
|
||||
}
|
||||
Command::CompactMetadata => {
|
||||
let lib = MovieLibrary::new(MOVIE_DIR);
|
||||
let lib = MovieLibrary::new(app.root);
|
||||
lib.compact_metadata()?;
|
||||
}
|
||||
Command::PrintDupes => {
|
||||
let lib = MovieLibrary::new(MOVIE_DIR);
|
||||
let lib = MovieLibrary::new(app.root);
|
||||
print_dupes(&lib);
|
||||
}
|
||||
Command::PrintAll => {
|
||||
let lib = MovieLibrary::new(MOVIE_DIR);
|
||||
let lib = MovieLibrary::new(app.root);
|
||||
let videos = lib.videos()?;
|
||||
|
||||
print_all(videos);
|
||||
}
|
||||
Command::UpdateMetadata => {
|
||||
let lib = MovieLibrary::new(MOVIE_DIR);
|
||||
let lib = MovieLibrary::new(app.root);
|
||||
lib.update_metadata()?;
|
||||
}
|
||||
Command::UpdateAndCompactMetadata => {
|
||||
let lib = MovieLibrary::new(MOVIE_DIR);
|
||||
let lib = MovieLibrary::new(app.root);
|
||||
lib.update_metadata()?;
|
||||
lib.compact_metadata()?;
|
||||
}
|
||||
Command::EmptyDirs => {
|
||||
let lib = MovieLibrary::new(app.root);
|
||||
let dirs = lib.empty_dirs()?;
|
||||
let root = Path::new(&lib.root);
|
||||
if !dirs.is_empty() {
|
||||
println!("Empty directories:");
|
||||
for d in dirs {
|
||||
println!(r#"rm -rf "{}""#, root.join(d).to_string_lossy());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -335,7 +335,7 @@ fn test_fullmetal() -> Result<(), Box<dyn Error>> {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_keep_lower_res_higher_bit_rate() -> Result<(), Box<dyn Error>> {
|
||||
fn test_keep_higher_res_lower_bit_rate() -> Result<(), Box<dyn Error>> {
|
||||
let mut movies = Movies {
|
||||
movies: vec![
|
||||
build_movie(vec![(
|
||||
@@ -361,15 +361,17 @@ fn test_keep_lower_res_higher_bit_rate() -> Result<(), Box<dyn Error>> {
|
||||
let got = movies.duplicate_candidates();
|
||||
let want = vec![(
|
||||
build_movie(vec![(
|
||||
"X Men The Last Stand (2006)/X.Men.The.Last.Stand.2006.1080p.BluRay.x264.DTS-ES.PRoDJi.mkv",
|
||||
(1920, 800),
|
||||
11349705,
|
||||
)]),
|
||||
vec![build_movie(vec![(
|
||||
"X Men The Last Stand (2006)/948f08a4ba784626ac13de77b77559dd.mkv",
|
||||
(1920, 1080),
|
||||
6574160,
|
||||
)])],
|
||||
)]),
|
||||
vec![
|
||||
build_movie(vec![(
|
||||
"X Men The Last Stand (2006)/X.Men.The.Last.Stand.2006.1080p.BluRay.x264.DTS-ES.PRoDJi.mkv",
|
||||
(1920, 800),
|
||||
11349705,
|
||||
)])
|
||||
],
|
||||
)];
|
||||
validate_duplicates(got, want);
|
||||
Ok(())
|
||||
|
||||
Reference in New Issue
Block a user