Files
music-sort/src/move_files.rs
T

142 lines
3.9 KiB
Rust

use chrono::Utc;
use glob::glob;
use lofty::prelude::ItemKey;
use lofty::tag::Accessor;
use lofty::tag::Tag;
use std::env::var;
use std::fs::OpenOptions;
use std::fs::{copy, create_dir, create_dir_all, remove_dir, rename};
use std::io::Write;
use std::path::PathBuf;
pub fn move_files(
file_path: PathBuf,
tag: Tag,
extra_files: [String; 9],
should_copy: bool,
has_parent: bool,
add_new_playlist: bool,
) -> Result<(), Box<dyn std::error::Error>> {
let target_dir = PathBuf::from("/home/user/Music/Tracks");
let artist = tag.artist();
let album = tag.album();
let title = tag.title();
let track_number = tag.get_string(ItemKey::TrackNumber);
let album_artist_path = tag.get_string(ItemKey::AlbumArtist).unwrap_or("");
let artist_dir = if !album_artist_path.is_empty() {
Some(album_artist_path)
} else {
artist.as_deref()
};
let album_dir = album.or(title.clone());
let (Some(artist_dir), Some(album_dir)) = (artist_dir, album_dir) else {
return Ok(());
};
let artist_dir = fix_filename(artist_dir);
let album_dir = fix_filename(&album_dir);
let target = target_dir.join(artist_dir).join(album_dir);
create_dir_all(&target)?;
let file_name = if let Some(track_number) = track_number {
let number: u32 = track_number.parse()?;
let artist = fix_filename(&artist.unwrap());
let title = fix_filename(&title.unwrap());
PathBuf::from(format!("{:02}. {} - {}.flac", number, artist, title,))
} else {
let artist = fix_filename(&artist.unwrap());
let title = fix_filename(&title.unwrap());
PathBuf::from(format!("01. {} - {}.flac", artist, title))
};
if should_copy {
copy(&file_path, target.join(&file_name))?;
} else {
rename(&file_path, target.join(&file_name))?;
}
if add_new_playlist {
new_playlist(target.join(file_name))?;
}
for ext in &extra_files {
let pattern = file_path.parent().unwrap().join(format!("*.{}", ext));
let paths: Vec<_> = glob(pattern.to_str().unwrap())?.collect::<Result<_, _>>()?;
for path in paths {
let destination = target.join(path.file_name().unwrap());
let result = if should_copy {
copy(&path, &destination).map(|_| ())
} else {
rename(&path, &destination)
};
if let Err(e) = result {
println!("Copy failed for {:?}: {e}", path);
}
}
}
let is_empty = has_parent && file_path.parent().unwrap().read_dir()?.next().is_none();
if is_empty {
remove_dir(file_path.parent().unwrap())?;
}
write_log(file_path)?;
Ok(())
}
fn fix_filename(name: &str) -> String {
name.chars()
.map(|c| match c {
'/' => '_',
c => c,
})
.collect()
}
fn new_playlist(path: PathBuf) -> std::result::Result<(), std::io::Error> {
let new_playlist_path = PathBuf::from("/home/user/Music/Playlists/active - new.m3u");
let mut new_playlist = OpenOptions::new()
.append(true)
.open(new_playlist_path)
.unwrap();
println!("{:?}", path);
writeln!(new_playlist, "{}", path.display())
}
fn write_log(file_path: PathBuf) -> Result<(), Box<dyn std::error::Error>> {
let home_dir: PathBuf = PathBuf::from(var("HOME").expect("HOME is not set"));
let data_dir = home_dir.join(".local").join("share").join("music-sort");
let log_file_path = data_dir.join("music-sort.log");
if !data_dir.exists() {
create_dir(&data_dir)?;
}
let mut log_file = OpenOptions::new()
.append(true)
.create(true)
.open(log_file_path)
.unwrap();
if let Err(e) = writeln!(
log_file,
"[{}]: Imported file: {:?}",
Utc::now().format("%Y-%m-%dT%H:%M:%S"),
file_path.file_name().unwrap()
) {
eprintln!("Couldn't write to file: {}", e);
}
Ok(())
}