feat: Completed support for viewing Lidarr artist details

This commit is contained in:
2026-01-09 16:22:03 -07:00
parent 269057867f
commit b2814371f0
74 changed files with 3488 additions and 567 deletions
@@ -0,0 +1,106 @@
#[cfg(test)]
mod tests {
use mockito::Matcher;
use pretty_assertions::assert_eq;
use serde_json::{json, Value};
use crate::models::lidarr_models::{Album, LidarrSerdeable};
use crate::network::lidarr_network::lidarr_network_test_utils::test_utils::{ALBUM_JSON};
use crate::network::lidarr_network::LidarrEvent;
use crate::network::network_tests::test_utils::{test_network, MockServarrApi};
#[tokio::test]
async fn test_handle_get_albums_event() {
let albums_json = json!([{
"id": 1,
"title": "Test Album",
"foreignAlbumId": "test-foreign-album-id",
"monitored": true,
"anyReleaseOk": true,
"profileId": 1,
"duration": 180,
"albumType": "Album",
"genres": ["Classical"],
"ratings": {"votes": 15, "value": 8.4},
"releaseDate": "2023-01-01T00:00:00Z",
"statistics": {
"trackFileCount": 10,
"trackCount": 10,
"totalTrackCount": 10,
"sizeOnDisk": 1024,
"percentOfTracks": 99.9
}
}]);
let response: Vec<Album> = serde_json::from_value(albums_json.clone()).unwrap();
let (mock, app, _server) = MockServarrApi::get()
.returns(albums_json)
.query("artistId=1")
.build_for(LidarrEvent::GetAlbums(1))
.await;
app.lock().await.server_tabs.set_index(2);
let mut network = test_network(&app);
let result = network.handle_lidarr_event(LidarrEvent::GetAlbums(1)).await;
mock.assert_async().await;
let LidarrSerdeable::Albums(albums) = result.unwrap() else {
panic!("Expected Albums");
};
assert_eq!(albums, response);
assert!(!app.lock().await.data.lidarr_data.albums.is_empty());
}
#[tokio::test]
async fn test_handle_toggle_album_monitoring_event() {
let mut expected_body: Value = serde_json::from_str(ALBUM_JSON).unwrap();
*expected_body.get_mut("monitored").unwrap() = json!(false);
let (get_mock, app, mut server) = MockServarrApi::get()
.returns(serde_json::from_str(ALBUM_JSON).unwrap())
.path("/1")
.build_for(LidarrEvent::GetAlbums(1))
.await;
let put_mock = server
.mock("PUT", "/api/v1/album/1")
.match_body(Matcher::Json(expected_body))
.match_header("X-Api-Key", "test1234")
.with_status(202)
.create_async()
.await;
app.lock().await.server_tabs.set_index(2);
let mut network = test_network(&app);
assert_ok!(
network
.handle_lidarr_event(LidarrEvent::ToggleAlbumMonitoring(1))
.await
);
get_mock.assert_async().await;
put_mock.assert_async().await;
}
#[tokio::test]
async fn test_handle_get_album_details_event() {
let expected_album: Album = serde_json::from_str(ALBUM_JSON).unwrap();
let (mock, app, _server) = MockServarrApi::get()
.returns(serde_json::from_str(ALBUM_JSON).unwrap())
.path("/1")
.build_for(LidarrEvent::GetAlbumDetails(1))
.await;
app.lock().await.server_tabs.set_index(2);
let mut network = test_network(&app);
let result = network
.handle_lidarr_event(LidarrEvent::GetAlbumDetails(1))
.await;
mock.assert_async().await;
let LidarrSerdeable::Album(album) = result.unwrap() else {
panic!("Expected Album");
};
assert_eq!(album, expected_album);
}
}
@@ -0,0 +1,121 @@
use crate::models::lidarr_models::{Album};
use crate::network::lidarr_network::LidarrEvent;
use crate::network::{Network, RequestMethod};
use anyhow::Result;
use log::{debug, info, warn};
use serde_json::{Value, json};
#[cfg(test)]
#[path = "lidarr_albums_network_tests.rs"]
mod lidarr_albums_network_tests;
impl Network<'_, '_> {
pub(in crate::network::lidarr_network) async fn get_albums(
&mut self,
artist_id: i64,
) -> Result<Vec<Album>> {
info!("Fetching albums for Lidarr artist with ID: {artist_id}");
let event = LidarrEvent::GetAlbums(artist_id);
let request_props = self
.request_props_from(
event,
RequestMethod::Get,
None::<()>,
None,
Some(format!("artistId={artist_id}")),
)
.await;
self
.handle_request::<(), Vec<Album>>(request_props, |mut albums_vec, mut app| {
albums_vec.sort_by(|a, b| a.id.cmp(&b.id));
app.data.lidarr_data.albums.set_items(albums_vec);
})
.await
}
pub(in crate::network::lidarr_network) async fn get_album_details(
&mut self,
album_id: i64,
) -> Result<Album> {
info!("Fetching details for Lidarr album with ID: {album_id}");
let event = LidarrEvent::GetAlbumDetails(album_id);
let request_props = self
.request_props_from(
event,
RequestMethod::Get,
None::<()>,
Some(format!("/{album_id}")),
None,
)
.await;
self
.handle_request::<(), Album>(request_props, |_, _| ())
.await
}
pub(in crate::network::lidarr_network) async fn toggle_album_monitoring(
&mut self,
album_id: i64,
) -> Result<()> {
let event = LidarrEvent::ToggleAlbumMonitoring(album_id);
info!("Toggling album monitoring for album with ID: {album_id}");
info!("Fetching album details for album with ID: {album_id}");
let detail_event = LidarrEvent::GetAlbums(0);
let request_props = self
.request_props_from(
detail_event,
RequestMethod::Get,
None::<()>,
Some(format!("/{album_id}")),
None,
)
.await;
let mut response = String::new();
self
.handle_request::<(), Value>(request_props, |detailed_album_body, _| {
response = detailed_album_body.to_string()
})
.await?;
info!("Constructing toggle album monitoring body");
match serde_json::from_str::<Value>(&response) {
Ok(mut detailed_album_body) => {
let monitored = detailed_album_body
.get("monitored")
.unwrap()
.as_bool()
.unwrap();
*detailed_album_body.get_mut("monitored").unwrap() = json!(!monitored);
debug!("Toggle album monitoring body: {detailed_album_body:?}");
let request_props = self
.request_props_from(
event,
RequestMethod::Put,
Some(detailed_album_body),
Some(format!("/{album_id}")),
None,
)
.await;
self
.handle_request::<Value, ()>(request_props, |_, _| ())
.await
}
Err(_) => {
warn!("Request for detailed album body was interrupted");
Ok(())
}
}
}
}
@@ -134,11 +134,10 @@ mod tests {
app.lock().await.server_tabs.set_index(2);
let mut network = test_network(&app);
assert!(
assert_ok!(
network
.handle_lidarr_event(LidarrEvent::ToggleArtistMonitoring(1))
.await
.is_ok()
);
get_mock.assert_async().await;
@@ -167,6 +166,52 @@ mod tests {
mock.assert_async().await;
}
#[tokio::test]
async fn test_handle_update_and_scan_artist_event() {
let (mock, app, _server) = MockServarrApi::post()
.with_request_body(json!({
"name": "RefreshArtist",
"artistId": 1
}))
.returns(json!({}))
.build_for(LidarrEvent::UpdateAndScanArtist(1))
.await;
app.lock().await.server_tabs.set_index(2);
let mut network = test_network(&app);
assert!(
network
.handle_lidarr_event(LidarrEvent::UpdateAndScanArtist(1))
.await
.is_ok()
);
mock.assert_async().await;
}
#[tokio::test]
async fn test_handle_trigger_automatic_artist_search_event() {
let (mock, app, _server) = MockServarrApi::post()
.with_request_body(json!({
"name": "ArtistSearch",
"artistId": 1
}))
.returns(json!({}))
.build_for(LidarrEvent::TriggerAutomaticArtistSearch(1))
.await;
app.lock().await.server_tabs.set_index(2);
let mut network = test_network(&app);
assert!(
network
.handle_lidarr_event(LidarrEvent::TriggerAutomaticArtistSearch(1))
.await
.is_ok()
);
mock.assert_async().await;
}
#[tokio::test]
async fn test_handle_edit_artist_event() {
let mut expected_body: Value = serde_json::from_str(ARTIST_JSON).unwrap();
@@ -0,0 +1,399 @@
use anyhow::Result;
use log::{debug, info, warn};
use serde_json::{Value, json};
use crate::models::Route;
use crate::models::lidarr_models::{
AddArtistBody, AddArtistSearchResult, Artist, DeleteArtistParams, EditArtistParams,
LidarrCommandBody,
};
use crate::models::servarr_data::lidarr::lidarr_data::ActiveLidarrBlock;
use crate::models::stateful_table::StatefulTable;
use crate::network::lidarr_network::LidarrEvent;
use crate::network::{Network, RequestMethod};
use urlencoding::encode;
#[cfg(test)]
#[path = "lidarr_artists_network_tests.rs"]
mod lidarr_artists_network_tests;
impl Network<'_, '_> {
pub(in crate::network::lidarr_network) async fn delete_artist(
&mut self,
delete_artist_params: DeleteArtistParams,
) -> Result<()> {
let event = LidarrEvent::DeleteArtist(DeleteArtistParams::default());
let DeleteArtistParams {
id,
delete_files,
add_import_list_exclusion,
} = delete_artist_params;
info!(
"Deleting Lidarr artist with ID: {id} with deleteFiles={delete_files} and addImportListExclusion={add_import_list_exclusion}"
);
let request_props = self
.request_props_from(
event,
RequestMethod::Delete,
None::<()>,
Some(format!("/{id}")),
Some(format!(
"deleteFiles={delete_files}&addImportListExclusion={add_import_list_exclusion}"
)),
)
.await;
self
.handle_request::<(), ()>(request_props, |_, _| ())
.await
}
pub(in crate::network::lidarr_network) async fn list_artists(&mut self) -> Result<Vec<Artist>> {
info!("Fetching Lidarr artists");
let event = LidarrEvent::ListArtists;
let request_props = self
.request_props_from(event, RequestMethod::Get, None::<()>, None, None)
.await;
self
.handle_request::<(), Vec<Artist>>(request_props, |mut artists_vec, mut app| {
if !matches!(
app.get_current_route(),
Route::Lidarr(ActiveLidarrBlock::ArtistsSortPrompt, _)
) {
artists_vec.sort_by(|a, b| a.id.cmp(&b.id));
app.data.lidarr_data.artists.set_items(artists_vec);
app.data.lidarr_data.artists.apply_sorting_toggle(false);
}
})
.await
}
pub(in crate::network::lidarr_network) async fn get_artist_details(
&mut self,
artist_id: i64,
) -> Result<Artist> {
info!("Fetching details for Lidarr artist with ID: {artist_id}");
let event = LidarrEvent::GetArtistDetails(artist_id);
let request_props = self
.request_props_from(
event,
RequestMethod::Get,
None::<()>,
Some(format!("/{artist_id}")),
None,
)
.await;
self
.handle_request::<(), Artist>(request_props, |_, _| ())
.await
}
pub(in crate::network::lidarr_network) async fn toggle_artist_monitoring(
&mut self,
artist_id: i64,
) -> Result<()> {
let event = LidarrEvent::ToggleArtistMonitoring(artist_id);
let detail_event = LidarrEvent::GetArtistDetails(artist_id);
info!("Toggling artist monitoring for artist with ID: {artist_id}");
info!("Fetching artist details for artist with ID: {artist_id}");
let request_props = self
.request_props_from(
detail_event,
RequestMethod::Get,
None::<()>,
Some(format!("/{artist_id}")),
None,
)
.await;
let mut response = String::new();
self
.handle_request::<(), Value>(request_props, |detailed_artist_body, _| {
response = detailed_artist_body.to_string()
})
.await?;
info!("Constructing toggle artist monitoring body");
match serde_json::from_str::<Value>(&response) {
Ok(mut detailed_artist_body) => {
let monitored = detailed_artist_body
.get("monitored")
.unwrap()
.as_bool()
.unwrap();
*detailed_artist_body.get_mut("monitored").unwrap() = json!(!monitored);
debug!("Toggle artist monitoring body: {detailed_artist_body:?}");
let request_props = self
.request_props_from(
event,
RequestMethod::Put,
Some(detailed_artist_body),
Some(format!("/{artist_id}")),
None,
)
.await;
self
.handle_request::<Value, ()>(request_props, |_, _| ())
.await
}
Err(_) => {
warn!("Request for detailed artist body was interrupted");
Ok(())
}
}
}
pub(in crate::network::lidarr_network) async fn update_all_artists(&mut self) -> Result<Value> {
info!("Updating all artists");
let event = LidarrEvent::UpdateAllArtists;
let body = LidarrCommandBody {
name: "RefreshArtist".to_owned(),
..LidarrCommandBody::default()
};
let request_props = self
.request_props_from(event, RequestMethod::Post, Some(body), None, None)
.await;
self
.handle_request::<LidarrCommandBody, Value>(request_props, |_, _| ())
.await
}
pub(in crate::network::lidarr_network) async fn update_and_scan_artist(
&mut self,
artist_id: i64,
) -> Result<Value> {
let event = LidarrEvent::UpdateAndScanArtist(artist_id);
info!("Updating and scanning artist with ID: {artist_id}");
let body = LidarrCommandBody {
name: "RefreshArtist".to_owned(),
artist_id: Some(artist_id),
..LidarrCommandBody::default()
};
let request_props = self
.request_props_from(event, RequestMethod::Post, Some(body), None, None)
.await;
self
.handle_request::<LidarrCommandBody, Value>(request_props, |_, _| ())
.await
}
pub(in crate::network::lidarr_network) async fn trigger_automatic_artist_search(
&mut self,
artist_id: i64,
) -> Result<Value> {
let event = LidarrEvent::TriggerAutomaticArtistSearch(artist_id);
info!("Searching indexers for artist with ID: {artist_id}");
let body = LidarrCommandBody {
name: "ArtistSearch".to_owned(),
artist_id: Some(artist_id),
..LidarrCommandBody::default()
};
let request_props = self
.request_props_from(event, RequestMethod::Post, Some(body), None, None)
.await;
self
.handle_request::<LidarrCommandBody, Value>(request_props, |_, _| ())
.await
}
pub(in crate::network::lidarr_network) async fn search_artist(
&mut self,
query: String,
) -> Result<Vec<AddArtistSearchResult>> {
info!("Searching for artist: {query}");
let event = LidarrEvent::SearchNewArtist(String::new());
let request_props = self
.request_props_from(
event,
RequestMethod::Get,
None::<()>,
None,
Some(format!("term={}", encode(&query))),
)
.await;
let result = self
.handle_request::<(), Vec<AddArtistSearchResult>>(request_props, |artist_vec, mut app| {
if artist_vec.is_empty() {
app.pop_and_push_navigation_stack(ActiveLidarrBlock::AddArtistEmptySearchResults.into());
} else if let Some(add_searched_artists) =
app.data.lidarr_data.add_searched_artists.as_mut()
{
add_searched_artists.set_items(artist_vec);
} else {
let mut add_searched_artists = StatefulTable::default();
add_searched_artists.set_items(artist_vec);
app.data.lidarr_data.add_searched_artists = Some(add_searched_artists);
}
})
.await;
if result.is_err() {
self.app.lock().await.data.lidarr_data.add_searched_artists = Some(StatefulTable::default());
}
result
}
pub(in crate::network::lidarr_network) async fn add_artist(
&mut self,
mut add_artist_body: AddArtistBody,
) -> Result<Value> {
info!("Adding Lidarr artist: {}", add_artist_body.artist_name);
if let Some(tag_input_str) = add_artist_body.tag_input_string.as_ref() {
let tag_ids_vec = self.extract_and_add_lidarr_tag_ids_vec(tag_input_str).await;
add_artist_body.tags = tag_ids_vec;
}
let event = LidarrEvent::AddArtist(AddArtistBody::default());
let request_props = self
.request_props_from(
event,
RequestMethod::Post,
Some(add_artist_body),
None,
None,
)
.await;
self
.handle_request::<AddArtistBody, Value>(request_props, |_, _| ())
.await
}
pub(in crate::network::lidarr_network) async fn edit_artist(
&mut self,
mut edit_artist_params: EditArtistParams,
) -> Result<()> {
info!("Editing Lidarr artist");
if let Some(tag_input_str) = edit_artist_params.tag_input_string.as_ref() {
let tag_ids_vec = self.extract_and_add_lidarr_tag_ids_vec(tag_input_str).await;
edit_artist_params.tags = Some(tag_ids_vec);
}
let artist_id = edit_artist_params.artist_id;
let detail_event = LidarrEvent::GetArtistDetails(artist_id);
let event = LidarrEvent::EditArtist(EditArtistParams::default());
info!("Fetching artist details for artist with ID: {artist_id}");
let request_props = self
.request_props_from(
detail_event,
RequestMethod::Get,
None::<()>,
Some(format!("/{artist_id}")),
None,
)
.await;
let mut response = String::new();
self
.handle_request::<(), Value>(request_props, |detailed_artist_body, _| {
response = detailed_artist_body.to_string()
})
.await?;
info!("Constructing edit artist body");
let mut detailed_artist_body: Value = serde_json::from_str(&response)?;
let (
monitored,
monitor_new_items,
quality_profile_id,
metadata_profile_id,
root_folder_path,
tags,
) = {
let monitored = edit_artist_params.monitored.unwrap_or(
detailed_artist_body["monitored"]
.as_bool()
.expect("Unable to deserialize 'monitored'"),
);
let monitor_new_items = edit_artist_params.monitor_new_items.unwrap_or_else(|| {
serde_json::from_value(detailed_artist_body["monitorNewItems"].clone())
.expect("Unable to deserialize 'monitorNewItems'")
});
let quality_profile_id = edit_artist_params.quality_profile_id.unwrap_or_else(|| {
detailed_artist_body["qualityProfileId"]
.as_i64()
.expect("Unable to deserialize 'qualityProfileId'")
});
let metadata_profile_id = edit_artist_params.metadata_profile_id.unwrap_or_else(|| {
detailed_artist_body["metadataProfileId"]
.as_i64()
.expect("Unable to deserialize 'metadataProfileId'")
});
let root_folder_path = edit_artist_params.root_folder_path.unwrap_or_else(|| {
detailed_artist_body["path"]
.as_str()
.expect("Unable to deserialize 'path'")
.to_owned()
});
let tags = if edit_artist_params.clear_tags {
vec![]
} else {
edit_artist_params.tags.unwrap_or(
detailed_artist_body["tags"]
.as_array()
.expect("Unable to deserialize 'tags'")
.iter()
.map(|item| item.as_i64().expect("Unable to deserialize tag ID"))
.collect(),
)
};
(
monitored,
monitor_new_items,
quality_profile_id,
metadata_profile_id,
root_folder_path,
tags,
)
};
*detailed_artist_body.get_mut("monitored").unwrap() = json!(monitored);
*detailed_artist_body.get_mut("monitorNewItems").unwrap() = json!(monitor_new_items);
*detailed_artist_body.get_mut("qualityProfileId").unwrap() = json!(quality_profile_id);
*detailed_artist_body.get_mut("metadataProfileId").unwrap() = json!(metadata_profile_id);
*detailed_artist_body.get_mut("path").unwrap() = json!(root_folder_path);
*detailed_artist_body.get_mut("tags").unwrap() = json!(tags);
debug!("Edit artist body: {detailed_artist_body:?}");
let request_props = self
.request_props_from(
event,
RequestMethod::Put,
Some(detailed_artist_body),
Some(format!("/{artist_id}")),
None,
)
.await;
self
.handle_request::<Value, ()>(request_props, |_, _| ())
.await
}
}
+2 -356
View File
@@ -1,356 +1,2 @@
use anyhow::Result;
use log::{debug, info, warn};
use serde_json::{Value, json};
use crate::models::Route;
use crate::models::lidarr_models::{
AddArtistBody, AddArtistSearchResult, Artist, DeleteArtistParams, EditArtistParams,
};
use crate::models::servarr_data::lidarr::lidarr_data::ActiveLidarrBlock;
use crate::models::servarr_models::CommandBody;
use crate::models::stateful_table::StatefulTable;
use crate::network::lidarr_network::LidarrEvent;
use crate::network::{Network, RequestMethod};
use urlencoding::encode;
#[cfg(test)]
#[path = "lidarr_library_network_tests.rs"]
mod lidarr_library_network_tests;
impl Network<'_, '_> {
pub(in crate::network::lidarr_network) async fn delete_artist(
&mut self,
delete_artist_params: DeleteArtistParams,
) -> Result<()> {
let event = LidarrEvent::DeleteArtist(DeleteArtistParams::default());
let DeleteArtistParams {
id,
delete_files,
add_import_list_exclusion,
} = delete_artist_params;
info!(
"Deleting Lidarr artist with ID: {id} with deleteFiles={delete_files} and addImportListExclusion={add_import_list_exclusion}"
);
let request_props = self
.request_props_from(
event,
RequestMethod::Delete,
None::<()>,
Some(format!("/{id}")),
Some(format!(
"deleteFiles={delete_files}&addImportListExclusion={add_import_list_exclusion}"
)),
)
.await;
self
.handle_request::<(), ()>(request_props, |_, _| ())
.await
}
pub(in crate::network::lidarr_network) async fn list_artists(&mut self) -> Result<Vec<Artist>> {
info!("Fetching Lidarr artists");
let event = LidarrEvent::ListArtists;
let request_props = self
.request_props_from(event, RequestMethod::Get, None::<()>, None, None)
.await;
self
.handle_request::<(), Vec<Artist>>(request_props, |mut artists_vec, mut app| {
if !matches!(
app.get_current_route(),
Route::Lidarr(ActiveLidarrBlock::ArtistsSortPrompt, _)
) {
artists_vec.sort_by(|a, b| a.id.cmp(&b.id));
app.data.lidarr_data.artists.set_items(artists_vec);
app.data.lidarr_data.artists.apply_sorting_toggle(false);
}
})
.await
}
pub(in crate::network::lidarr_network) async fn get_artist_details(
&mut self,
artist_id: i64,
) -> Result<Artist> {
info!("Fetching details for Lidarr artist with ID: {artist_id}");
let event = LidarrEvent::GetArtistDetails(artist_id);
let request_props = self
.request_props_from(
event,
RequestMethod::Get,
None::<()>,
Some(format!("/{artist_id}")),
None,
)
.await;
self
.handle_request::<(), Artist>(request_props, |_, _| ())
.await
}
pub(in crate::network::lidarr_network) async fn toggle_artist_monitoring(
&mut self,
artist_id: i64,
) -> Result<()> {
let event = LidarrEvent::ToggleArtistMonitoring(artist_id);
let detail_event = LidarrEvent::GetArtistDetails(artist_id);
info!("Toggling artist monitoring for artist with ID: {artist_id}");
info!("Fetching artist details for artist with ID: {artist_id}");
let request_props = self
.request_props_from(
detail_event,
RequestMethod::Get,
None::<()>,
Some(format!("/{artist_id}")),
None,
)
.await;
let mut response = String::new();
self
.handle_request::<(), Value>(request_props, |detailed_artist_body, _| {
response = detailed_artist_body.to_string()
})
.await?;
info!("Constructing toggle artist monitoring body");
match serde_json::from_str::<Value>(&response) {
Ok(mut detailed_artist_body) => {
let monitored = detailed_artist_body
.get("monitored")
.unwrap()
.as_bool()
.unwrap();
*detailed_artist_body.get_mut("monitored").unwrap() = json!(!monitored);
debug!("Toggle artist monitoring body: {detailed_artist_body:?}");
let request_props = self
.request_props_from(
event,
RequestMethod::Put,
Some(detailed_artist_body),
Some(format!("/{artist_id}")),
None,
)
.await;
self
.handle_request::<Value, ()>(request_props, |_, _| ())
.await
}
Err(_) => {
warn!("Request for detailed artist body was interrupted");
Ok(())
}
}
}
pub(in crate::network::lidarr_network) async fn update_all_artists(&mut self) -> Result<Value> {
info!("Updating all artists");
let event = LidarrEvent::UpdateAllArtists;
let body = CommandBody {
name: "RefreshArtist".to_owned(),
};
let request_props = self
.request_props_from(event, RequestMethod::Post, Some(body), None, None)
.await;
self
.handle_request::<CommandBody, Value>(request_props, |_, _| ())
.await
}
pub(in crate::network::lidarr_network) async fn search_artist(
&mut self,
query: String,
) -> Result<Vec<AddArtistSearchResult>> {
info!("Searching for artist: {query}");
let event = LidarrEvent::SearchNewArtist(String::new());
let request_props = self
.request_props_from(
event,
RequestMethod::Get,
None::<()>,
None,
Some(format!("term={}", encode(&query))),
)
.await;
let result = self
.handle_request::<(), Vec<AddArtistSearchResult>>(request_props, |artist_vec, mut app| {
if artist_vec.is_empty() {
app.pop_and_push_navigation_stack(ActiveLidarrBlock::AddArtistEmptySearchResults.into());
} else if let Some(add_searched_artists) =
app.data.lidarr_data.add_searched_artists.as_mut()
{
add_searched_artists.set_items(artist_vec);
} else {
let mut add_searched_artists = StatefulTable::default();
add_searched_artists.set_items(artist_vec);
app.data.lidarr_data.add_searched_artists = Some(add_searched_artists);
}
})
.await;
if result.is_err() {
self.app.lock().await.data.lidarr_data.add_searched_artists = Some(StatefulTable::default());
}
result
}
pub(in crate::network::lidarr_network) async fn add_artist(
&mut self,
mut add_artist_body: AddArtistBody,
) -> Result<Value> {
info!("Adding Lidarr artist: {}", add_artist_body.artist_name);
if let Some(tag_input_str) = add_artist_body.tag_input_string.as_ref() {
let tag_ids_vec = self.extract_and_add_lidarr_tag_ids_vec(tag_input_str).await;
add_artist_body.tags = tag_ids_vec;
}
let event = LidarrEvent::AddArtist(AddArtistBody::default());
let request_props = self
.request_props_from(
event,
RequestMethod::Post,
Some(add_artist_body),
None,
None,
)
.await;
self
.handle_request::<AddArtistBody, Value>(request_props, |_, _| ())
.await
}
pub(in crate::network::lidarr_network) async fn edit_artist(
&mut self,
mut edit_artist_params: EditArtistParams,
) -> Result<()> {
info!("Editing Lidarr artist");
if let Some(tag_input_str) = edit_artist_params.tag_input_string.as_ref() {
let tag_ids_vec = self.extract_and_add_lidarr_tag_ids_vec(tag_input_str).await;
edit_artist_params.tags = Some(tag_ids_vec);
}
let artist_id = edit_artist_params.artist_id;
let detail_event = LidarrEvent::GetArtistDetails(artist_id);
let event = LidarrEvent::EditArtist(EditArtistParams::default());
info!("Fetching artist details for artist with ID: {artist_id}");
let request_props = self
.request_props_from(
detail_event,
RequestMethod::Get,
None::<()>,
Some(format!("/{artist_id}")),
None,
)
.await;
let mut response = String::new();
self
.handle_request::<(), Value>(request_props, |detailed_artist_body, _| {
response = detailed_artist_body.to_string()
})
.await?;
info!("Constructing edit artist body");
let mut detailed_artist_body: Value = serde_json::from_str(&response)?;
let (
monitored,
monitor_new_items,
quality_profile_id,
metadata_profile_id,
root_folder_path,
tags,
) = {
let monitored = edit_artist_params.monitored.unwrap_or(
detailed_artist_body["monitored"]
.as_bool()
.expect("Unable to deserialize 'monitored'"),
);
let monitor_new_items = edit_artist_params.monitor_new_items.unwrap_or_else(|| {
serde_json::from_value(detailed_artist_body["monitorNewItems"].clone())
.expect("Unable to deserialize 'monitorNewItems'")
});
let quality_profile_id = edit_artist_params.quality_profile_id.unwrap_or_else(|| {
detailed_artist_body["qualityProfileId"]
.as_i64()
.expect("Unable to deserialize 'qualityProfileId'")
});
let metadata_profile_id = edit_artist_params.metadata_profile_id.unwrap_or_else(|| {
detailed_artist_body["metadataProfileId"]
.as_i64()
.expect("Unable to deserialize 'metadataProfileId'")
});
let root_folder_path = edit_artist_params.root_folder_path.unwrap_or_else(|| {
detailed_artist_body["path"]
.as_str()
.expect("Unable to deserialize 'path'")
.to_owned()
});
let tags = if edit_artist_params.clear_tags {
vec![]
} else {
edit_artist_params.tags.unwrap_or(
detailed_artist_body["tags"]
.as_array()
.expect("Unable to deserialize 'tags'")
.iter()
.map(|item| item.as_i64().expect("Unable to deserialize tag ID"))
.collect(),
)
};
(
monitored,
monitor_new_items,
quality_profile_id,
metadata_profile_id,
root_folder_path,
tags,
)
};
*detailed_artist_body.get_mut("monitored").unwrap() = json!(monitored);
*detailed_artist_body.get_mut("monitorNewItems").unwrap() = json!(monitor_new_items);
*detailed_artist_body.get_mut("qualityProfileId").unwrap() = json!(quality_profile_id);
*detailed_artist_body.get_mut("metadataProfileId").unwrap() = json!(metadata_profile_id);
*detailed_artist_body.get_mut("path").unwrap() = json!(root_folder_path);
*detailed_artist_body.get_mut("tags").unwrap() = json!(tags);
debug!("Edit artist body: {detailed_artist_body:?}");
let request_props = self
.request_props_from(
event,
RequestMethod::Put,
Some(detailed_artist_body),
Some(format!("/{artist_id}")),
None,
)
.await;
self
.handle_request::<Value, ()>(request_props, |_, _| ())
.await
}
}
mod albums;
mod artists;
@@ -3,9 +3,9 @@
pub mod test_utils {
use crate::models::HorizontallyScrollableText;
use crate::models::lidarr_models::{
AddArtistSearchResult, Artist, ArtistStatistics, ArtistStatus, DownloadRecord, DownloadStatus,
DownloadsResponse, EditArtistParams, Member, MetadataProfile, NewItemMonitorType, Ratings,
SystemStatus,
AddArtistSearchResult, Album, AlbumStatistics, Artist, ArtistStatistics, ArtistStatus,
DownloadRecord, DownloadStatus, DownloadsResponse, EditArtistParams, Member, MetadataProfile,
NewItemMonitorType, Ratings, SystemStatus,
};
use crate::models::servarr_models::{QualityProfile, RootFolder, Tag};
use bimap::BiMap;
@@ -50,6 +50,27 @@ pub mod test_utils {
"percentOfTracks": 99.9
}
}"#;
pub const ALBUM_JSON: &str = r#"{
"id": 1,
"title": "Test Album",
"foreignAlbumId": "test-foreign-album-id",
"monitored": true,
"anyReleaseOk": true,
"profileId": 1,
"duration": 180,
"albumType": "Album",
"genres": ["Classical"],
"ratings": {"votes": 15, "value": 8.4},
"releaseDate": "2023-01-01T00:00:00Z",
"statistics": {
"trackFileCount": 10,
"trackCount": 10,
"totalTrackCount": 10,
"sizeOnDisk": 1024,
"percentOfTracks": 99.9
}
}"#;
pub fn member() -> Member {
Member {
@@ -199,4 +220,33 @@ pub mod test_utils {
ratings: Some(ratings()),
}
}
pub fn album_statistics() -> AlbumStatistics {
AlbumStatistics {
track_file_count: 10,
track_count: 10,
total_track_count: 10,
size_on_disk: 1024,
percent_of_tracks: 99.9,
}
}
pub fn album() -> Album {
Album {
id: 1,
title: "Test Album".into(),
foreign_album_id: "test-foreign-album-id".to_string(),
monitored: true,
any_release_ok: true,
profile_id: 1,
duration: 180,
album_type: Some("Album".to_owned()),
genres: vec!["Classical".to_owned()],
ratings: Some(ratings()),
release_date: Some(DateTime::from(
DateTime::parse_from_rfc3339("2023-01-01T00:00:00Z").unwrap(),
)),
statistics: Some(album_statistics()),
}
}
}
@@ -46,10 +46,24 @@ mod tests {
}
#[rstest]
fn test_resource_command(#[values(LidarrEvent::UpdateAllArtists)] event: LidarrEvent) {
fn test_resource_command(
#[values(
LidarrEvent::UpdateAllArtists,
LidarrEvent::TriggerAutomaticArtistSearch(0),
LidarrEvent::UpdateAndScanArtist(0)
)]
event: LidarrEvent,
) {
assert_str_eq!(event.resource(), "/command");
}
#[rstest]
fn test_resource_albums(
#[values(LidarrEvent::GetAlbums(0), LidarrEvent::ToggleAlbumMonitoring(0), LidarrEvent::GetAlbumDetails(0))] event: LidarrEvent,
) {
assert_str_eq!(event.resource(), "/album");
}
#[rstest]
#[case(LidarrEvent::GetDiskSpace, "/diskspace")]
#[case(LidarrEvent::GetDownloads(500), "/queue")]
+25 -1
View File
@@ -28,6 +28,8 @@ pub enum LidarrEvent {
DeleteArtist(DeleteArtistParams),
DeleteTag(i64),
EditArtist(EditArtistParams),
GetAlbums(i64),
GetAlbumDetails(i64),
GetArtistDetails(i64),
GetDiskSpace,
GetDownloads(u64),
@@ -41,8 +43,11 @@ pub enum LidarrEvent {
HealthCheck,
ListArtists,
SearchNewArtist(String),
ToggleAlbumMonitoring(i64),
ToggleArtistMonitoring(i64),
TriggerAutomaticArtistSearch(i64),
UpdateAllArtists,
UpdateAndScanArtist(i64),
}
impl NetworkResource for LidarrEvent {
@@ -55,10 +60,13 @@ impl NetworkResource for LidarrEvent {
| LidarrEvent::ListArtists
| LidarrEvent::AddArtist(_)
| LidarrEvent::ToggleArtistMonitoring(_) => "/artist",
LidarrEvent::GetAlbums(_) | LidarrEvent::ToggleAlbumMonitoring(_) | LidarrEvent::GetAlbumDetails(_) => "/album",
LidarrEvent::GetDiskSpace => "/diskspace",
LidarrEvent::GetDownloads(_) => "/queue",
LidarrEvent::GetHostConfig | LidarrEvent::GetSecurityConfig => "/config/host",
LidarrEvent::UpdateAllArtists => "/command",
LidarrEvent::TriggerAutomaticArtistSearch(_)
| LidarrEvent::UpdateAllArtists
| LidarrEvent::UpdateAndScanArtist(_) => "/command",
LidarrEvent::GetMetadataProfiles => "/metadataprofile",
LidarrEvent::GetQualityProfiles => "/qualityprofile",
LidarrEvent::GetRootFolders => "/rootfolder",
@@ -89,10 +97,14 @@ impl Network<'_, '_> {
.delete_lidarr_tag(tag_id)
.await
.map(LidarrSerdeable::from),
LidarrEvent::GetAlbums(artist_id) => {
self.get_albums(artist_id).await.map(LidarrSerdeable::from)
}
LidarrEvent::GetArtistDetails(artist_id) => self
.get_artist_details(artist_id)
.await
.map(LidarrSerdeable::from),
LidarrEvent::GetAlbumDetails(album_id) => self.get_album_details(album_id).await.map(LidarrSerdeable::from),
LidarrEvent::GetDiskSpace => self.get_lidarr_diskspace().await.map(LidarrSerdeable::from),
LidarrEvent::GetDownloads(count) => self
.get_lidarr_downloads(count)
@@ -128,11 +140,23 @@ impl Network<'_, '_> {
LidarrEvent::SearchNewArtist(query) => {
self.search_artist(query).await.map(LidarrSerdeable::from)
}
LidarrEvent::ToggleAlbumMonitoring(album_id) => self
.toggle_album_monitoring(album_id)
.await
.map(LidarrSerdeable::from),
LidarrEvent::ToggleArtistMonitoring(artist_id) => self
.toggle_artist_monitoring(artist_id)
.await
.map(LidarrSerdeable::from),
LidarrEvent::TriggerAutomaticArtistSearch(artist_id) => self
.trigger_automatic_artist_search(artist_id)
.await
.map(LidarrSerdeable::from),
LidarrEvent::UpdateAllArtists => self.update_all_artists().await.map(LidarrSerdeable::from),
LidarrEvent::UpdateAndScanArtist(artist_id) => self
.update_and_scan_artist(artist_id)
.await
.map(LidarrSerdeable::from),
LidarrEvent::EditArtist(params) => self.edit_artist(params).await.map(LidarrSerdeable::from),
LidarrEvent::AddArtist(body) => self.add_artist(body).await.map(LidarrSerdeable::from),
}