Compare commits

..

No commits in common. "86708ebdb2c40e0fb488f36e309a88b4cfdfc9ff" and "4163ccb5c27c65d1955e82f1ea3ab563c581ad51" have entirely different histories.

6 changed files with 159 additions and 303 deletions

View File

@ -17,7 +17,7 @@ You should have received a copy of the GNU General Public License along with Lum
//! Where the sled.rs library uses `Result<Result<A, Error>, FatalError>`, these are a little hard to
//! work with. This library works out a set of utility functions that allow us to work with the
//! nested errors in the same way as a regular Result.
use std::{error::Error, fmt};
use std::error::Error;
/// Implement this trait for the application's fatal errors.
///
@ -110,37 +110,6 @@ impl<A, FE, E> From<Result<A, E>> for Flow<A, FE, E> {
}
}
impl<A, FE, E> fmt::Debug for Flow<A, FE, E>
where
A: fmt::Debug,
FE: fmt::Debug,
E: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Flow::Ok(val) => f.write_fmt(format_args!("Flow::Ok {:?}", val)),
Flow::Err(err) => f.write_fmt(format_args!("Flow::Err {:?}", err)),
Flow::Fatal(err) => f.write_fmt(format_args!("Flow::Fatal {:?}", err)),
}
}
}
impl<A, FE, E> PartialEq for Flow<A, FE, E>
where
A: PartialEq,
FE: PartialEq,
E: PartialEq,
{
fn eq(&self, rhs: &Self) -> bool {
match (self, rhs) {
(Flow::Ok(val), Flow::Ok(rhs)) => val == rhs,
(Flow::Err(_), Flow::Err(_)) => true,
(Flow::Fatal(_), Flow::Fatal(_)) => true,
_ => false,
}
}
}
/// Convenience function to create an ok value.
pub fn ok<A, FE: FatalError, E: Error>(val: A) -> Flow<A, FE, E> {
Flow::Ok(val)
@ -208,25 +177,43 @@ mod test {
}
}
impl PartialEq for Flow<i32, FatalError, Error> {
fn eq(&self, rhs: &Self) -> bool {
match (self, rhs) {
(Flow::Ok(val), Flow::Ok(rhs)) => val == rhs,
(Flow::Err(_), Flow::Err(_)) => true,
(Flow::Fatal(_), Flow::Fatal(_)) => true,
_ => false,
}
}
}
impl std::fmt::Debug for Flow<i32, FatalError, Error> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Flow::Ok(val) => f.write_fmt(format_args!("Flow::Ok {}", val)),
Flow::Err(err) => f.write_fmt(format_args!("Flow::Err {:?}", err)),
Flow::Fatal(err) => f.write_fmt(format_args!("Flow::Fatal {:?}", err)),
}
}
}
#[test]
fn it_can_map_things() {
let success: Flow<i32, FatalError, Error> = ok(15);
let success = ok(15);
assert_eq!(ok(16), success.map(|v| v + 1));
}
#[test]
fn it_can_chain_success() {
let success: Flow<i32, FatalError, Error> = ok(15);
let success = ok(15);
assert_eq!(ok(16), success.and_then(|v| ok(v + 1)));
}
#[test]
fn it_can_handle_an_error() {
let failure: Flow<i32, FatalError, Error> = error(Error::Error);
assert_eq!(
ok::<i32, FatalError, Error>(16),
failure.or_else(|_| ok(16))
);
let failure = error(Error::Error);
assert_eq!(ok(16), failure.or_else(|_| ok(16)));
}
#[test]

View File

@ -27,10 +27,10 @@ pub enum Message {
#[derive(Clone, Debug)]
pub enum Event {
Paused(TrackId, Duration),
Playing(TrackId, Duration),
Paused(Track, Duration),
Playing(Track, Duration),
Stopped,
Position(TrackId, Duration),
Position(Track, Duration),
}
#[derive(Debug)]
@ -113,16 +113,14 @@ impl AsRef<String> for TrackId {
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[derive(Clone, Debug)]
pub struct TrackInfo {
pub id: TrackId,
pub track_number: Option<i32>,
pub name: Option<String>,
pub album: Option<String>,
pub artist: Option<String>,
}
/*
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Track {
@ -132,7 +130,6 @@ pub struct Track {
pub album: Option<String>,
pub artist: Option<String>,
}
*/
/*
impl From<&mpris::Metadata> for Track {
@ -157,13 +154,13 @@ impl From<mpris::Metadata> for Track {
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum State {
Playing(TrackInfo),
Paused(TrackInfo),
Playing(Track),
Paused(Track),
Stopped,
}
pub struct CurrentlyPlaying {
track: TrackInfo,
track: Track,
position: Duration,
}

View File

@ -1,5 +1,4 @@
use crate::{
audio::TrackInfo,
database::{Database, MemoryIndex, MusicIndex},
Error, FatalError,
};
@ -15,6 +14,20 @@ use std::{
time::{Duration, Instant},
};
#[derive(Debug, Error)]
pub enum ScannerError {
#[error("Cannot scan {0}")]
CannotScan(PathBuf),
#[error("IO error {0}")]
IO(std::io::Error),
}
impl From<std::io::Error> for ScannerError {
fn from(err: std::io::Error) -> Self {
Self::IO(err)
}
}
pub enum ControlMsg {
Exit,
}
@ -39,6 +52,87 @@ pub struct Core {
control_tx: Sender<ControlMsg>,
}
fn scan_frequency() -> Duration {
Duration::from_secs(60)
}
pub struct FileScanner {
db: Arc<dyn MusicIndex>,
control_rx: Receiver<ControlMsg>,
tracker_tx: Sender<TrackMsg>,
next_scan: Instant,
music_directories: Vec<PathBuf>,
}
impl FileScanner {
fn new(
db: Arc<dyn MusicIndex>,
roots: Vec<PathBuf>,
control_rx: Receiver<ControlMsg>,
tracker_tx: Sender<TrackMsg>,
) -> Self {
Self {
db,
control_rx,
tracker_tx,
next_scan: Instant::now(),
music_directories: roots,
}
}
fn scan(&mut self) {
loop {
match self.control_rx.recv_timeout(Duration::from_millis(100)) {
Ok(ControlMsg::Exit) => return,
Err(RecvTimeoutError::Timeout) => (),
Err(RecvTimeoutError::Disconnected) => return,
}
if Instant::now() >= self.next_scan {
for root in self.music_directories.iter() {
self.scan_dir(vec![root.clone()]);
}
self.next_scan = Instant::now() + scan_frequency();
}
}
}
fn scan_dir(&self, mut paths: Vec<PathBuf>) -> Flow<(), FatalError, ScannerError> {
while let Some(dir) = paths.pop() {
println!("scanning {:?}", dir);
return_error!(self.scan_dir_(&mut paths, dir));
}
ok(())
}
fn scan_dir_(
&self,
paths: &mut Vec<PathBuf>,
dir: PathBuf,
) -> Flow<(), FatalError, ScannerError> {
let dir_iter = return_error!(Flow::from(dir.read_dir().map_err(ScannerError::from)));
for entry in dir_iter {
match entry {
Ok(entry) if entry.path().is_dir() => paths.push(entry.path()),
Ok(entry) => {
let _ = return_fatal!(self.scan_file(entry.path()).or_else(|err| {
println!("scan_file failed: {:?}", err);
ok::<(), FatalError, ScannerError>(())
}));
()
}
Err(err) => {
println!("scan_dir could not read path: ({:?})", err);
}
}
}
ok(())
}
fn scan_file(&self, path: PathBuf) -> Flow<(), FatalError, ScannerError> {
ok(())
}
}
impl Core {
pub fn new(db: Arc<dyn MusicIndex>) -> Flow<Core, FatalError, Error> {
let (control_tx, control_rx) = channel::<ControlMsg>();
@ -46,7 +140,15 @@ impl Core {
let (track_handle, track_rx) = {
let (track_tx, track_rx) = channel();
let db = db.clone();
let track_handle = thread::spawn(move || {});
let track_handle = thread::spawn(move || {
FileScanner::new(
db,
vec![PathBuf::from("/home/savanni/Music/")],
control_rx,
track_tx,
)
.scan();
});
(track_handle, track_rx)
};
@ -66,10 +168,6 @@ impl Core {
})
}
pub fn list_tracks<'a>(&'a self) -> Flow<Vec<TrackInfo>, FatalError, Error> {
self.db.list_tracks().map_err(Error::DatabaseError)
}
pub fn exit(&self) {
let _ = self.control_tx.send(ControlMsg::Exit);
/*
@ -80,80 +178,4 @@ impl Core {
}
#[cfg(test)]
mod test {
use super::*;
use crate::audio::{TrackId, TrackInfo};
use std::collections::HashSet;
fn with_example_index<F>(f: F)
where
F: Fn(Core),
{
let index = MemoryIndex::new();
index.add_track(TrackInfo {
id: TrackId::from("/home/savanni/Track 1.mp3".to_owned()),
track_number: None,
name: None,
album: None,
artist: None,
});
index.add_track(TrackInfo {
id: TrackId::from("/home/savanni/Track 2.mp3".to_owned()),
track_number: None,
name: None,
album: None,
artist: None,
});
index.add_track(TrackInfo {
id: TrackId::from("/home/savanni/Track 3.mp3".to_owned()),
track_number: None,
name: None,
album: None,
artist: None,
});
index.add_track(TrackInfo {
id: TrackId::from("/home/savanni/Track 4.mp3".to_owned()),
track_number: None,
name: None,
album: None,
artist: None,
});
index.add_track(TrackInfo {
id: TrackId::from("/home/savanni/Track 5.mp3".to_owned()),
track_number: None,
name: None,
album: None,
artist: None,
});
match Core::new(Arc::new(index)) {
Flow::Ok(core) => f(core),
Flow::Err(error) => panic!("{:?}", error),
Flow::Fatal(error) => panic!("{:?}", error),
}
}
#[test]
fn it_lists_tracks() {
with_example_index(|core| match core.list_tracks() {
Flow::Ok(tracks) => {
let track_ids = tracks
.iter()
.map(|t| t.id.clone())
.collect::<HashSet<TrackId>>();
assert_eq!(track_ids.len(), 5);
assert_eq!(
track_ids,
HashSet::from([
TrackId::from("/home/savanni/Track 1.mp3".to_owned()),
TrackId::from("/home/savanni/Track 2.mp3".to_owned()),
TrackId::from("/home/savanni/Track 3.mp3".to_owned()),
TrackId::from("/home/savanni/Track 4.mp3".to_owned()),
TrackId::from("/home/savanni/Track 5.mp3".to_owned()),
])
);
}
Flow::Fatal(err) => panic!("fatal error: {:?}", err),
Flow::Err(err) => panic!("error: {:?}", err),
})
}
}
mod test {}

View File

@ -1,5 +1,5 @@
use crate::{
audio::{TrackId, TrackInfo},
audio::{Track, TrackId, TrackInfo},
FatalError,
};
use flow::{error, ok, Flow};
@ -11,7 +11,7 @@ use std::{
};
use thiserror::Error;
#[derive(Debug, Error, PartialEq)]
#[derive(Debug, Error)]
pub enum DatabaseError {
#[error("database is unreadable")]
DatabaseUnreadable,
@ -20,14 +20,13 @@ pub enum DatabaseError {
}
pub trait MusicIndex: Sync + Send {
fn add_track(&self, track: TrackInfo) -> Flow<(), FatalError, DatabaseError>;
fn remove_track(&self, id: &TrackId) -> Flow<(), FatalError, DatabaseError>;
fn get_track_info(&self, id: &TrackId) -> Flow<Option<TrackInfo>, FatalError, DatabaseError>;
fn list_tracks<'a>(&'a self) -> Flow<Vec<TrackInfo>, FatalError, DatabaseError>;
fn add_track(&mut self, track: &TrackInfo) -> Flow<Track, FatalError, DatabaseError>;
fn remove_track(&mut self, id: &TrackId) -> Flow<(), FatalError, DatabaseError>;
fn get_track_info(&self, id: &TrackId) -> Flow<Option<Track>, FatalError, DatabaseError>;
}
pub struct MemoryIndex {
tracks: RwLock<HashMap<TrackId, TrackInfo>>,
tracks: RwLock<HashMap<TrackId, Track>>,
}
impl MemoryIndex {
@ -39,13 +38,21 @@ impl MemoryIndex {
}
impl MusicIndex for MemoryIndex {
fn add_track(&self, info: TrackInfo) -> Flow<(), FatalError, DatabaseError> {
fn add_track(&mut self, info: &TrackInfo) -> Flow<Track, FatalError, DatabaseError> {
let id = TrackId::default();
let track = Track {
id: id.clone(),
track_number: info.track_number,
name: info.name.clone(),
album: info.album.clone(),
artist: info.artist.clone(),
};
let mut tracks = self.tracks.write().unwrap();
tracks.insert(info.id.clone(), info);
ok(())
tracks.insert(id, track.clone());
ok(track)
}
fn remove_track(&self, id: &TrackId) -> Flow<(), FatalError, DatabaseError> {
fn remove_track(&mut self, id: &TrackId) -> Flow<(), FatalError, DatabaseError> {
let mut tracks = self.tracks.write().unwrap();
tracks.remove(&id);
ok(())
@ -54,23 +61,13 @@ impl MusicIndex for MemoryIndex {
fn get_track_info<'a>(
&'a self,
id: &TrackId,
) -> Flow<Option<TrackInfo>, FatalError, DatabaseError> {
) -> Flow<Option<Track>, FatalError, DatabaseError> {
let track = {
let tracks = self.tracks.read().unwrap();
tracks.get(&id).cloned()
};
ok(track)
}
fn list_tracks<'a>(&'a self) -> Flow<Vec<TrackInfo>, FatalError, DatabaseError> {
ok(self
.tracks
.read()
.unwrap()
.values()
.cloned()
.collect::<Vec<TrackInfo>>())
}
}
pub struct ManagedConnection<'a> {
@ -107,35 +104,3 @@ impl Database {
pool.push(conn);
}
}
#[cfg(test)]
mod test {
use super::*;
fn with_memory_index<F>(f: F)
where
F: Fn(&dyn MusicIndex),
{
let index = MemoryIndex::new();
f(&index)
}
#[test]
fn it_saves_and_loads_data() {
with_memory_index(|index| {
let info = TrackInfo {
id: TrackId::from("track_1".to_owned()),
track_number: None,
name: None,
album: None,
artist: None,
};
index.add_track(info.clone());
assert_eq!(
Flow::Ok(Some(info)),
index.get_track_info(&TrackId::from("track_1".to_owned()))
);
});
}
}

View File

@ -1,11 +1,10 @@
pub mod audio;
pub mod core;
pub mod database;
pub mod music_scanner;
use database::DatabaseError;
use thiserror::Error;
#[derive(Debug, Error, PartialEq)]
#[derive(Debug, Error)]
pub enum Error {
#[error("Database error: {0}")]
DatabaseError(DatabaseError),
@ -17,7 +16,7 @@ impl From<DatabaseError> for Error {
}
}
#[derive(Debug, Error, PartialEq)]
#[derive(Debug, Error)]
pub enum FatalError {
#[error("Unexpected error")]
UnexpectedError,

View File

@ -1,114 +0,0 @@
use crate::{
core::{ControlMsg, TrackMsg},
database::MusicIndex,
FatalError,
};
use flow::{ok, return_error, return_fatal, Flow};
use std::{
path::PathBuf,
sync::{
mpsc::{Receiver, RecvTimeoutError, Sender},
Arc,
},
time::{Duration, Instant},
};
use thiserror::Error;
fn scan_frequency() -> Duration {
Duration::from_secs(60)
}
#[derive(Debug, Error)]
pub enum ScannerError {
#[error("Cannot scan {0}")]
CannotScan(PathBuf),
#[error("IO error {0}")]
IO(std::io::Error),
}
impl From<std::io::Error> for ScannerError {
fn from(err: std::io::Error) -> Self {
Self::IO(err)
}
}
pub trait MusicScanner {
fn scan(&self);
}
pub struct FileScanner {
db: Arc<dyn MusicIndex>,
control_rx: Receiver<ControlMsg>,
tracker_tx: Sender<TrackMsg>,
next_scan: Instant,
music_directories: Vec<PathBuf>,
}
impl FileScanner {
fn new(
db: Arc<dyn MusicIndex>,
roots: Vec<PathBuf>,
control_rx: Receiver<ControlMsg>,
tracker_tx: Sender<TrackMsg>,
) -> Self {
Self {
db,
control_rx,
tracker_tx,
next_scan: Instant::now(),
music_directories: roots,
}
}
fn scan(&mut self) {
loop {
match self.control_rx.recv_timeout(Duration::from_millis(100)) {
Ok(ControlMsg::Exit) => return,
Err(RecvTimeoutError::Timeout) => (),
Err(RecvTimeoutError::Disconnected) => return,
}
if Instant::now() >= self.next_scan {
for root in self.music_directories.iter() {
self.scan_dir(vec![root.clone()]);
}
self.next_scan = Instant::now() + scan_frequency();
}
}
}
fn scan_dir(&self, mut paths: Vec<PathBuf>) -> Flow<(), FatalError, ScannerError> {
while let Some(dir) = paths.pop() {
println!("scanning {:?}", dir);
return_error!(self.scan_dir_(&mut paths, dir));
}
ok(())
}
fn scan_dir_(
&self,
paths: &mut Vec<PathBuf>,
dir: PathBuf,
) -> Flow<(), FatalError, ScannerError> {
let dir_iter = return_error!(Flow::from(dir.read_dir().map_err(ScannerError::from)));
for entry in dir_iter {
match entry {
Ok(entry) if entry.path().is_dir() => paths.push(entry.path()),
Ok(entry) => {
let _ = return_fatal!(self.scan_file(entry.path()).or_else(|err| {
println!("scan_file failed: {:?}", err);
ok::<(), FatalError, ScannerError>(())
}));
()
}
Err(err) => {
println!("scan_dir could not read path: ({:?})", err);
}
}
}
ok(())
}
fn scan_file(&self, path: PathBuf) -> Flow<(), FatalError, ScannerError> {
ok(())
}
}