Undo some 'cargo fmt' changes.

This commit is contained in:
Craig Drummond 2022-04-13 21:32:44 +01:00
parent 985902325e
commit 0653e365b8
6 changed files with 64 additions and 192 deletions

View File

@ -63,11 +63,7 @@ fn check_dir_entry(
if pb.is_dir() {
let check = pb.join(DONT_ANALYSE);
if check.exists() {
log::info!(
"Skipping '{}', found '{}'",
pb.to_string_lossy(),
DONT_ANALYSE
);
log::info!("Skipping '{}', found '{}'", pb.to_string_lossy(), DONT_ANALYSE);
} else {
get_file_list(db, mpath, &pb, track_paths, cue_tracks);
}
@ -137,9 +133,7 @@ pub fn analyse_new_files(db: &db::Db, mpath: &PathBuf, track_paths: Vec<String>)
db.add_track(&sname, &meta, &track.analysis);
analysed += 1;
}
Err(e) => {
failed.push(format!("{} - {}", sname, e));
}
Err(e) => { failed.push(format!("{} - {}", sname, e)); }
};
progress.inc(1);
@ -177,9 +171,7 @@ pub fn analyse_new_files(db: &db::Db, mpath: &PathBuf, track_paths: Vec<String>)
Ok(())
}
pub fn analyze_cue_tracks(
tracks: Vec<cue::CueTrack>,
) -> mpsc::IntoIter<(cue::CueTrack, BlissResult<Song>)> {
pub fn analyze_cue_tracks(tracks: Vec<cue::CueTrack>) -> mpsc::IntoIter<(cue::CueTrack, BlissResult<Song>)> {
let num_cpus = num_cpus::get();
let last_track_duration = Duration::new(cue::LAST_TRACK_DURATION, 0);
@ -269,11 +261,7 @@ pub fn analyze_cue_tracks(
rx.into_iter()
}
pub fn analyse_new_cue_tracks(
db: &db::Db,
mpath: &PathBuf,
cue_tracks: Vec<cue::CueTrack>,
) -> Result<()> {
pub fn analyse_new_cue_tracks(db: &db::Db, mpath: &PathBuf, cue_tracks: Vec<cue::CueTrack>) -> Result<()> {
let total = cue_tracks.len();
let progress = ProgressBar::new(total.try_into().unwrap()).with_style(
ProgressStyle::default_bar()
@ -310,11 +298,7 @@ pub fn analyse_new_cue_tracks(
};
progress.inc(1);
}
progress.finish_with_message(format!(
"{} Analysed. {} Failure(s).",
analysed,
failed.len()
));
progress.finish_with_message(format!("{} Analysed. {} Failure(s).", analysed, failed.len()));
if !failed.is_empty() {
let total = failed.len();
failed.truncate(MAX_ERRORS_TO_SHOW);
@ -330,13 +314,7 @@ pub fn analyse_new_cue_tracks(
Ok(())
}
pub fn analyse_files(
db_path: &str,
mpaths: &Vec<PathBuf>,
dry_run: bool,
keep_old: bool,
max_num_tracks: usize,
) {
pub fn analyse_files(db_path: &str, mpaths: &Vec<PathBuf>, dry_run: bool, keep_old: bool, max_num_tracks: usize) {
let mut db = db::Db::new(&String::from(db_path));
let mut track_count_left = max_num_tracks;
@ -396,10 +374,8 @@ pub fn analyse_files(
if !track_paths.is_empty() {
match analyse_new_files(&db, &mpath, track_paths) {
Ok(_) => {}
Err(e) => {
log::error!("Analysis returned error: {}", e);
}
Ok(_) => { }
Err(e) => { log::error!("Analysis returned error: {}", e); }
}
} else {
log::info!("No new tracks to analyse");

View File

@ -49,12 +49,7 @@ pub fn parse(audio_path: &PathBuf, cue_path: &PathBuf) -> Vec<CueTrack> {
Some((_, start)) => {
let mut track_path = audio_path.clone();
let ext = audio_path.extension().unwrap().to_string_lossy();
track_path.set_extension(format!(
"{}{}{}",
ext,
MARKER,
resp.len() + 1
));
track_path.set_extension(format!("{}{}{}", ext, MARKER, resp.len() + 1));
let mut ctrack = CueTrack {
audio_path: audio_path.clone(),
@ -80,14 +75,12 @@ pub fn parse(audio_path: &PathBuf, cue_path: &PathBuf) -> Vec<CueTrack> {
resp.push(ctrack);
}
None => {}
None => { }
}
}
}
}
Err(e) => {
log::error!("Failed to parse '{}'. {}", cue_path.to_string_lossy(), e);
}
Err(e) => { log::error!("Failed to parse '{}'. {}", cue_path.to_string_lossy(), e); }
}
for i in 0..(resp.len() - 1) {

View File

@ -105,10 +105,7 @@ impl Db {
process::exit(-1);
}
let cmd = self.conn.execute(
"CREATE UNIQUE INDEX IF NOT EXISTS Tracks_idx ON Tracks(File)",
[],
);
let cmd = self.conn.execute("CREATE UNIQUE INDEX IF NOT EXISTS Tracks_idx ON Tracks(File)", []);
if cmd.is_err() {
log::error!("Failed to create DB index");
@ -125,12 +122,8 @@ impl Db {
if cfg!(windows) {
db_path = db_path.replace("\\", "/");
}
let mut stmt = self
.conn
.prepare("SELECT rowid FROM Tracks WHERE File=:path;")?;
let track_iter = stmt
.query_map(&[(":path", &db_path)], |row| Ok(row.get(0)?))
.unwrap();
let mut stmt = self.conn.prepare("SELECT rowid FROM Tracks WHERE File=:path;")?;
let track_iter = stmt.query_map(&[(":path", &db_path)], |row| Ok(row.get(0)?)).unwrap();
let mut rowid: usize = 0;
for tr in track_iter {
rowid = tr.unwrap();
@ -153,7 +146,7 @@ impl Db {
analysis[AnalysisIndex::StdDeviationSpectralRolloff], analysis[AnalysisIndex::MeanSpectralFlatness], analysis[AnalysisIndex::StdDeviationSpectralFlatness], analysis[AnalysisIndex::MeanLoudness], analysis[AnalysisIndex::StdDeviationLoudness],
analysis[AnalysisIndex::Chroma1], analysis[AnalysisIndex::Chroma2], analysis[AnalysisIndex::Chroma3], analysis[AnalysisIndex::Chroma4], analysis[AnalysisIndex::Chroma5],
analysis[AnalysisIndex::Chroma6], analysis[AnalysisIndex::Chroma7], analysis[AnalysisIndex::Chroma8], analysis[AnalysisIndex::Chroma9], analysis[AnalysisIndex::Chroma10]]) {
Ok(_) => { },
Ok(_) => { }
Err(e) => { log::error!("Failed to insert '{}' into database. {}", path, e); }
}
} else {
@ -163,12 +156,12 @@ impl Db {
analysis[AnalysisIndex::StdDeviationSpectralRolloff], analysis[AnalysisIndex::MeanSpectralFlatness], analysis[AnalysisIndex::StdDeviationSpectralFlatness], analysis[AnalysisIndex::MeanLoudness], analysis[AnalysisIndex::StdDeviationLoudness],
analysis[AnalysisIndex::Chroma1], analysis[AnalysisIndex::Chroma2], analysis[AnalysisIndex::Chroma3], analysis[AnalysisIndex::Chroma4], analysis[AnalysisIndex::Chroma5],
analysis[AnalysisIndex::Chroma6], analysis[AnalysisIndex::Chroma7], analysis[AnalysisIndex::Chroma8], analysis[AnalysisIndex::Chroma9], analysis[AnalysisIndex::Chroma10], id]) {
Ok(_) => { },
Ok(_) => { }
Err(e) => { log::error!("Failed to update '{}' in database. {}", path, e); }
}
}
}
Err(_) => {}
Err(_) => { }
}
}
@ -218,9 +211,7 @@ impl Db {
let count_before = self.get_track_count();
for t in to_remove {
//log::debug!("Remove '{}'", t);
let cmd = self
.conn
.execute("DELETE FROM Tracks WHERE File = ?;", params![t]);
let cmd = self.conn.execute("DELETE FROM Tracks WHERE File = ?;", params![t]);
if let Err(e) = cmd {
log::error!("Failed to remove '{}' - {}", t, e)
@ -296,7 +287,7 @@ impl Db {
} else if ftags != dtags {
match self.conn.execute("UPDATE Tracks SET Title=?, Artist=?, AlbumArtist=?, Album=?, Genre=?, Duration=? WHERE rowid=?;",
params![ftags.title, ftags.artist, ftags.album_artist, ftags.album, ftags.genre, ftags.duration, dbtags.rowid]) {
Ok(_) => { updated += 1; },
Ok(_) => { updated += 1; }
Err(e) => { log::error!("Failed to update tags of '{}'. {}", dbtags.file, e); }
}
}
@ -322,18 +313,13 @@ impl Db {
log::info!("Ignore: {}", line);
if line.starts_with("SQL:") {
let sql = &line[4..];
let cmd = self
.conn
.execute(&format!("UPDATE Tracks Set Ignore=1 WHERE {}", sql), []);
let cmd = self.conn.execute(&format!("UPDATE Tracks Set Ignore=1 WHERE {}", sql), []);
if let Err(e) = cmd {
log::error!("Failed set Ignore column for '{}'. {}", line, e);
}
} else {
let cmd = self.conn.execute(
&format!("UPDATE Tracks SET Ignore=1 WHERE File LIKE \"{}%\"", line),
[],
);
let cmd = self.conn.execute(&format!("UPDATE Tracks SET Ignore=1 WHERE File LIKE \"{}%\"", line), []);
if let Err(e) = cmd {
log::error!("Failed set Ignore column for '{}'. {}", line, e);

View File

@ -47,14 +47,8 @@ fn main() {
let config_file_help = format!("config file (default: {})", &config_file);
let music_path_help = format!("Music folder (default: {})", &music_path);
let db_path_help = format!("Database location (default: {})", &db_path);
let logging_help = format!(
"Log level; trace, debug, info, warn, error. (default: {})",
logging
);
let ignore_file_help = format!(
"File contains items to mark as ignored. (default: {})",
ignore_file
);
let logging_help = format!("Log level; trace, debug, info, warn, error. (default: {})", logging);
let ignore_file_help = format!("File contains items to mark as ignored. (default: {})", ignore_file);
let lms_host_help = format!("LMS hostname or IP address (default: {})", &lms_host);
let description = format!("Bliss Analyser v{}", VERSION);
@ -62,66 +56,27 @@ fn main() {
// borrow per scope, hence this section is enclosed in { }
let mut arg_parse = ArgumentParser::new();
arg_parse.set_description(&description);
arg_parse
.refer(&mut config_file)
.add_option(&["-c", "--config"], Store, &config_file_help);
arg_parse
.refer(&mut music_path)
.add_option(&["-m", "--music"], Store, &music_path_help);
arg_parse
.refer(&mut db_path)
.add_option(&["-d", "--db"], Store, &db_path_help);
arg_parse
.refer(&mut logging)
.add_option(&["-l", "--logging"], Store, &logging_help);
arg_parse.refer(&mut keep_old).add_option(
&["-k", "--keep-old"],
StoreTrue,
"Don't remove tracks from DB if they don't exist (used with analyse task)",
);
arg_parse.refer(&mut dry_run).add_option(
&["-r", "--dry-run"],
StoreTrue,
"Dry run, only show what needs to be done (used with analyse task)",
);
arg_parse
.refer(&mut ignore_file)
.add_option(&["-i", "--ignore"], Store, &ignore_file_help);
arg_parse
.refer(&mut lms_host)
.add_option(&["-L", "--lms"], Store, &lms_host_help);
arg_parse.refer(&mut max_num_tracks).add_option(
&["-n", "--numtracks"],
Store,
"Maximum number of tracks to analyse",
);
arg_parse.refer(&mut task).add_argument(
"task",
Store,
"Task to perform; analyse, tags, ignore, upload, stopmixer.",
);
arg_parse.refer(&mut config_file).add_option(&["-c", "--config"], Store, &config_file_help);
arg_parse.refer(&mut music_path).add_option(&["-m", "--music"], Store, &music_path_help);
arg_parse.refer(&mut db_path).add_option(&["-d", "--db"], Store, &db_path_help);
arg_parse.refer(&mut logging).add_option(&["-l", "--logging"], Store, &logging_help);
arg_parse.refer(&mut keep_old).add_option(&["-k", "--keep-old"], StoreTrue, "Don't remove tracks from DB if they don't exist (used with analyse task)");
arg_parse.refer(&mut dry_run).add_option(&["-r", "--dry-run"], StoreTrue, "Dry run, only show what needs to be done (used with analyse task)");
arg_parse.refer(&mut ignore_file).add_option(&["-i", "--ignore"], Store, &ignore_file_help);
arg_parse.refer(&mut lms_host).add_option(&["-L", "--lms"], Store, &lms_host_help);
arg_parse.refer(&mut max_num_tracks).add_option(&["-n", "--numtracks"], Store, "Maximum number of tracks to analyse");
arg_parse.refer(&mut task).add_argument("task", Store, "Task to perform; analyse, tags, ignore, upload, stopmixer.");
arg_parse.parse_args_or_exit();
}
if !(logging.eq_ignore_ascii_case("trace")
|| logging.eq_ignore_ascii_case("debug")
|| logging.eq_ignore_ascii_case("info")
|| logging.eq_ignore_ascii_case("warn")
|| logging.eq_ignore_ascii_case("error"))
{
if !(logging.eq_ignore_ascii_case("trace") || logging.eq_ignore_ascii_case("debug") || logging.eq_ignore_ascii_case("info")
|| logging.eq_ignore_ascii_case("warn") || logging.eq_ignore_ascii_case("error")) {
logging = String::from("info");
}
let mut builder =
env_logger::Builder::from_env(env_logger::Env::default().filter_or("XXXXXXXX", logging));
let mut builder = env_logger::Builder::from_env(env_logger::Env::default().filter_or("XXXXXXXX", logging));
builder.filter(Some("bliss_audio"), LevelFilter::Error);
builder.format(|buf, record| {
writeln!(
buf,
"[{} {:.1}] {}",
Local::now().format("%Y-%m-%d %H:%M:%S"),
record.level(),
record.args()
)
writeln!(buf, "[{} {:.1}] {}", Local::now().format("%Y-%m-%d %H:%M:%S"), record.level(), record.args())
});
builder.init();
@ -130,12 +85,8 @@ fn main() {
process::exit(-1);
}
if !task.eq_ignore_ascii_case("analyse")
&& !task.eq_ignore_ascii_case("tags")
&& !task.eq_ignore_ascii_case("ignore")
&& !task.eq_ignore_ascii_case("upload")
&& !task.eq_ignore_ascii_case("stopmixer")
{
if !task.eq_ignore_ascii_case("analyse") && !task.eq_ignore_ascii_case("tags") && !task.eq_ignore_ascii_case("ignore")
&& !task.eq_ignore_ascii_case("upload") && !task.eq_ignore_ascii_case("stopmixer") {
log::error!("Invalid task ({}) supplied", task);
process::exit(-1);
}
@ -146,33 +97,24 @@ fn main() {
let mut config = Ini::new();
match config.load(&config_file) {
Ok(_) => {
let path_keys: [&str; 5] =
["music", "music_1", "music_2", "music_3", "music_4"];
let path_keys: [&str; 5] = ["music", "music_1", "music_2", "music_3", "music_4"];
for key in &path_keys {
match config.get(TOP_LEVEL_INI_TAG, key) {
Some(val) => {
music_paths.push(PathBuf::from(&val));
}
None => {}
Some(val) => { music_paths.push(PathBuf::from(&val)); }
None => { }
}
}
match config.get(TOP_LEVEL_INI_TAG, "db") {
Some(val) => {
db_path = val;
}
None => {}
Some(val) => { db_path = val; }
None => { }
}
match config.get(TOP_LEVEL_INI_TAG, "lms") {
Some(val) => {
lms_host = val;
}
None => {}
Some(val) => { lms_host = val; }
None => { }
}
match config.get(TOP_LEVEL_INI_TAG, "ignore") {
Some(val) => {
ignore_file = val;
}
None => {}
Some(val) => { ignore_file = val; }
None => { }
}
}
Err(e) => {
@ -215,10 +157,7 @@ fn main() {
process::exit(-1);
}
if !mpath.is_dir() {
log::error!(
"Music path ({}) is not a directory",
mpath.to_string_lossy()
);
log::error!("Music path ({}) is not a directory", mpath.to_string_lossy());
process::exit(-1);
}
}

View File

@ -29,10 +29,7 @@ pub fn read(track: &String) -> db::Metadata {
meta.title = tag.title().unwrap_or_default().to_string();
meta.artist = tag.artist().unwrap_or_default().to_string();
meta.album = tag.album().unwrap_or_default().to_string();
meta.album_artist = tag
.get_string(&ItemKey::AlbumArtist)
.unwrap_or_default()
.to_string();
meta.album_artist = tag.get_string(&ItemKey::AlbumArtist).unwrap_or_default().to_string();
meta.genre = tag.genre().unwrap_or_default().to_string();
// Check whether MP3 as numeric genre, and if so covert to text
@ -53,8 +50,7 @@ pub fn read(track: &String) -> db::Metadata {
if re.is_match(&genre) {
match genre.find(")") {
Some(end) => {
let test =
genre.to_string().substring(1, end).parse::<u8>();
let test = genre.to_string().substring(1, end).parse::<u8>();
if let Ok(val) = test {
let idx: usize = val as usize;
@ -64,13 +60,13 @@ pub fn read(track: &String) -> db::Metadata {
}
}
}
None => {}
None => { }
}
}
}
}
}
None => {}
None => { }
}
}

View File

@ -18,8 +18,7 @@ fn fail(msg: &str) {
}
pub fn stop_mixer(lms: &String) {
let stop_req =
"{\"id\":1, \"method\":\"slim.request\",\"params\":[\"\",[\"blissmixer\",\"stop\"]]}";
let stop_req = "{\"id\":1, \"method\":\"slim.request\",\"params\":[\"\",[\"blissmixer\",\"stop\"]]}";
log::info!("Asking plugin to stop mixer");
let req = ureq::post(&format!("http://{}:9000/jsonrpc.js", lms)).send_string(&stop_req);
@ -45,28 +44,18 @@ pub fn upload_db(db_path: &String, lms: &String) {
let p = txt.substring(0, e);
let test = p.parse::<u16>();
match test {
Ok(val) => {
port = val;
}
Err(_) => {
fail("Could not parse resp (cast)");
}
Ok(val) => { port = val; }
Err(_) => { fail("Could not parse resp (cast)"); }
}
}
None => {
fail("Could not parse resp (closing)");
}
None => { fail("Could not parse resp (closing)"); }
}
}
None => {
fail("Could not parse resp (no port)");
}
},
None => { fail("Could not parse resp (no port)"); }
}
Err(_) => fail("No text?"),
},
Err(e) => {
fail(&format!("Failed to ask LMS plugin to allow upload. {}", e));
}
Err(e) => { fail(&format!("Failed to ask LMS plugin to allow upload. {}", e)); }
}
if port == 0 {
@ -83,23 +72,16 @@ pub fn upload_db(db_path: &String, lms: &String) {
match ureq::put(&format!("http://{}:{}/upload", lms, port))
.set("Content-Length", &meta.len().to_string())
.set("Content-Type", "application/octet-stream")
.send(buffered_reader)
{
.send(buffered_reader) {
Ok(_) => {
log::info!("Database uploaded");
stop_mixer(lms);
}
Err(e) => {
fail(&format!("Failed to upload database. {}", e));
}
Err(e) => { fail(&format!("Failed to upload database. {}", e)); }
}
}
Err(e) => {
fail(&format!("Failed to open database. {}", e));
}
},
Err(e) => {
fail(&format!("Failed to open database. {}", e));
Err(e) => { fail(&format!("Failed to open database. {}", e)); }
}
Err(e) => { fail(&format!("Failed to open database. {}", e)); }
}
}