New fetch module - old functionality
Some checks failed
Cargo CI / Build and Test (pull_request) Failing after 1m56s
Cargo CI / Lint (pull_request) Failing after 1m4s

This commit is contained in:
Wojciech Kozlowski 2024-09-01 22:47:48 +02:00
parent 9552311d02
commit 7925d8ce91
4 changed files with 429 additions and 443 deletions

View File

@ -1,21 +1,7 @@
use std::{ use crate::tui::app::{
sync::{mpsc, Arc, Mutex},
thread, time,
};
use musichoard::collection::{
album::AlbumMeta,
artist::ArtistMeta,
musicbrainz::{IMusicBrainzRef, Mbid},
};
use crate::tui::{
app::{
machine::{App, AppInner, AppMachine}, machine::{App, AppInner, AppMachine},
selection::{Delta, ListSelection}, selection::{Delta, ListSelection},
AppMatchesInfo, AppPublic, AppState, IAppInteractBrowse, AppPublic, AppState, IAppInteractBrowse,
},
lib::interface::musicbrainz::{Error as MbError, IMusicBrainz},
}; };
pub struct AppBrowse; pub struct AppBrowse;
@ -93,31 +79,7 @@ impl IAppInteractBrowse for AppMachine<AppBrowse> {
} }
fn fetch_musicbrainz(self) -> Self::APP { fn fetch_musicbrainz(self) -> Self::APP {
let coll = self.inner.music_hoard.get_collection(); AppMachine::app_fetch_new(self.inner)
let artist = match self.inner.selection.state_artist(coll) {
Some(artist_state) => &coll[artist_state.index],
None => {
return AppMachine::error(self.inner, "cannot fetch: no artist selected").into()
}
};
let (matches_tx, matches_rx) = mpsc::channel::<FetchResult>();
match artist.meta.musicbrainz {
Some(ref arid) => {
let musicbrainz = Arc::clone(&self.inner.musicbrainz);
let arid = arid.mbid().clone();
let albums = artist.albums.iter().map(|a| &a.meta).cloned().collect();
thread::spawn(|| Self::fetch_albums(musicbrainz, matches_tx, arid, albums));
}
None => {
let musicbrainz = Arc::clone(&self.inner.musicbrainz);
let artist = artist.meta.clone();
thread::spawn(|| Self::fetch_artist(musicbrainz, matches_tx, artist));
}
};
AppMachine::app_matches(self.inner, matches_rx)
} }
fn no_op(self) -> Self::APP { fn no_op(self) -> Self::APP {
@ -125,63 +87,6 @@ impl IAppInteractBrowse for AppMachine<AppBrowse> {
} }
} }
pub type FetchError = MbError;
pub type FetchResult = Result<AppMatchesInfo, FetchError>;
pub type FetchSender = mpsc::Sender<FetchResult>;
pub type FetchReceiver = mpsc::Receiver<FetchResult>;
trait IAppInteractBrowsePrivate {
fn fetch_artist(
musicbrainz: Arc<Mutex<dyn IMusicBrainz + Send>>,
matches_tx: FetchSender,
artist: ArtistMeta,
);
fn fetch_albums(
musicbrainz: Arc<Mutex<dyn IMusicBrainz + Send>>,
matches_tx: FetchSender,
arid: Mbid,
albums: Vec<AlbumMeta>,
);
}
impl IAppInteractBrowsePrivate for AppMachine<AppBrowse> {
fn fetch_artist(
musicbrainz: Arc<Mutex<dyn IMusicBrainz + Send>>,
matches_tx: FetchSender,
artist: ArtistMeta,
) {
let result = musicbrainz.lock().unwrap().search_artist(&artist);
let result = result.map(|list| AppMatchesInfo::artist(artist, list));
matches_tx.send(result).ok();
}
fn fetch_albums(
musicbrainz: Arc<Mutex<dyn IMusicBrainz + Send>>,
matches_tx: FetchSender,
arid: Mbid,
albums: Vec<AlbumMeta>,
) {
let mut musicbrainz = musicbrainz.lock().unwrap();
let mut album_iter = albums.into_iter().peekable();
while let Some(album) = album_iter.next() {
if album.musicbrainz.is_some() {
continue;
}
let result = musicbrainz.search_release_group(&arid, &album);
let result = result.map(|list| AppMatchesInfo::album(album, list));
if matches_tx.send(result).is_err() {
// If receiver disconnects just drop the rest.
return;
}
if album_iter.peek().is_some() {
thread::sleep(time::Duration::from_secs(1));
}
}
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use mockall::{predicate, Sequence}; use mockall::{predicate, Sequence};
@ -269,208 +174,208 @@ mod tests {
app.unwrap_search(); app.unwrap_search();
} }
#[test] // #[test]
fn fetch_musicbrainz() { // fn fetch_musicbrainz() {
let mut mb_api = MockIMusicBrainz::new(); // let mut mb_api = MockIMusicBrainz::new();
let arid: Mbid = "11111111-1111-1111-1111-111111111111".try_into().unwrap(); // let arid: Mbid = "11111111-1111-1111-1111-111111111111".try_into().unwrap();
let album_1 = COLLECTION[1].albums[0].meta.clone(); // let album_1 = COLLECTION[1].albums[0].meta.clone();
let album_4 = COLLECTION[1].albums[3].meta.clone(); // let album_4 = COLLECTION[1].albums[3].meta.clone();
let album_match_1_1 = Match::new(100, album_1.clone()); // let album_match_1_1 = Match::new(100, album_1.clone());
let album_match_1_2 = Match::new(50, album_4.clone()); // let album_match_1_2 = Match::new(50, album_4.clone());
let album_match_4_1 = Match::new(100, album_4.clone()); // let album_match_4_1 = Match::new(100, album_4.clone());
let album_match_4_2 = Match::new(30, album_1.clone()); // let album_match_4_2 = Match::new(30, album_1.clone());
let matches_1 = vec![album_match_1_1.clone(), album_match_1_2.clone()]; // let matches_1 = vec![album_match_1_1.clone(), album_match_1_2.clone()];
let matches_4 = vec![album_match_4_1.clone(), album_match_4_2.clone()]; // let matches_4 = vec![album_match_4_1.clone(), album_match_4_2.clone()];
let result_1: Result<Vec<Match<AlbumMeta>>, musicbrainz::Error> = Ok(matches_1.clone()); // let result_1: Result<Vec<Match<AlbumMeta>>, musicbrainz::Error> = Ok(matches_1.clone());
let result_4: Result<Vec<Match<AlbumMeta>>, musicbrainz::Error> = Ok(matches_4.clone()); // let result_4: Result<Vec<Match<AlbumMeta>>, musicbrainz::Error> = Ok(matches_4.clone());
// Other albums have an MBID and so they will be skipped. // // Other albums have an MBID and so they will be skipped.
let mut seq = Sequence::new(); // let mut seq = Sequence::new();
mb_api // mb_api
.expect_search_release_group() // .expect_search_release_group()
.with(predicate::eq(arid.clone()), predicate::eq(album_1.clone())) // .with(predicate::eq(arid.clone()), predicate::eq(album_1.clone()))
.times(1) // .times(1)
.in_sequence(&mut seq) // .in_sequence(&mut seq)
.return_once(|_, _| result_1); // .return_once(|_, _| result_1);
mb_api // mb_api
.expect_search_release_group() // .expect_search_release_group()
.with(predicate::eq(arid.clone()), predicate::eq(album_4.clone())) // .with(predicate::eq(arid.clone()), predicate::eq(album_4.clone()))
.times(1) // .times(1)
.in_sequence(&mut seq) // .in_sequence(&mut seq)
.return_once(|_, _| result_4); // .return_once(|_, _| result_4);
let browse = AppMachine::browse(inner_with_mb(music_hoard(COLLECTION.to_owned()), mb_api)); // let browse = AppMachine::browse(inner_with_mb(music_hoard(COLLECTION.to_owned()), mb_api));
// Use the second artist for this test. // // Use the second artist for this test.
let browse = browse.increment_selection(Delta::Line).unwrap_browse(); // let browse = browse.increment_selection(Delta::Line).unwrap_browse();
let mut app = browse.fetch_musicbrainz(); // let mut app = browse.fetch_musicbrainz();
let public = app.get(); // let public = app.get();
assert!(matches!(public.state, AppState::Matches(_))); // assert!(matches!(public.state, AppState::Matches(_)));
let public_matches = public.state.unwrap_matches(); // let public_matches = public.state.unwrap_matches();
let mut matches_1: Vec<MatchOption<AlbumMeta>> = // let mut matches_1: Vec<MatchOption<AlbumMeta>> =
matches_1.into_iter().map(Into::into).collect(); // matches_1.into_iter().map(Into::into).collect();
matches_1.push(MatchOption::CannotHaveMbid); // matches_1.push(MatchOption::CannotHaveMbid);
let expected = Some(AppMatchesInfo::Album(AppAlbumMatches { // let expected = Some(AppMatchesInfo::Album(AppAlbumMatches {
matching: album_1.clone(), // matching: album_1.clone(),
list: matches_1.clone(), // list: matches_1.clone(),
})); // }));
assert_eq!(public_matches.matches, expected.as_ref()); // assert_eq!(public_matches.matches, expected.as_ref());
let mut app = app.unwrap_matches().select(); // let mut app = app.unwrap_matches().select();
let public = app.get(); // let public = app.get();
assert!(matches!(public.state, AppState::Matches(_))); // assert!(matches!(public.state, AppState::Matches(_)));
let public_matches = public.state.unwrap_matches(); // let public_matches = public.state.unwrap_matches();
let mut matches_4: Vec<MatchOption<AlbumMeta>> = // let mut matches_4: Vec<MatchOption<AlbumMeta>> =
matches_4.into_iter().map(Into::into).collect(); // matches_4.into_iter().map(Into::into).collect();
matches_4.push(MatchOption::CannotHaveMbid); // matches_4.push(MatchOption::CannotHaveMbid);
let expected = Some(AppMatchesInfo::Album(AppAlbumMatches { // let expected = Some(AppMatchesInfo::Album(AppAlbumMatches {
matching: album_4.clone(), // matching: album_4.clone(),
list: matches_4.clone(), // list: matches_4.clone(),
})); // }));
assert_eq!(public_matches.matches, expected.as_ref()); // assert_eq!(public_matches.matches, expected.as_ref());
let app = app.unwrap_matches().select(); // let app = app.unwrap_matches().select();
app.unwrap_browse(); // app.unwrap_browse();
} // }
#[test] // #[test]
fn fetch_musicbrainz_no_artist() { // fn fetch_musicbrainz_no_artist() {
let browse = AppMachine::browse(inner(music_hoard(vec![]))); // let browse = AppMachine::browse(inner(music_hoard(vec![])));
let app = browse.fetch_musicbrainz(); // let app = browse.fetch_musicbrainz();
app.unwrap_error(); // app.unwrap_error();
} // }
#[test] // #[test]
fn fetch_musicbrainz_no_artist_mbid() { // fn fetch_musicbrainz_no_artist_mbid() {
let mut mb_api = MockIMusicBrainz::new(); // let mut mb_api = MockIMusicBrainz::new();
let artist = COLLECTION[3].meta.clone(); // let artist = COLLECTION[3].meta.clone();
let artist_match_1 = Match::new(100, artist.clone()); // let artist_match_1 = Match::new(100, artist.clone());
let artist_match_2 = Match::new(50, artist.clone()); // let artist_match_2 = Match::new(50, artist.clone());
let matches = vec![artist_match_1.clone(), artist_match_2.clone()]; // let matches = vec![artist_match_1.clone(), artist_match_2.clone()];
let result: Result<Vec<Match<ArtistMeta>>, musicbrainz::Error> = Ok(matches.clone()); // let result: Result<Vec<Match<ArtistMeta>>, musicbrainz::Error> = Ok(matches.clone());
mb_api // mb_api
.expect_search_artist() // .expect_search_artist()
.with(predicate::eq(artist.clone())) // .with(predicate::eq(artist.clone()))
.times(1) // .times(1)
.return_once(|_| result); // .return_once(|_| result);
let browse = AppMachine::browse(inner_with_mb(music_hoard(COLLECTION.to_owned()), mb_api)); // let browse = AppMachine::browse(inner_with_mb(music_hoard(COLLECTION.to_owned()), mb_api));
// Use the fourth artist for this test as they have no MBID. // // Use the fourth artist for this test as they have no MBID.
let browse = browse.increment_selection(Delta::Line).unwrap_browse(); // let browse = browse.increment_selection(Delta::Line).unwrap_browse();
let browse = browse.increment_selection(Delta::Line).unwrap_browse(); // let browse = browse.increment_selection(Delta::Line).unwrap_browse();
let browse = browse.increment_selection(Delta::Line).unwrap_browse(); // let browse = browse.increment_selection(Delta::Line).unwrap_browse();
let mut app = browse.fetch_musicbrainz(); // let mut app = browse.fetch_musicbrainz();
let public = app.get(); // let public = app.get();
assert!(matches!(public.state, AppState::Matches(_))); // assert!(matches!(public.state, AppState::Matches(_)));
let public_matches = public.state.unwrap_matches(); // let public_matches = public.state.unwrap_matches();
let mut matches: Vec<MatchOption<ArtistMeta>> = // let mut matches: Vec<MatchOption<ArtistMeta>> =
matches.into_iter().map(Into::into).collect(); // matches.into_iter().map(Into::into).collect();
matches.push(MatchOption::CannotHaveMbid); // matches.push(MatchOption::CannotHaveMbid);
let expected = Some(AppMatchesInfo::Artist(AppArtistMatches { // let expected = Some(AppMatchesInfo::Artist(AppArtistMatches {
matching: artist.clone(), // matching: artist.clone(),
list: matches.clone(), // list: matches.clone(),
})); // }));
assert_eq!(public_matches.matches, expected.as_ref()); // assert_eq!(public_matches.matches, expected.as_ref());
let app = app.unwrap_matches().select(); // let app = app.unwrap_matches().select();
app.unwrap_browse(); // app.unwrap_browse();
} // }
#[test] // #[test]
fn fetch_musicbrainz_artist_api_error() { // fn fetch_musicbrainz_artist_api_error() {
let mut mb_api = MockIMusicBrainz::new(); // let mut mb_api = MockIMusicBrainz::new();
let error = Err(musicbrainz::Error::RateLimit); // let error = Err(musicbrainz::Error::RateLimit);
mb_api // mb_api
.expect_search_artist() // .expect_search_artist()
.times(1) // .times(1)
.return_once(|_| error); // .return_once(|_| error);
let browse = AppMachine::browse(inner_with_mb(music_hoard(COLLECTION.to_owned()), mb_api)); // let browse = AppMachine::browse(inner_with_mb(music_hoard(COLLECTION.to_owned()), mb_api));
// Use the fourth artist for this test as they have no MBID. // // Use the fourth artist for this test as they have no MBID.
let browse = browse.increment_selection(Delta::Line).unwrap_browse(); // let browse = browse.increment_selection(Delta::Line).unwrap_browse();
let browse = browse.increment_selection(Delta::Line).unwrap_browse(); // let browse = browse.increment_selection(Delta::Line).unwrap_browse();
let browse = browse.increment_selection(Delta::Line).unwrap_browse(); // let browse = browse.increment_selection(Delta::Line).unwrap_browse();
let app = browse.fetch_musicbrainz(); // let app = browse.fetch_musicbrainz();
app.unwrap_error(); // app.unwrap_error();
} // }
#[test] // #[test]
fn fetch_musicbrainz_album_api_error() { // fn fetch_musicbrainz_album_api_error() {
let mut mb_api = MockIMusicBrainz::new(); // let mut mb_api = MockIMusicBrainz::new();
let error = Err(musicbrainz::Error::RateLimit); // let error = Err(musicbrainz::Error::RateLimit);
mb_api // mb_api
.expect_search_release_group() // .expect_search_release_group()
.times(1) // .times(1)
.return_once(|_, _| error); // .return_once(|_, _| error);
let browse = AppMachine::browse(inner_with_mb(music_hoard(COLLECTION.to_owned()), mb_api)); // let browse = AppMachine::browse(inner_with_mb(music_hoard(COLLECTION.to_owned()), mb_api));
let app = browse.fetch_musicbrainz(); // let app = browse.fetch_musicbrainz();
app.unwrap_error(); // app.unwrap_error();
} // }
#[test] // #[test]
fn fetch_musicbrainz_artist_receiver_disconnect() { // fn fetch_musicbrainz_artist_receiver_disconnect() {
let (tx, rx) = mpsc::channel::<FetchResult>(); // let (tx, rx) = mpsc::channel::<FetchResult>();
drop(rx); // drop(rx);
let mut mb_api = MockIMusicBrainz::new(); // let mut mb_api = MockIMusicBrainz::new();
mb_api // mb_api
.expect_search_artist() // .expect_search_artist()
.times(1) // .times(1)
.return_once(|_| Ok(vec![])); // .return_once(|_| Ok(vec![]));
// We only check it does not panic and that it doesn't call the API more than once. // // We only check it does not panic and that it doesn't call the API more than once.
AppMachine::fetch_artist(Arc::new(Mutex::new(mb_api)), tx, COLLECTION[3].meta.clone()); // AppMachine::fetch_artist(Arc::new(Mutex::new(mb_api)), tx, COLLECTION[3].meta.clone());
} // }
#[test] // #[test]
fn fetch_musicbrainz_albums_receiver_disconnect() { // fn fetch_musicbrainz_albums_receiver_disconnect() {
let (tx, rx) = mpsc::channel::<FetchResult>(); // let (tx, rx) = mpsc::channel::<FetchResult>();
drop(rx); // drop(rx);
let mut mb_api = MockIMusicBrainz::new(); // let mut mb_api = MockIMusicBrainz::new();
mb_api // mb_api
.expect_search_release_group() // .expect_search_release_group()
.times(1) // .times(1)
.return_once(|_, _| Ok(vec![])); // .return_once(|_, _| Ok(vec![]));
// We only check it does not panic and that it doesn't call the API more than once. // // We only check it does not panic and that it doesn't call the API more than once.
let mbref = &COLLECTION[1].meta.musicbrainz; // let mbref = &COLLECTION[1].meta.musicbrainz;
let albums = &COLLECTION[1].albums; // let albums = &COLLECTION[1].albums;
AppMachine::fetch_albums( // AppMachine::fetch_albums(
Arc::new(Mutex::new(mb_api)), // Arc::new(Mutex::new(mb_api)),
tx, // tx,
mbref.as_ref().unwrap().mbid().clone(), // mbref.as_ref().unwrap().mbid().clone(),
albums.iter().map(|a| &a.meta).cloned().collect(), // albums.iter().map(|a| &a.meta).cloned().collect(),
); // );
} // }
#[test] #[test]
fn no_op() { fn no_op() {

View File

@ -1,15 +1,74 @@
use crate::tui::app::{ use std::{
machine::{App, AppInner, AppMachine}, sync::{mpsc, Arc, Mutex},
AppPublic, AppState, IAppInteractFetch, thread, time,
}; };
pub struct AppFetch; use musichoard::collection::{
album::AlbumMeta,
artist::ArtistMeta,
musicbrainz::{IMusicBrainzRef, Mbid},
};
use crate::tui::{
app::{
machine::{App, AppInner, AppMachine},
AppMatchesInfo, AppPublic, AppState, IAppInteractFetch,
},
lib::interface::musicbrainz::{Error as MbError, IMusicBrainz},
};
use super::matches::AppMatches;
pub struct AppFetch {
fetch_rx: FetchReceiver,
}
impl AppMachine<AppFetch> { impl AppMachine<AppFetch> {
pub fn fetch(inner: AppInner) -> Self { pub fn app_fetch_new(inner: AppInner) -> App {
AppMachine { let coll = inner.music_hoard.get_collection();
inner, let artist = match inner.selection.state_artist(coll) {
state: AppFetch, Some(artist_state) => &coll[artist_state.index],
None => return AppMachine::error(inner, "cannot fetch: no artist selected").into(),
};
let (fetch_tx, fetch_rx) = mpsc::channel::<FetchResult>();
match artist.meta.musicbrainz {
Some(ref arid) => {
let musicbrainz = Arc::clone(&inner.musicbrainz);
let arid = arid.mbid().clone();
let albums = artist.albums.iter().map(|a| &a.meta).cloned().collect();
thread::spawn(|| Self::fetch_albums(musicbrainz, fetch_tx, arid, albums));
}
None => {
let musicbrainz = Arc::clone(&inner.musicbrainz);
let artist = artist.meta.clone();
thread::spawn(|| Self::fetch_artist(musicbrainz, fetch_tx, artist));
}
};
let fetch = AppFetch { fetch_rx };
AppMachine::app_fetch_next(inner, fetch, true)
}
pub fn app_fetch_next(inner: AppInner, fetch: AppFetch, first: bool) -> App {
match fetch.fetch_rx.recv() {
Ok(fetch_result) => match fetch_result {
Ok(mut next_match) => {
next_match.push_cannot_have_mbid();
let current = Some(next_match);
AppMachine::matches(inner, AppMatches::new(current, fetch)).into()
}
Err(err) => AppMachine::error(inner, format!("fetch failed: {err}")).into(),
},
// only happens when the sender disconnects which means it finished its job
Err(_) => {
if first {
AppMachine::matches(inner, AppMatches::empty(fetch)).into()
} else {
AppMachine::browse(inner).into()
}
}
} }
} }
} }
@ -44,3 +103,60 @@ impl IAppInteractFetch for AppMachine<AppFetch> {
self.into() self.into()
} }
} }
type FetchError = MbError;
type FetchResult = Result<AppMatchesInfo, FetchError>;
type FetchSender = mpsc::Sender<FetchResult>;
type FetchReceiver = mpsc::Receiver<FetchResult>;
trait IAppInteractFetchPrivate {
fn fetch_artist(
musicbrainz: Arc<Mutex<dyn IMusicBrainz + Send>>,
fetch_tx: FetchSender,
artist: ArtistMeta,
);
fn fetch_albums(
musicbrainz: Arc<Mutex<dyn IMusicBrainz + Send>>,
fetch_tx: FetchSender,
arid: Mbid,
albums: Vec<AlbumMeta>,
);
}
impl IAppInteractFetchPrivate for AppMachine<AppFetch> {
fn fetch_artist(
musicbrainz: Arc<Mutex<dyn IMusicBrainz + Send>>,
fetch_tx: FetchSender,
artist: ArtistMeta,
) {
let result = musicbrainz.lock().unwrap().search_artist(&artist);
let result = result.map(|list| AppMatchesInfo::artist(artist, list));
fetch_tx.send(result).ok();
}
fn fetch_albums(
musicbrainz: Arc<Mutex<dyn IMusicBrainz + Send>>,
fetch_tx: FetchSender,
arid: Mbid,
albums: Vec<AlbumMeta>,
) {
let mut musicbrainz = musicbrainz.lock().unwrap();
let mut album_iter = albums.into_iter().peekable();
while let Some(album) = album_iter.next() {
if album.musicbrainz.is_some() {
continue;
}
let result = musicbrainz.search_release_group(&arid, &album);
let result = result.map(|list| AppMatchesInfo::album(album, list));
if fetch_tx.send(result).is_err() {
// If receiver disconnects just drop the rest.
return;
}
if album_iter.peek().is_some() {
thread::sleep(time::Duration::from_secs(1));
}
}
}
}

View File

@ -1,11 +1,13 @@
use std::cmp; use std::cmp;
use crate::tui::app::{ use crate::tui::app::{
machine::{browse::FetchReceiver, App, AppInner, AppMachine}, machine::{App, AppInner, AppMachine},
AppAlbumMatches, AppArtistMatches, AppMatchesInfo, AppPublic, AppPublicMatches, AppState, AppAlbumMatches, AppArtistMatches, AppMatchesInfo, AppPublic, AppPublicMatches, AppState,
IAppInteractMatches, MatchOption, WidgetState, IAppInteractMatches, MatchOption, WidgetState,
}; };
use super::fetch::AppFetch;
impl AppArtistMatches { impl AppArtistMatches {
fn len(&self) -> usize { fn len(&self) -> usize {
self.list.len() self.list.len()
@ -34,7 +36,7 @@ impl AppMatchesInfo {
} }
} }
fn push_cannot_have_mbid(&mut self) { pub fn push_cannot_have_mbid(&mut self) {
match self { match self {
Self::Artist(a) => a.push_cannot_have_mbid(), Self::Artist(a) => a.push_cannot_have_mbid(),
Self::Album(a) => a.push_cannot_have_mbid(), Self::Album(a) => a.push_cannot_have_mbid(),
@ -43,29 +45,33 @@ impl AppMatchesInfo {
} }
pub struct AppMatches { pub struct AppMatches {
matches_rx: FetchReceiver,
current: Option<AppMatchesInfo>, current: Option<AppMatchesInfo>,
state: WidgetState, state: WidgetState,
fetch: AppFetch,
} }
impl AppMatches { impl AppMatches {
fn empty(matches_rx: FetchReceiver) -> Self { pub fn empty(fetch: AppFetch) -> Self {
Self::new(None, fetch)
}
pub fn new(current: Option<AppMatchesInfo>, fetch: AppFetch) -> Self {
let mut state = WidgetState::default();
if current.is_some() {
state.list.select(Some(0));
}
AppMatches { AppMatches {
matches_rx, current,
current: None, state,
state: WidgetState::default(), fetch,
} }
} }
} }
impl AppMachine<AppMatches> { impl AppMachine<AppMatches> {
fn matches(inner: AppInner, state: AppMatches) -> Self { pub fn matches(inner: AppInner, state: AppMatches) -> Self {
AppMachine { inner, state } AppMachine { inner, state }
} }
pub fn app_matches(inner: AppInner, matches_rx: FetchReceiver) -> App {
AppMachine::matches(inner, AppMatches::empty(matches_rx)).fetch_first()
}
} }
impl From<AppMachine<AppMatches>> for App { impl From<AppMachine<AppMatches>> for App {
@ -113,7 +119,7 @@ impl IAppInteractMatches for AppMachine<AppMatches> {
} }
fn select(self) -> Self::APP { fn select(self) -> Self::APP {
self.fetch_next() AppMachine::app_fetch_next(self.inner, self.state.fetch, false)
} }
fn abort(self) -> Self::APP { fn abort(self) -> Self::APP {
@ -125,47 +131,6 @@ impl IAppInteractMatches for AppMachine<AppMatches> {
} }
} }
trait IAppInteractMatchesPrivate
where
Self: Sized,
{
fn fetch_first(self) -> App;
fn fetch_next(self) -> App;
fn fetch(self, first: bool) -> App;
}
impl IAppInteractMatchesPrivate for AppMachine<AppMatches> {
fn fetch_first(self) -> App {
self.fetch(true)
}
fn fetch_next(self) -> App {
self.fetch(false)
}
fn fetch(mut self, first: bool) -> App {
match self.state.matches_rx.recv() {
Ok(fetch_result) => match fetch_result {
Ok(mut next_match) => {
next_match.push_cannot_have_mbid();
self.state.current = Some(next_match);
self.state.state.list.select(Some(0));
AppMachine::matches(self.inner, self.state).into()
}
Err(err) => AppMachine::error(self.inner, format!("fetch failed: {err}")).into(),
},
// only happens when the sender disconnects which means it finished its job
Err(_) => {
if first {
AppMachine::matches(self.inner, AppMatches::empty(self.state.matches_rx)).into()
} else {
AppMachine::browse(self.inner).into()
}
}
}
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::sync::mpsc; use std::sync::mpsc;
@ -254,150 +219,150 @@ mod tests {
vec![matches_info_1, matches_info_2] vec![matches_info_1, matches_info_2]
} }
fn receiver(matches_info_vec: Vec<AppMatchesInfo>) -> FetchReceiver { // fn receiver(matches_info_vec: Vec<AppMatchesInfo>) -> FetchReceiver {
let (tx, rx) = mpsc::channel(); // let (tx, rx) = mpsc::channel();
for matches_info in matches_info_vec.into_iter() { // for matches_info in matches_info_vec.into_iter() {
tx.send(Ok(matches_info)).unwrap(); // tx.send(Ok(matches_info)).unwrap();
} // }
rx // rx
} // }
fn push_cannot_have_mbid(matches_info_vec: &mut [AppMatchesInfo]) { // fn push_cannot_have_mbid(matches_info_vec: &mut [AppMatchesInfo]) {
for matches_info in matches_info_vec.iter_mut() { // for matches_info in matches_info_vec.iter_mut() {
matches_info.push_cannot_have_mbid(); // matches_info.push_cannot_have_mbid();
} // }
} // }
#[test] // #[test]
fn create_empty() { // fn create_empty() {
let matches = // let matches =
AppMachine::app_matches(inner(music_hoard(vec![])), receiver(vec![])).unwrap_matches(); // AppMachine::app_matches(inner(music_hoard(vec![])), receiver(vec![])).unwrap_matches();
let widget_state = WidgetState::default(); // let widget_state = WidgetState::default();
assert_eq!(matches.state.current, None); // assert_eq!(matches.state.current, None);
assert_eq!(matches.state.state, widget_state); // assert_eq!(matches.state.state, widget_state);
let mut app = matches.no_op(); // let mut app = matches.no_op();
let public = app.get(); // let public = app.get();
let public_matches = public.state.unwrap_matches(); // let public_matches = public.state.unwrap_matches();
assert_eq!(public_matches.matches, None); // assert_eq!(public_matches.matches, None);
assert_eq!(public_matches.state, &widget_state); // assert_eq!(public_matches.state, &widget_state);
} // }
#[test] // #[test]
fn create_nonempty() { // fn create_nonempty() {
let mut matches_info_vec = album_matches_info_vec(); // let mut matches_info_vec = album_matches_info_vec();
let matches = AppMachine::app_matches( // let matches = AppMachine::app_matches(
inner(music_hoard(vec![])), // inner(music_hoard(vec![])),
receiver(matches_info_vec.clone()), // receiver(matches_info_vec.clone()),
) // )
.unwrap_matches(); // .unwrap_matches();
push_cannot_have_mbid(&mut matches_info_vec); // push_cannot_have_mbid(&mut matches_info_vec);
let mut widget_state = WidgetState::default(); // let mut widget_state = WidgetState::default();
widget_state.list.select(Some(0)); // widget_state.list.select(Some(0));
assert_eq!(matches.state.current.as_ref(), Some(&matches_info_vec[0])); // assert_eq!(matches.state.current.as_ref(), Some(&matches_info_vec[0]));
assert_eq!(matches.state.state, widget_state); // assert_eq!(matches.state.state, widget_state);
let mut app = matches.no_op(); // let mut app = matches.no_op();
let public = app.get(); // let public = app.get();
let public_matches = public.state.unwrap_matches(); // let public_matches = public.state.unwrap_matches();
assert_eq!(public_matches.matches, Some(&matches_info_vec[0])); // assert_eq!(public_matches.matches, Some(&matches_info_vec[0]));
assert_eq!(public_matches.state, &widget_state); // assert_eq!(public_matches.state, &widget_state);
} // }
fn matches_flow(mut matches_info_vec: Vec<AppMatchesInfo>) { // fn matches_flow(mut matches_info_vec: Vec<AppMatchesInfo>) {
let matches = AppMachine::app_matches( // let matches = AppMachine::app_matches(
inner(music_hoard(vec![])), // inner(music_hoard(vec![])),
receiver(matches_info_vec.clone()), // receiver(matches_info_vec.clone()),
) // )
.unwrap_matches(); // .unwrap_matches();
push_cannot_have_mbid(&mut matches_info_vec); // push_cannot_have_mbid(&mut matches_info_vec);
let mut widget_state = WidgetState::default(); // let mut widget_state = WidgetState::default();
widget_state.list.select(Some(0)); // widget_state.list.select(Some(0));
assert_eq!(matches.state.current.as_ref(), Some(&matches_info_vec[0])); // assert_eq!(matches.state.current.as_ref(), Some(&matches_info_vec[0]));
assert_eq!(matches.state.state, widget_state); // assert_eq!(matches.state.state, widget_state);
let matches = matches.prev_match().unwrap_matches(); // let matches = matches.prev_match().unwrap_matches();
assert_eq!(matches.state.current.as_ref(), Some(&matches_info_vec[0])); // assert_eq!(matches.state.current.as_ref(), Some(&matches_info_vec[0]));
assert_eq!(matches.state.state.list.selected(), Some(0)); // assert_eq!(matches.state.state.list.selected(), Some(0));
let matches = matches.next_match().unwrap_matches(); // let matches = matches.next_match().unwrap_matches();
assert_eq!(matches.state.current.as_ref(), Some(&matches_info_vec[0])); // assert_eq!(matches.state.current.as_ref(), Some(&matches_info_vec[0]));
assert_eq!(matches.state.state.list.selected(), Some(1)); // assert_eq!(matches.state.state.list.selected(), Some(1));
// Next is CannotHaveMBID // // Next is CannotHaveMBID
let matches = matches.next_match().unwrap_matches(); // let matches = matches.next_match().unwrap_matches();
assert_eq!(matches.state.current.as_ref(), Some(&matches_info_vec[0])); // assert_eq!(matches.state.current.as_ref(), Some(&matches_info_vec[0]));
assert_eq!(matches.state.state.list.selected(), Some(2)); // assert_eq!(matches.state.state.list.selected(), Some(2));
let matches = matches.next_match().unwrap_matches(); // let matches = matches.next_match().unwrap_matches();
assert_eq!(matches.state.current.as_ref(), Some(&matches_info_vec[0])); // assert_eq!(matches.state.current.as_ref(), Some(&matches_info_vec[0]));
assert_eq!(matches.state.state.list.selected(), Some(2)); // assert_eq!(matches.state.state.list.selected(), Some(2));
let matches = matches.select().unwrap_matches(); // let matches = matches.select().unwrap_matches();
assert_eq!(matches.state.current.as_ref(), Some(&matches_info_vec[1])); // assert_eq!(matches.state.current.as_ref(), Some(&matches_info_vec[1]));
assert_eq!(matches.state.state.list.selected(), Some(0)); // assert_eq!(matches.state.state.list.selected(), Some(0));
// And it's done // // And it's done
matches.select().unwrap_browse(); // matches.select().unwrap_browse();
} // }
#[test] // #[test]
fn artist_matches_flow() { // fn artist_matches_flow() {
matches_flow(artist_matches_info_vec()); // matches_flow(artist_matches_info_vec());
} // }
#[test] // #[test]
fn album_matches_flow() { // fn album_matches_flow() {
matches_flow(album_matches_info_vec()); // matches_flow(album_matches_info_vec());
} // }
#[test] // #[test]
fn matches_abort() { // fn matches_abort() {
let mut matches_info_vec = album_matches_info_vec(); // let mut matches_info_vec = album_matches_info_vec();
let matches = AppMachine::app_matches( // let matches = AppMachine::app_matches(
inner(music_hoard(vec![])), // inner(music_hoard(vec![])),
receiver(matches_info_vec.clone()), // receiver(matches_info_vec.clone()),
) // )
.unwrap_matches(); // .unwrap_matches();
push_cannot_have_mbid(&mut matches_info_vec); // push_cannot_have_mbid(&mut matches_info_vec);
let mut widget_state = WidgetState::default(); // let mut widget_state = WidgetState::default();
widget_state.list.select(Some(0)); // widget_state.list.select(Some(0));
assert_eq!(matches.state.current.as_ref(), Some(&matches_info_vec[0])); // assert_eq!(matches.state.current.as_ref(), Some(&matches_info_vec[0]));
assert_eq!(matches.state.state, widget_state); // assert_eq!(matches.state.state, widget_state);
matches.abort().unwrap_browse(); // matches.abort().unwrap_browse();
} // }
#[test] // #[test]
fn matches_select_empty() { // fn matches_select_empty() {
let matches = // let matches =
AppMachine::app_matches(inner(music_hoard(vec![])), receiver(vec![])).unwrap_matches(); // AppMachine::app_matches(inner(music_hoard(vec![])), receiver(vec![])).unwrap_matches();
assert_eq!(matches.state.current, None); // assert_eq!(matches.state.current, None);
matches.select().unwrap_browse(); // matches.select().unwrap_browse();
} // }
#[test] // #[test]
fn no_op() { // fn no_op() {
let matches = // let matches =
AppMachine::app_matches(inner(music_hoard(vec![])), receiver(vec![])).unwrap_matches(); // AppMachine::app_matches(inner(music_hoard(vec![])), receiver(vec![])).unwrap_matches();
let app = matches.no_op(); // let app = matches.no_op();
app.unwrap_matches(); // app.unwrap_matches();
} // }
} }

View File

@ -328,24 +328,24 @@ mod tests {
assert!(!app.is_running()); assert!(!app.is_running());
} }
#[test] // #[test]
fn state_matches() { // fn state_matches() {
let mut app = App::new(music_hoard_init(vec![]), mb_api()); // let mut app = App::new(music_hoard_init(vec![]), mb_api());
assert!(app.is_running()); // assert!(app.is_running());
let (_, rx) = mpsc::channel(); // let (_, rx) = mpsc::channel();
app = AppMachine::app_matches(app.unwrap_browse().inner, rx); // app = AppMachine::app_matches(app.unwrap_browse().inner, rx);
let state = app.state(); // let state = app.state();
assert!(matches!(state, AppState::Matches(_))); // assert!(matches!(state, AppState::Matches(_)));
app = state; // app = state;
let public = app.get(); // let public = app.get();
assert!(matches!(public.state, AppState::Matches(_))); // assert!(matches!(public.state, AppState::Matches(_)));
let app = app.force_quit(); // let app = app.force_quit();
assert!(!app.is_running()); // assert!(!app.is_running());
} // }
#[test] #[test]
fn state_error() { fn state_error() {