Removed unused imports, moved some tests to mod tests

This commit is contained in:
G2-Games 2024-03-23 23:34:47 -05:00
parent c4c842e637
commit 9da9b00bef
10 changed files with 152 additions and 164 deletions

View file

@ -1,7 +1,7 @@
use std::{ use std::{
path::PathBuf, path::PathBuf,
fs::{File, OpenOptions, self}, fs::{File, OpenOptions, self},
io::{Error, Write, Read}, sync::{Arc, RwLock}, io::{Error, Write, Read},
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -9,8 +9,6 @@ use serde_json::to_string_pretty;
use thiserror::Error; use thiserror::Error;
use uuid::Uuid; use uuid::Uuid;
use crate::music_storage::library::{MusicLibrary, self};
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfigLibrary { pub struct ConfigLibrary {
pub name: String, pub name: String,
@ -166,47 +164,54 @@ pub enum ConfigError {
} }
#[test] #[cfg(test)]
fn config_test() { mod tests {
let lib_a = ConfigLibrary::new(PathBuf::from("test-config/library1"), String::from("library1"), None); use std::{path::PathBuf, sync::{Arc, RwLock}};
let lib_b = ConfigLibrary::new(PathBuf::from("test-config/library2"), String::from("library2"), None); use crate::music_storage::library::MusicLibrary;
let lib_c = ConfigLibrary::new(PathBuf::from("test-config/library3"), String::from("library3"), None); use super::{Config, ConfigLibraries, ConfigLibrary};
let config = Config {
path: PathBuf::from("test-config/config_test.json"), #[test]
libraries: ConfigLibraries { fn config_test() {
libraries: vec![ let lib_a = ConfigLibrary::new(PathBuf::from("test-config/library1"), String::from("library1"), None);
lib_a.clone(), let lib_b = ConfigLibrary::new(PathBuf::from("test-config/library2"), String::from("library2"), None);
lib_b.clone(), let lib_c = ConfigLibrary::new(PathBuf::from("test-config/library3"), String::from("library3"), None);
lib_c.clone(), let config = Config {
], path: PathBuf::from("test-config/config_test.json"),
libraries: ConfigLibraries {
libraries: vec![
lib_a.clone(),
lib_b.clone(),
lib_c.clone(),
],
..Default::default()
},
..Default::default() ..Default::default()
}, };
..Default::default() config.write_file();
}; let arc = Arc::new(RwLock::from(config));
config.write_file(); MusicLibrary::init(arc.clone(), lib_a.uuid).unwrap();
let arc = Arc::new(RwLock::from(config)); MusicLibrary::init(arc.clone(), lib_b.uuid).unwrap();
MusicLibrary::init(arc.clone(), lib_a.uuid).unwrap(); MusicLibrary::init(arc.clone(), lib_c.uuid).unwrap();
MusicLibrary::init(arc.clone(), lib_b.uuid).unwrap();
MusicLibrary::init(arc.clone(), lib_c.uuid).unwrap();
} }
#[test] #[test]
fn test2() { fn test2() {
let config = Config::read_file(PathBuf::from("test-config/config_test.json")).unwrap(); let config = Config::read_file(PathBuf::from("test-config/config_test.json")).unwrap();
let uuid = config.libraries.get_default().unwrap().uuid; let uuid = config.libraries.get_default().unwrap().uuid;
let mut lib = MusicLibrary::init(Arc::new(RwLock::from(config.clone())), uuid).unwrap(); let mut lib = MusicLibrary::init(Arc::new(RwLock::from(config.clone())), uuid).unwrap();
lib.scan_folder("test-config/music/").unwrap(); lib.scan_folder("test-config/music/").unwrap();
lib.save(config.clone()).unwrap(); lib.save(config.clone()).unwrap();
dbg!(&lib); dbg!(&lib);
dbg!(&config); dbg!(&config);
} }
#[test] #[test]
fn test3() { fn test3() {
let config = Config::read_file(PathBuf::from("test-config/config_test.json")).unwrap(); let config = Config::read_file(PathBuf::from("test-config/config_test.json")).unwrap();
let uuid = config.libraries.get_default().unwrap().uuid; let uuid = config.libraries.get_default().unwrap().uuid;
let lib = MusicLibrary::init(Arc::new(RwLock::from(config.clone())), uuid).unwrap(); let lib = MusicLibrary::init(Arc::new(RwLock::from(config.clone())), uuid).unwrap();
dbg!(lib); dbg!(lib);
}
} }

View file

@ -1,7 +1,3 @@
use std::{marker::PhantomData, fs::File, path::PathBuf};
use font::Font;
pub enum Setting { pub enum Setting {
String { String {
name: String, name: String,

View file

@ -1,4 +1,4 @@
#![allow(unused)] #[allow(dead_code)]
pub mod music_storage { pub mod music_storage {
pub mod library; pub mod library;

View file

@ -1,5 +1,3 @@
use std::{env, thread, time};
use super::controller::Controller; use super::controller::Controller;

View file

@ -2,33 +2,23 @@
//! player. It manages queues, playback, library access, and //! player. It manages queues, playback, library access, and
//! other functions //! other functions
use std::path::{Path, PathBuf}; use std::path::PathBuf;
use std::sync::{Arc, RwLock}; use std::sync::{Arc, RwLock};
use std::time::Duration;
use crossbeam_channel::{Sender, Receiver}; use crossbeam_channel::{Sender, Receiver};
// use std::sync::mpsc;
use crossbeam_channel; use crossbeam_channel;
use gstreamer::format::Default; use std::thread::spawn;
use gstreamer::query::Uri;
use std::thread::{self, sleep, spawn};
use std::error::Error; use std::error::Error;
use crossbeam_channel::unbounded; use crossbeam_channel::unbounded;
use rayon::iter::Rev;
use uuid::Uuid; use uuid::Uuid;
use crate::config;
use crate::music_storage::library::{Tag, URI}; use crate::music_storage::library::{Tag, URI};
use crate::music_storage::playlist::Playlist;
use crate::{ use crate::{
music_player::Player,
music_storage::library::{MusicLibrary, Song}, music_storage::library::{MusicLibrary, Song},
config::config::Config, config::config::Config,
music_controller::queue::Queue, music_controller::queue::Queue,
}; };
use super::queue::{QueueItem, QueueState};
pub struct Controller { pub struct Controller {
// queues: Vec<Queue>, // queues: Vec<Queue>,
config: Arc<RwLock<Config>>, config: Arc<RwLock<Config>>,
@ -266,7 +256,7 @@ impl Controller {
} }
}); });
self.queue_mail.push(out_thread_queue); self.queue_mail.push(out_thread_queue);
Ok((self.queue_mail.len() - 1)) Ok(self.queue_mail.len() - 1)
} }
fn q_play(&self, index: usize) -> Result<(), Box<dyn Error>> { fn q_play(&self, index: usize) -> Result<(), Box<dyn Error>> {
@ -306,36 +296,43 @@ impl Controller {
} }
#[test] #[cfg(test)]
fn play_test() { mod tests {
let mut a = match Controller::start("test-config/config_test.json".to_string()) { use std::{thread::sleep, time::Duration};
Ok(c) => c,
Err(e) => panic!("{e}")
};
sleep(Duration::from_millis(500));
let i = a.q_new().unwrap(); use super::Controller;
a.q_set_volume(i, 0.04);
// a.new_queue();
let songs = a.lib_get_songs();
a.q_enqueue(i, songs[2].location.clone());
// a.enqueue(1, songs[2].location.clone());
a.q_play(i).unwrap();
// a.play(1).unwrap();
sleep(Duration::from_secs(10)); #[test]
a.q_pause(i); fn play_test() {
sleep(Duration::from_secs(10)); let mut a = match Controller::start("test-config/config_test.json".to_string()) {
a.q_play(i); Ok(c) => c,
sleep(Duration::from_secs(1000)); Err(e) => panic!("{e}")
} };
sleep(Duration::from_millis(500));
#[test]
fn test_() { let i = a.q_new().unwrap();
let a = match Controller::start("test-config/config_test.json".to_string()) { a.q_set_volume(i, 0.04);
Ok(c) => c, // a.new_queue();
Err(e) => panic!("{e}") let songs = a.lib_get_songs();
}; a.q_enqueue(i, songs[2].location.clone());
a.lib_scan_folder("F:/Music/Mp3".to_string()); // a.enqueue(1, songs[2].location.clone());
a.lib_save(); a.q_play(i).unwrap();
// a.play(1).unwrap();
sleep(Duration::from_secs(10));
a.q_pause(i);
sleep(Duration::from_secs(10));
a.q_play(i);
sleep(Duration::from_secs(1000));
}
#[test]
fn test_() {
let a = match Controller::start("test-config/config_test.json".to_string()) {
Ok(c) => c,
Err(e) => panic!("{e}")
};
a.lib_scan_folder("F:/Music/Mp3".to_string());
a.lib_save();
}
} }

View file

@ -1,8 +1,12 @@
use font::opentype::tables::font_variations::InstanceFlags;
use uuid::Uuid; use uuid::Uuid;
use crate::{
use crate::{music_player::Player, music_storage::library::{Album, MusicLibrary, Song, URI}}; music_player::Player,
use std::{error::Error, ops::Add, path::Path, sync::{Arc, RwLock}, thread::sleep, time::Duration}; music_storage::library::{Album, MusicLibrary, URI}
};
use std::{
error::Error,
sync::{Arc, RwLock}
};
#[derive(Debug, PartialEq, Clone, Copy)] #[derive(Debug, PartialEq, Clone, Copy)]
pub enum QueueState { pub enum QueueState {
@ -169,7 +173,7 @@ impl<'a> Queue<'a> {
let empty = self.is_empty(); let empty = self.is_empty();
self.items.insert( self.items.insert(
(ind + if !empty && ind_ == None { 1 } else { 2 }), ind + if !empty && ind_ == None { 1 } else { 2 },
QueueItem { QueueItem {
item, item,
state: if empty { state: if empty {
@ -282,8 +286,6 @@ impl<'a> Queue<'a> {
pub fn prev() {} pub fn prev() {}
pub fn enqueue_item(&mut self, item: QueueItem, lib: Arc<RwLock<MusicLibrary>>) -> Result<(), Box<dyn Error>> { pub fn enqueue_item(&mut self, item: QueueItem, lib: Arc<RwLock<MusicLibrary>>) -> Result<(), Box<dyn Error>> {
use QueueItemType::*;
if let Some(uri) = item.item.get_uri(lib) { if let Some(uri) = item.item.get_uri(lib) {
self.player.enqueue_next(&uri)?; self.player.enqueue_next(&uri)?;
}else { }else {

View file

@ -7,15 +7,13 @@ use std::collections::{BTreeMap, HashMap};
use std::fs::File; use std::fs::File;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::str::FromStr; use std::str::FromStr;
use std::sync::{Arc, RwLock};
use std::time::Duration as StdDur; use std::time::Duration as StdDur;
use std::vec::Vec; use std::vec::Vec;
use chrono::prelude::*; use chrono::prelude::*;
use crate::config::config::{Config, ConfigLibrary};
use crate::music_storage::db_reader::extern_library::ExternalLibrary; use crate::music_storage::db_reader::extern_library::ExternalLibrary;
use crate::music_storage::library::{AlbumArt, MusicLibrary, Service, Song, Tag, URI, BannedType}; use crate::music_storage::library::{AlbumArt, Service, Song, Tag, URI};
use crate::music_storage::utils; use crate::music_storage::utils;
use urlencoding::decode; use urlencoding::decode;
@ -331,18 +329,27 @@ impl ITunesSong {
} }
} }
#[test] #[cfg(test)]
fn itunes_lib_test() { mod tests {
let mut config = Config::read_file(PathBuf::from("test-config/config_test.json")).unwrap(); use std::{path::{Path, PathBuf}, sync::{Arc, RwLock}};
let config_lib = ConfigLibrary::new(PathBuf::from("test-config/library2"), String::from("library2"), None);
config.libraries.libraries.push(config_lib.clone());
let songs = ITunesLibrary::from_file(Path::new("test-config\\iTunesLib.xml")).to_songs(); use crate::{config::config::{Config, ConfigLibrary}, music_storage::{db_reader::extern_library::ExternalLibrary, library::MusicLibrary}};
let mut library = MusicLibrary::init(Arc::new(RwLock::from(config.clone())), config_lib.uuid).unwrap(); use super::ITunesLibrary;
songs.iter().for_each(|song| library.add_song(song.to_owned()).unwrap()); #[test]
fn itunes_lib_test() {
let mut config = Config::read_file(PathBuf::from("test-config/config_test.json")).unwrap();
let config_lib = ConfigLibrary::new(PathBuf::from("test-config/library2"), String::from("library2"), None);
config.libraries.libraries.push(config_lib.clone());
config.write_file().unwrap(); let songs = ITunesLibrary::from_file(Path::new("test-config\\iTunesLib.xml")).to_songs();
library.save(config).unwrap();
let mut library = MusicLibrary::init(Arc::new(RwLock::from(config.clone())), config_lib.uuid).unwrap();
songs.iter().for_each(|song| library.add_song(song.to_owned()).unwrap());
config.write_file().unwrap();
library.save(config).unwrap();
}
} }

View file

@ -5,9 +5,7 @@ use crate::config::config::Config;
// Various std things // Various std things
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::error::Error; use std::error::Error;
use std::io::BufWriter;
use std::ops::ControlFlow::{Break, Continue}; use std::ops::ControlFlow::{Break, Continue};
use std::ops::Deref;
// Files // Files
use file_format::{FileFormat, Kind}; use file_format::{FileFormat, Kind};
@ -15,11 +13,12 @@ use glib::filename_to_uri;
use image::guess_format; use image::guess_format;
use lofty::{AudioFile, ItemKey, ItemValue, ParseOptions, Probe, TagType, TaggedFileExt}; use lofty::{AudioFile, ItemKey, ItemValue, ParseOptions, Probe, TagType, TaggedFileExt};
use rcue::parser::parse_from_file; use rcue::parser::parse_from_file;
use tempfile::tempfile;
use uuid::Uuid; use uuid::Uuid;
use std::fs::{self, OpenOptions}; use std::fs;
use tempfile::TempDir;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use walkdir::WalkDir; use walkdir::WalkDir;
use image::ImageFormat::*;
// Time // Time
use chrono::{serde::ts_milliseconds_option, DateTime, Utc}; use chrono::{serde::ts_milliseconds_option, DateTime, Utc};
@ -163,11 +162,8 @@ pub struct Song {
#[test] #[test]
fn get_art_test() { fn get_art_test() {
use urlencoding::decode;
let s = Song::from_file(Path::new("F:\\Music\\Mp3\\ななひら\\Colory Starry\\05 - Fly Away!.mp3")).unwrap(); let s = Song::from_file(Path::new("F:\\Music\\Mp3\\ななひら\\Colory Starry\\05 - Fly Away!.mp3")).unwrap();
s.open_album_art(0).inspect_err(|e| println!("{e:?}")); s.open_album_art(0).inspect_err(|e| println!("{e:?}")).unwrap();
} }
impl Song { impl Song {
@ -440,22 +436,24 @@ impl Song {
use urlencoding::decode; use urlencoding::decode;
if index >= self.album_art.len() { if index >= self.album_art.len() {
return Err("index out of bounds?".into()); return Err("Index out of bounds".into());
} }
let uri: String = match &self.album_art[index] { let uri = match &self.album_art[index] {
AlbumArt::External(uri) => { AlbumArt::External(uri) => {
decode(match uri.as_uri().strip_prefix("file:///") { Some(e) => e, None => return Err("Invalid path?".into()) })?.into_owned() PathBuf::from(decode(match uri.as_uri().strip_prefix("file:///") {
Some(e) => e,
None => return Err("Invalid path?".into())
})?.to_owned().to_string())
}, },
AlbumArt::Embedded(_) => { AlbumArt::Embedded(_) => {
let normal_options = ParseOptions::new().parsing_mode(lofty::ParsingMode::Relaxed); let normal_options = ParseOptions::new().parsing_mode(lofty::ParsingMode::Relaxed);
let blank_tag = &lofty::Tag::new(TagType::Id3v2); let blank_tag = &lofty::Tag::new(TagType::Id3v2);
let tagged_file: lofty::TaggedFile; let tagged_file: lofty::TaggedFile;
let uri = dbg!(urlencoding::decode(self.location.as_uri().strip_prefix("file:///").unwrap())?.into_owned()); let uri = urlencoding::decode(self.location.as_uri().strip_prefix("file://").unwrap())?.into_owned();
let tag = match Probe::open(uri)?.options(normal_options).read() { let tag = match Probe::open(uri).unwrap().options(normal_options).read() {
Ok(file) => { Ok(file) => {
tagged_file = file; tagged_file = file;
@ -476,26 +474,22 @@ impl Song {
let format = dbg!(guess_format(data)?); let format = dbg!(guess_format(data)?);
let img = image::load_from_memory(data)?; let img = image::load_from_memory(data)?;
let mut location = String::new(); let tmp_dir = TempDir::new()?;
let i: u32 = 0; let fmt = match format {
loop { Jpeg => "jpeg",
use image::ImageFormat::*; Png => "png",
//TODO: create a place for temporary images _ => todo!(),
let fmt = match format {
Jpeg => "jpeg",
Png => "png",
_ => todo!(),
};
location = format!("./test-config/images/tempcover{i}.{fmt}.tmp");
break;
}; };
img.save_with_format(&location, format)?;
location.to_string() let file_path = tmp_dir.path().join(format!("{}.{fmt}", self.uuid));
open(&file_path).unwrap();
img.save_with_format(&file_path, format).unwrap();
file_path
}, },
}; };
open(uri)?; dbg!(open(uri)?);
Ok(()) Ok(())
} }

View file

@ -1,21 +1,10 @@
use std::{fs::File, path::{Path, PathBuf}, io::{Read, Error}}; use std::{fs::File, io::{Read, Error}};
use bincode::config;
use chrono::Duration; use chrono::Duration;
use uuid::Uuid; use uuid::Uuid;
// use walkdir::Error; use super::library::{AlbumArt, Song, Tag};
use crate::music_controller::controller::Controller; use m3u8_rs::{MediaPlaylist, MediaPlaylistType, MediaSegment, Playlist as List2};
use super::{
library::{AlbumArt, Song, Tag},
music_collection::MusicCollection, db_reader::{
itunes::reader::ITunesLibrary,
extern_library::ExternalLibrary
},
};
use m3u8_rs::{MediaPlaylist, MediaPlaylistType, MediaSegment, Playlist as List2, MasterPlaylist};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum SortOrder { pub enum SortOrder {

View file

@ -1,10 +1,7 @@
use std::any::Any;
use std::fs::{File, self}; use std::fs::{File, self};
use std::io::{BufReader, BufWriter}; use std::io::{BufReader, BufWriter};
use std::os::windows::fs::MetadataExt;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::error::Error; use std::error::Error;
use walkdir::WalkDir; use walkdir::WalkDir;
use file_format::{FileFormat, Kind}; use file_format::{FileFormat, Kind};
use snap; use snap;
@ -12,6 +9,9 @@ use deunicode::deunicode_with_tofu;
use super::library::{AlbumArt, URI}; use super::library::{AlbumArt, URI};
#[cfg(target_family = "windows")]
use std::os::windows::fs::MetadataExt;
pub(super) fn normalize(input_string: &str) -> String { pub(super) fn normalize(input_string: &str) -> String {
// Normalize the string to latin characters... this needs a lot of work // Normalize the string to latin characters... this needs a lot of work
let mut normalized = deunicode_with_tofu(input_string, " "); let mut normalized = deunicode_with_tofu(input_string, " ");