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,6 +164,12 @@ pub enum ConfigError {
} }
#[cfg(test)]
mod tests {
use std::{path::PathBuf, sync::{Arc, RwLock}};
use crate::music_storage::library::MusicLibrary;
use super::{Config, ConfigLibraries, ConfigLibrary};
#[test] #[test]
fn config_test() { fn config_test() {
let lib_a = ConfigLibrary::new(PathBuf::from("test-config/library1"), String::from("library1"), None); let lib_a = ConfigLibrary::new(PathBuf::from("test-config/library1"), String::from("library1"), None);
@ -210,3 +214,4 @@ fn test3() {
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,6 +296,12 @@ impl Controller {
} }
#[cfg(test)]
mod tests {
use std::{thread::sleep, time::Duration};
use super::Controller;
#[test] #[test]
fn play_test() { fn play_test() {
let mut a = match Controller::start("test-config/config_test.json".to_string()) { let mut a = match Controller::start("test-config/config_test.json".to_string()) {
@ -339,3 +335,4 @@ fn test_() {
a.lib_scan_folder("F:/Music/Mp3".to_string()); a.lib_scan_folder("F:/Music/Mp3".to_string());
a.lib_save(); 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,6 +329,14 @@ impl ITunesSong {
} }
} }
#[cfg(test)]
mod tests {
use std::{path::{Path, PathBuf}, sync::{Arc, RwLock}};
use crate::{config::config::{Config, ConfigLibrary}, music_storage::{db_reader::extern_library::ExternalLibrary, library::MusicLibrary}};
use super::ITunesLibrary;
#[test] #[test]
fn itunes_lib_test() { fn itunes_lib_test() {
let mut config = Config::read_file(PathBuf::from("test-config/config_test.json")).unwrap(); let mut config = Config::read_file(PathBuf::from("test-config/config_test.json")).unwrap();
@ -346,3 +352,4 @@ fn itunes_lib_test() {
config.write_file().unwrap(); config.write_file().unwrap();
library.save(config).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;
loop {
use image::ImageFormat::*;
//TODO: create a place for temporary images
let fmt = match format { let fmt = match format {
Jpeg => "jpeg", Jpeg => "jpeg",
Png => "png", Png => "png",
_ => todo!(), _ => todo!(),
}; };
location = format!("./test-config/images/tempcover{i}.{fmt}.tmp"); let file_path = tmp_dir.path().join(format!("{}.{fmt}", self.uuid));
break;
};
img.save_with_format(&location, format)?;
location.to_string() 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, " ");