diff --git a/docs/manual/using-lumina/index.md b/docs/manual/using-lumina/index.md index 02d614a0..28e501b8 100644 --- a/docs/manual/using-lumina/index.md +++ b/docs/manual/using-lumina/index.md @@ -68,7 +68,7 @@ Book libraries track consumption progress by default. Reopening a book continues ## Browsing your music -Opening a music library shows a page with the library title, a search box, a sort toggle, a count of items, a grid of artist cards, an alphabetical picker down the side, and pagination at the bottom. +Opening a music library shows a page with the library title, a search box, a sort toggle, a count of items, a **Deleted items** button, a grid of artist cards, an alphabetical picker down the side, and pagination at the bottom. - **Search** filters the artists by name; press Enter or use the search button. - **Sort** toggles between ascending and descending order. @@ -77,7 +77,9 @@ Opening a music library shows a page with the library title, a search box, a sor Each artist is a card; selecting it opens the artist's page, and the card's actions menu offers **View details**, **Play**, **Shuffle**, **Add to playlist** and **Delete**. The heart on the card marks the artist as a favorite. -The artist page is also where you edit the artist. It lists the artist's albums as cards, each leading to its own album page, followed by the artist's general information, contributors, ratings, genres, tags, aliases, areas and identifiers. The album page holds the album's information and its tracks, and the track page holds the track's details. The album page also shows the artwork Lumina stored for the album as a strip of thumbnails beside the main image, and selecting a thumbnail displays that image in place of the cover. Deleting an artist, album or track removes it from Lumina's catalogue; your files are not touched. +The artist page is also where you edit the artist. It lists the artist's albums as cards, each leading to its own album page, followed by the artist's general information, contributors, ratings, genres, tags, aliases, areas and identifiers. The album page holds the album's information and its tracks, and the track page holds the track's details. The album page also shows the artwork Lumina stored for the album as a strip of thumbnails beside the main image, and selecting a thumbnail displays that image in place of the cover. + +Deleting an artist, album or track asks for confirmation and moves it to the library's **Deleted items**, together with the metadata and artwork Lumina stored for it. The file behind it is left untouched. The item stops appearing in the library, and an automatic scan does not add it back. An artist always keeps at least one album, so the last album of an artist cannot be deleted. If a file is later removed from disk, the next scan permanently removes the deleted track, including its stored artwork, and the albums and artists left with no files, including their stored artwork. The **Deleted items** button on the artists page lists the deleted artists, albums and tracks, and restores one when you select **Restore**. Restoring an artist or an album brings back the items inside it that were not deleted on their own. The music pages also play what they show. The artist page has a **Play all** control that plays the artist's releases in the order the page presents them, one release after another. The actions menu of a music library card on the home page, of an artist card, and of an album card offers **Play** and **Shuffle**. Play starts the library at its first artist and continues through the remaining artists in artist page order, starts the artist's discography in the order the artist page presents it, or starts the release in disc and track order. Shuffle starts the library, the artist's discography or the release with a list of up to 100 tracks sampled uniformly at random from every track of that scope, and continues in random order without repeating a track that is already queued. The album page has a **Play album** control that plays the release in disc and track order, and every track row has its own play control that plays just that track. The track page has a **Play track** control for the track it shows. Every track row on the album page also has an actions menu: **Add to playlist** opens the playlist picker for that track, **Add to play queue** appends it to the end of the player queue or starts it when the queue is empty, and **Play all from here** replaces the queue with that track and the rest of the album and starts playing. Starting playback opens the player bar at the bottom of the window. It keeps playing while you move between pages, and the bar shows the track name, with the album name underneath when the track belongs to a named album, the progress of the current track, a segmented VU meter that follows the level of the track, and the volume, together with previous, play or pause, stop, next and repeat controls. When you expand it, it also shows the cover art, the current track name, the release type, the release name and year, the artist name, and a carousel of the album's stored artwork, next to the queue, where every entry carries its album cover, including when only one track is queued. Selecting an artwork in the carousel shows it as the main cover. The expanded queue moves the current track to the top whenever playback advances, so it stays visible even in a long list. The current track's favorite is the heart on the bar between the repeat and mute controls, and every entry of the expanded queue carries its own heart. The queue's own playlist picker appends the whole queue, in order, to one of your playlists. The double chevron at the right points up to expand the bar and down to collapse it. Stop is the square control next to play or pause; in the condensed bar it stops playback and slides the bar out of view. diff --git a/docs/technical/api/favorites/Api.Favorites.md b/docs/technical/api/favorites/Api.Favorites.md index 733c5c00..7b132e47 100644 --- a/docs/technical/api/favorites/Api.Favorites.md +++ b/docs/technical/api/favorites/Api.Favorites.md @@ -137,7 +137,7 @@ Returns the favorites of the current user, from the most recently favorited. The "collectionTitle": "A Night at the Opera", "creatorId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", "creatorName": "Queen", - "coverPath": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg" + "coverPath": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/A Night at the Opera-e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg" }, { "mediaKind": "Book", diff --git a/docs/technical/api/library/audio-library/music-library/Api.Albums.md b/docs/technical/api/library/audio-library/music-library/Api.Albums.md index c69b3693..e9e02fd5 100644 --- a/docs/technical/api/library/audio-library/music-library/Api.Albums.md +++ b/docs/technical/api/library/audio-library/music-library/Api.Albums.md @@ -27,6 +27,12 @@ - [Get Album Tracks Lite](#get-album-tracks-lite) - [Get Album Tracks Lite Request](#get-album-tracks-lite-request) - [Get Album Tracks Lite Response](#get-album-tracks-lite-response) + - [Get Deleted Albums](#get-deleted-albums) + - [Get Deleted Albums Request](#get-deleted-albums-request) + - [Get Deleted Albums Response](#get-deleted-albums-response) + - [Restore Album](#restore-album) + - [Restore Album Request](#restore-album-request) + - [Restore Album Response](#restore-album-response) ## Album @@ -531,12 +537,12 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b ] } ], - "coverPath": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg", + "coverPath": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/A Night at the Opera-e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg", "artwork": [ { "type": "Cover", "ordinal": 0, - "path": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg" + "path": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/A Night at the Opera-e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg" } ] } @@ -797,12 +803,12 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- ] } ], - "coverPath": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg", + "coverPath": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/A Night at the Opera-e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg", "artwork": [ { "type": "Cover", "ordinal": 0, - "path": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg" + "path": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/A Night at the Opera-e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg" } ] } @@ -836,7 +842,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "id": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "title": "A Night at the Opera", "totalTracks": 12, - "coverPath": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg", + "coverPath": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/A Night at the Opera-e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg", "releaseYear": 1975, "releaseTypes": [ "Album" ] } @@ -1102,12 +1108,12 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- ] } ], - "coverPath": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg", + "coverPath": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/A Night at the Opera-e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg", "artwork": [ { "type": "Cover", "ordinal": 0, - "path": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg" + "path": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/A Night at the Opera-e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg" }, { "type": "Back", @@ -1447,12 +1453,12 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- ] } ], - "coverPath": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg", + "coverPath": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/A Night at the Opera-e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg", "artwork": [ { "type": "Cover", "ordinal": 0, - "path": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg" + "path": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/A Night at the Opera-e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg" } ] } @@ -1484,7 +1490,7 @@ Content-Type: image/jpeg ```json { - "coverPath": "/media/music/music-3f2504e0-4f89-41d3-9a0c-0305e82c3301/Queen-2b0e5f5a-0b3f-4b7e-8f4a-8c9e3d2f5a6b/A Night at the Opera-7c1d2e3f-4a5b-6c7d-8e9f-0a1b2c3d4e5f/cover.jpg" + "coverPath": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/A Night at the Opera-e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg" } ``` @@ -1499,7 +1505,7 @@ DELETE api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f 200 Ok ``` -Deletes the album identified by the route, together with its tracks. An artist must always keep at least one album. +Soft deletes the album identified by the route. The stored metadata, artwork and track paths are kept, so the album can be restored, and its tracks stay reserved, so a scan does not add them back. The album is hidden until it is restored. An artist must always keep at least one album, so the last album of an artist cannot be deleted and the request fails with a forbidden problem. ### Get Album Tracks @@ -1643,3 +1649,51 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- "numberOfPages": 1 } ``` + + +### Get Deleted Albums + +#### Get Deleted Albums Request + +```js +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/albums/deleted-items +``` + +#### Get Deleted Albums Response + +```js +200 Ok +``` + +```json +[ + { + "id": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "artistId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", + "artistName": "Queen", + "title": "A Night at the Opera", + "deletedOnUtc": "2026-11-14T18:35:00Z", + "coverPath": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d/A Night at the Opera-b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e/cover.jpg" + } +] +``` + +An album whose artist is also deleted is not returned until the artist is restored. + + +### Restore Album + +#### Restore Album Request + +```js +POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/{albumId}/restore +``` + +#### Restore Album Response + +```js +200 Ok +``` + +Restores the deleted album identified by the route, together with its stored metadata, artwork and the tracks that were not deleted on their own. diff --git a/docs/technical/api/library/audio-library/music-library/Api.Artists.md b/docs/technical/api/library/audio-library/music-library/Api.Artists.md index fec7c403..acbbf079 100644 --- a/docs/technical/api/library/audio-library/music-library/Api.Artists.md +++ b/docs/technical/api/library/audio-library/music-library/Api.Artists.md @@ -21,6 +21,12 @@ - [Update Artist Cover Request](#update-artist-cover-request) - [Update Artist Cover Response](#update-artist-cover-response) - [Delete Artist](#delete-artist) + - [Get Deleted Artists](#get-deleted-artists) + - [Get Deleted Artists Request](#get-deleted-artists-request) + - [Get Deleted Artists Response](#get-deleted-artists-response) + - [Restore Artist](#restore-artist) + - [Restore Artist Request](#restore-artist-request) + - [Restore Artist Response](#restore-artist-response) ## Artist @@ -672,17 +678,17 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists ] } ], - "coverPath": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg", + "coverPath": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/A Night at the Opera-e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg", "artwork": [ { "type": "Cover", "ordinal": 0, - "path": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg" + "path": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/A Night at the Opera-e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg" } ] } ], - "coverPath": "/media/music/Queen-3b3a19f3/cover.jpg" + "coverPath": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/cover.jpg" } ``` @@ -1021,17 +1027,17 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists?currentPage=1& ] } ], - "coverPath": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg", + "coverPath": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/A Night at the Opera-e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg", "artwork": [ { "type": "Cover", "ordinal": 0, - "path": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg" + "path": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/A Night at the Opera-e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg" } ] } ], - "coverPath": "/media/music/Queen-3b3a19f3/cover.jpg" + "coverPath": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/cover.jpg" } ], "currentPage": 1, @@ -1072,7 +1078,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/lite?currentPa { "id": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", "name": "Queen", - "coverPath": "/media/music/Queen-3b3a19f3/cover.jpg" + "coverPath": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/cover.jpg" } ], "currentPage": 1, @@ -1410,17 +1416,17 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} ] } ], - "coverPath": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg", + "coverPath": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/A Night at the Opera-e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg", "artwork": [ { "type": "Cover", "ordinal": 0, - "path": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg" + "path": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/A Night at the Opera-e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg" } ] } ], - "coverPath": "/media/music/Queen-3b3a19f3/cover.jpg" + "coverPath": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/cover.jpg" } ``` @@ -2076,17 +2082,17 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} ] } ], - "coverPath": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg", + "coverPath": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/A Night at the Opera-e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg", "artwork": [ { "type": "Cover", "ordinal": 0, - "path": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg" + "path": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/A Night at the Opera-e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg" } ] } ], - "coverPath": "/media/music/Queen-3b3a19f3/cover.jpg" + "coverPath": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/cover.jpg" } ``` @@ -2116,7 +2122,7 @@ Content-Type: image/jpeg ```json { - "coverPath": "/media/music/music-3f2504e0-4f89-41d3-9a0c-0305e82c3301/Queen-2b0e5f5a-0b3f-4b7e-8f4a-8c9e3d2f5a6b/cover.jpg" + "coverPath": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/cover.jpg" } ``` @@ -2131,4 +2137,48 @@ DELETE api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} 200 Ok ``` -Deletes the artist identified by the route, together with its albums and tracks. +Soft deletes the artist identified by the route. The stored metadata, artwork, albums and tracks are kept, so the artist can be restored, and their paths stay reserved, so a scan does not add them back. + + +### Get Deleted Artists + +#### Get Deleted Artists Request + +```js +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/deleted-items +``` + +#### Get Deleted Artists Response + +```js +200 Ok +``` + +```json +[ + { + "id": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "name": "Queen", + "deletedOnUtc": "2026-11-14T18:35:00Z", + "coverPath": "/media/music/music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/Queen-a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d/cover.jpg" + } +] +``` + + +### Restore Artist + +#### Restore Artist Request + +```js +POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId}/restore +``` + +#### Restore Artist Response + +```js +200 Ok +``` + +Restores the deleted artist identified by the route, together with its stored metadata, artwork and the albums and tracks that were not deleted on their own. An artist cannot be restored when a visible artist with the same name already exists in the library. diff --git a/docs/technical/api/library/audio-library/music-library/Api.Tracks.md b/docs/technical/api/library/audio-library/music-library/Api.Tracks.md index 6e8fe848..07dd247e 100644 --- a/docs/technical/api/library/audio-library/music-library/Api.Tracks.md +++ b/docs/technical/api/library/audio-library/music-library/Api.Tracks.md @@ -24,6 +24,12 @@ - [Update Track Request](#update-track-request) - [Update Track Response](#update-track-response) - [Delete Track](#delete-track) + - [Get Deleted Tracks](#get-deleted-tracks) + - [Get Deleted Tracks Request](#get-deleted-tracks-request) + - [Get Deleted Tracks Response](#get-deleted-tracks-response) + - [Restore Track](#restore-track) + - [Restore Track Request](#restore-track-request) + - [Restore Track Response](#restore-track-response) ## Track @@ -360,7 +366,7 @@ Returns a uniformly random selection of tracks from every track of the library, "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "albumTitle": "A Night at the Opera", "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", - "coverPath": "\\media\\music\\music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a\\QUEEN\\Album\\A night at the opera-e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f\\cover.jpg" + "coverPath": "\\media\\music\\music-3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a\\Queen-d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a\\Album\\A night at the opera-e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f\\cover.jpg" } ] ``` @@ -688,4 +694,54 @@ DELETE api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f 200 Ok ``` -Deletes the track identified by the route. +Soft deletes the track identified by the route. The stored metadata, artwork and file path are kept, so the track can be restored, and its path stays reserved, so a scan does not add it back. + + +### Get Deleted Tracks + +#### Get Deleted Tracks Request + +```js +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/tracks/deleted-items +``` + +#### Get Deleted Tracks Response + +```js +200 Ok +``` + +```json +[ + { + "id": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "artistId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", + "artistName": "Queen", + "albumId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", + "albumTitle": "A Night at the Opera", + "title": "Bohemian Rhapsody", + "path": "/music/queen/a-night-at-the-opera/01 - Bohemian Rhapsody.flac", + "deletedOnUtc": "2026-11-14T18:35:00Z" + } +] +``` + +A track whose album or artist is also deleted is not returned until the album and the artist are restored. + + +### Restore Track + +#### Restore Track Request + +```js +POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/{trackId}/restore +``` + +#### Restore Track Response + +```js +200 Ok +``` + +Restores the deleted track identified by the route, together with its stored metadata and artwork. diff --git a/docs/technical/requests/library/audio-library/music-library/albums/GetDeletedAlbums.http b/docs/technical/requests/library/audio-library/music-library/albums/GetDeletedAlbums.http new file mode 100644 index 00000000..7ebc0cf9 --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/albums/GetDeletedAlbums.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/albums/deleted-items +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/audio-library/music-library/albums/RestoreAlbum.http b/docs/technical/requests/library/audio-library/music-library/albums/RestoreAlbum.http new file mode 100644 index 00000000..5d2d5c51 --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/albums/RestoreAlbum.http @@ -0,0 +1,2 @@ +POST {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{{$guid}}/albums/{{$guid}}/restore +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/audio-library/music-library/artists/GetDeletedArtists.http b/docs/technical/requests/library/audio-library/music-library/artists/GetDeletedArtists.http new file mode 100644 index 00000000..ce93eee9 --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/artists/GetDeletedArtists.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/deleted-items +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/audio-library/music-library/artists/RestoreArtist.http b/docs/technical/requests/library/audio-library/music-library/artists/RestoreArtist.http new file mode 100644 index 00000000..78e4a090 --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/artists/RestoreArtist.http @@ -0,0 +1,2 @@ +POST {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{{$guid}}/restore +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/audio-library/music-library/tracks/GetDeletedTracks.http b/docs/technical/requests/library/audio-library/music-library/tracks/GetDeletedTracks.http new file mode 100644 index 00000000..1626a1ca --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/tracks/GetDeletedTracks.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/tracks/deleted-items +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/audio-library/music-library/tracks/RestoreTrack.http b/docs/technical/requests/library/audio-library/music-library/tracks/RestoreTrack.http new file mode 100644 index 00000000..8266fa47 --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/tracks/RestoreTrack.http @@ -0,0 +1,2 @@ +POST {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{{$guid}}/albums/{{$guid}}/tracks/{{$guid}}/restore +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/theming/Theming.md b/docs/technical/theming/Theming.md index 5de9e49f..3cc92304 100644 --- a/docs/technical/theming/Theming.md +++ b/docs/technical/theming/Theming.md @@ -86,7 +86,7 @@ The manifest is a JSON object describing the theme. The example below is the man "name": "Editorial Paper", "description": "A clean, readable proof of concept theme.", "author": "Lumina", - "version": "1.5.61", + "version": "1.6.0", "preview": "assets/preview.svg", "templates": { "default": "templates/index.html" @@ -180,6 +180,7 @@ Known page keys: | `shared/audio-player/playlist-item` | The playlist item of the audio player bar. | | `library/written-content-library/book-library/books/index` | The books browsing page. | | `library/written-content-library/book-library/books/deleted-items` | The deleted items page of a book library, which restores deleted books. | +| `library/audio-library/music-library/deleted-items` | The deleted items page of a music library, which restores deleted artists, albums and tracks. | | `playlists/index` | The page that lists and deletes the playlists of the current user. | | `playlists/item` | The page that creates a playlist, or edits, reorders, plays and deletes an existing playlist of the current user. The `isNew` page data field tells the two modes apart. | | `favorites/index` | The page that lists, filters and removes the favorites of the current user across media kinds. | @@ -621,6 +622,42 @@ The page script drives these hooks: A theme that provides this page must keep these hooks and render the anti-forgery token, or reimplement the restore behavior itself. +#### The Music Deleted Items Page + +`library/audio-library/music-library/deleted-items` lists the artists, albums and tracks that were deleted from a music library and lets the user restore them. Its fallback is `Core/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.cshtml`. The bundled themes ship their own `templates/library/audio-library/music-library/deleted-items.html`; when a theme has no template for the page, the application renders the fallback view. + +Template resolution walks up the path scopes, so a theme that ships `templates/library/audio-library/music-library.html` without a `deleted-items.html` would render that parent template for this page. A theme that provides a music library parent template must also provide the deleted items template. + +Page data: + +| Field | Content | +| --- | --- | +| `libraryId` | The Id of the library whose deleted music items are listed. | +| `libraryTitle` | The title of that library. | +| `deletedArtistsJson` | The deleted artists, serialized as a JSON array. Each item carries `id`, `libraryId`, `name`, `deletedOnUtc` and `coverPath`. | +| `deletedAlbumsJson` | The deleted albums, serialized as a JSON array. Each item carries `id`, `libraryId`, `artistId`, `artistName`, `title`, `deletedOnUtc` and `coverPath`. | +| `deletedTracksJson` | The deleted tracks, serialized as a JSON array. Each item carries `id`, `libraryId`, `artistId`, `artistName`, `albumId`, `albumTitle`, `title`, `path` and `deletedOnUtc`. | +| `artistRestoreUrl` | The route template that restores a deleted artist. The trailing `00000000-0000-0000-0000-000000000000` is replaced by the Id of the artist, and `libraryId` is appended as a query parameter. | +| `albumRestoreUrl` | The route template that restores a deleted album. Its two `00000000-0000-0000-0000-000000000000` segments are replaced, in order, by the Id of the artist and the Id of the album, and `libraryId` is appended as a query parameter. | +| `trackRestoreUrl` | The route template that restores a deleted track. Its three `00000000-0000-0000-0000-000000000000` segments are replaced, in order, by the Id of the artist, the Id of the album and the Id of the track, and `libraryId` is appended as a query parameter. | +| `backUrl` | The route of the artists page of the library. | +| `antiforgeryToken` | The anti-forgery request token for the restore POST. | +| `strings` | The localized strings of the page, keyed by their resource names. | +| `stringsJson` | The same localized strings serialized as JSON, with camel case keys, for the page script. | + +The page script drives these hooks: + +| Hook | Purpose | +| --- | --- | +| `btn-back-to-library` | Returns to the artists page of the library. | +| `deleted-artists-table`, `deleted-albums-table` and `deleted-tracks-table` | Hold the deleted artists, albums and tracks. The restore click handler is bound at the document level. | +| `no-deleted-music-items` | The empty state, shown when no deleted music items remain. | +| `.deleted-music-item-row` | A deleted music item row, carrying its kind in `data-row-type` and the Ids it needs to restore in `data-artist-id`, `data-album-id` and `data-track-id`. Removed after a successful restore. | +| `.btn-restore-artist`, `.btn-restore-album` and `.btn-restore-track` | The restore button of a row, carrying the same Ids as its row. | +| `input[name="__RequestVerificationToken"]` | The anti-forgery token that the restore POST sends. | + +A theme that provides this page must keep these hooks and render the anti-forgery token, or reimplement the restore behavior itself. The `library/audio-library/music-library/artists/index` page supplies a `deletedItemsUrl` page data field with the route of this page, and the artists page template must also provide the `deleted-items-button` hook when it wants to link to it. The page reads the library from the `libraryId` query parameter, so a theme that links to `deletedItemsUrl` must append `?libraryId=` with the Id of the library, as the application template does; the route alone lands on the home page. + #### The Playlist Pages `playlists/index` receives a model with the following fields: diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumEntity.cs index c42bbf90..ae33e664 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumEntity.cs @@ -231,6 +231,17 @@ public class AlbumEntity : IStorageEntity, IAuditableEntity /// public string? MetadataProvider { get; set; } + /// + /// Gets or sets a value indicating whether the album was deleted by the user and is waiting to be restored or permanently removed. + /// A deleted album is kept out of every catalogue read and is not materialized again by scans, so that an automatic scan never undoes the deletion. + /// + public bool IsDeleted { get; set; } + + /// + /// Gets or sets the date and time when the album was deleted, or when the album is not deleted. + /// + public DateTime? DeletedOnUtc { get; set; } + /// /// Gets or sets the time and date when the entity was added. /// diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistEntity.cs index 380683c4..7e884880 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistEntity.cs @@ -150,6 +150,17 @@ public class ArtistEntity : IStorageEntity, IAuditableEntity /// public string? MetadataProvider { get; set; } + /// + /// Gets or sets a value indicating whether the artist was deleted by the user and is waiting to be restored or permanently removed. + /// A deleted artist is kept out of every catalogue read and is not materialized again by scans, so that an automatic scan never undoes the deletion. + /// + public bool IsDeleted { get; set; } + + /// + /// Gets or sets the date and time when the artist was deleted, or when the artist is not deleted. + /// + public DateTime? DeletedOnUtc { get; set; } + /// /// Gets or sets the time and date when the entity was added. /// diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntity.cs index 246685ca..a052cba3 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntity.cs @@ -291,6 +291,17 @@ public class TrackEntity : IStorageEntity, IAuditableEntity /// public string? MetadataProvider { get; set; } + /// + /// Gets or sets a value indicating whether the track was deleted by the user and is waiting to be restored or permanently removed. + /// A deleted track is kept out of every catalogue read and is not materialized again by scans, so that an automatic scan never undoes the deletion. + /// + public bool IsDeleted { get; set; } + + /// + /// Gets or sets the date and time when the track was deleted, or when the track is not deleted. + /// + public DateTime? DeletedOnUtc { get; set; } + /// /// Gets or sets the time and date when the entity was added. /// diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IAlbumRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IAlbumRepository.cs index 4ad209be..d72e9edd 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IAlbumRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IAlbumRepository.cs @@ -24,13 +24,61 @@ public interface IAlbumRepository : IRepository, IDeleteByIdRepositoryAction { /// - /// Gets all the albums of the artist identified by . + /// Gets the albums of the artist identified by that are not soft deleted. /// /// The Id of the artist whose albums are retrieved. /// Cancellation token that can be used to stop the execution. /// An containing either a collection of , or an error. Task>> GetByArtistIdAsync(Guid artistId, CancellationToken cancellationToken); + /// + /// Gets all the albums of the artist identified by , whether they are soft deleted or not. + /// + /// The Id of the artist whose albums are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + Task>> GetByArtistIdIncludingDeletedAsync(Guid artistId, CancellationToken cancellationToken); + + /// + /// Gets the album identified by , whether it is soft deleted or not, without loading its navigation properties. + /// + /// The Id of the album to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either the , or an error. + Task> GetIncludingDeletedByIdAsync(Guid id, CancellationToken cancellationToken); + + /// + /// Gets the soft deleted album identified by , when its artist is not soft deleted. + /// + /// The Id of the soft deleted album to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either the soft deleted , when the album does not exist, is not soft deleted, or its artist is soft deleted, or an error. + Task> GetSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken); + + /// + /// Gets the soft deleted albums of the media library identified by , whose artist is not soft deleted. + /// + /// The Id of the media library whose soft deleted albums are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the soft deleted albums, or an error. + Task>> GetSoftDeletedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Soft deletes the album identified by , without removing its stored metadata or artwork, when another visible album of its artist remains. + /// + /// The Id of the album to soft delete. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> SoftDeleteByIdAsync(Guid id, CancellationToken cancellationToken); + + /// + /// Restores the soft deleted album identified by . + /// + /// The Id of the album to restore. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> RestoreSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken); + /// /// Gets the lightweight read models of the albums of the artist identified by , projecting only the fields needed to display the albums in a card-based grid or a list. /// diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IArtistRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IArtistRepository.cs index b1aed090..b3f2235f 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IArtistRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IArtistRepository.cs @@ -86,4 +86,36 @@ public interface IArtistRepository : IRepository, /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. Task> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Gets the soft deleted artist identified by . + /// + /// The Id of the soft deleted artist to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either the soft deleted , when the artist does not exist or is not soft deleted, or an error. + Task> GetSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken); + + /// + /// Gets the soft deleted artists of the media library identified by . + /// + /// The Id of the media library whose soft deleted artists are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the soft deleted artists, or an error. + Task>> GetSoftDeletedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Soft deletes the artist identified by , without removing its stored metadata or artwork. + /// + /// The Id of the artist to soft delete. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> SoftDeleteByIdAsync(Guid id, CancellationToken cancellationToken); + + /// + /// Restores the soft deleted artist identified by . + /// + /// The Id of the artist to restore. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> RestoreSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs index ce7ebd7d..de7c1d97 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs @@ -33,13 +33,21 @@ public interface ITrackRepository : IRepository, Task>> GetExistingPathsAsync(Guid libraryId, IReadOnlyCollection paths, CancellationToken cancellationToken); /// - /// Gets all the tracks of the album identified by . + /// Gets the tracks of the album identified by that are not soft deleted. /// /// The Id of the album whose tracks are retrieved. /// Cancellation token that can be used to stop the execution. /// An containing either a collection of , or an error. Task>> GetByAlbumIdAsync(Guid albumId, CancellationToken cancellationToken); + /// + /// Gets all the tracks of the album identified by , whether they are soft deleted or not. + /// + /// The Id of the album whose tracks are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + Task>> GetByAlbumIdIncludingDeletedAsync(Guid albumId, CancellationToken cancellationToken); + /// /// Gets the lightweight read models of the tracks of the album identified by , projecting only the fields needed to display the tracks of an album. /// @@ -146,4 +154,36 @@ public interface ITrackRepository : IRepository, /// Cancellation token that can be used to stop the execution. /// An containing either the existing tracks, or an error. Task>> GetByIdsAsync(IReadOnlyCollection trackIds, bool shouldIncludeNavigationProperties, CancellationToken cancellationToken); + + /// + /// Gets the soft deleted track identified by , when its album and artist are not soft deleted. + /// + /// The Id of the soft deleted track to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either the soft deleted , when the track does not exist, is not soft deleted, or its album or artist is soft deleted, or an error. + Task> GetSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken); + + /// + /// Gets the soft deleted tracks of the media library identified by , whose album and artist are not soft deleted. + /// + /// The Id of the media library whose soft deleted tracks are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the soft deleted tracks, or an error. + Task>> GetSoftDeletedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Soft deletes the track identified by , without removing its stored metadata or artwork. + /// + /// The Id of the track to soft delete. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> SoftDeleteByIdAsync(Guid id, CancellationToken cancellationToken); + + /// + /// Restores the soft deleted track identified by . + /// + /// The Id of the track to restore. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> RestoreSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs index f85aabf0..6ca6bec2 100644 --- a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs +++ b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Telemetry; -using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; using Lumina.Application.Core.MediaLibrary.Management.Deletion; using Lumina.Domain.Common.Events; using Microsoft.Extensions.DependencyInjection; @@ -45,7 +44,6 @@ public static class ApplicationLayerServices services.AddScoped(); services.AddScoped(); - services.AddScoped(); foreach (var registration in handlerRegistrations) { diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumEntityMapping.cs index 105cc548..03807d27 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumEntityMapping.cs @@ -228,6 +228,25 @@ public static class AlbumEntityMapping artwork ?? []); } + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The date and time when the album was deleted. + /// The optional path of the image representing the album. + /// The converted response entity. + public static DeletedAlbumResponse ToResponse(this AlbumEntity repositoryEntity, DateTime deletedOnUtc, string? coverPath = null) + { + return new DeletedAlbumResponse( + repositoryEntity.Id, + repositoryEntity.LibraryId, + repositoryEntity.ArtistId, + repositoryEntity.Artist?.Name ?? string.Empty, + repositoryEntity.Title, + deletedOnUtc, + coverPath); + } + /// /// Converts to a collection of . /// diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistEntityMapping.cs index c77a161e..c118463d 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistEntityMapping.cs @@ -183,6 +183,23 @@ public static class ArtistEntityMapping coverPath); } + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The date and time when the artist was deleted. + /// The optional path of the image representing the artist. + /// The converted response entity. + public static DeletedArtistResponse ToResponse(this ArtistEntity repositoryEntity, DateTime deletedOnUtc, string? coverPath = null) + { + return new DeletedArtistResponse( + repositoryEntity.Id, + repositoryEntity.LibraryId, + repositoryEntity.Name, + deletedOnUtc, + coverPath); + } + /// /// Converts to a collection of . /// diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMapping.cs index c4f755f4..286bb68b 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMapping.cs @@ -293,6 +293,26 @@ public static class TrackEntityMapping repositoryEntity.Container); } + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The date and time when the track was deleted. + /// The converted response entity. + public static DeletedTrackResponse ToResponse(this TrackEntity repositoryEntity, DateTime deletedOnUtc) + { + return new DeletedTrackResponse( + repositoryEntity.Id, + repositoryEntity.LibraryId, + repositoryEntity.Album?.ArtistId ?? Guid.Empty, + repositoryEntity.Album?.Artist?.Name ?? string.Empty, + repositoryEntity.AlbumId, + repositoryEntity.Album?.Title ?? string.Empty, + repositoryEntity.Title, + repositoryEntity.Path, + deletedOnUtc); + } + /// /// Converts to a collection of . /// diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandHandler.cs index 173bbe3b..e2d62d54 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandHandler.cs @@ -8,7 +8,6 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; -using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; @@ -29,7 +28,6 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums. public class DeleteAlbumCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; - private readonly IMusicArtworkCleanupService _musicArtworkCleanupService; private readonly IAuthorizationService _authorizationService; private readonly ICurrentUserService _currentUserService; private readonly IValidator _validator; @@ -38,14 +36,12 @@ public class DeleteAlbumCommandHandler : ICommandHandler class. /// /// Injected unit of work for interacting with the data access layer repositories. - /// Injected service for removing the artwork of a music library item and of its children. /// Injected service for authorization related functionality. /// Injected service to retrieve the current user information. /// Injected validator for application validation rules. - public DeleteAlbumCommandHandler(IUnitOfWork unitOfWork, IMusicArtworkCleanupService musicArtworkCleanupService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + public DeleteAlbumCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) { _unitOfWork = unitOfWork; - _musicArtworkCleanupService = musicArtworkCleanupService; _authorizationService = authorizationService; _currentUserService = currentUserService; _validator = validator; @@ -74,7 +70,7 @@ public class DeleteAlbumCommandHandler : ICommandHandler getArtistResult = await _unitOfWork.ArtistRepository .GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); if (getArtistResult.IsFailure) @@ -94,10 +90,6 @@ public class DeleteAlbumCommandHandler : ICommandHandler album.Id == albumId); - if (existingAlbum is null) - return DomainErrors.Music.AlbumNotFound; - // An album can only belong to a library that exists, so a client can never delete an album of a library of the host that is not there. Result getLibraryResult = await _unitOfWork.LibraryRepository .GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); @@ -106,29 +98,25 @@ public class DeleteAlbumCommandHandler : ICommandHandler artistResult = existingArtist.ToDomainEntity(); if (artistResult.IsFailure) return artistResult.Errors; - // The album is an entity inside the artist aggregate, so it is referenced by object, not by id; the aggregate member is located here and passed through. Album? domainAlbum = artistResult.Value.Albums.FirstOrDefault(album => album.Id.Value == albumId); if (domainAlbum is null) return DomainErrors.Music.AlbumNotFound; - Result removeAlbumResult = artistResult.Value.RemoveAlbum(domainAlbum); - if (removeAlbumResult.IsFailure) - return removeAlbumResult.Errors; - // The artwork of the album and of its tracks does not cascade from the album row, because the artwork table is shared by all the music - // library item types, so it is removed first, while the album and its tracks are still present. - Result deleteArtworkResult = await _musicArtworkCleanupService.DeleteAlbumArtworkAsync(albumId, cancellationToken).ConfigureAwait(false); - if (deleteArtworkResult.IsFailure) - return deleteArtworkResult.Errors; - Result updateResult = await _unitOfWork.ArtistRepository - .UpdateAsync(artistResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); - if (updateResult.IsFailure) - return updateResult.Errors; + Result canRemoveAlbumResult = artistResult.Value.CanRemoveAlbum(domainAlbum); + if (canRemoveAlbumResult.IsFailure) + return canRemoveAlbumResult.Errors; + + // The album is soft deleted, so its metadata, artwork and track paths stay available until the user restores it or the files disappear + // from disk. The tracks of the album are not deleted themselves, so restoring the album brings back the tracks that were not deleted on their own. + // The write re-checks the last-album condition because this snapshot can be stale. + Result deleteAlbumResult = await _unitOfWork.AlbumRepository.SoftDeleteByIdAsync(albumId, cancellationToken).ConfigureAwait(false); + if (deleteAlbumResult.IsFailure) + return deleteAlbumResult.Errors; + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); if (saveChangesResult.IsFailure) return saveChangesResult.Errors; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/RestoreAlbum/RestoreAlbumCommand.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/RestoreAlbum/RestoreAlbumCommand.cs new file mode 100644 index 00000000..0212bd4e --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/RestoreAlbum/RestoreAlbumCommand.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum; + +/// +/// Command for restoring a deleted album by its Id. +/// +/// The unique identifier of the media library this album belongs to, taken from the route. +/// The unique identifier of the artist the album belongs to, taken from the route. +/// The unique identifier of the album to restore, taken from the route. +[DebuggerDisplay("AlbumId: {AlbumId}")] +public record RestoreAlbumCommand( + string? LibraryId, + string? ArtistId, + string? AlbumId +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/RestoreAlbum/RestoreAlbumCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/RestoreAlbum/RestoreAlbumCommandHandler.cs new file mode 100644 index 00000000..359e31c6 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/RestoreAlbum/RestoreAlbumCommandHandler.cs @@ -0,0 +1,97 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum; + +/// +/// Handler for the command to restore a deleted album by its Id. +/// +public class RestoreAlbumCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public RestoreAlbumCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the command to restore a deleted album by its Id. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> HandleAsync(RestoreAlbumCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + Guid albumId = Guid.Parse(command.AlbumId!); + + // A deleted album whose artist is also deleted is not restorable on its own, so the repository reports it as missing until the artist is restored. + Result getAlbumResult = await _unitOfWork.AlbumRepository.GetSoftDeletedByIdAsync(albumId, cancellationToken).ConfigureAwait(false); + if (getAlbumResult.IsFailure) + return getAlbumResult.Errors; + if (getAlbumResult.Value is null) + return DomainErrors.Music.AlbumNotFound; + AlbumEntity existingAlbum = getAlbumResult.Value; + + // Resource scoping: the album must belong to the artist and library named by the route, so that an album can never be restored through + // another library's route; the mismatch is reported as not found, without disclosing that the album exists elsewhere. + if (existingAlbum.LibraryId != libraryId || existingAlbum.ArtistId != artistId) + return DomainErrors.Music.AlbumNotFound; + + // Admins can restore the albums of all libraries; for everyone else, only the albums of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(existingAlbum.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result restoreAlbumResult = await _unitOfWork.AlbumRepository.RestoreSoftDeletedByIdAsync(existingAlbum.Id, cancellationToken).ConfigureAwait(false); + if (restoreAlbumResult.IsFailure) + return restoreAlbumResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + return Result.Updated; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/RestoreAlbum/RestoreAlbumCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/RestoreAlbum/RestoreAlbumCommandValidator.cs new file mode 100644 index 00000000..a7b2aaa2 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/RestoreAlbum/RestoreAlbumCommandValidator.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum; + +/// +/// Validates the needed validation rules for . +/// +public class RestoreAlbumCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public RestoreAlbumCommandValidator() + { + // Validates the identifier of the media library that owns the album, taken from the route. + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(command => command.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(command => command.LibraryId is not null && command.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist the album belongs to, taken from the route. + RuleFor(command => command.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(command => command.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(command => command.ArtistId is not null && command.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + // Validates the identifier of the deleted album, taken from the route. + RuleFor(command => command.AlbumId) + .NotEmpty() + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + RuleFor(command => command.AlbumId) + .Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty) + .When(command => command.AlbumId is not null && command.AlbumId.Length > 0) + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandHandler.cs index cc24503b..dff603ff 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandHandler.cs @@ -121,13 +121,14 @@ public class UpdateAlbumCoverCommandHandler : ICommandHandler artwork.ArtworkType == ArtworkType.Cover) .Select(artwork => artwork.FileName) .FirstOrDefault(); - string? releaseTypeName = ExtractReleaseTypeDirectoryName(existingCoverPath, artistName) + string? releaseTypeName = ExtractReleaseTypeDirectoryName(existingCoverPath, artistName, existingAlbum.ArtistId) ?? (existingAlbum.ReleaseTypes.Count > 0 ? existingAlbum.ReleaseTypes[0].ReleaseType.ToString() : null); Result storeArtworkResult = await _musicArtworkService.SaveAlbumArtworkAsync( existingAlbum.LibraryId, existingAlbum.Id, libraryName, + existingAlbum.ArtistId, artistName, existingAlbum.Title, command.Cover!, @@ -164,19 +165,21 @@ public class UpdateAlbumCoverCommandHandler : ICommandHandler /// The relative path of the existing cover image of the album, or when the album has no cover. /// The name of the artist of the album. + /// The Id of the artist of the album. /// The name of the on-disk release type directory, or when the album does not use one. - private string? ExtractReleaseTypeDirectoryName(string? coverRelativePath, string artistName) + private string? ExtractReleaseTypeDirectoryName(string? coverRelativePath, string artistName, Guid artistId) { if (string.IsNullOrWhiteSpace(coverRelativePath)) return null; - // The path is media/music/{library}/{artist}[/{releaseType}]/{album}/{file}, so the segment right before the album directory is the release - // type directory when the album uses one, and the artist directory otherwise. An artist whose name happens to match a release type, like - // "Live", must not be mistaken for one, so the segment is only accepted as a release type when it is not the directory of the artist. + // The path is media/music/{libraryName}-{libraryId}/{artistName}-{artistId}[/{releaseType}]/{albumTitle}-{albumId}/{file}, so the segment + // right before the album directory is the release type directory when the album uses one, and the artist directory otherwise. An artist + // whose name happens to match a release type, like "Live", must not be mistaken for one, so the segment is only accepted as a release type + // when it is not the directory of the artist. string[] segments = coverRelativePath.Split(_pathService.PathSeparator, StringSplitOptions.RemoveEmptyEntries); if (segments.Length < 3) return null; string candidate = segments[^3]; - if (IsArtistDirectory(candidate, artistName)) + if (IsArtistDirectory(candidate, artistName, artistId)) return null; return Enum.TryParse(candidate, ignoreCase: true, out MusicReleaseType releaseType) && Enum.IsDefined(releaseType) ? candidate : null; } @@ -186,12 +189,12 @@ public class UpdateAlbumCoverCommandHandler : ICommandHandler /// The path segment to be checked. /// The name of the artist of the album. + /// The Id of the artist of the album. /// when the segment is the artwork directory of the artist, otherwise. - private bool IsArtistDirectory(string pathSegment, string artistName) + private bool IsArtistDirectory(string pathSegment, string artistName, Guid artistId) { - if (string.IsNullOrWhiteSpace(artistName)) - return false; - Result artistSegmentResult = _pathService.SanitizeSegment(artistName); + string resolvedArtistName = string.IsNullOrWhiteSpace(artistName) ? "Unknown" : artistName; + Result artistSegmentResult = _pathService.SanitizeCompositeSegment(resolvedArtistName, artistId.ToString()); return artistSegmentResult.IsSuccess && string.Equals(pathSegment, artistSegmentResult.Value.Name, StringComparison.OrdinalIgnoreCase); } diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetDeletedAlbums/GetDeletedAlbumsQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetDeletedAlbums/GetDeletedAlbumsQuery.cs new file mode 100644 index 00000000..ef211751 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetDeletedAlbums/GetDeletedAlbumsQuery.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums; + +/// +/// Query for getting the deleted albums of a media library. +/// +/// The unique identifier of the media library whose deleted albums are retrieved, taken from the route. +[DebuggerDisplay("LibraryId: {LibraryId}")] +public record GetDeletedAlbumsQuery( + string? LibraryId +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetDeletedAlbums/GetDeletedAlbumsQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetDeletedAlbums/GetDeletedAlbumsQueryHandler.cs new file mode 100644 index 00000000..13219902 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetDeletedAlbums/GetDeletedAlbumsQueryHandler.cs @@ -0,0 +1,95 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums; + +/// +/// Handler for the query to get the deleted albums of a media library. +/// +public class GetDeletedAlbumsQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public GetDeletedAlbumsQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the query to get the deleted albums of a media library. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// An containing either the deleted albums, or an error. + public async Task>> HandleAsync(GetDeletedAlbumsQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the library id of the route is a non-empty Guid before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + + // Admins can see all libraries; for everyone else, only the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result> getDeletedAlbumsResult = await _unitOfWork.AlbumRepository.GetSoftDeletedByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (getDeletedAlbumsResult.IsFailure) + return getDeletedAlbumsResult.Errors; + + IReadOnlyList deletedAlbums = getDeletedAlbumsResult.Value; + Result> getArtworkResult = await _unitOfWork.MusicArtworkRepository + .GetByOwnersAsync(MusicArtworkOwnerType.Album, [.. deletedAlbums.Select(album => album.Id)], cancellationToken).ConfigureAwait(false); + if (getArtworkResult.IsFailure) + return getArtworkResult.Errors; + + // A cover row can exist before its file is resolved, so rows without a stored file name are skipped instead of hiding a resolved cover. + Dictionary coverPaths = getArtworkResult.Value + .Where(artwork => artwork.ArtworkType == ArtworkType.Cover && !string.IsNullOrWhiteSpace(artwork.FileName)) + .GroupBy(artwork => artwork.OwnerId) + .ToDictionary(group => group.Key, group => group.Select(artwork => artwork.FileName!).First()); + + return Result.From>( + [.. deletedAlbums.Select(album => album.ToResponse(album.DeletedOnUtc ?? album.CreatedOnUtc, coverPaths.GetValueOrDefault(album.Id)))]); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetDeletedAlbums/GetDeletedAlbumsQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetDeletedAlbums/GetDeletedAlbumsQueryValidator.cs new file mode 100644 index 00000000..bb5272e1 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetDeletedAlbums/GetDeletedAlbumsQueryValidator.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums; + +/// +/// Validates the needed validation rules for . +/// +public class GetDeletedAlbumsQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetDeletedAlbumsQueryValidator() + { + // Validates the identifier of the media library whose deleted albums are retrieved, taken from the route. + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandler.cs index ed03a91b..ded505f4 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandler.cs @@ -7,7 +7,6 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; -using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; @@ -25,7 +24,6 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists public class DeleteArtistCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; - private readonly IMusicArtworkCleanupService _musicArtworkCleanupService; private readonly IAuthorizationService _authorizationService; private readonly ICurrentUserService _currentUserService; private readonly IValidator _validator; @@ -34,14 +32,12 @@ public class DeleteArtistCommandHandler : ICommandHandler class. /// /// Injected unit of work for interacting with the data access layer repositories. - /// Injected service for removing the artwork of a music library item and of its children. /// Injected service for authorization related functionality. /// Injected service to retrieve the current user information. /// Injected validator for application validation rules. - public DeleteArtistCommandHandler(IUnitOfWork unitOfWork, IMusicArtworkCleanupService musicArtworkCleanupService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + public DeleteArtistCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) { _unitOfWork = unitOfWork; - _musicArtworkCleanupService = musicArtworkCleanupService; _authorizationService = authorizationService; _currentUserService = currentUserService; _validator = validator; @@ -96,13 +92,9 @@ public class DeleteArtistCommandHandler : ICommandHandler deleteArtworkResult = await _musicArtworkCleanupService.DeleteArtistArtworkAsync(artistId, cancellationToken).ConfigureAwait(false); - if (deleteArtworkResult.IsFailure) - return deleteArtworkResult.Errors; - - Result deleteArtistResult = await _unitOfWork.ArtistRepository.DeleteByIdAsync(artistId, cancellationToken).ConfigureAwait(false); + // The artist is soft deleted, so its metadata, artwork and paths stay available until the user restores it or the files disappear from disk. + // Keeping the row is also what makes the deletion survive an automatic scan, because the scan treats its track paths as already catalogued. + Result deleteArtistResult = await _unitOfWork.ArtistRepository.SoftDeleteByIdAsync(artistId, cancellationToken).ConfigureAwait(false); if (deleteArtistResult.IsFailure) return deleteArtistResult.Errors; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/RestoreArtist/RestoreArtistCommand.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/RestoreArtist/RestoreArtistCommand.cs new file mode 100644 index 00000000..964d668f --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/RestoreArtist/RestoreArtistCommand.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist; + +/// +/// Command for restoring a deleted artist by its Id. +/// +/// The unique identifier of the media library this artist belongs to, taken from the route. +/// The unique identifier of the artist to restore, taken from the route. +[DebuggerDisplay("ArtistId: {ArtistId}")] +public record RestoreArtistCommand( + string? LibraryId, + string? ArtistId +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/RestoreArtist/RestoreArtistCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/RestoreArtist/RestoreArtistCommandHandler.cs new file mode 100644 index 00000000..57f4840b --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/RestoreArtist/RestoreArtistCommandHandler.cs @@ -0,0 +1,103 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist; + +/// +/// Handler for the command to restore a deleted artist by its Id. +/// +public class RestoreArtistCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public RestoreArtistCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the command to restore a deleted artist by its Id. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> HandleAsync(RestoreArtistCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + + Result getArtistResult = await _unitOfWork.ArtistRepository.GetSoftDeletedByIdAsync(artistId, cancellationToken).ConfigureAwait(false); + if (getArtistResult.IsFailure) + return getArtistResult.Errors; + if (getArtistResult.Value is null) + return DomainErrors.Music.ArtistNotFound; + ArtistEntity existingArtist = getArtistResult.Value; + + // Resource scoping: the artist must belong to the library named by the route, so that an artist can never be restored through another + // library's route; the mismatch is reported as not found, without disclosing that the artist exists in another library. + if (existingArtist.LibraryId != libraryId) + return DomainErrors.Music.ArtistNotFound; + + // Admins can restore the artists of all libraries; for everyone else, only the artists of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(existingArtist.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + // The name of a visible artist is unique within a library, so an artist can only be restored while no visible artist took over its name. + // The lookup only considers visible artists, so it can never return the deleted artist itself. + Result getArtistByNameResult = await _unitOfWork.ArtistRepository.GetByNameAsync(existingArtist.LibraryId, existingArtist.Name, cancellationToken).ConfigureAwait(false); + if (getArtistByNameResult.IsFailure) + return getArtistByNameResult.Errors; + if (getArtistByNameResult.Value is not null) + return DomainErrors.Music.ArtistAlreadyExists; + + Result restoreArtistResult = await _unitOfWork.ArtistRepository.RestoreSoftDeletedByIdAsync(existingArtist.Id, cancellationToken).ConfigureAwait(false); + if (restoreArtistResult.IsFailure) + return restoreArtistResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + return Result.Updated; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/RestoreArtist/RestoreArtistCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/RestoreArtist/RestoreArtistCommandValidator.cs new file mode 100644 index 00000000..c79bf693 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/RestoreArtist/RestoreArtistCommandValidator.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist; + +/// +/// Validates the needed validation rules for . +/// +public class RestoreArtistCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public RestoreArtistCommandValidator() + { + // Validates the identifier of the media library that owns the artist, taken from the route. + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(command => command.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(command => command.LibraryId is not null && command.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the deleted artist, taken from the route. + RuleFor(command => command.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(command => command.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(command => command.ArtistId is not null && command.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandHandler.cs index 7b84738e..da128373 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandHandler.cs @@ -113,6 +113,7 @@ public class UpdateArtistCoverCommandHandler : ICommandHandler storeArtworkResult = await _musicArtworkService.SaveArtistArtworkAsync( existingArtist.LibraryId, libraryName, + existingArtist.Id, existingArtist.Name, command.Cover!, command.FileName!, diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetDeletedArtists/GetDeletedArtistsQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetDeletedArtists/GetDeletedArtistsQuery.cs new file mode 100644 index 00000000..59c3dae2 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetDeletedArtists/GetDeletedArtistsQuery.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists; + +/// +/// Query for getting the deleted artists of a media library. +/// +/// The unique identifier of the media library whose deleted artists are retrieved, taken from the route. +[DebuggerDisplay("LibraryId: {LibraryId}")] +public record GetDeletedArtistsQuery( + string? LibraryId +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetDeletedArtists/GetDeletedArtistsQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetDeletedArtists/GetDeletedArtistsQueryHandler.cs new file mode 100644 index 00000000..e62808de --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetDeletedArtists/GetDeletedArtistsQueryHandler.cs @@ -0,0 +1,95 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists; + +/// +/// Handler for the query to get the deleted artists of a media library. +/// +public class GetDeletedArtistsQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public GetDeletedArtistsQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the query to get the deleted artists of a media library. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// An containing either the deleted artists, or an error. + public async Task>> HandleAsync(GetDeletedArtistsQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the library id of the route is a non-empty Guid before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + + // Admins can see all libraries; for everyone else, only the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result> getDeletedArtistsResult = await _unitOfWork.ArtistRepository.GetSoftDeletedByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (getDeletedArtistsResult.IsFailure) + return getDeletedArtistsResult.Errors; + + IReadOnlyList deletedArtists = getDeletedArtistsResult.Value; + Result> getArtworkResult = await _unitOfWork.MusicArtworkRepository + .GetByOwnersAsync(MusicArtworkOwnerType.Artist, [.. deletedArtists.Select(artist => artist.Id)], cancellationToken).ConfigureAwait(false); + if (getArtworkResult.IsFailure) + return getArtworkResult.Errors; + + // A cover row can exist before its file is resolved, so rows without a stored file name are skipped instead of hiding a resolved cover. + Dictionary coverPaths = getArtworkResult.Value + .Where(artwork => artwork.ArtworkType == ArtworkType.Cover && !string.IsNullOrWhiteSpace(artwork.FileName)) + .GroupBy(artwork => artwork.OwnerId) + .ToDictionary(group => group.Key, group => group.Select(artwork => artwork.FileName!).First()); + + return Result.From>( + [.. deletedArtists.Select(artist => artist.ToResponse(artist.DeletedOnUtc ?? artist.CreatedOnUtc, coverPaths.GetValueOrDefault(artist.Id)))]); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetDeletedArtists/GetDeletedArtistsQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetDeletedArtists/GetDeletedArtistsQueryValidator.cs new file mode 100644 index 00000000..184e83c0 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetDeletedArtists/GetDeletedArtistsQueryValidator.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists; + +/// +/// Validates the needed validation rules for . +/// +public class GetDeletedArtistsQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetDeletedArtistsQueryValidator() + { + // Validates the identifier of the media library whose deleted artists are retrieved, taken from the route. + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkCleanupService.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkCleanupService.cs deleted file mode 100644 index 7da9ca4f..00000000 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkCleanupService.cs +++ /dev/null @@ -1,38 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; -using System; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; - -/// -/// Interface for the service that removes the artwork records and the stored artwork files of a music library item, together with the artwork of its children. -/// -public interface IMusicArtworkCleanupService -{ - /// - /// Removes the artwork records and the stored artwork files of the artist identified by , together with the artwork of its albums and tracks. - /// - /// The Id of the artist whose artwork is removed. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> DeleteArtistArtworkAsync(Guid artistId, CancellationToken cancellationToken); - - /// - /// Removes the artwork records and the stored artwork files of the album identified by , together with the artwork of its tracks. - /// - /// The Id of the album whose artwork is removed. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> DeleteAlbumArtworkAsync(Guid albumId, CancellationToken cancellationToken); - - /// - /// Removes the artwork records and the stored artwork files of the track identified by . - /// - /// The Id of the track whose artwork is removed. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> DeleteTrackArtworkAsync(Guid trackId, CancellationToken cancellationToken); -} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkService.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkService.cs index 3c1690e6..37cc9ff4 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkService.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkService.cs @@ -20,13 +20,14 @@ public interface IMusicArtworkService /// The Id of the media library the album belongs to. /// The Id of the album. /// The name of the media library the album belongs to. + /// The Id of the artist of the album. /// The name of the artist of the album. /// The title of the album. /// The artwork to store. /// The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When , no release type segment is added. /// Cancellation token that can be used to stop the execution. /// An containing either the relative path of the stored artwork, or an error. - Task> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, ArtworkDto artwork, string? releaseTypeName, CancellationToken cancellationToken); + Task> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, Guid artistId, string artistName, string albumTitle, ArtworkDto artwork, string? releaseTypeName, CancellationToken cancellationToken); /// /// Stores the uploaded of the album into the internal media directory, and returns the relative path of the stored artwork. @@ -34,6 +35,7 @@ public interface IMusicArtworkService /// The Id of the media library the album belongs to. /// The Id of the album. /// The name of the media library the album belongs to. + /// The Id of the artist of the album. /// The name of the artist of the album. /// The title of the album. /// The stream of the uploaded artwork to store. @@ -41,7 +43,7 @@ public interface IMusicArtworkService /// The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When , no release type segment is added. /// Cancellation token that can be used to stop the execution. /// An containing either the relative path of the stored artwork, or an error. - Task> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, Stream artwork, string fileName, string? releaseTypeName, CancellationToken cancellationToken); + Task> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, Guid artistId, string artistName, string albumTitle, Stream artwork, string fileName, string? releaseTypeName, CancellationToken cancellationToken); /// /// Deletes the stored artwork of the album from the internal media directory. @@ -49,43 +51,47 @@ public interface IMusicArtworkService /// The Id of the media library the album belongs to. /// The Id of the album. /// The name of the media library the album belongs to. + /// The Id of the artist of the album. /// The name of the artist of the album. /// The title of the album. /// The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When omitted, no release type segment is added. /// An representing either a successful operation, or an error. - Result DeleteAlbumArtwork(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, string? releaseTypeName = null); + Result DeleteAlbumArtwork(Guid libraryId, Guid albumId, string libraryName, Guid artistId, string artistName, string albumTitle, string? releaseTypeName = null); /// /// Stores the of the artist into the internal media directory, and returns the relative path of the stored artwork. /// /// The Id of the media library the artist belongs to. /// The name of the media library the artist belongs to. + /// The Id of the artist. /// The name of the artist. /// The artwork to store. /// Cancellation token that can be used to stop the execution. /// An containing either the relative path of the stored artwork, or an error. - Task> SaveArtistArtworkAsync(Guid libraryId, string libraryName, string artistName, ArtworkDto artwork, CancellationToken cancellationToken); + Task> SaveArtistArtworkAsync(Guid libraryId, string libraryName, Guid artistId, string artistName, ArtworkDto artwork, CancellationToken cancellationToken); /// /// Stores the uploaded of the artist into the internal media directory, and returns the relative path of the stored artwork. /// /// The Id of the media library the artist belongs to. /// The name of the media library the artist belongs to. + /// The Id of the artist. /// The name of the artist. /// The stream of the uploaded artwork to store. /// The name of the uploaded artwork file. /// Cancellation token that can be used to stop the execution. /// An containing either the relative path of the stored artwork, or an error. - Task> SaveArtistArtworkAsync(Guid libraryId, string libraryName, string artistName, Stream artwork, string fileName, CancellationToken cancellationToken); + Task> SaveArtistArtworkAsync(Guid libraryId, string libraryName, Guid artistId, string artistName, Stream artwork, string fileName, CancellationToken cancellationToken); /// /// Deletes the stored artwork of the artist from the internal media directory. /// /// The Id of the media library the artist belongs to. /// The name of the media library the artist belongs to. + /// The Id of the artist. /// The name of the artist. /// An representing either a successful operation, or an error. - Result DeleteArtistArtwork(Guid libraryId, string libraryName, string artistName); + Result DeleteArtistArtwork(Guid libraryId, string libraryName, Guid artistId, string artistName); /// /// Deletes the stored artwork file at from the internal media directory, when it still exists. diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkCleanupService.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkCleanupService.cs deleted file mode 100644 index 42864d01..00000000 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkCleanupService.cs +++ /dev/null @@ -1,119 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; -using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; - -/// -/// Service that removes the artwork records and the stored artwork files of a music library item, together with the artwork of its children. -/// The artwork table is shared by all the music library item types and references its owners by a plain id, so the artwork of an item does not -/// cascade when the item is removed, and is removed explicitly instead, from the innermost children outwards. -/// -internal sealed class MusicArtworkCleanupService : IMusicArtworkCleanupService -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IMusicArtworkService _musicArtworkService; - - /// - /// Initializes a new instance of the class. - /// - /// Injected unit of work for interacting with the data access layer repositories. - /// Injected service for removing the stored artwork files of a music library item. - public MusicArtworkCleanupService(IUnitOfWork unitOfWork, IMusicArtworkService musicArtworkService) - { - _unitOfWork = unitOfWork; - _musicArtworkService = musicArtworkService; - } - - /// - /// Removes the artwork records and the stored artwork files of the artist identified by , together with the artwork of its albums and tracks. - /// - /// The Id of the artist whose artwork is removed. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> DeleteArtistArtworkAsync(Guid artistId, CancellationToken cancellationToken) - { - // The albums and the tracks of the artist are removed by the database through the cascading foreign keys, so only the artwork of the - // children has to be collected here, and it has to be removed before the artwork of the artist itself, from the innermost children outwards. - Result> getAlbumsResult = await _unitOfWork.AlbumRepository.GetByArtistIdAsync(artistId, cancellationToken).ConfigureAwait(false); - if (getAlbumsResult.IsFailure) - return getAlbumsResult.Errors; - - foreach (AlbumEntity album in getAlbumsResult.Value) - { - Result deleteAlbumArtworkResult = await DeleteAlbumArtworkAsync(album.Id, cancellationToken).ConfigureAwait(false); - if (deleteAlbumArtworkResult.IsFailure) - return deleteAlbumArtworkResult.Errors; - } - - return await DeleteOwnerArtworkAsync(MusicArtworkOwnerType.Artist, artistId, cancellationToken).ConfigureAwait(false); - } - - /// - /// Removes the artwork records and the stored artwork files of the album identified by , together with the artwork of its tracks. - /// - /// The Id of the album whose artwork is removed. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> DeleteAlbumArtworkAsync(Guid albumId, CancellationToken cancellationToken) - { - // The tracks of the album are removed by the database through the cascading foreign keys, so only their artwork has to be removed here, - // before the artwork of the album itself. - Result> getTracksResult = await _unitOfWork.TrackRepository.GetByAlbumIdAsync(albumId, cancellationToken).ConfigureAwait(false); - if (getTracksResult.IsFailure) - return getTracksResult.Errors; - - foreach (TrackEntity track in getTracksResult.Value) - { - Result deleteTrackArtworkResult = await DeleteTrackArtworkAsync(track.Id, cancellationToken).ConfigureAwait(false); - if (deleteTrackArtworkResult.IsFailure) - return deleteTrackArtworkResult.Errors; - } - - return await DeleteOwnerArtworkAsync(MusicArtworkOwnerType.Album, albumId, cancellationToken).ConfigureAwait(false); - } - - /// - /// Removes the artwork records and the stored artwork files of the track identified by . - /// - /// The Id of the track whose artwork is removed. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public Task> DeleteTrackArtworkAsync(Guid trackId, CancellationToken cancellationToken) - { - return DeleteOwnerArtworkAsync(MusicArtworkOwnerType.Track, trackId, cancellationToken); - } - - /// - /// Removes the artwork records and the stored artwork files of the single music library item identified by and . - /// - /// The type of the music library item whose artwork is removed. - /// The Id of the music library item whose artwork is removed. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - private async Task> DeleteOwnerArtworkAsync(MusicArtworkOwnerType ownerType, Guid ownerId, CancellationToken cancellationToken) - { - Result> getArtworkResult = await _unitOfWork.MusicArtworkRepository.GetByOwnerAsync(ownerType, ownerId, cancellationToken).ConfigureAwait(false); - if (getArtworkResult.IsFailure) - return getArtworkResult.Errors; - - // The stored files do not cascade from their records either, so every stored file is removed before its record is; the artwork whose file has not been resolved yet has no file to remove. - foreach (MusicArtworkEntity artwork in getArtworkResult.Value) - { - if (string.IsNullOrWhiteSpace(artwork.FileName)) - continue; - Result deleteStoredArtworkResult = _musicArtworkService.DeleteStoredArtwork(artwork.FileName); - if (deleteStoredArtworkResult.IsFailure) - return deleteStoredArtworkResult.Errors; - } - - return await _unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(ownerType, ownerId, cancellationToken).ConfigureAwait(false); - } -} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandHandler.cs index 5f7dfd3f..fc75e9e2 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandHandler.cs @@ -7,14 +7,9 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; -using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; -using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; -using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; using System; using System.Collections.Generic; -using System.Linq; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; @@ -29,7 +24,6 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks. public class DeleteTrackCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; - private readonly IMusicArtworkCleanupService _musicArtworkCleanupService; private readonly IAuthorizationService _authorizationService; private readonly ICurrentUserService _currentUserService; private readonly IValidator _validator; @@ -38,14 +32,12 @@ public class DeleteTrackCommandHandler : ICommandHandler class. /// /// Injected unit of work for interacting with the data access layer repositories. - /// Injected service for removing the artwork of a music library item and of its children. /// Injected service for authorization related functionality. /// Injected service to retrieve the current user information. /// Injected validator for application validation rules. - public DeleteTrackCommandHandler(IUnitOfWork unitOfWork, IMusicArtworkCleanupService musicArtworkCleanupService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + public DeleteTrackCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) { _unitOfWork = unitOfWork; - _musicArtworkCleanupService = musicArtworkCleanupService; _authorizationService = authorizationService; _currentUserService = currentUserService; _validator = validator; @@ -75,9 +67,9 @@ public class DeleteTrackCommandHandler : ICommandHandler getArtistResult = await _unitOfWork.ArtistRepository - .GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + .GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); if (getArtistResult.IsFailure) return getArtistResult.Errors; if (getArtistResult.Value is null) @@ -95,13 +87,6 @@ public class DeleteTrackCommandHandler : ICommandHandler album.Id == albumId); - if (existingAlbum is null) - return DomainErrors.Music.AlbumNotFound; - TrackEntity? existingTrack = existingAlbum.Tracks.FirstOrDefault(track => track.Id == trackId); - if (existingTrack is null) - return DomainErrors.Music.TrackNotFound; - // A track can only belong to a library that exists, so a client can never delete a track of a library of the host that is not there. Result getLibraryResult = await _unitOfWork.LibraryRepository .GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); @@ -110,31 +95,25 @@ public class DeleteTrackCommandHandler : ICommandHandler artistResult = existingArtist.ToDomainEntity(); - if (artistResult.IsFailure) - return artistResult.Errors; - // The album and the track are entities inside the artist aggregate, so they are referenced by object, not by id; the aggregate members are located here and passed through. - Album? domainAlbum = artistResult.Value.Albums.FirstOrDefault(album => album.Id.Value == albumId); - if (domainAlbum is null) + Result getAlbumResult = await _unitOfWork.AlbumRepository + .GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getAlbumResult.IsFailure) + return getAlbumResult.Errors; + if (getAlbumResult.Value is null || getAlbumResult.Value.ArtistId != artistId || getAlbumResult.Value.LibraryId != libraryId) return DomainErrors.Music.AlbumNotFound; - Track? domainTrack = domainAlbum.Tracks.FirstOrDefault(track => track.Id.Value == trackId); - if (domainTrack is null) + + Result getTrackResult = await _unitOfWork.TrackRepository + .GetByIdAsync(trackId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getTrackResult.IsFailure) + return getTrackResult.Errors; + if (getTrackResult.Value is null || getTrackResult.Value.AlbumId != albumId || getTrackResult.Value.LibraryId != libraryId) return DomainErrors.Music.TrackNotFound; - Result removeTrackResult = artistResult.Value.RemoveTrackFromAlbum(domainAlbum, domainTrack); - if (removeTrackResult.IsFailure) - return removeTrackResult.Errors; - // The artwork of the track does not cascade from the track row, because the artwork table is shared by all the music library item - // types, so it is removed first, while the track is still present. - Result deleteArtworkResult = await _musicArtworkCleanupService.DeleteTrackArtworkAsync(trackId, cancellationToken).ConfigureAwait(false); - if (deleteArtworkResult.IsFailure) - return deleteArtworkResult.Errors; - - Result updateResult = await _unitOfWork.ArtistRepository.UpdateAsync(artistResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); - if (updateResult.IsFailure) - return updateResult.Errors; + // The track is soft deleted, so its metadata, artwork and path stay available until the user restores it or the file disappears from disk. + // Keeping the row is also what makes the deletion survive an automatic scan, because the scan treats its path as already catalogued. + Result deleteTrackResult = await _unitOfWork.TrackRepository.SoftDeleteByIdAsync(trackId, cancellationToken).ConfigureAwait(false); + if (deleteTrackResult.IsFailure) + return deleteTrackResult.Errors; Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); if (saveChangesResult.IsFailure) diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/RestoreTrack/RestoreTrackCommand.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/RestoreTrack/RestoreTrackCommand.cs new file mode 100644 index 00000000..be5d5e55 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/RestoreTrack/RestoreTrackCommand.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack; + +/// +/// Command for restoring a deleted track by its Id. +/// +/// The unique identifier of the media library this track belongs to, taken from the route. +/// The unique identifier of the artist the album of the track belongs to, taken from the route. +/// The unique identifier of the album the track belongs to, taken from the route. +/// The unique identifier of the track to restore, taken from the route. +[DebuggerDisplay("TrackId: {TrackId}")] +public record RestoreTrackCommand( + string? LibraryId, + string? ArtistId, + string? AlbumId, + string? TrackId +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/RestoreTrack/RestoreTrackCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/RestoreTrack/RestoreTrackCommandHandler.cs new file mode 100644 index 00000000..0f198a57 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/RestoreTrack/RestoreTrackCommandHandler.cs @@ -0,0 +1,106 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack; + +/// +/// Handler for the command to restore a deleted track by its Id. +/// +public class RestoreTrackCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public RestoreTrackCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the command to restore a deleted track by its Id. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> HandleAsync(RestoreTrackCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + Guid albumId = Guid.Parse(command.AlbumId!); + Guid trackId = Guid.Parse(command.TrackId!); + + // A deleted track whose album or artist is also deleted is not restorable on its own, so the repository reports it as missing until + // the album and the artist are restored. + Result getTrackResult = await _unitOfWork.TrackRepository.GetSoftDeletedByIdAsync(trackId, cancellationToken).ConfigureAwait(false); + if (getTrackResult.IsFailure) + return getTrackResult.Errors; + if (getTrackResult.Value is null) + return DomainErrors.Music.TrackNotFound; + TrackEntity existingTrack = getTrackResult.Value; + + // Resource scoping: the track must belong to the album, the artist and the library named by the route, so that a track can never be + // restored through another library's route; the mismatch is reported as not found, without disclosing that the track exists elsewhere. + if (existingTrack.LibraryId != libraryId || existingTrack.AlbumId != albumId) + return DomainErrors.Music.TrackNotFound; + + // Admins can restore the tracks of all libraries; for everyone else, only the tracks of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(existingTrack.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result getAlbumResult = await _unitOfWork.AlbumRepository + .GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getAlbumResult.IsFailure) + return getAlbumResult.Errors; + if (getAlbumResult.Value is null || getAlbumResult.Value.ArtistId != artistId) + return DomainErrors.Music.TrackNotFound; + + Result restoreTrackResult = await _unitOfWork.TrackRepository.RestoreSoftDeletedByIdAsync(existingTrack.Id, cancellationToken).ConfigureAwait(false); + if (restoreTrackResult.IsFailure) + return restoreTrackResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + return Result.Updated; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/RestoreTrack/RestoreTrackCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/RestoreTrack/RestoreTrackCommandValidator.cs new file mode 100644 index 00000000..21b154b9 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/RestoreTrack/RestoreTrackCommandValidator.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack; + +/// +/// Validates the needed validation rules for . +/// +public class RestoreTrackCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public RestoreTrackCommandValidator() + { + // Validates the identifier of the media library that owns the track, taken from the route. + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(command => command.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(command => command.LibraryId is not null && command.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist the album of the track belongs to, taken from the route. + RuleFor(command => command.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(command => command.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(command => command.ArtistId is not null && command.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + // Validates the identifier of the album the track belongs to, taken from the route. + RuleFor(command => command.AlbumId) + .NotEmpty() + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + RuleFor(command => command.AlbumId) + .Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty) + .When(command => command.AlbumId is not null && command.AlbumId.Length > 0) + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + // Validates the identifier of the deleted track, taken from the route. + RuleFor(command => command.TrackId) + .NotEmpty() + .WithError(Errors.Music.TrackIdCannotBeEmpty); + + RuleFor(command => command.TrackId) + .Must(trackId => Guid.TryParse(trackId, out Guid parsedTrackId) && parsedTrackId != Guid.Empty) + .When(command => command.TrackId is not null && command.TrackId.Length > 0) + .WithError(Errors.Music.TrackIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetDeletedTracks/GetDeletedTracksQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetDeletedTracks/GetDeletedTracksQuery.cs new file mode 100644 index 00000000..dbf25f0b --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetDeletedTracks/GetDeletedTracksQuery.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks; + +/// +/// Query for getting the deleted tracks of a media library. +/// +/// The unique identifier of the media library whose deleted tracks are retrieved, taken from the route. +[DebuggerDisplay("LibraryId: {LibraryId}")] +public record GetDeletedTracksQuery( + string? LibraryId +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetDeletedTracks/GetDeletedTracksQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetDeletedTracks/GetDeletedTracksQueryHandler.cs new file mode 100644 index 00000000..f053a4fb --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetDeletedTracks/GetDeletedTracksQueryHandler.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks; + +/// +/// Handler for the query to get the deleted tracks of a media library. +/// +public class GetDeletedTracksQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public GetDeletedTracksQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the query to get the deleted tracks of a media library. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// An containing either the deleted tracks, or an error. + public async Task>> HandleAsync(GetDeletedTracksQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the library id of the route is a non-empty Guid before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + + // Admins can see all libraries; for everyone else, only the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result> getDeletedTracksResult = await _unitOfWork.TrackRepository.GetSoftDeletedByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (getDeletedTracksResult.IsFailure) + return getDeletedTracksResult.Errors; + + return Result.From>( + [.. getDeletedTracksResult.Value.Select(track => track.ToResponse(track.DeletedOnUtc ?? track.CreatedOnUtc))]); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetDeletedTracks/GetDeletedTracksQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetDeletedTracks/GetDeletedTracksQueryValidator.cs new file mode 100644 index 00000000..09b8bce2 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetDeletedTracks/GetDeletedTracksQueryValidator.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks; + +/// +/// Validates the needed validation rules for . +/// +public class GetDeletedTracksQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetDeletedTracksQueryValidator() + { + // Validates the identifier of the media library whose deleted tracks are retrieved, taken from the route. + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategy.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategy.cs index 7acb3af4..e17f790a 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategy.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategy.cs @@ -1,9 +1,11 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -20,6 +22,8 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Deletion; internal sealed class MusicMediaLibraryItemDeletionStrategy : IMediaLibraryItemDeletionStrategy { private readonly IUnitOfWork _unitOfWork; + private readonly IMusicArtworkService _musicArtworkService; + private readonly ILogger _logger; /// /// The media library type that this deletion strategy supports. @@ -30,9 +34,13 @@ internal sealed class MusicMediaLibraryItemDeletionStrategy : IMediaLibraryItemD /// Initializes a new instance of the class. /// /// Injected unit of work for interacting with the data access layer repositories. - public MusicMediaLibraryItemDeletionStrategy(IUnitOfWork unitOfWork) + /// Injected service for deleting the stored artwork files of the music library items. + /// Injected logger used to report the issues encountered while deleting the media library item. + public MusicMediaLibraryItemDeletionStrategy(IUnitOfWork unitOfWork, IMusicArtworkService musicArtworkService, ILogger logger) { _unitOfWork = unitOfWork; + _musicArtworkService = musicArtworkService; + _logger = logger; } /// @@ -46,6 +54,7 @@ internal sealed class MusicMediaLibraryItemDeletionStrategy : IMediaLibraryItemD public async Task> DeleteItemAsync(Guid libraryId, string path, CancellationToken cancellationToken) { // Load the track stored at the deleted path, which might have been already removed. + // Soft deleted tracks are included on purpose: when their file disappears from disk, they must be removed permanently too. Result getTrackResult = await _unitOfWork.TrackRepository.GetByPathAsync(libraryId, path, cancellationToken).ConfigureAwait(false); if (getTrackResult.IsFailure) return getTrackResult.Errors; @@ -57,7 +66,7 @@ internal sealed class MusicMediaLibraryItemDeletionStrategy : IMediaLibraryItemD Guid albumId = track.AlbumId; // Delete the stored artwork of the track, which has no cascade relationship because the artwork table is shared by all the music library item types. - Result deleteTrackArtworkResult = await _unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, trackId, cancellationToken).ConfigureAwait(false); + Result deleteTrackArtworkResult = await DeleteStoredArtworkAndRowsAsync(MusicArtworkOwnerType.Track, trackId, cancellationToken).ConfigureAwait(false); if (deleteTrackArtworkResult.IsFailure) return deleteTrackArtworkResult.Errors; @@ -65,8 +74,8 @@ internal sealed class MusicMediaLibraryItemDeletionStrategy : IMediaLibraryItemD if (deleteTrackResult.IsFailure) return deleteTrackResult.Errors; - // Load the album the deleted track belonged to, to determine whether it is left with no children. - Result getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, cancellationToken: cancellationToken).ConfigureAwait(false); + // Load the album the deleted track belonged to, whether the album itself is soft deleted or not, to determine whether it is left with no children. + Result getAlbumResult = await _unitOfWork.AlbumRepository.GetIncludingDeletedByIdAsync(albumId, cancellationToken).ConfigureAwait(false); if (getAlbumResult.IsFailure) return getAlbumResult.Errors; AlbumEntity? album = getAlbumResult.Value; @@ -75,13 +84,14 @@ internal sealed class MusicMediaLibraryItemDeletionStrategy : IMediaLibraryItemD Guid artistId = album.ArtistId; - Result> getRemainingTracksResult = await _unitOfWork.TrackRepository.GetByAlbumIdAsync(albumId, cancellationToken).ConfigureAwait(false); + // Soft deleted tracks are counted as well, because their files still exist and the album must survive until the last one of them disappears. + Result> getRemainingTracksResult = await _unitOfWork.TrackRepository.GetByAlbumIdIncludingDeletedAsync(albumId, cancellationToken).ConfigureAwait(false); if (getRemainingTracksResult.IsFailure) return getRemainingTracksResult.Errors; // The deleted track is still tracked by the change tracker until the changes are saved, so it is excluded explicitly. if (getRemainingTracksResult.Value.All(remainingTrack => remainingTrack.Id == trackId)) { - Result deleteAlbumArtworkResult = await _unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, cancellationToken).ConfigureAwait(false); + Result deleteAlbumArtworkResult = await DeleteStoredArtworkAndRowsAsync(MusicArtworkOwnerType.Album, albumId, cancellationToken).ConfigureAwait(false); if (deleteAlbumArtworkResult.IsFailure) return deleteAlbumArtworkResult.Errors; @@ -89,13 +99,14 @@ internal sealed class MusicMediaLibraryItemDeletionStrategy : IMediaLibraryItemD if (deleteAlbumResult.IsFailure) return deleteAlbumResult.Errors; - Result> getRemainingAlbumsResult = await _unitOfWork.AlbumRepository.GetByArtistIdAsync(artistId, cancellationToken).ConfigureAwait(false); + // Soft deleted albums are counted as well, because their tracks still exist and the artist must survive until the last one of them disappears. + Result> getRemainingAlbumsResult = await _unitOfWork.AlbumRepository.GetByArtistIdIncludingDeletedAsync(artistId, cancellationToken).ConfigureAwait(false); if (getRemainingAlbumsResult.IsFailure) return getRemainingAlbumsResult.Errors; // The deleted album is still tracked by the change tracker until the changes are saved, so it is excluded explicitly. if (getRemainingAlbumsResult.Value.All(remainingAlbum => remainingAlbum.Id == albumId)) { - Result deleteArtistArtworkResult = await _unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, cancellationToken).ConfigureAwait(false); + Result deleteArtistArtworkResult = await DeleteStoredArtworkAndRowsAsync(MusicArtworkOwnerType.Artist, artistId, cancellationToken).ConfigureAwait(false); if (deleteArtistArtworkResult.IsFailure) return deleteArtistArtworkResult.Errors; @@ -108,6 +119,35 @@ internal sealed class MusicMediaLibraryItemDeletionStrategy : IMediaLibraryItemD return await SaveChangesAsync(cancellationToken).ConfigureAwait(false); } + /// + /// Deletes the stored artwork files of the music library item of the provided identified by , + /// and then deletes the artwork rows of that item. + /// + /// The type of the music library item that owns the artwork. + /// The Id of the music library item that owns the artwork. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> DeleteStoredArtworkAndRowsAsync(MusicArtworkOwnerType ownerType, Guid ownerId, CancellationToken cancellationToken) + { + Result> getArtworkResult = await _unitOfWork.MusicArtworkRepository + .GetByOwnerAsync(ownerType, ownerId, cancellationToken).ConfigureAwait(false); + if (getArtworkResult.IsFailure) + return getArtworkResult.Errors; + + // The stored files are deleted best-effort, since a missing or locked file must not prevent the permanent removal of the media library item. + foreach (MusicArtworkEntity artwork in getArtworkResult.Value) + { + if (string.IsNullOrWhiteSpace(artwork.FileName)) + continue; + + Result deleteStoredArtworkResult = _musicArtworkService.DeleteStoredArtwork(artwork.FileName); + if (deleteStoredArtworkResult.IsFailure) + _logger.LogWarning("Failed to delete the stored {OwnerType} artwork at '{ArtworkPath}' of the music library item with Id '{OwnerId}', the file might remain orphaned.", ownerType, artwork.FileName, ownerId); + } + + return await _unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(ownerType, ownerId, cancellationToken).ConfigureAwait(false); + } + /// /// Persists the changes made to the storage medium. /// diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandler.cs index 571372f6..23500983 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandler.cs @@ -78,7 +78,7 @@ public class LibraryDeletedDomainEventHandler : IDomainEventHandler librarySegmentResult = _pathService.SanitizeSegment($"{domainEvent.Library.Title}-{libraryId}"); + Result librarySegmentResult = _pathService.SanitizeCompositeSegment(domainEvent.Library.Title, libraryId.ToString()); if (librarySegmentResult.IsFailure) throw new EventualConsistencyException(librarySegmentResult.FirstError, librarySegmentResult.Errors); DeleteLibraryDirectory(_mediaSettingsModel.BooksDirectory, librarySegmentResult.Value.Name); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/DeletedAlbumResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/DeletedAlbumResponse.cs new file mode 100644 index 00000000..de548e14 --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/DeletedAlbumResponse.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Represents a music album that the user deleted and can restore. +/// +/// The unique identifier of the album. +/// The unique identifier of the media library the album belongs to. +/// The unique identifier of the artist the album belongs to. +/// The name of the artist the album belongs to. +/// The title of the album. +/// The date and time when the album was deleted. +/// The relative path of the stored cover image of the album, when it has one. +public record DeletedAlbumResponse( + Guid Id, + Guid LibraryId, + Guid ArtistId, + string ArtistName, + string Title, + DateTime DeletedOnUtc, + string? CoverPath +); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/DeletedArtistResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/DeletedArtistResponse.cs new file mode 100644 index 00000000..2bf4be3f --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/DeletedArtistResponse.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Represents a music artist that the user deleted and can restore. +/// +/// The unique identifier of the artist. +/// The unique identifier of the media library the artist belongs to. +/// The name of the artist. +/// The date and time when the artist was deleted. +/// The relative path of the stored cover image of the artist, when it has one. +public record DeletedArtistResponse( + Guid Id, + Guid LibraryId, + string Name, + DateTime DeletedOnUtc, + string? CoverPath +); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/DeletedTrackResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/DeletedTrackResponse.cs new file mode 100644 index 00000000..bbcbfbf3 --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/DeletedTrackResponse.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Represents a music track that the user deleted and can restore. +/// +/// The unique identifier of the track. +/// The unique identifier of the media library the track belongs to. +/// The unique identifier of the artist the track belongs to. +/// The name of the artist the track belongs to. +/// The unique identifier of the album the track belongs to. +/// The title of the album the track belongs to. +/// The title of the track. +/// The file system path of the track. +/// The date and time when the track was deleted. +public record DeletedTrackResponse( + Guid Id, + Guid LibraryId, + Guid ArtistId, + string ArtistName, + Guid AlbumId, + string AlbumTitle, + string Title, + string Path, + DateTime DeletedOnUtc +); diff --git a/src/Lumina.DataAccess/Common/Configuration/AlbumConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/AlbumConfiguration.cs index 29e95f2f..845ddd36 100644 --- a/src/Lumina.DataAccess/Common/Configuration/AlbumConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/AlbumConfiguration.cs @@ -130,6 +130,12 @@ public class AlbumConfiguration : IEntityTypeConfiguration builder.Property(album => album.MetadataProvider) .HasMaxLength(100) .HasColumnOrder(38); + builder.Property(album => album.IsDeleted) + .IsRequired() + .HasDefaultValue(false) + .HasColumnOrder(39); + builder.Property(album => album.DeletedOnUtc) + .HasColumnOrder(40); builder.HasOne(album => album.Artist) .WithMany(artist => artist.Albums) @@ -232,5 +238,9 @@ public class AlbumConfiguration : IEntityTypeConfiguration builder.HasIndex(album => new { album.ArtistId, album.Title }); builder.HasIndex(album => new { album.LibraryId, album.Title }); + // The deleted items page filters by library and deletion state, and orders by the stored deletion time, the title and the Id, so the + // filtered index follows the same order and no temporary B-tree is needed for the sort, while visible rows add no entries to it. + builder.HasIndex(album => new { album.LibraryId, album.IsDeleted, album.DeletedOnUtc, album.Title, album.Id }) + .HasFilter("\"IsDeleted\" = 1"); } } diff --git a/src/Lumina.DataAccess/Common/Configuration/ArtistConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/ArtistConfiguration.cs index a4a63eb7..b6ecfb88 100644 --- a/src/Lumina.DataAccess/Common/Configuration/ArtistConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/ArtistConfiguration.cs @@ -83,6 +83,12 @@ public class ArtistConfiguration : IEntityTypeConfiguration builder.Property(artist => artist.MetadataProvider) .HasMaxLength(100) .HasColumnOrder(19); + builder.Property(artist => artist.IsDeleted) + .IsRequired() + .HasDefaultValue(false) + .HasColumnOrder(20); + builder.Property(artist => artist.DeletedOnUtc) + .HasColumnOrder(21); // The areas are owned value objects that are never referenced on their own, so they are stored as JSON documents next to the artist. builder.OwnsOne(artist => artist.Area, areaBuilder => areaBuilder.ToJson()); @@ -202,7 +208,14 @@ public class ArtistConfiguration : IEntityTypeConfiguration .HasForeignKey(contributor => contributor.ArtistId) .OnDelete(DeleteBehavior.Cascade); + // The same visible artist cannot appear twice in the same library, while a deleted artist does not block a new visible artist with the + // same name, so that a new file of an artist the user deleted can still materialize as a new, visible artist. builder.HasIndex(artist => new { artist.LibraryId, artist.Name }) - .IsUnique(); // the same artist cannot appear twice in the same library + .IsUnique() + .HasFilter("\"IsDeleted\" = 0"); + // The deleted items page filters by library and deletion state, and orders by the stored deletion time, the name and the Id, so the + // filtered index follows the same order and no temporary B-tree is needed for the sort, while visible rows add no entries to it. + builder.HasIndex(artist => new { artist.LibraryId, artist.IsDeleted, artist.DeletedOnUtc, artist.Name, artist.Id }) + .HasFilter("\"IsDeleted\" = 1"); } } diff --git a/src/Lumina.DataAccess/Common/Configuration/TrackConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/TrackConfiguration.cs index 1999f0fa..0a23b645 100644 --- a/src/Lumina.DataAccess/Common/Configuration/TrackConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/TrackConfiguration.cs @@ -155,6 +155,12 @@ public class TrackConfiguration : IEntityTypeConfiguration builder.Property(track => track.Container) .HasMaxLength(50) .HasColumnOrder(49); + builder.Property(track => track.IsDeleted) + .IsRequired() + .HasDefaultValue(false) + .HasColumnOrder(50); + builder.Property(track => track.DeletedOnUtc) + .HasColumnOrder(51); builder.HasOne(track => track.Album) .WithMany(album => album.Tracks) @@ -291,5 +297,9 @@ public class TrackConfiguration : IEntityTypeConfiguration builder.HasIndex(track => new { track.AlbumId, track.TrackNumber }); builder.HasIndex(track => new { track.LibraryId, track.Path }) .IsUnique(); // the same physical track file cannot appear twice in the same library + // The deleted items page filters by library and deletion state, and orders by the stored deletion time, the title and the Id, so the + // filtered index follows the same order and no temporary B-tree is needed for the sort, while visible rows add no entries to it. + builder.HasIndex(track => new { track.LibraryId, track.IsDeleted, track.DeletedOnUtc, track.Title, track.Id }) + .HasFilter("\"IsDeleted\" = 1"); } } diff --git a/src/Lumina.DataAccess/Common/Migrations/20261114210438_AddsMusicDeletionState.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20261114210438_AddsMusicDeletionState.Designer.cs new file mode 100644 index 00000000..a51dd98a --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261114210438_AddsMusicDeletionState.Designer.cs @@ -0,0 +1,3956 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20261114210438_AddsMusicDeletionState")] + partial class AddsMusicDeletionState + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("AlbumGenres", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("AlbumGenres", (string)null); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("AlbumTags", (string)null); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("ArtistGenres", (string)null); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("ArtistTags", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Favorites.FavoriteEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("MediaKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId", "CreatedOnUtc"); + + b.HasIndex("UserId", "MediaKind", "CreatedOnUtc"); + + b.HasIndex("UserId", "MediaKind", "MediaItemId") + .IsUnique(); + + b.ToTable("Favorites", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaConsumption.MediaConsumptionRecordEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ConsecutivePagesRead") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0) + .HasColumnOrder(14); + + b.Property("ConsumedDurationMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("EndedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LastActivityOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("LastPositionKind") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastPositionLocation") + .HasMaxLength(4096) + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastPositionTimeOffsetMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LastProgressFraction") + .HasColumnType("REAL") + .HasColumnOrder(13); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("MediaKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER") + .HasColumnOrder(15); + + b.HasKey("Id"); + + b.HasIndex("UserId", "MediaKind", "StartedOnUtc"); + + b.HasIndex("UserId", "MediaKind", "MediaItemId", "LastActivityOnUtc"); + + b.ToTable("MediaConsumptionRecords", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaConsumption.MediaResumePointEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LastConsumedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("LastPositionKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastPositionLocation") + .HasMaxLength(4096) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("LastPositionTimeOffsetMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("LastProgressFraction") + .HasColumnType("REAL") + .HasColumnOrder(8); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.HasKey("Id"); + + b.HasIndex("UserId", "MediaKind", "MediaItemId") + .IsUnique(); + + b.ToTable("MediaResumePoints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("AlbumId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("AlbumContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Barcode") + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("DeletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(39); + + b.Property("Label") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaFormat") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(36); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Packaging") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ReleaseStatus") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("ReleaseTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TotalDiscs") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("TotalTracks") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.HasKey("Id"); + + b.HasIndex("ArtistId", "Title"); + + b.HasIndex("LibraryId", "Title"); + + b.HasIndex("LibraryId", "IsDeleted", "DeletedOnUtc", "Title", "Id") + .HasFilter("\"IsDeleted\" = 1"); + + b.ToTable("Albums", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("ArtistId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("ArtistContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Country") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("DeletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Gender") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(20); + + b.Property("IsEnded") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("LifeSpanBegin") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LifeSpanEnd") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(17); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Type") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("Website") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "Name") + .IsUnique() + .HasFilter("\"IsDeleted\" = 0"); + + b.HasIndex("LibraryId", "IsDeleted", "DeletedOnUtc", "Name", "Id") + .HasFilter("\"IsDeleted\" = 1"); + + b.ToTable("Artists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("OwnerId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("OwnerType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("OwnerType", "OwnerId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("MusicArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicLibraryScanItemMetadataEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("ArtistName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryScanId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.PrimitiveCollection("Moods") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReleaseName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("ReleaseType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("ReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(28); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(29); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(26); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(27); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("TrackTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("LibraryScanId", "Path") + .IsUnique(); + + b.ToTable("MusicLibraryScanItemMetadata", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("TrackId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("TrackContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(44); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(23); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("Bpm") + .HasColumnType("INTEGER") + .HasColumnOrder(30); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(49); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("DeletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(51); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(27); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(50); + + b.Property("IsVideo") + .HasColumnType("INTEGER") + .HasColumnOrder(31); + + b.Property("Key") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(42); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(43); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(41); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(47); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(48); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(45); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(46); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(26); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("WorkType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.HasKey("Id"); + + b.HasIndex("AlbumId", "TrackNumber"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.HasIndex("LibraryId", "IsDeleted", "DeletedOnUtc", "Title", "Id") + .HasFilter("\"IsDeleted\" = 1"); + + b.ToTable("Tracks", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CompletionThresholdPercentage") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("IsContentOnSsd") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(18); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("PathTemplateFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("ShouldTrackConsumptionProgress") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(16); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("DeletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(42); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(41); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.HasIndex("LibraryId", "IsDeleted", "DeletedOnUtc", "Title", "Id"); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("EntryCount") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0) + .HasColumnOrder(10); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Type") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0L) + .HasColumnOrder(9); + + b.HasKey("Id"); + + b.HasIndex("UserId", "UpdatedOnUtc"); + + b.ToTable("Playlists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemType") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PlaylistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Position") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("MediaItemId"); + + b.HasIndex("PlaylistId", "Position") + .IsUnique(); + + b.ToTable("PlaylistEntries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryBookReaderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryBookReaderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Hour") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("IntervalMinutes") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("LastCompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastStartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Minute") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("OwnerUserId") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ScheduleType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.ToTable("ScheduledJobs", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobExecutionEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("IsCycleRun") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ScheduledJobId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("WasCycleActive") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("ScheduledJobId"); + + b.HasIndex("StartedOnUtc", "ScheduledJobId"); + + b.ToTable("ScheduledJobExecutions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.SchedulerDisplayPreferencesEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayTimeSpan") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("DisplayTimeUnit") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("JobTypeFilter") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("SchedulerDisplayPreferences", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsGaplessPlaybackEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("IsMuted") + .HasColumnType("INTEGER") + .HasColumnOrder(29); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ReplayGainMode") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("ShouldAggregateArtworkWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldAutoplay") + .HasColumnType("INTEGER") + .HasColumnOrder(15); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("ShouldKeepDownloadingWhilePaused") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("ShouldPreserveBookStyles") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("StreamingQuality") + .HasColumnType("INTEGER") + .HasColumnOrder(18); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Volume") + .HasColumnType("REAL") + .HasColumnOrder(28); + + b.Property("VuMeterHighThreshold") + .HasColumnType("REAL") + .HasColumnOrder(23); + + b.Property("VuMeterMediumThreshold") + .HasColumnType("REAL") + .HasColumnOrder(22); + + b.Property("VuMeterOrientation") + .HasColumnType("INTEGER") + .HasColumnOrder(19); + + b.Property("VuMeterPeakHoldDurationInMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("VuMeterPeakReleasePerSecond") + .HasColumnType("REAL") + .HasColumnOrder(27); + + b.Property("VuMeterReleasePerSecond") + .HasColumnType("REAL") + .HasColumnOrder(26); + + b.Property("VuMeterSegmentCount") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("VuMeterSegmentGap") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("VuMeterShowPeak") + .HasColumnType("INTEGER") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("TrackGenres", (string)null); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("TrackTags", (string)null); + }); + + modelBuilder.Entity("AlbumGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Favorites.FavoriteEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaConsumption.MediaConsumptionRecordEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaConsumption.MediaResumePointEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany("Contributors") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", "Artist") + .WithMany("Albums") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumCatalogNumberEntity", "CatalogNumbers", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("CatalogNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumCatalogNumbers", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumReleaseTypeEntity", "ReleaseTypes", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("ReleaseType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumReleaseTypes", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.Navigation("Artist"); + + b.Navigation("CatalogNumbers"); + + b.Navigation("Ratings"); + + b.Navigation("ReleaseTypes"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany("Contributors") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "Area", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("Area") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "BeginArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("BeginArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "EndArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("EndArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistAliasEntity", "Aliases", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("BeginDate") + .HasColumnType("TEXT"); + + b1.Property("EndDate") + .HasColumnType("TEXT"); + + b1.Property("IsEnded") + .HasColumnType("INTEGER"); + + b1.Property("IsPrimary") + .HasColumnType("INTEGER"); + + b1.Property("Locale") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("Type") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistAliases", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIpiEntity", "Ipis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIpis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIsniEntity", "Isnis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIsnis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.Navigation("Aliases"); + + b.Navigation("Area"); + + b.Navigation("BeginArea"); + + b.Navigation("EndArea"); + + b.Navigation("Ipis"); + + b.Navigation("Isnis"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany("Contributors") + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", "Album") + .WithMany("Tracks") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackIsrcEntity", "Isrcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnName("ISRC"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackIsrcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackMoodEntity", "Moods", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackMoods", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkIswcEntity", "WorkIswcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkIswcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkLanguageEntity", "WorkLanguages", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LanguageCode") + .IsRequired() + .HasMaxLength(5) + .HasColumnType("TEXT"); + + b1.Property("LanguageName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("NativeName") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkLanguages", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.Navigation("Album"); + + b.Navigation("Isrcs"); + + b.Navigation("Moods"); + + b.Navigation("Ratings"); + + b.Navigation("WorkIswcs"); + + b.Navigation("WorkLanguages"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryPathTemplatePartEntity", "PathTemplateParts", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("IsOptional") + .HasColumnType("INTEGER"); + + b1.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Position") + .HasColumnType("INTEGER") + .HasColumnName("Position"); + + b1.Property("Representation") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId", "Position") + .IsUnique(); + + b1.ToTable("LibraryPathTemplateParts", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("PathTemplateParts"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Artwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Contributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", null) + .WithMany("Entries") + .HasForeignKey("PlaylistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Navigation("Contributors"); + + b.Navigation("Tracks"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Navigation("Albums"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("Artwork"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Navigation("Entries"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261114210438_AddsMusicDeletionState.cs b/src/Lumina.DataAccess/Common/Migrations/20261114210438_AddsMusicDeletionState.cs new file mode 100644 index 00000000..ed54ba59 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261114210438_AddsMusicDeletionState.cs @@ -0,0 +1,139 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsMusicDeletionState : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_Artists_LibraryId_Name", + table: "Artists"); + + migrationBuilder.AddColumn( + name: "DeletedOnUtc", + table: "Tracks", + type: "TEXT", + nullable: true) + .Annotation("Relational:ColumnOrder", 51); + + migrationBuilder.AddColumn( + name: "IsDeleted", + table: "Tracks", + type: "INTEGER", + nullable: false, + defaultValue: false) + .Annotation("Relational:ColumnOrder", 50); + + migrationBuilder.AddColumn( + name: "DeletedOnUtc", + table: "Artists", + type: "TEXT", + nullable: true) + .Annotation("Relational:ColumnOrder", 21); + + migrationBuilder.AddColumn( + name: "IsDeleted", + table: "Artists", + type: "INTEGER", + nullable: false, + defaultValue: false) + .Annotation("Relational:ColumnOrder", 20); + + migrationBuilder.AddColumn( + name: "DeletedOnUtc", + table: "Albums", + type: "TEXT", + nullable: true) + .Annotation("Relational:ColumnOrder", 40); + + migrationBuilder.AddColumn( + name: "IsDeleted", + table: "Albums", + type: "INTEGER", + nullable: false, + defaultValue: false) + .Annotation("Relational:ColumnOrder", 39); + + migrationBuilder.CreateIndex( + name: "IX_Tracks_LibraryId_IsDeleted_DeletedOnUtc_Title_Id", + table: "Tracks", + columns: new[] { "LibraryId", "IsDeleted", "DeletedOnUtc", "Title", "Id" }, + filter: "\"IsDeleted\" = 1"); + + migrationBuilder.CreateIndex( + name: "IX_Artists_LibraryId_IsDeleted_DeletedOnUtc_Name_Id", + table: "Artists", + columns: new[] { "LibraryId", "IsDeleted", "DeletedOnUtc", "Name", "Id" }, + filter: "\"IsDeleted\" = 1"); + + migrationBuilder.CreateIndex( + name: "IX_Artists_LibraryId_Name", + table: "Artists", + columns: new[] { "LibraryId", "Name" }, + unique: true, + filter: "\"IsDeleted\" = 0"); + + migrationBuilder.CreateIndex( + name: "IX_Albums_LibraryId_IsDeleted_DeletedOnUtc_Title_Id", + table: "Albums", + columns: new[] { "LibraryId", "IsDeleted", "DeletedOnUtc", "Title", "Id" }, + filter: "\"IsDeleted\" = 1"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_Tracks_LibraryId_IsDeleted_DeletedOnUtc_Title_Id", + table: "Tracks"); + + migrationBuilder.DropIndex( + name: "IX_Artists_LibraryId_IsDeleted_DeletedOnUtc_Name_Id", + table: "Artists"); + + migrationBuilder.DropIndex( + name: "IX_Artists_LibraryId_Name", + table: "Artists"); + + migrationBuilder.DropIndex( + name: "IX_Albums_LibraryId_IsDeleted_DeletedOnUtc_Title_Id", + table: "Albums"); + + migrationBuilder.DropColumn( + name: "DeletedOnUtc", + table: "Tracks"); + + migrationBuilder.DropColumn( + name: "IsDeleted", + table: "Tracks"); + + migrationBuilder.DropColumn( + name: "DeletedOnUtc", + table: "Artists"); + + migrationBuilder.DropColumn( + name: "IsDeleted", + table: "Artists"); + + migrationBuilder.DropColumn( + name: "DeletedOnUtc", + table: "Albums"); + + migrationBuilder.DropColumn( + name: "IsDeleted", + table: "Albums"); + + migrationBuilder.CreateIndex( + name: "IX_Artists_LibraryId_Name", + table: "Artists", + columns: new[] { "LibraryId", "Name" }, + unique: true); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index e4311226..224df559 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -652,6 +652,10 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(32); + b.Property("DeletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(40); + b.Property("Description") .HasMaxLength(2000) .HasColumnType("TEXT") @@ -662,6 +666,12 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(6); + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(39); + b.Property("Label") .HasMaxLength(255) .HasColumnType("TEXT") @@ -807,6 +817,9 @@ namespace Lumina.DataAccess.Common.Migrations b.HasIndex("LibraryId", "Title"); + b.HasIndex("LibraryId", "IsDeleted", "DeletedOnUtc", "Title", "Id") + .HasFilter("\"IsDeleted\" = 1"); + b.ToTable("Albums", (string)null); }); @@ -875,6 +888,10 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(13); + b.Property("DeletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(21); + b.Property("Disambiguation") .HasMaxLength(255) .HasColumnType("TEXT") @@ -885,6 +902,12 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(6); + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(20); + b.Property("IsEnded") .HasColumnType("INTEGER") .HasColumnOrder(10); @@ -954,7 +977,11 @@ namespace Lumina.DataAccess.Common.Migrations b.HasKey("Id"); b.HasIndex("LibraryId", "Name") - .IsUnique(); + .IsUnique() + .HasFilter("\"IsDeleted\" = 0"); + + b.HasIndex("LibraryId", "IsDeleted", "DeletedOnUtc", "Name", "Id") + .HasFilter("\"IsDeleted\" = 1"); b.ToTable("Artists", (string)null); }); @@ -1279,6 +1306,10 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(37); + b.Property("DeletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(51); + b.Property("Description") .HasMaxLength(2000) .HasColumnType("TEXT") @@ -1297,6 +1328,12 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("INTEGER") .HasColumnOrder(20); + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(50); + b.Property("IsVideo") .HasColumnType("INTEGER") .HasColumnOrder(31); @@ -1459,6 +1496,9 @@ namespace Lumina.DataAccess.Common.Migrations b.HasIndex("LibraryId", "Path") .IsUnique(); + b.HasIndex("LibraryId", "IsDeleted", "DeletedOnUtc", "Title", "Id") + .HasFilter("\"IsDeleted\" = 1"); + b.ToTable("Tracks", (string)null); }); diff --git a/src/Lumina.DataAccess/Core/Repositories/Favorites/FavoriteRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Favorites/FavoriteRepository.cs index 5a7319f4..b08b7565 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Favorites/FavoriteRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Favorites/FavoriteRepository.cs @@ -113,17 +113,17 @@ internal sealed class FavoriteRepository : IFavoriteRepository { FavoriteMediaKind.MusicArtist => await _luminaDbContext.Artists .AsNoTracking() - .Where(artist => artist.Id == mediaItemId) + .Where(artist => artist.Id == mediaItemId && !artist.IsDeleted) .Select(artist => (Guid?)artist.LibraryId) .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false), FavoriteMediaKind.MusicAlbum => await _luminaDbContext.Albums .AsNoTracking() - .Where(album => album.Id == mediaItemId) + .Where(album => album.Id == mediaItemId && !album.IsDeleted && !album.Artist!.IsDeleted) .Select(album => (Guid?)album.LibraryId) .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false), FavoriteMediaKind.MusicTrack => await _luminaDbContext.Tracks .AsNoTracking() - .Where(track => track.Id == mediaItemId) + .Where(track => track.Id == mediaItemId && !track.IsDeleted && !track.Album!.IsDeleted && !track.Album!.Artist!.IsDeleted) .Select(track => (Guid?)track.LibraryId) .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false), FavoriteMediaKind.Book => await _luminaDbContext.Books @@ -293,7 +293,7 @@ internal sealed class FavoriteRepository : IFavoriteRepository // The cover of the artist is the cover artwork stored for it, if any, the same one the artist listing exposes. rows = await _luminaDbContext.Artists .AsNoTracking() - .Where(artist => requestedIds.Contains(artist.Id)) + .Where(artist => requestedIds.Contains(artist.Id) && !artist.IsDeleted) .Select(artist => new DisplayRow( artist.Id, artist.LibraryId, @@ -311,7 +311,7 @@ internal sealed class FavoriteRepository : IFavoriteRepository case FavoriteMediaKind.MusicAlbum: rows = await (from album in _luminaDbContext.Albums.AsNoTracking() join artist in _luminaDbContext.Artists on album.ArtistId equals artist.Id - where requestedIds.Contains(album.Id) + where requestedIds.Contains(album.Id) && !album.IsDeleted && !artist.IsDeleted select new DisplayRow( album.Id, album.LibraryId, @@ -331,7 +331,7 @@ internal sealed class FavoriteRepository : IFavoriteRepository rows = await (from track in _luminaDbContext.Tracks.AsNoTracking() join album in _luminaDbContext.Albums on track.AlbumId equals album.Id join artist in _luminaDbContext.Artists on album.ArtistId equals artist.Id - where requestedIds.Contains(track.Id) + where requestedIds.Contains(track.Id) && !track.IsDeleted && !album.IsDeleted && !artist.IsDeleted select new DisplayRow( track.Id, track.LibraryId, diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs index 7add1179..9dc26117 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs @@ -3,6 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums; using Lumina.DataAccess.Common.Persistence; using Lumina.DataAccess.Core.UoW; @@ -28,16 +29,19 @@ internal sealed class AlbumRepository : IAlbumRepository { private readonly LuminaDbContext _luminaDbContext; private readonly ITrackRepository _trackRepository; + private readonly IDateTimeProvider _dateTimeProvider; /// /// Initializes a new instance of the class. /// /// Injected Entity Framework DbContext. /// Injected repository for tracks. - public AlbumRepository(LuminaDbContext luminaDbContext, ITrackRepository trackRepository) + /// Injected provider for the current UTC time, used to stamp deletions deterministically. + public AlbumRepository(LuminaDbContext luminaDbContext, ITrackRepository trackRepository, IDateTimeProvider dateTimeProvider) { _luminaDbContext = luminaDbContext; _trackRepository = trackRepository; + _dateTimeProvider = dateTimeProvider; } /// @@ -121,7 +125,7 @@ internal sealed class AlbumRepository : IAlbumRepository .Include(repositoryAlbum => repositoryAlbum.Ratings) .Include(repositoryAlbum => repositoryAlbum.Contributors) .AsSplitQuery() - .FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.Id == data.Id, cancellationToken).ConfigureAwait(false); + .FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.Id == data.Id && !repositoryAlbum.IsDeleted && !repositoryAlbum.Artist!.IsDeleted, cancellationToken).ConfigureAwait(false); if (foundAlbum is null) return Errors.Music.AlbumNotFound; @@ -141,9 +145,17 @@ internal sealed class AlbumRepository : IAlbumRepository // The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor. Guid artistId = foundAlbum.ArtistId; Guid libraryId = foundAlbum.LibraryId; + bool isDeleted = foundAlbum.IsDeleted; + DateTime? deletedOnUtc = foundAlbum.DeletedOnUtc; EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundAlbum, data); foundAlbum.ArtistId = artistId; foundAlbum.LibraryId = libraryId; + // The deletion state is owned by the explicit delete and restore operations. Clearing the modified flags keeps it out of the UPDATE statement, + // so an edit that raced with a delete can never write the deletion state back and resurrect the album. + foundAlbum.IsDeleted = isDeleted; + foundAlbum.DeletedOnUtc = deletedOnUtc; + _luminaDbContext.Entry(foundAlbum).Property(album => album.IsDeleted).IsModified = false; + _luminaDbContext.Entry(foundAlbum).Property(album => album.DeletedOnUtc).IsModified = false; // Tags and genres are shared across the whole database, so the stored rows whose names already exist are reused, and only the missing names are inserted. Result reconcileTagsResult = await SharedReferenceResolver.ReconcileAsync(_luminaDbContext, foundAlbum.Tags, data.Tags, Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); @@ -204,7 +216,8 @@ internal sealed class AlbumRepository : IAlbumRepository /// An containing either an , or an error. public async Task> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) { - IQueryable query = _luminaDbContext.Albums; + // A deleted album, or an album of a deleted artist, is kept in the storage medium only so that its paths stay reserved and it can be restored, so it is never returned to a caller. + IQueryable query = _luminaDbContext.Albums.Where(album => !album.IsDeleted && !album.Artist!.IsDeleted); if (!shouldTrackEntities) query = query.AsNoTracking(); if (shouldIncludeNavigationProperties) @@ -215,17 +228,17 @@ internal sealed class AlbumRepository : IAlbumRepository .Include(album => album.Tags) .Include(album => album.Genres) .Include(album => album.Contributors) - .Include(album => album.Tracks) + .Include(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Ratings) - .Include(album => album.Tracks) + .Include(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Genres) - .Include(album => album.Tracks) + .Include(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Tags) - .Include(album => album.Tracks) + .Include(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Moods) - .Include(album => album.Tracks) + .Include(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Isrcs) - .Include(album => album.Tracks) + .Include(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Contributors) .AsSplitQuery(); } @@ -233,7 +246,7 @@ internal sealed class AlbumRepository : IAlbumRepository } /// - /// Gets all the albums of the artist identified by . + /// Gets the albums of the artist identified by that are not soft deleted. /// /// The Id of the artist whose albums are retrieved. /// Cancellation token that can be used to stop the execution. @@ -245,25 +258,54 @@ internal sealed class AlbumRepository : IAlbumRepository .Include(album => album.Tags) .Include(album => album.Genres) .Include(album => album.Contributors) - .Include(album => album.Tracks) + .Include(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Ratings) - .Include(album => album.Tracks) + .Include(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Genres) - .Include(album => album.Tracks) + .Include(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Tags) - .Include(album => album.Tracks) + .Include(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Moods) - .Include(album => album.Tracks) + .Include(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Isrcs) - .Include(album => album.Tracks) + .Include(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Contributors) .AsSplitQuery() + .Where(album => album.ArtistId == artistId && !album.IsDeleted && !album.Artist!.IsDeleted) + .OrderBy(album => album.Title) + .ThenBy(album => album.Id) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets all the albums of the artist identified by , whether they are soft deleted or not. + /// + /// The Id of the artist whose albums are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + public async Task>> GetByArtistIdIncludingDeletedAsync(Guid artistId, CancellationToken cancellationToken) + { + return await _luminaDbContext.Albums + .AsNoTracking() .Where(album => album.ArtistId == artistId) .OrderBy(album => album.Title) .ThenBy(album => album.Id) .ToListAsync(cancellationToken).ConfigureAwait(false); } + /// + /// Gets the album identified by , whether it is soft deleted or not, without loading its navigation properties. + /// + /// The Id of the album to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either the , or an error. + public async Task> GetIncludingDeletedByIdAsync(Guid id, CancellationToken cancellationToken) + { + return await _luminaDbContext.Albums + .AsNoTracking() + .FirstOrDefaultAsync(album => album.Id == id, cancellationToken).ConfigureAwait(false); + } + /// /// Gets the lightweight read models of the albums of the artist identified by , /// or all of them when the pagination data is , projecting only the fields needed to display the albums in a card-based grid. @@ -279,7 +321,7 @@ internal sealed class AlbumRepository : IAlbumRepository // The cover of the album is the cover artwork stored for it, if any, and it is exposed so that the clients can display it without loading the whole album. IQueryable liteRowsQuery = _luminaDbContext.Albums .AsNoTracking() - .Where(album => album.ArtistId == artistId) + .Where(album => album.ArtistId == artistId && !album.IsDeleted && !album.Artist!.IsDeleted) .OrderBy(album => album.Title) .ThenBy(album => album.Id) .Select(album => new AlbumLiteRow( @@ -335,7 +377,7 @@ internal sealed class AlbumRepository : IAlbumRepository public async Task> GetByTitleAsync(Guid artistId, string title, CancellationToken cancellationToken) { AlbumEntity? album = await _luminaDbContext.Albums - .FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.ArtistId == artistId && repositoryAlbum.Title == title, cancellationToken).ConfigureAwait(false); + .FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.ArtistId == artistId && repositoryAlbum.Title == title && !repositoryAlbum.IsDeleted && !repositoryAlbum.Artist!.IsDeleted, cancellationToken).ConfigureAwait(false); return album; } @@ -352,10 +394,98 @@ internal sealed class AlbumRepository : IAlbumRepository string directoryPrefix = directoryPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar; AlbumEntity? album = await _luminaDbContext.Albums .FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.ArtistId == artistId + && !repositoryAlbum.IsDeleted + && !repositoryAlbum.Artist!.IsDeleted && repositoryAlbum.Tracks.Any(track => track.Path.StartsWith(directoryPrefix)), cancellationToken).ConfigureAwait(false); return album; } + /// + /// Gets the soft deleted album identified by , when its artist is not soft deleted. + /// + /// The Id of the soft deleted album to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either the soft deleted , when the album does not exist, is not soft deleted, or its artist is soft deleted, or an error. + public async Task> GetSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken) + { + return await _luminaDbContext.Albums + .AsNoTracking() + .FirstOrDefaultAsync(album => album.Id == id && album.IsDeleted && !album.Artist!.IsDeleted, cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the soft deleted albums of the media library identified by , whose artist is not soft deleted. + /// + /// The Id of the media library whose soft deleted albums are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the soft deleted albums, or an error. + public async Task>> GetSoftDeletedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken) + { + return await _luminaDbContext.Albums + .AsNoTracking() + .Include(album => album.Artist) + .Where(album => album.LibraryId == libraryId && album.IsDeleted && !album.Artist!.IsDeleted) + // The deletion time is stored when the album is deleted, so later writes to the hidden row cannot change the order of the deleted items, + // and every deleted row carries a deletion time because the delete operation always sets it. All terms sort descending, so the filtered + // (LibraryId, IsDeleted, DeletedOnUtc, Title, Id) index can be scanned backwards and the database does not build a temporary B-tree. + .OrderByDescending(album => album.DeletedOnUtc) + .ThenByDescending(album => album.Title) + .ThenByDescending(album => album.Id) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Soft deletes the album identified by , without removing its stored metadata or artwork, when another visible album of its artist remains. + /// + /// + /// The update is executed directly against the storage medium, so an entity already tracked by the caller is not refreshed, and the audit fields + /// stamped by the change tracker are not updated; the deletion time is stored in instead. + /// + /// The Id of the album to soft delete. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> SoftDeleteByIdAsync(Guid id, CancellationToken cancellationToken) + { + DateTime deletedOnUtc = _dateTimeProvider.UtcNow; + + // The condition that an artist must have at least one remaining album is re-checked here so a delete that raced with another cannot leave the artist without albums. + int updatedRows = await _luminaDbContext.Albums + .Where(album => album.Id == id + && !album.IsDeleted + && _luminaDbContext.Albums.Any(sibling => sibling.ArtistId == album.ArtistId && sibling.Id != album.Id && !sibling.IsDeleted)) + .ExecuteUpdateAsync(setters => setters + .SetProperty(album => album.IsDeleted, true) + .SetProperty(album => album.DeletedOnUtc, deletedOnUtc), cancellationToken).ConfigureAwait(false); + if (updatedRows > 0) + return Result.Updated; + + // The update matched nothing, so the album is missing, is already deleted, or is the last visible album of its artist. The row is read + // only to report the reason, never to decide the transition. + AlbumEntity? album = await _luminaDbContext.Albums + .AsNoTracking() + .FirstOrDefaultAsync(candidate => candidate.Id == id, cancellationToken).ConfigureAwait(false); + if (album is null || album.IsDeleted) + return Errors.Music.AlbumNotFound; + return Errors.Music.ArtistMustHaveAtLeastOneAlbum; + } + + /// + /// Restores the soft deleted album identified by . + /// + /// The Id of the album to restore. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> RestoreSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken) + { + AlbumEntity? album = await _luminaDbContext.Albums.FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.Id == id, cancellationToken).ConfigureAwait(false); + if (album is null || !album.IsDeleted) + return Errors.Music.AlbumNotFound; + + album.IsDeleted = false; + album.DeletedOnUtc = null; + return Result.Updated; + } + /// /// Deletes the album identified by , together with its tracks and its contributions, by the database cascade. /// @@ -382,7 +512,7 @@ internal sealed class AlbumRepository : IAlbumRepository public async Task> GetAlbumsNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken) { return await _luminaDbContext.Albums - .CountAsync(album => album.LibraryId == libraryId && album.MetadataStatus != MetadataStatus.Enriched, cancellationToken).ConfigureAwait(false); + .CountAsync(album => album.LibraryId == libraryId && !album.IsDeleted && !album.Artist!.IsDeleted && album.MetadataStatus != MetadataStatus.Enriched, cancellationToken).ConfigureAwait(false); } /// @@ -395,6 +525,8 @@ internal sealed class AlbumRepository : IAlbumRepository { return await _luminaDbContext.Albums .CountAsync(album => album.LibraryId == libraryId + && !album.IsDeleted + && !album.Artist!.IsDeleted && !_luminaDbContext.MusicArtwork.Any(musicArtwork => musicArtwork.OwnerType == MusicArtworkOwnerType.Album && musicArtwork.OwnerId == album.Id && (musicArtwork.Status == ArtworkStatus.Enriched || musicArtwork.Status == ArtworkStatus.NotAvailable)), cancellationToken).ConfigureAwait(false); @@ -416,6 +548,8 @@ internal sealed class AlbumRepository : IAlbumRepository .AsNoTracking() .Include(album => album.Artist) .Where(album => album.LibraryId == libraryId + && !album.IsDeleted + && !album.Artist!.IsDeleted && !excludedIds.Contains(album.Id) && !_luminaDbContext.MusicArtwork.Any(musicArtwork => musicArtwork.OwnerType == MusicArtworkOwnerType.Album && musicArtwork.OwnerId == album.Id @@ -439,7 +573,7 @@ internal sealed class AlbumRepository : IAlbumRepository List rows = await _luminaDbContext.Tracks .AsNoTracking() - .Where(track => albumIdsList.Contains(track.AlbumId)) + .Where(track => albumIdsList.Contains(track.AlbumId) && !track.IsDeleted) .OrderBy(track => track.AlbumId) .ThenBy(track => track.Path) .Select(track => new AlbumTrackPathRow(track.AlbumId, track.Path)) diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs index faf9039b..89e3d7db 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs @@ -5,6 +5,7 @@ using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists; using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Common.Specifications; using Lumina.DataAccess.Common.Persistence; using Lumina.DataAccess.Core.Repositories.MusicLibrary.Specifications; @@ -38,6 +39,7 @@ internal sealed class ArtistRepository : IArtistRepository private readonly LuminaDbContext _luminaDbContext; private readonly IAlbumRepository _albumRepository; private readonly ITrackRepository _trackRepository; + private readonly IDateTimeProvider _dateTimeProvider; /// /// Initializes a new instance of the class. @@ -45,11 +47,13 @@ internal sealed class ArtistRepository : IArtistRepository /// Injected Entity Framework DbContext. /// Injected repository for albums. /// Injected repository for tracks. - public ArtistRepository(LuminaDbContext luminaDbContext, IAlbumRepository albumRepository, ITrackRepository trackRepository) + /// Injected provider for the current UTC time, used to stamp deletions deterministically. + public ArtistRepository(LuminaDbContext luminaDbContext, IAlbumRepository albumRepository, ITrackRepository trackRepository, IDateTimeProvider dateTimeProvider) { _luminaDbContext = luminaDbContext; _albumRepository = albumRepository; _trackRepository = trackRepository; + _dateTimeProvider = dateTimeProvider; } /// @@ -65,7 +69,7 @@ internal sealed class ArtistRepository : IArtistRepository return Errors.Music.ArtistAlreadyExists; // An artist is unique within its library by its name, so the same artist can never be registered twice in the same library. - bool doesArtistNameExist = await _luminaDbContext.Artists.AnyAsync(repositoryArtist => repositoryArtist.LibraryId == artist.LibraryId && repositoryArtist.Name == artist.Name, cancellationToken: cancellationToken).ConfigureAwait(false); + bool doesArtistNameExist = await _luminaDbContext.Artists.AnyAsync(repositoryArtist => repositoryArtist.LibraryId == artist.LibraryId && repositoryArtist.Name == artist.Name && !repositoryArtist.IsDeleted, cancellationToken: cancellationToken).ConfigureAwait(false); if (doesArtistNameExist) return Errors.Music.ArtistAlreadyExists; @@ -154,14 +158,27 @@ internal sealed class ArtistRepository : IArtistRepository .ThenInclude(album => album.Tracks) .ThenInclude(track => track.Contributors) .AsSplitQuery() - .FirstOrDefaultAsync(repositoryArtist => repositoryArtist.Id == data.Id, cancellationToken).ConfigureAwait(false); + .FirstOrDefaultAsync(repositoryArtist => repositoryArtist.Id == data.Id && !repositoryArtist.IsDeleted, cancellationToken).ConfigureAwait(false); if (foundArtist is null) return Errors.Music.ArtistNotFound; + // A soft deleted album or track is kept out of every edit, so a payload that names one, even under another parent, must not rewrite it. + Result validateNoSoftDeletedItemsResult = ValidateNoSoftDeletedItemsAreEdited(foundArtist, data); + if (validateNoSoftDeletedItemsResult.IsFailure) + return validateNoSoftDeletedItemsResult.Errors; + // The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor. Guid libraryId = foundArtist.LibraryId; + bool isDeleted = foundArtist.IsDeleted; + DateTime? deletedOnUtc = foundArtist.DeletedOnUtc; EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundArtist, data); foundArtist.LibraryId = libraryId; + // The deletion state is owned by the explicit delete and restore operations. Clearing the modified flags keeps it out of the UPDATE statement, + // so an edit that raced with a delete can never write the deletion state back and resurrect the artist. + foundArtist.IsDeleted = isDeleted; + foundArtist.DeletedOnUtc = deletedOnUtc; + _luminaDbContext.Entry(foundArtist).Property(artist => artist.IsDeleted).IsModified = false; + _luminaDbContext.Entry(foundArtist).Property(artist => artist.DeletedOnUtc).IsModified = false; // A contributor participation is matched by the contributor and the role they played. Matched participations keep their identity and their audit columns, so a // contributor that is displayed or linked elsewhere is never deleted and re-inserted just because another field of the artist was edited. @@ -257,7 +274,8 @@ internal sealed class ArtistRepository : IArtistRepository // albums and their tracks are updated in place, so that persisted entities keep their identity across an edit. An album whose data did // not change produces no write statement, because its own repository only applies the values that actually changed. List incomingAlbumIds = [.. data.Albums.Select(album => album.Id)]; - foreach (AlbumEntity removedAlbum in foundArtist.Albums.Where(album => !incomingAlbumIds.Contains(album.Id)).ToList()) + // A soft deleted album is kept out of every edit, so it is never removed from the tracked aggregate, which would permanently delete it. + foreach (AlbumEntity removedAlbum in foundArtist.Albums.Where(album => !album.IsDeleted && !incomingAlbumIds.Contains(album.Id)).ToList()) foundArtist.Albums.Remove(removedAlbum); foreach (AlbumEntity incomingAlbum in data.Albums) @@ -283,6 +301,30 @@ internal sealed class ArtistRepository : IArtistRepository return Result.Updated; } + /// + /// Ensures no incoming album or track of matches a soft deleted album or track of . + /// + /// The tracked artist that is being updated. + /// The artist carrying the desired albums and tracks. + /// An representing either a successful check, or an error. + private static Result ValidateNoSoftDeletedItemsAreEdited(ArtistEntity foundArtist, ArtistEntity data) + { + Dictionary storedAlbums = foundArtist.Albums.ToDictionary(album => album.Id); + Dictionary storedTracks = foundArtist.Albums.SelectMany(album => album.Tracks).ToDictionary(track => track.Id); + + foreach (AlbumEntity incomingAlbum in data.Albums) + { + if (storedAlbums.TryGetValue(incomingAlbum.Id, out AlbumEntity? storedAlbum) && storedAlbum.IsDeleted) + return Errors.Music.AlbumNotFound; + + foreach (TrackEntity incomingTrack in incomingAlbum.Tracks) + if (storedTracks.TryGetValue(incomingTrack.Id, out TrackEntity? storedTrack) && storedTrack.IsDeleted) + return Errors.Music.TrackNotFound; + } + + return Result.Success; + } + /// /// Gets the file system paths of the tracks that are not yet stored and will therefore be inserted when is applied over . /// @@ -341,7 +383,8 @@ internal sealed class ArtistRepository : IArtistRepository private async Task> ReconcileTracksAsync(AlbumEntity existingAlbum, AlbumEntity incomingAlbum, CancellationToken cancellationToken) { List incomingTrackIds = [.. incomingAlbum.Tracks.Select(track => track.Id)]; - foreach (TrackEntity removedTrack in existingAlbum.Tracks.Where(track => !incomingTrackIds.Contains(track.Id)).ToList()) + // A soft deleted track is kept out of every edit, so it is never removed from the tracked album, which would permanently delete it. + foreach (TrackEntity removedTrack in existingAlbum.Tracks.Where(track => !track.IsDeleted && !incomingTrackIds.Contains(track.Id)).ToList()) existingAlbum.Tracks.Remove(removedTrack); foreach (TrackEntity incomingTrack in incomingAlbum.Tracks) @@ -375,40 +418,43 @@ internal sealed class ArtistRepository : IArtistRepository /// An containing either an , or an error. public async Task> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) { - IQueryable query = _luminaDbContext.Artists; + // A deleted artist is kept in the storage medium only so that its paths stay reserved and it can be restored, so it is never returned to a caller. + IQueryable query = _luminaDbContext.Artists.Where(artist => !artist.IsDeleted); if (!shouldTrackEntities) query = query.AsNoTracking(); if (shouldIncludeNavigationProperties) { + // The albums and the tracks of an artist are child entities of its aggregate, so the deleted ones are filtered out of the graph + // that a caller edits or displays, while the repository keeps them stored for a restore. query = query .Include(artist => artist.Tags) .Include(artist => artist.Genres) .Include(artist => artist.Contributors) - .Include(artist => artist.Albums) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) .ThenInclude(album => album.Ratings) - .Include(artist => artist.Albums) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) .ThenInclude(album => album.Genres) - .Include(artist => artist.Albums) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) .ThenInclude(album => album.Tags) - .Include(artist => artist.Albums) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) .ThenInclude(album => album.Contributors) - .Include(artist => artist.Albums) - .ThenInclude(album => album.Tracks) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) + .ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Ratings) - .Include(artist => artist.Albums) - .ThenInclude(album => album.Tracks) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) + .ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Genres) - .Include(artist => artist.Albums) - .ThenInclude(album => album.Tracks) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) + .ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Tags) - .Include(artist => artist.Albums) - .ThenInclude(album => album.Tracks) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) + .ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Moods) - .Include(artist => artist.Albums) - .ThenInclude(album => album.Tracks) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) + .ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Isrcs) - .Include(artist => artist.Albums) - .ThenInclude(album => album.Tracks) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) + .ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Contributors) .AsSplitQuery(); } @@ -446,7 +492,7 @@ internal sealed class ArtistRepository : IArtistRepository /// An containing either a , or an error. public async Task>> GetAllAsync(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto { - IQueryable artistsQuery = _luminaDbContext.Artists; + IQueryable artistsQuery = _luminaDbContext.Artists.Where(artist => !artist.IsDeleted); if (!shouldTrackEntities) artistsQuery = artistsQuery.AsNoTracking(); if (shouldIncludeNavigationProperties) @@ -455,31 +501,31 @@ internal sealed class ArtistRepository : IArtistRepository .Include(artist => artist.Tags) .Include(artist => artist.Genres) .Include(artist => artist.Contributors) - .Include(artist => artist.Albums) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) .ThenInclude(album => album.Ratings) - .Include(artist => artist.Albums) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) .ThenInclude(album => album.Genres) - .Include(artist => artist.Albums) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) .ThenInclude(album => album.Tags) - .Include(artist => artist.Albums) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) .ThenInclude(album => album.Contributors) - .Include(artist => artist.Albums) - .ThenInclude(album => album.Tracks) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) + .ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Ratings) - .Include(artist => artist.Albums) - .ThenInclude(album => album.Tracks) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) + .ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Genres) - .Include(artist => artist.Albums) - .ThenInclude(album => album.Tracks) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) + .ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Tags) - .Include(artist => artist.Albums) - .ThenInclude(album => album.Tracks) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) + .ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Moods) - .Include(artist => artist.Albums) - .ThenInclude(album => album.Tracks) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) + .ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Isrcs) - .Include(artist => artist.Albums) - .ThenInclude(album => album.Tracks) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) + .ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Contributors) .AsSplitQuery(); } @@ -550,13 +596,13 @@ internal sealed class ArtistRepository : IArtistRepository return Errors.Library.FilterMustIncludeLibraryId; // The lightweight read models are retrieved without tracking by default, because they are never modified by the caller. - IQueryable artistsQuery = _luminaDbContext.Artists; + IQueryable artistsQuery = _luminaDbContext.Artists.Where(artist => !artist.IsDeleted); if (!shouldTrackEntities) artistsQuery = artistsQuery.AsNoTracking(); if (shouldIncludeNavigationProperties) artistsQuery = artistsQuery .Include(artist => artist.Contributors) - .Include(artist => artist.Albums) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) .AsSplitQuery(); artistsQuery = artistsQuery.Where(artist => artist.LibraryId == libraryFilter.LibraryId); @@ -702,8 +748,10 @@ internal sealed class ArtistRepository : IArtistRepository /// An containing either the with the provided name, or an error. public async Task> GetByNameAsync(Guid libraryId, string name, CancellationToken cancellationToken) { + // A deleted artist is not returned to the scan, so a scan that finds a new file of the same artist materializes a new, visible artist + // instead of attaching the file to the deleted one. ArtistEntity? artist = await _luminaDbContext.Artists - .FirstOrDefaultAsync(repositoryArtist => repositoryArtist.LibraryId == libraryId && repositoryArtist.Name == name, cancellationToken).ConfigureAwait(false); + .FirstOrDefaultAsync(repositoryArtist => repositoryArtist.LibraryId == libraryId && repositoryArtist.Name == name && !repositoryArtist.IsDeleted, cancellationToken).ConfigureAwait(false); return artist; } @@ -729,45 +777,46 @@ internal sealed class ArtistRepository : IArtistRepository .Include(artist => artist.Tags) .Include(artist => artist.Ratings) .Include(artist => artist.Contributors) - .Include(artist => artist.Albums) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) .ThenInclude(album => album.ReleaseTypes) - .Include(artist => artist.Albums) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) .ThenInclude(album => album.Genres) - .Include(artist => artist.Albums) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) .ThenInclude(album => album.Tags) - .Include(artist => artist.Albums) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) .ThenInclude(album => album.Ratings) - .Include(artist => artist.Albums) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) .ThenInclude(album => album.Contributors) - .Include(artist => artist.Albums) - .ThenInclude(album => album.Tracks) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) + .ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Genres) - .Include(artist => artist.Albums) - .ThenInclude(album => album.Tracks) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) + .ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Tags) - .Include(artist => artist.Albums) - .ThenInclude(album => album.Tracks) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) + .ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Ratings) - .Include(artist => artist.Albums) - .ThenInclude(album => album.Tracks) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) + .ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Moods) - .Include(artist => artist.Albums) - .ThenInclude(album => album.Tracks) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) + .ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Isrcs) - .Include(artist => artist.Albums) - .ThenInclude(album => album.Tracks) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) + .ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.Contributors) - .Include(artist => artist.Albums) - .ThenInclude(album => album.Tracks) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) + .ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.WorkLanguages) - .Include(artist => artist.Albums) - .ThenInclude(album => album.Tracks) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) + .ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted)) .ThenInclude(track => track.WorkIswcs) .AsSplitQuery() .Where(artist => artist.LibraryId == libraryId + && !artist.IsDeleted && (artist.MetadataStatus != MetadataStatus.Enriched - || artist.Albums.Any(album => album.MetadataStatus != MetadataStatus.Enriched) - || artist.Albums.Any(album => album.Tracks.Any(track => track.MetadataStatus != MetadataStatus.Enriched))) + || artist.Albums.Any(album => !album.IsDeleted && album.MetadataStatus != MetadataStatus.Enriched) + || artist.Albums.Any(album => !album.IsDeleted && album.Tracks.Any(track => !track.IsDeleted && track.MetadataStatus != MetadataStatus.Enriched))) && (lastName == null || artist.Name.CompareTo(lastName) > 0)) .OrderBy(artist => artist.Name) .Take(pageSize) @@ -784,9 +833,10 @@ internal sealed class ArtistRepository : IArtistRepository { return await _luminaDbContext.Artists .CountAsync(artist => artist.LibraryId == libraryId + && !artist.IsDeleted && (artist.MetadataStatus != MetadataStatus.Enriched - || artist.Albums.Any(album => album.MetadataStatus != MetadataStatus.Enriched) - || artist.Albums.Any(album => album.Tracks.Any(track => track.MetadataStatus != MetadataStatus.Enriched))), cancellationToken).ConfigureAwait(false); + || artist.Albums.Any(album => !album.IsDeleted && album.MetadataStatus != MetadataStatus.Enriched) + || artist.Albums.Any(album => !album.IsDeleted && album.Tracks.Any(track => !track.IsDeleted && track.MetadataStatus != MetadataStatus.Enriched))), cancellationToken).ConfigureAwait(false); } /// @@ -799,6 +849,7 @@ internal sealed class ArtistRepository : IArtistRepository { return await _luminaDbContext.Artists .CountAsync(artist => artist.LibraryId == libraryId + && !artist.IsDeleted && !_luminaDbContext.MusicArtwork.Any(musicArtwork => musicArtwork.OwnerType == MusicArtworkOwnerType.Artist && musicArtwork.OwnerId == artist.Id && (musicArtwork.Status == ArtworkStatus.Enriched || musicArtwork.Status == ArtworkStatus.NotAvailable)), cancellationToken).ConfigureAwait(false); @@ -817,10 +868,11 @@ internal sealed class ArtistRepository : IArtistRepository { return await _luminaDbContext.Artists .AsNoTracking() - .Include(artist => artist.Albums) - .ThenInclude(album => album.Tracks) + .Include(artist => artist.Albums.Where(album => !album.IsDeleted)) + .ThenInclude(album => album.Tracks.Where(track => !track.IsDeleted)) .AsSplitQuery() .Where(artist => artist.LibraryId == libraryId + && !artist.IsDeleted && !_luminaDbContext.MusicArtwork.Any(musicArtwork => musicArtwork.OwnerType == MusicArtworkOwnerType.Artist && musicArtwork.OwnerId == artist.Id && (musicArtwork.Status == ArtworkStatus.Enriched || musicArtwork.Status == ArtworkStatus.NotAvailable)) @@ -844,6 +896,73 @@ internal sealed class ArtistRepository : IArtistRepository return Result.Updated; } + /// + /// Gets the soft deleted artist identified by . + /// + /// The Id of the soft deleted artist to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either the soft deleted , when the artist does not exist or is not soft deleted, or an error. + public async Task> GetSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken) + { + return await _luminaDbContext.Artists + .AsNoTracking() + .FirstOrDefaultAsync(artist => artist.Id == id && artist.IsDeleted, cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the soft deleted artists of the media library identified by . + /// + /// The Id of the media library whose soft deleted artists are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the soft deleted artists, or an error. + public async Task>> GetSoftDeletedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken) + { + return await _luminaDbContext.Artists + .AsNoTracking() + .Where(artist => artist.LibraryId == libraryId && artist.IsDeleted) + // The deletion time is stored when the artist is deleted, so later writes to the hidden row cannot change the order of the deleted items, + // and every deleted row carries a deletion time because the delete operation always sets it. All terms sort descending, so the filtered + // (LibraryId, IsDeleted, DeletedOnUtc, Name, Id) index can be scanned backwards and the database does not build a temporary B-tree. + .OrderByDescending(artist => artist.DeletedOnUtc) + .ThenByDescending(artist => artist.Name) + .ThenByDescending(artist => artist.Id) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Soft deletes the artist identified by , without removing its stored metadata or artwork. + /// + /// The Id of the artist to soft delete. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> SoftDeleteByIdAsync(Guid id, CancellationToken cancellationToken) + { + ArtistEntity? artist = await _luminaDbContext.Artists.FirstOrDefaultAsync(repositoryArtist => repositoryArtist.Id == id, cancellationToken).ConfigureAwait(false); + if (artist is null || artist.IsDeleted) + return Errors.Music.ArtistNotFound; + + artist.IsDeleted = true; + artist.DeletedOnUtc = _dateTimeProvider.UtcNow; + return Result.Updated; + } + + /// + /// Restores the soft deleted artist identified by . + /// + /// The Id of the artist to restore. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> RestoreSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken) + { + ArtistEntity? artist = await _luminaDbContext.Artists.FirstOrDefaultAsync(repositoryArtist => repositoryArtist.Id == id, cancellationToken).ConfigureAwait(false); + if (artist is null || !artist.IsDeleted) + return Errors.Music.ArtistNotFound; + + artist.IsDeleted = false; + artist.DeletedOnUtc = null; + return Result.Updated; + } + /// /// Deletes all the artists of the media library identified by , together with their albums and tracks and their related data. /// diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs index 685c79cb..2e720e5b 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs @@ -3,6 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; using Lumina.DataAccess.Common.Persistence; using Lumina.DataAccess.Core.UoW; @@ -26,14 +27,17 @@ namespace Lumina.DataAccess.Core.Repositories.MusicLibrary; internal sealed class TrackRepository : ITrackRepository { private readonly LuminaDbContext _luminaDbContext; + private readonly IDateTimeProvider _dateTimeProvider; /// /// Initializes a new instance of the class. /// /// Injected Entity Framework DbContext. - public TrackRepository(LuminaDbContext luminaDbContext) + /// Injected provider for the current UTC time, used to stamp deletions deterministically. + public TrackRepository(LuminaDbContext luminaDbContext, IDateTimeProvider dateTimeProvider) { _luminaDbContext = luminaDbContext; + _dateTimeProvider = dateTimeProvider; } /// @@ -73,6 +77,10 @@ internal sealed class TrackRepository : ITrackRepository /// /// Gets the subset of that is already used by a track of the library identified by . /// + /// + /// Soft deleted tracks are included on purpose: their paths must still count as taken, so that a scan never materializes a track that the user + /// deleted back into the catalogue. + /// /// The Id of the library whose tracks are searched. /// The track paths to check. /// Cancellation token that can be used to stop the execution. @@ -113,7 +121,10 @@ internal sealed class TrackRepository : ITrackRepository .Include(repositoryTrack => repositoryTrack.Moods) .Include(repositoryTrack => repositoryTrack.Isrcs) .AsSplitQuery() - .FirstOrDefaultAsync(repositoryTrack => repositoryTrack.Id == data.Id, cancellationToken).ConfigureAwait(false); + .FirstOrDefaultAsync(repositoryTrack => repositoryTrack.Id == data.Id + && !repositoryTrack.IsDeleted + && !repositoryTrack.Album!.IsDeleted + && !repositoryTrack.Album!.Artist!.IsDeleted, cancellationToken).ConfigureAwait(false); if (foundTrack is null) return Errors.Music.TrackNotFound; @@ -133,9 +144,17 @@ internal sealed class TrackRepository : ITrackRepository // The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor. Guid albumId = foundTrack.AlbumId; Guid libraryId = foundTrack.LibraryId; + bool isDeleted = foundTrack.IsDeleted; + DateTime? deletedOnUtc = foundTrack.DeletedOnUtc; EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundTrack, data); foundTrack.AlbumId = albumId; foundTrack.LibraryId = libraryId; + // The deletion state is owned by the explicit delete and restore operations. Clearing the modified flags keeps it out of the UPDATE statement, + // so an edit that raced with a delete can never write the deletion state back and resurrect the track. + foundTrack.IsDeleted = isDeleted; + foundTrack.DeletedOnUtc = deletedOnUtc; + _luminaDbContext.Entry(foundTrack).Property(track => track.IsDeleted).IsModified = false; + _luminaDbContext.Entry(foundTrack).Property(track => track.DeletedOnUtc).IsModified = false; // Tags and genres are shared across the whole database, so the stored rows whose names already exist are reused, and only the missing names are inserted. Result reconcileTagsResult = await SharedReferenceResolver.ReconcileAsync(_luminaDbContext, foundTrack.Tags, data.Tags, Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); @@ -212,7 +231,9 @@ internal sealed class TrackRepository : ITrackRepository /// An containing either a , or an error. public async Task> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) { - IQueryable query = _luminaDbContext.Tracks; + // A deleted track, or a track of a deleted album or artist, is kept in the storage medium only so that its path stays reserved and it + // can be restored, so it is never returned to a caller. + IQueryable query = _luminaDbContext.Tracks.Where(track => !track.IsDeleted && !track.Album!.IsDeleted && !track.Album!.Artist!.IsDeleted); if (!shouldTrackEntities) query = query.AsNoTracking(); if (shouldIncludeNavigationProperties) @@ -232,7 +253,7 @@ internal sealed class TrackRepository : ITrackRepository } /// - /// Gets all the tracks of the album identified by . + /// Gets the tracks of the album identified by that are not soft deleted. /// /// The Id of the album whose tracks are retrieved. /// Cancellation token that can be used to stop the execution. @@ -247,8 +268,25 @@ internal sealed class TrackRepository : ITrackRepository .Include(track => track.Isrcs) .Include(track => track.Contributors) .AsSplitQuery() + .Where(track => track.AlbumId == albumId && !track.IsDeleted && !track.Album!.IsDeleted && !track.Album!.Artist!.IsDeleted) + .OrderBy(track => track.DiscNumber ?? 1) // Some releases don't have a disc number, assume 1. + .ThenBy(track => track.TrackNumber) + .ThenBy(track => track.Id) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets all the tracks of the album identified by , whether they are soft deleted or not. + /// + /// The Id of the album whose tracks are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + public async Task>> GetByAlbumIdIncludingDeletedAsync(Guid albumId, CancellationToken cancellationToken) + { + return await _luminaDbContext.Tracks + .AsNoTracking() .Where(track => track.AlbumId == albumId) - .OrderBy(track => track.DiscNumber ?? 1) // some releases don't have a disc number, assume 1 + .OrderBy(track => track.DiscNumber ?? 1) .ThenBy(track => track.TrackNumber) .ThenBy(track => track.Id) .ToListAsync(cancellationToken).ConfigureAwait(false); @@ -267,8 +305,8 @@ internal sealed class TrackRepository : ITrackRepository // The lightweight read models are always retrieved without tracking, because they are never modified by the caller. IQueryable liteRowsQuery = _luminaDbContext.Tracks .AsNoTracking() - .Where(track => track.AlbumId == albumId) - .OrderBy(track => track.DiscNumber ?? 1) // some releases don't have a disc number, assume 1 + .Where(track => track.AlbumId == albumId && !track.IsDeleted && !track.Album!.IsDeleted && !track.Album!.Artist!.IsDeleted) + .OrderBy(track => track.DiscNumber ?? 1) // Some releases don't have a disc number, assume 1. .ThenBy(track => track.TrackNumber) .ThenBy(track => track.Id) .Select(track => new TrackLiteRow( @@ -325,7 +363,7 @@ internal sealed class TrackRepository : ITrackRepository { IQueryable query = _luminaDbContext.Tracks .AsNoTracking() - .Where(track => track.LibraryId == libraryId); + .Where(track => track.LibraryId == libraryId && !track.IsDeleted && !track.Album!.IsDeleted && !track.Album!.Artist!.IsDeleted); if (artistId is not null) query = query.Where(track => track.Album!.ArtistId == artistId.Value); @@ -357,6 +395,10 @@ internal sealed class TrackRepository : ITrackRepository /// /// Gets the track of the library identified by that is stored at the provided . /// + /// + /// Soft deleted tracks are included on purpose: when the file disappears from disk, the scan deletion strategy must be able to permanently + /// remove a track that the user had already deleted, instead of leaving its soft deleted row behind. + /// /// The Id of the library whose track is retrieved. /// The file system path of the track to retrieve. /// Cancellation token that can be used to stop the execution. @@ -388,7 +430,13 @@ internal sealed class TrackRepository : ITrackRepository // that is not in the named library, album and artist simply yields no row. return await _luminaDbContext.Tracks .AsNoTracking() - .Where(track => track.Id == trackId && track.LibraryId == libraryId && track.AlbumId == albumId && track.Album!.ArtistId == artistId) + .Where(track => track.Id == trackId + && track.LibraryId == libraryId + && track.AlbumId == albumId + && track.Album!.ArtistId == artistId + && !track.IsDeleted + && !track.Album!.IsDeleted + && !track.Album!.Artist!.IsDeleted) .Select(track => new TrackStreamDto( track.Path, track.LibraryId, @@ -424,7 +472,13 @@ internal sealed class TrackRepository : ITrackRepository // that is not in the named library, album and artist simply yields no row. return await _luminaDbContext.Tracks .AsNoTracking() - .Where(track => track.Id == trackId && track.LibraryId == libraryId && track.AlbumId == albumId && track.Album!.ArtistId == artistId) + .Where(track => track.Id == trackId + && track.LibraryId == libraryId + && track.AlbumId == albumId + && track.Album!.ArtistId == artistId + && !track.IsDeleted + && !track.Album!.IsDeleted + && !track.Album!.Artist!.IsDeleted) .Select(track => new TrackPlaybackManifestDto( track.Path, track.Container, @@ -441,6 +495,89 @@ internal sealed class TrackRepository : ITrackRepository .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); } + /// + /// Gets the soft deleted track identified by , when its album and artist are not soft deleted. + /// + /// The Id of the soft deleted track to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either the soft deleted , when the track does not exist, is not soft deleted, or its album or artist is soft deleted, or an error. + public async Task> GetSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken) + { + return await _luminaDbContext.Tracks + .AsNoTracking() + .FirstOrDefaultAsync(track => track.Id == id + && track.IsDeleted + && !track.Album!.IsDeleted + && !track.Album!.Artist!.IsDeleted, cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the soft deleted tracks of the media library identified by , whose album and artist are not soft deleted. + /// + /// The Id of the media library whose soft deleted tracks are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the soft deleted tracks, or an error. + public async Task>> GetSoftDeletedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken) + { + return await _luminaDbContext.Tracks + .AsNoTracking() + .Include(track => track.Album) + .ThenInclude(album => album!.Artist) + .Where(track => track.LibraryId == libraryId + && track.IsDeleted + && !track.Album!.IsDeleted + && !track.Album!.Artist!.IsDeleted) + // The deletion time is stored when the track is deleted, so later writes to the hidden row cannot change the order of the deleted items, + // and every deleted row carries a deletion time because the delete operation always sets it. All terms sort descending, so the filtered + // (LibraryId, IsDeleted, DeletedOnUtc, Title, Id) index can be scanned backwards and the database does not build a temporary B-tree. + .OrderByDescending(track => track.DeletedOnUtc) + .ThenByDescending(track => track.Title) + .ThenByDescending(track => track.Id) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Soft deletes the track identified by , without removing its stored metadata or artwork. + /// + /// + /// The update is executed directly against the storage medium, so an entity already tracked by the caller is not refreshed, and the audit fields + /// stamped by the change tracker are not updated; the deletion time is stored in instead. + /// + /// The Id of the track to soft delete. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> SoftDeleteByIdAsync(Guid id, CancellationToken cancellationToken) + { + DateTime deletedOnUtc = _dateTimeProvider.UtcNow; + + // The update covers the existence check and the transition in one statement, so two concurrent deletes of the same track cannot both succeed. + int updatedRows = await _luminaDbContext.Tracks + .Where(track => track.Id == id && !track.IsDeleted) + .ExecuteUpdateAsync(setters => setters + .SetProperty(track => track.IsDeleted, true) + .SetProperty(track => track.DeletedOnUtc, deletedOnUtc), cancellationToken).ConfigureAwait(false); + if (updatedRows == 0) + return Errors.Music.TrackNotFound; + return Result.Updated; + } + + /// + /// Restores the soft deleted track identified by . + /// + /// The Id of the track to restore. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> RestoreSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken) + { + TrackEntity? track = await _luminaDbContext.Tracks.FirstOrDefaultAsync(repositoryTrack => repositoryTrack.Id == id, cancellationToken).ConfigureAwait(false); + if (track is null || !track.IsDeleted) + return Errors.Music.TrackNotFound; + + track.IsDeleted = false; + track.DeletedOnUtc = null; + return Result.Updated; + } + /// /// Deletes the track identified by , together with its owned collections and contributions, by the database cascade. /// @@ -529,7 +666,11 @@ internal sealed class TrackRepository : ITrackRepository public async Task> GetTracksNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken) { return await _luminaDbContext.Tracks - .CountAsync(track => track.LibraryId == libraryId && track.MetadataStatus != MetadataStatus.Enriched, cancellationToken).ConfigureAwait(false); + .CountAsync(track => track.LibraryId == libraryId + && !track.IsDeleted + && !track.Album!.IsDeleted + && !track.Album!.Artist!.IsDeleted + && track.MetadataStatus != MetadataStatus.Enriched, cancellationToken).ConfigureAwait(false); } /// @@ -566,7 +707,7 @@ internal sealed class TrackRepository : ITrackRepository { List chunkCounts = await _luminaDbContext.Tracks .AsNoTracking() - .Where(track => chunk.Contains(track.Id)) + .Where(track => chunk.Contains(track.Id) && !track.IsDeleted && !track.Album!.IsDeleted && !track.Album!.Artist!.IsDeleted) .GroupBy(track => track.LibraryId) .Select(group => new TrackLibraryCount { @@ -616,7 +757,7 @@ internal sealed class TrackRepository : ITrackRepository .Include(track => track.Contributors) .AsSplitQuery(); } - tracks.AddRange(await query.Where(track => chunk.Contains(track.Id)).ToListAsync(cancellationToken).ConfigureAwait(false)); + tracks.AddRange(await query.Where(track => chunk.Contains(track.Id) && !track.IsDeleted && !track.Album!.IsDeleted && !track.Album!.Artist!.IsDeleted).ToListAsync(cancellationToken).ConfigureAwait(false)); } return Result.From>(tracks); } diff --git a/src/Lumina.DataAccess/Core/Repositories/Playlists/PlaylistRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Playlists/PlaylistRepository.cs index ee38ba94..e05a2f0f 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Playlists/PlaylistRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Playlists/PlaylistRepository.cs @@ -578,6 +578,9 @@ internal sealed class PlaylistRepository : IPlaylistRepository INNER JOIN Albums AS album ON album.Id = track.AlbumId INNER JOIN Artists AS artist ON artist.Id = album.ArtistId WHERE track.LibraryId = @libraryId + AND track.IsDeleted = 0 + AND album.IsDeleted = 0 + AND artist.IsDeleted = 0 """); if (artistId is not null) insertSql.Append(" AND album.ArtistId = @artistId"); @@ -965,7 +968,7 @@ internal sealed class PlaylistRepository : IPlaylistRepository List chunkDetails = await (from track in _luminaDbContext.Tracks.AsNoTracking() join album in _luminaDbContext.Albums on track.AlbumId equals album.Id join artist in _luminaDbContext.Artists on album.ArtistId equals artist.Id - where chunk.Contains(track.Id) + where chunk.Contains(track.Id) && !track.IsDeleted && !album.IsDeleted && !artist.IsDeleted select new PlaylistEntryDisplayDto( track.Id, track.Title, diff --git a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs index 5ef3399c..ee5d81a3 100644 --- a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs +++ b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs @@ -145,7 +145,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable { get { - _artistRepository ??= new ArtistRepository(_luminaDbContext, AlbumRepository, TrackRepository); + _artistRepository ??= new ArtistRepository(_luminaDbContext, AlbumRepository, TrackRepository, _dateTimeProvider); return _artistRepository; } } @@ -157,7 +157,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable { get { - _albumRepository ??= new AlbumRepository(_luminaDbContext, TrackRepository); + _albumRepository ??= new AlbumRepository(_luminaDbContext, TrackRepository, _dateTimeProvider); return _albumRepository; } } @@ -169,7 +169,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable { get { - _trackRepository ??= new TrackRepository(_luminaDbContext); + _trackRepository ??= new TrackRepository(_luminaDbContext, _dateTimeProvider); return _trackRepository; } } diff --git a/src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs b/src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs index 8cd20fbe..26eba934 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs @@ -15,6 +15,7 @@ public static partial class Errors public static Error PathMustBeMaximum260CharactersLong => Error.Failure(description: nameof(PathMustBeMaximum260CharactersLong)); public static Error FileCopyError => Error.Failure(description: nameof(FileCopyError)); public static Error FileMoveError => Error.Failure(description: nameof(FileMoveError)); + public static Error FileDeleteError => Error.Failure(description: nameof(FileDeleteError)); public static Error DirectoryCopyError => Error.Failure(description: nameof(DirectoryCopyError)); public static Error DirectoryMoveError => Error.Failure(description: nameof(DirectoryMoveError)); public static Error FileNotFound => Error.NotFound(description: nameof(FileNotFound)); diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Artist.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Artist.cs index 9fda2db6..ece4b512 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Artist.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Artist.cs @@ -433,6 +433,20 @@ public sealed class Artist : AggregateRoot return Result.Created; } + /// + /// Ensures the provided can be removed from the artist, without leaving the artist without albums. + /// + /// The album that is about to be removed or deleted. + /// An representing either a successful check, or an error. + public Result CanRemoveAlbum(Album album) + { + if (!_albums.Contains(album)) + return Errors.Music.TheArtistDoesNotHaveTheAlbum; + if (_albums.Count is 1) + return Errors.Music.ArtistMustHaveAtLeastOneAlbum; + return true; + } + /// /// Removes an album from the artist. /// @@ -440,10 +454,9 @@ public sealed class Artist : AggregateRoot /// An representing either a successful operation, or an error. public Result RemoveAlbum(Album album) { - if (!_albums.Contains(album)) - return Errors.Music.TheArtistDoesNotHaveTheAlbum; - if (_albums.Count is 1) - return Errors.Music.ArtistMustHaveAtLeastOneAlbum; + Result canRemoveAlbumResult = CanRemoveAlbum(album); + if (canRemoveAlbumResult.IsFailure) + return canRemoveAlbumResult.Errors; _albums.Remove(album); return Result.Deleted; } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs index 5d8a19fe..880d4e29 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs @@ -284,7 +284,19 @@ internal class FileProviderService : IFileProviderService // Check if the user has access permissions to the provided path. if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete)) return Errors.Permission.UnauthorizedAccess; - _fileSystem.File.Delete(path.Path); - return Result.Deleted; + try + { + _fileSystem.File.Delete(path.Path); + return Result.Deleted; + } + catch (UnauthorizedAccessException) + { + return Errors.Permission.UnauthorizedAccess; + } + catch (IOException) + { + // A file that is locked by another process, or is read-only, cannot be deleted, but that must not abort the caller. + return Errors.FileSystemManagement.FileDeleteError; + } } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs index b5b41a02..a8bbb10f 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs @@ -80,6 +80,15 @@ public interface IPathService /// An containing the sanitized path segment, or an error. Result SanitizeSegment(string name); + /// + /// Sanitizes a human-readable into a safe path segment that ends with , + /// truncating only the name when the combined segment would exceed the maximum segment length. + /// + /// The human-readable name to sanitize. + /// The identifier that must be preserved at the end of the segment. + /// An containing the sanitized path segment, or an error. + Result SanitizeCompositeSegment(string name, string identifier); + /// /// Returns the root portion of the given path. /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs index c2e5929a..88a06ed4 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs @@ -185,6 +185,27 @@ public class PathService : IPathService return PathSegment.Create(sanitized, isDirectory: true, isDrive: false); } + /// + /// Sanitizes a human-readable into a safe path segment that ends with , + /// truncating only the name when the combined segment would exceed the maximum segment length. + /// + /// The human-readable name to sanitize. + /// The identifier that must be preserved at the end of the segment. + /// An containing the sanitized path segment, or an error. + public Result SanitizeCompositeSegment(string name, string identifier) + { + if (string.IsNullOrWhiteSpace(identifier)) + return Errors.FileSystemManagement.NameCannotBeEmpty; + + // The identifier is the part that tells two items with the same name apart, so only the name is ever shortened to fit the limit. + string suffix = $"-{identifier}"; + if (suffix.Length >= MAX_DIRECTORY_SEGMENT_LENGTH) + return Errors.FileSystemManagement.InvalidPath; + int nameLengthBudget = MAX_DIRECTORY_SEGMENT_LENGTH - suffix.Length; + string nameWithinBudget = name.Length > nameLengthBudget ? name[..nameLengthBudget].TrimEnd() : name; + return SanitizeSegment($"{nameWithinBudget}{suffix}"); + } + /// /// Returns the root portion of the given path. /// diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkService.cs index a2c4866a..ca9de085 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkService.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkService.cs @@ -55,15 +55,16 @@ internal sealed class MusicArtworkService : IMusicArtworkService /// The Id of the media library the album belongs to. /// The Id of the album. /// The name of the media library the album belongs to. + /// The Id of the artist of the album. /// The name of the artist of the album. /// The title of the album. /// The artwork to store. /// The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When , no release type segment is added. /// Cancellation token that can be used to stop the execution. /// An containing either the relative path of the stored artwork, or an error. - public async Task> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, ArtworkDto artwork, string? releaseTypeName, CancellationToken cancellationToken) + public async Task> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, Guid artistId, string artistName, string albumTitle, ArtworkDto artwork, string? releaseTypeName, CancellationToken cancellationToken) { - Result artworkDirectoryPathResult = BuildAlbumArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle, releaseTypeName); + Result artworkDirectoryPathResult = BuildAlbumArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle, releaseTypeName); if (artworkDirectoryPathResult.IsFailure) return artworkDirectoryPathResult.Errors; return await SaveArtworkAsync(artworkDirectoryPathResult.Value, artwork, cancellationToken).ConfigureAwait(false); @@ -74,13 +75,14 @@ internal sealed class MusicArtworkService : IMusicArtworkService /// /// The Id of the media library the artist belongs to. /// The name of the media library the artist belongs to. + /// The Id of the artist. /// The name of the artist. /// The artwork to store. /// Cancellation token that can be used to stop the execution. /// An containing either the relative path of the stored artwork, or an error. - public async Task> SaveArtistArtworkAsync(Guid libraryId, string libraryName, string artistName, ArtworkDto artwork, CancellationToken cancellationToken) + public async Task> SaveArtistArtworkAsync(Guid libraryId, string libraryName, Guid artistId, string artistName, ArtworkDto artwork, CancellationToken cancellationToken) { - Result artworkDirectoryPathResult = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName); + Result artworkDirectoryPathResult = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistId, artistName); if (artworkDirectoryPathResult.IsFailure) return artworkDirectoryPathResult.Errors; return await SaveArtworkAsync(artworkDirectoryPathResult.Value, artwork, cancellationToken).ConfigureAwait(false); @@ -92,6 +94,7 @@ internal sealed class MusicArtworkService : IMusicArtworkService /// The Id of the media library the album belongs to. /// The Id of the album. /// The name of the media library the album belongs to. + /// The Id of the artist of the album. /// The name of the artist of the album. /// The title of the album. /// The stream of the uploaded artwork to store. @@ -99,14 +102,14 @@ internal sealed class MusicArtworkService : IMusicArtworkService /// The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When , no release type segment is added. /// Cancellation token that can be used to stop the execution. /// An containing either the relative path of the stored artwork, or an error. - public async Task> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, Stream artwork, string fileName, string? releaseTypeName, CancellationToken cancellationToken) + public async Task> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, Guid artistId, string artistName, string albumTitle, Stream artwork, string fileName, string? releaseTypeName, CancellationToken cancellationToken) { // The uploaded bytes are persisted to a temporary file first, so that the storage pipeline can treat the upload like any other local artwork source and clean it up afterwards. string temporaryPath = BuildTemporaryUploadPath(fileName); try { await WriteUploadedArtworkAsync(artwork, temporaryPath, cancellationToken).ConfigureAwait(false); - return await SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, new ArtworkDto(ArtworkType.Cover, 0, temporaryPath, null, IsTemporary: true), releaseTypeName, cancellationToken).ConfigureAwait(false); + return await SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, new ArtworkDto(ArtworkType.Cover, 0, temporaryPath, null, IsTemporary: true), releaseTypeName, cancellationToken).ConfigureAwait(false); } finally { @@ -119,19 +122,20 @@ internal sealed class MusicArtworkService : IMusicArtworkService /// /// The Id of the media library the artist belongs to. /// The name of the media library the artist belongs to. + /// The Id of the artist. /// The name of the artist. /// The stream of the uploaded artwork to store. /// The name of the uploaded artwork file. /// Cancellation token that can be used to stop the execution. /// An containing either the relative path of the stored artwork, or an error. - public async Task> SaveArtistArtworkAsync(Guid libraryId, string libraryName, string artistName, Stream artwork, string fileName, CancellationToken cancellationToken) + public async Task> SaveArtistArtworkAsync(Guid libraryId, string libraryName, Guid artistId, string artistName, Stream artwork, string fileName, CancellationToken cancellationToken) { // The uploaded bytes are persisted to a temporary file first, so that the storage pipeline can treat the upload like any other local artwork source and clean it up afterwards. string temporaryPath = BuildTemporaryUploadPath(fileName); try { await WriteUploadedArtworkAsync(artwork, temporaryPath, cancellationToken).ConfigureAwait(false); - return await SaveArtistArtworkAsync(libraryId, libraryName, artistName, new ArtworkDto(ArtworkType.Cover, 0, temporaryPath, null, IsTemporary: true), cancellationToken).ConfigureAwait(false); + return await SaveArtistArtworkAsync(libraryId, libraryName, artistId, artistName, new ArtworkDto(ArtworkType.Cover, 0, temporaryPath, null, IsTemporary: true), cancellationToken).ConfigureAwait(false); } finally { @@ -232,13 +236,14 @@ internal sealed class MusicArtworkService : IMusicArtworkService /// The Id of the media library the album belongs to. /// The Id of the album. /// The name of the media library the album belongs to. + /// The Id of the artist of the album. /// The name of the artist of the album. /// The title of the album. /// The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When omitted, no release type segment is added. /// An representing either a successful operation, or an error. - public Result DeleteAlbumArtwork(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, string? releaseTypeName = null) + public Result DeleteAlbumArtwork(Guid libraryId, Guid albumId, string libraryName, Guid artistId, string artistName, string albumTitle, string? releaseTypeName = null) { - Result artworkDirectoryPathResult = BuildAlbumArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle, releaseTypeName); + Result artworkDirectoryPathResult = BuildAlbumArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle, releaseTypeName); if (artworkDirectoryPathResult.IsFailure) return artworkDirectoryPathResult.Errors; return DeleteArtworkInDirectory(artworkDirectoryPathResult.Value); @@ -249,11 +254,12 @@ internal sealed class MusicArtworkService : IMusicArtworkService /// /// The Id of the media library the artist belongs to. /// The name of the media library the artist belongs to. + /// The Id of the artist. /// The name of the artist. /// An representing either a successful operation, or an error. - public Result DeleteArtistArtwork(Guid libraryId, string libraryName, string artistName) + public Result DeleteArtistArtwork(Guid libraryId, string libraryName, Guid artistId, string artistName) { - Result artworkDirectoryPathResult = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName); + Result artworkDirectoryPathResult = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistId, artistName); if (artworkDirectoryPathResult.IsFailure) return artworkDirectoryPathResult.Errors; return DeleteArtworkInDirectory(artworkDirectoryPathResult.Value); @@ -281,8 +287,7 @@ internal sealed class MusicArtworkService : IMusicArtworkService if (!fileExistsResult.Value) return Result.Deleted; - _environmentContext.FileProviderService.DeleteFile(filePathIdResult.Value); - return Result.Deleted; + return _environmentContext.FileProviderService.DeleteFile(filePathIdResult.Value); } /// @@ -469,13 +474,14 @@ internal sealed class MusicArtworkService : IMusicArtworkService /// The Id of the media library the album belongs to. /// The Id of the album. /// The name of the media library the album belongs to. + /// The Id of the artist of the album. /// The name of the artist of the album. /// The title of the album. /// The name of the release type directory the album is stored under on disk, or to store the artwork directly under the artist directory. /// An containing either the file system path of the album artwork directory, or an error. - private Result BuildAlbumArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, string? releaseTypeName) + private Result BuildAlbumArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, Guid artistId, string artistName, string albumTitle, string? releaseTypeName) { - Result artistPathResult = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName); + Result artistPathResult = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistId, artistName); if (artistPathResult.IsFailure) return artistPathResult.Errors; @@ -492,7 +498,7 @@ internal sealed class MusicArtworkService : IMusicArtworkService albumParentPathResult = releaseTypePathResult; } - Result albumSegmentResult = _pathService.SanitizeSegment($"{albumTitle}-{albumId}"); + Result albumSegmentResult = _pathService.SanitizeCompositeSegment(albumTitle, albumId.ToString()); if (albumSegmentResult.IsFailure) return albumSegmentResult.Errors; return _pathService.CombinePath(albumParentPathResult.Value, albumSegmentResult.Value.Name); @@ -504,15 +510,19 @@ internal sealed class MusicArtworkService : IMusicArtworkService /// /// The Id of the media library the artist belongs to. /// The name of the media library the artist belongs to. + /// The Id of the artist. /// The name of the artist. /// An containing either the file system path of the artist artwork directory, or an error. - private Result BuildArtistArtworkDirectoryPath(Guid libraryId, string libraryName, string artistName) + private Result BuildArtistArtworkDirectoryPath(Guid libraryId, string libraryName, Guid artistId, string artistName) { Result libraryPathResult = BuildLibraryArtworkDirectoryPath(libraryId, libraryName); if (libraryPathResult.IsFailure) return libraryPathResult.Errors; - Result artistSegmentResult = _pathService.SanitizeSegment(string.IsNullOrWhiteSpace(artistName) ? "Unknown" : artistName); + // The Id is part of the segment because a deleted artist and a visible artist can share a name, and each must keep its own artwork. + // The composite segment keeps the Id even when the name is long enough to need shortening. + string resolvedArtistName = string.IsNullOrWhiteSpace(artistName) ? "Unknown" : artistName; + Result artistSegmentResult = _pathService.SanitizeCompositeSegment(resolvedArtistName, artistId.ToString()); if (artistSegmentResult.IsFailure) return artistSegmentResult.Errors; return _pathService.CombinePath(libraryPathResult.Value, artistSegmentResult.Value.Name); @@ -533,7 +543,7 @@ internal sealed class MusicArtworkService : IMusicArtworkService if (musicPathResult.IsFailure) return musicPathResult.Errors; - Result librarySegmentResult = _pathService.SanitizeSegment($"{libraryName}-{libraryId}"); + Result librarySegmentResult = _pathService.SanitizeCompositeSegment(libraryName, libraryId.ToString()); if (librarySegmentResult.IsFailure) return librarySegmentResult.Errors; return _pathService.CombinePath(musicPathResult.Value, librarySegmentResult.Value.Name); diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs index 8697d40d..849be525 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs @@ -329,8 +329,8 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr artworkProviders, musicArtworkService, fileHashService, - () => musicArtworkService!.DeleteArtistArtwork(artistEntity.LibraryId, libraryName, artistName), - (artwork, token) => musicArtworkService!.SaveArtistArtworkAsync(artistEntity.LibraryId, libraryName, artistName, artwork, token), + () => musicArtworkService!.DeleteArtistArtwork(artistEntity.LibraryId, libraryName, artistEntity.Id, artistName), + (artwork, token) => musicArtworkService!.SaveArtistArtworkAsync(artistEntity.LibraryId, libraryName, artistEntity.Id, artistName, artwork, token), shouldAggregateArtworkWhenMissing, unitOfWork, cancellationToken).ConfigureAwait(false); @@ -380,8 +380,8 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr artworkProviders, musicArtworkService, fileHashService, - () => musicArtworkService!.DeleteAlbumArtwork(albumEntity.LibraryId, albumEntity.Id, libraryName, artistName, albumEntity.Title, releaseTypeName), - (artwork, token) => musicArtworkService!.SaveAlbumArtworkAsync(albumEntity.LibraryId, albumEntity.Id, libraryName, artistName, albumEntity.Title, artwork, releaseTypeName, token), + () => musicArtworkService!.DeleteAlbumArtwork(albumEntity.LibraryId, albumEntity.Id, libraryName, albumEntity.ArtistId, artistName, albumEntity.Title, releaseTypeName), + (artwork, token) => musicArtworkService!.SaveAlbumArtworkAsync(albumEntity.LibraryId, albumEntity.Id, libraryName, albumEntity.ArtistId, artistName, albumEntity.Title, artwork, releaseTypeName, token), shouldAggregateArtworkWhenMissing, unitOfWork, cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs index 33a82ee5..c6337165 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs @@ -327,13 +327,13 @@ internal sealed class BookArtworkService : IBookArtworkService if (booksPathResult.IsFailure) return booksPathResult.Errors; - Result librarySegmentResult = _pathService.SanitizeSegment($"{libraryName}-{libraryId}"); + Result librarySegmentResult = _pathService.SanitizeCompositeSegment(libraryName, libraryId.ToString()); if (librarySegmentResult.IsFailure) return librarySegmentResult.Errors; Result authorSegmentResult = _pathService.SanitizeSegment(string.IsNullOrWhiteSpace(authorName) ? "Unknown" : authorName); if (authorSegmentResult.IsFailure) return authorSegmentResult.Errors; - Result bookSegmentResult = _pathService.SanitizeSegment($"{bookTitle}-{bookId}"); + Result bookSegmentResult = _pathService.SanitizeCompositeSegment(bookTitle, bookId.ToString()); if (bookSegmentResult.IsFailure) return bookSegmentResult.Errors; diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Albums.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Albums.cs index 2933c8f6..35d0bd7a 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Albums.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Albums.cs @@ -17,6 +17,8 @@ public static partial class ApiRoutes public const string UPDATE_ALBUM = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}"; public const string UPDATE_ALBUM_COVER = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover"; public const string DELETE_ALBUM = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}"; + public const string GET_DELETED_ALBUMS = "/libraries/{libraryId}/albums/deleted-items"; + public const string RESTORE_ALBUM = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/restore"; public const string GET_ALBUM_TRACKS = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks"; public const string GET_ALBUM_TRACKS_LITE = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite"; } diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Artists.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Artists.cs index d8c1bd07..9504495b 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Artists.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Artists.cs @@ -17,5 +17,7 @@ public static partial class ApiRoutes public const string UPDATE_ARTIST = "/libraries/{libraryId}/artists/{artistId}"; public const string UPDATE_ARTIST_COVER = "/libraries/{libraryId}/artists/{artistId}/cover"; public const string DELETE_ARTIST = "/libraries/{libraryId}/artists/{artistId}"; + public const string GET_DELETED_ARTISTS = "/libraries/{libraryId}/artists/deleted-items"; + public const string RESTORE_ARTIST = "/libraries/{libraryId}/artists/{artistId}/restore"; } } diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs index a61fb46c..bbf56a7e 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs @@ -15,6 +15,8 @@ public static partial class ApiRoutes public const string SHUFFLE_TRACKS = "/libraries/{libraryId}/tracks/shuffle"; public const string UPDATE_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; public const string DELETE_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; + public const string GET_DELETED_TRACKS = "/libraries/{libraryId}/tracks/deleted-items"; + public const string RESTORE_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore"; public const string STREAM_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream"; public const string STREAM_TRACK_SEGMENT = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream/deliveries/{deliveryId}/segments/{segmentIndex}"; public const string GET_PLAYBACK_MANIFEST = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest"; diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointSummary.cs index 1a3b17eb..57e6f9af 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointSummary.cs @@ -19,7 +19,7 @@ public class DeleteAlbumEndpointSummary : Summary +/// API endpoint for the /libraries/{libraryId}/albums/deleted-items route. +/// +public class GetDeletedAlbumsEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getDeletedAlbumsQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get deleted albums queries. + public GetDeletedAlbumsEndpoint(IQueryHandler>> getDeletedAlbumsQueryHandler) + { + _getDeletedAlbumsQueryHandler = getDeletedAlbumsQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Albums.GET_DELETED_ALBUMS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the deleted albums of the library identified by the route. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // Take the unique identifier of the library from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + Result> result = await _getDeletedAlbumsQueryHandler.HandleAsync(new GetDeletedAlbumsQuery(libraryId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetDeletedAlbums/GetDeletedAlbumsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetDeletedAlbums/GetDeletedAlbumsEndpointSummary.cs new file mode 100644 index 00000000..2d81c4be --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetDeletedAlbums/GetDeletedAlbumsEndpointSummary.cs @@ -0,0 +1,92 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetDeletedAlbums; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedAlbumsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetDeletedAlbumsEndpointSummary() + { + Summary = "Retrieves the deleted albums of a media library."; + Description = "Returns the albums of the media library identified by the route that the user deleted and that can still be restored, ordered by the time they were deleted, most recent first. An album whose artist is also deleted is not returned until the artist is restored. The list is returned to an Admin, who can see the deleted albums of all libraries, or to the owner of the library."; + + ResponseParam(response => response.Id, "The Id of the deleted album."); + ResponseParam(response => response.LibraryId, "The Id of the media library the deleted album belongs to."); + ResponseParam(response => response.ArtistId, "The Id of the artist the deleted album belongs to."); + ResponseParam(response => response.ArtistName, "The name of the artist the deleted album belongs to."); + ResponseParam(response => response.Title, "The title of the deleted album."); + ResponseParam(response => response.DeletedOnUtc, "The date and time when the album was deleted."); + ResponseParam(response => response.CoverPath, "The path of the cover image of the deleted album, if available."); + + Response(200, "The deleted albums are returned.", + example: new DeletedAlbumResponse[] + { + new( + Id: Guid.Parse("b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + ArtistId: Guid.Parse("a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"), + ArtistName: "Queen", + Title: "A Night at the Opera", + DeletedOnUtc: DateTime.UtcNow, + CoverPath: "/media/music/queen/a-night-at-the-opera/cover.jpg" + ) + } + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/albums/deleted-items" + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/albums/deleted-items", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/albums/deleted-items", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreAlbum/RestoreAlbumEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreAlbum/RestoreAlbumEndpoint.cs new file mode 100644 index 00000000..4ed32f8e --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreAlbum/RestoreAlbumEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreAlbum; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId}/restore route. +/// +public class RestoreAlbumEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _restoreAlbumCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling restore album commands. + public RestoreAlbumEndpoint(ICommandHandler> restoreAlbumCommandHandler) + { + _restoreAlbumCommandHandler = restoreAlbumCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.POST); + Routes(ApiRoutes.Albums.RESTORE_ALBUM); + Version(1); + DontCatchExceptions(); + } + + /// + /// Restores the deleted album identified by the route. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // Take the unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString(); + Result result = await _restoreAlbumCommandHandler.HandleAsync(new RestoreAlbumCommand(libraryId, artistId, albumId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreAlbum/RestoreAlbumEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreAlbum/RestoreAlbumEndpointSummary.cs new file mode 100644 index 00000000..899f68e2 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreAlbum/RestoreAlbumEndpointSummary.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreAlbum; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class RestoreAlbumEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public RestoreAlbumEndpointSummary() + { + Summary = "Restores a deleted album."; + Description = "Restores the album identified by the route, together with its stored metadata, artwork and the tracks that were not deleted on their own. The album is restored by an Admin, who can restore the albums of all libraries, or by the owner of the library of the album."; + + Response(200, "The album was successfully restored."); + + Response(401, "Authentication required.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/restore" + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/restore", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested album does not exist, is not deleted, or its artist is deleted.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "AlbumNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/restore", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/restore", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "AlbumIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointSummary.cs index c9149866..c0f1923c 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointSummary.cs @@ -19,7 +19,7 @@ public class DeleteArtistEndpointSummary : Summary +/// API endpoint for the /libraries/{libraryId}/artists/deleted-items route. +/// +public class GetDeletedArtistsEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getDeletedArtistsQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get deleted artists queries. + public GetDeletedArtistsEndpoint(IQueryHandler>> getDeletedArtistsQueryHandler) + { + _getDeletedArtistsQueryHandler = getDeletedArtistsQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Artists.GET_DELETED_ARTISTS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the deleted artists of the library identified by the route. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // Take the unique identifier of the library from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + Result> result = await _getDeletedArtistsQueryHandler.HandleAsync(new GetDeletedArtistsQuery(libraryId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetDeletedArtists/GetDeletedArtistsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetDeletedArtists/GetDeletedArtistsEndpointSummary.cs new file mode 100644 index 00000000..b5214ec5 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetDeletedArtists/GetDeletedArtistsEndpointSummary.cs @@ -0,0 +1,88 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetDeletedArtists; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedArtistsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetDeletedArtistsEndpointSummary() + { + Summary = "Retrieves the deleted artists of a media library."; + Description = "Returns the artists of the media library identified by the route that the user deleted and that can still be restored, ordered by the time they were deleted, most recent first. The list is returned to an Admin, who can see the deleted artists of all libraries, or to the owner of the library."; + + ResponseParam(response => response.Id, "The Id of the deleted artist."); + ResponseParam(response => response.LibraryId, "The Id of the media library the deleted artist belongs to."); + ResponseParam(response => response.Name, "The name of the deleted artist."); + ResponseParam(response => response.DeletedOnUtc, "The date and time when the artist was deleted."); + ResponseParam(response => response.CoverPath, "The path of the cover image of the deleted artist, if available."); + + Response(200, "The deleted artists are returned.", + example: new DeletedArtistResponse[] + { + new( + Id: Guid.Parse("a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + Name: "Queen", + DeletedOnUtc: DateTime.UtcNow, + CoverPath: "/media/music/queen/cover.jpg" + ) + } + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/deleted-items" + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/deleted-items", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/deleted-items", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreArtist/RestoreArtistEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreArtist/RestoreArtistEndpoint.cs new file mode 100644 index 00000000..f536a5c7 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreArtist/RestoreArtistEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreArtist; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/restore route. +/// +public class RestoreArtistEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _restoreArtistCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling restore artist commands. + public RestoreArtistEndpoint(ICommandHandler> restoreArtistCommandHandler) + { + _restoreArtistCommandHandler = restoreArtistCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.POST); + Routes(ApiRoutes.Artists.RESTORE_ARTIST); + Version(1); + DontCatchExceptions(); + } + + /// + /// Restores the deleted artist identified by the route. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // Take the unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + Result result = await _restoreArtistCommandHandler.HandleAsync(new RestoreArtistCommand(libraryId, artistId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreArtist/RestoreArtistEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreArtist/RestoreArtistEndpointSummary.cs new file mode 100644 index 00000000..5f1b185e --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreArtist/RestoreArtistEndpointSummary.cs @@ -0,0 +1,95 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreArtist; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class RestoreArtistEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public RestoreArtistEndpointSummary() + { + Summary = "Restores a deleted artist."; + Description = "Restores the artist identified by the route, together with its stored metadata, artwork and the tracks that were not deleted on their own. The artist is restored by an Admin, who can restore the artists of all libraries, or by the owner of the library of the artist."; + + Response(200, "The artist was successfully restored."); + + Response(401, "Authentication required.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/restore" + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/restore", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested artist does not exist or is not deleted.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "ArtistNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/restore", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(409, "The request failed because a visible artist with the same name already exists in the library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "ArtistAlreadyExists", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/restore", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/restore", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpointSummary.cs index a9668122..f7092bed 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpointSummary.cs @@ -19,7 +19,7 @@ public class DeleteTrackEndpointSummary : Summary +/// API endpoint for the /libraries/{libraryId}/tracks/deleted-items route. +/// +public class GetDeletedTracksEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getDeletedTracksQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get deleted tracks queries. + public GetDeletedTracksEndpoint(IQueryHandler>> getDeletedTracksQueryHandler) + { + _getDeletedTracksQueryHandler = getDeletedTracksQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Tracks.GET_DELETED_TRACKS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the deleted tracks of the library identified by the route. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // Take the unique identifier of the library from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + Result> result = await _getDeletedTracksQueryHandler.HandleAsync(new GetDeletedTracksQuery(libraryId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetDeletedTracks/GetDeletedTracksEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetDeletedTracks/GetDeletedTracksEndpointSummary.cs new file mode 100644 index 00000000..36f035c9 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetDeletedTracks/GetDeletedTracksEndpointSummary.cs @@ -0,0 +1,96 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetDeletedTracks; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedTracksEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetDeletedTracksEndpointSummary() + { + Summary = "Retrieves the deleted tracks of a media library."; + Description = "Returns the tracks of the media library identified by the route that the user deleted and that can still be restored, ordered by the time they were deleted, most recent first. A track whose album or artist is also deleted is not returned until the album and the artist are restored. The list is returned to an Admin, who can see the deleted tracks of all libraries, or to the owner of the library."; + + ResponseParam(response => response.Id, "The Id of the deleted track."); + ResponseParam(response => response.LibraryId, "The Id of the media library the deleted track belongs to."); + ResponseParam(response => response.ArtistId, "The Id of the artist the deleted track belongs to."); + ResponseParam(response => response.ArtistName, "The name of the artist the deleted track belongs to."); + ResponseParam(response => response.AlbumId, "The Id of the album the deleted track belongs to."); + ResponseParam(response => response.AlbumTitle, "The title of the album the deleted track belongs to."); + ResponseParam(response => response.Title, "The title of the deleted track."); + ResponseParam(response => response.Path, "The file system path of the deleted track."); + ResponseParam(response => response.DeletedOnUtc, "The date and time when the track was deleted."); + + Response(200, "The deleted tracks are returned.", + example: new DeletedTrackResponse[] + { + new( + Id: Guid.Parse("c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + ArtistId: Guid.Parse("a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"), + ArtistName: "Queen", + AlbumId: Guid.Parse("b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e"), + AlbumTitle: "A Night at the Opera", + Title: "Bohemian Rhapsody", + Path: "/music/queen/a-night-at-the-opera/01 - Bohemian Rhapsody.flac", + DeletedOnUtc: DateTime.UtcNow + ) + } + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/tracks/deleted-items" + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/tracks/deleted-items", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/tracks/deleted-items", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreTrack/RestoreTrackEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreTrack/RestoreTrackEndpoint.cs new file mode 100644 index 00000000..4b777e18 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreTrack/RestoreTrackEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreTrack; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore route. +/// +public class RestoreTrackEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _restoreTrackCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling restore track commands. + public RestoreTrackEndpoint(ICommandHandler> restoreTrackCommandHandler) + { + _restoreTrackCommandHandler = restoreTrackCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.POST); + Routes(ApiRoutes.Tracks.RESTORE_TRACK); + Version(1); + DontCatchExceptions(); + } + + /// + /// Restores the deleted track identified by the route. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // Take the unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString(); + string? trackId = HttpContext.Request.RouteValues["trackId"]?.ToString(); + Result result = await _restoreTrackCommandHandler.HandleAsync(new RestoreTrackCommand(libraryId, artistId, albumId, trackId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreTrack/RestoreTrackEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreTrack/RestoreTrackEndpointSummary.cs new file mode 100644 index 00000000..897ec7ba --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreTrack/RestoreTrackEndpointSummary.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreTrack; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class RestoreTrackEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public RestoreTrackEndpointSummary() + { + Summary = "Restores a deleted track."; + Description = "Restores the track identified by the route, together with its stored metadata and artwork. The track is restored by an Admin, who can restore the tracks of all libraries, or by the owner of the library of the track."; + + Response(200, "The track was successfully restored."); + + Response(401, "Authentication required.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/restore" + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/restore", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested track does not exist, is not deleted, or its album or artist is deleted.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "TrackNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/restore", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/restore", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "AlbumIdCannotBeEmpty", + "TrackIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip b/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip index 3b91aba8..3ae5a3c7 100644 Binary files a/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip and b/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip differ diff --git a/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip b/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip index 42dd9e48..392433a2 100644 Binary files a/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip and b/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip differ diff --git a/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/DeletedMusicAlbumDto.cs b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/DeletedMusicAlbumDto.cs new file mode 100644 index 00000000..10a3f513 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/DeletedMusicAlbumDto.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; + +/// +/// Data transfer object for a music album that the user deleted and can restore. +/// +/// The Id of the deleted album. +/// The Id of the media library the deleted album belongs to. +/// The Id of the artist the deleted album belongs to. +/// The name of the artist the deleted album belongs to. +/// The title of the deleted album. +/// The date and time when the album was deleted. +/// The relative path of the stored cover image of the deleted album, when it has one. +[DebuggerDisplay("Title: {Title}")] +public sealed record DeletedMusicAlbumDto( + Guid Id, + Guid LibraryId, + Guid ArtistId, + string ArtistName, + string Title, + DateTime DeletedOnUtc, + string? CoverPath +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/DeletedMusicArtistDto.cs b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/DeletedMusicArtistDto.cs new file mode 100644 index 00000000..b767a13e --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/DeletedMusicArtistDto.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; + +/// +/// Data transfer object for a music artist that the user deleted and can restore. +/// +/// The Id of the deleted artist. +/// The Id of the media library the deleted artist belongs to. +/// The name of the deleted artist. +/// The date and time when the artist was deleted. +/// The relative path of the stored cover image of the deleted artist, when it has one. +[DebuggerDisplay("Name: {Name}")] +public sealed record DeletedMusicArtistDto( + Guid Id, + Guid LibraryId, + string Name, + DateTime DeletedOnUtc, + string? CoverPath +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/DeletedMusicItemsPageDto.cs b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/DeletedMusicItemsPageDto.cs new file mode 100644 index 00000000..b8e15def --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/DeletedMusicItemsPageDto.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; + +/// +/// Data transfer object carrying the data needed by the deleted items page of a music library. +/// +/// The media library whose deleted music items are shown. +/// The deleted artists of the media library, ordered by the time they were deleted, most recent first. +/// The deleted albums of the media library, ordered by the time they were deleted, most recent first. +/// The deleted tracks of the media library, ordered by the time they were deleted, most recent first. +public sealed record DeletedMusicItemsPageDto( + LibraryDto Library, + IReadOnlyList DeletedArtists, + IReadOnlyList DeletedAlbums, + IReadOnlyList DeletedTracks +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/DeletedMusicTrackDto.cs b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/DeletedMusicTrackDto.cs new file mode 100644 index 00000000..cc60a850 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/DeletedMusicTrackDto.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; + +/// +/// Data transfer object for a music track that the user deleted and can restore. +/// +/// The Id of the deleted track. +/// The Id of the media library the deleted track belongs to. +/// The Id of the artist the deleted track belongs to. +/// The name of the artist the deleted track belongs to. +/// The Id of the album the deleted track belongs to. +/// The title of the album the deleted track belongs to. +/// The title of the deleted track. +/// The file system path of the deleted track. +/// The date and time when the track was deleted. +[DebuggerDisplay("Title: {Title}")] +public sealed record DeletedMusicTrackDto( + Guid Id, + Guid LibraryId, + Guid ArtistId, + string ArtistName, + Guid AlbumId, + string AlbumTitle, + string Title, + string Path, + DateTime DeletedOnUtc +); diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Music.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Music.cs index 59622a18..4e66deb9 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Music.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Music.cs @@ -15,16 +15,22 @@ public static partial class ApiRoutes public const string UPDATE_ARTIST = "libraries/{libraryId}/artists/{artistId}"; public const string UPDATE_ARTIST_COVER = "libraries/{libraryId}/artists/{artistId}/cover"; public const string DELETE_ARTIST = "libraries/{libraryId}/artists/{artistId}"; + public const string GET_DELETED_ARTISTS = "libraries/{libraryId}/artists/deleted-items"; + public const string RESTORE_ARTIST = "libraries/{libraryId}/artists/{artistId}/restore"; public const string GET_ARTIST_ALBUMS_LITE = "libraries/{libraryId}/artists/{artistId}/albums/lite"; public const string GET_ALBUM = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}"; public const string UPDATE_ALBUM = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}"; public const string UPDATE_ALBUM_COVER = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover"; public const string DELETE_ALBUM = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}"; + public const string GET_DELETED_ALBUMS = "libraries/{libraryId}/albums/deleted-items"; + public const string RESTORE_ALBUM = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/restore"; public const string GET_ALBUM_TRACKS_LITE = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite"; public const string SHUFFLE_TRACKS = "libraries/{libraryId}/tracks/shuffle"; public const string GET_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; public const string UPDATE_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; public const string DELETE_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; + public const string GET_DELETED_TRACKS = "libraries/{libraryId}/tracks/deleted-items"; + public const string RESTORE_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore"; public const string STREAM_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream"; public const string STREAM_TRACK_SEGMENT = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream/deliveries/{deliveryId}/segments/{segmentIndex}"; public const string GET_PLAYBACK_MANIFEST = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest"; diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Music.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Music.cs index 1279314c..af5c0562 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Music.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Music.cs @@ -11,24 +11,28 @@ public static partial class WebRoutes public static class Music { public const string ARTISTS_INDEX = "{culture}/library/audio-library/music-library/artists"; + public const string DELETED_MUSIC_ITEMS = "{culture}/library/audio-library/music-library/deleted-items"; public const string GET_ARTISTS = "{culture}/library/audio-library/music-library/artists/api-get-artists"; public const string ARTIST = "{culture}/library/audio-library/music-library/artists/{artistId}"; public const string GET_ARTIST = "{culture}/library/audio-library/music-library/artists/{artistId}/api-get-artist"; public const string SAVE_ARTIST = "{culture}/library/audio-library/music-library/artists/{artistId}/api-save-artist"; public const string UPDATE_ARTIST_COVER = "{culture}/library/audio-library/music-library/artists/{artistId}/api-update-cover"; public const string DELETE_ARTIST = "{culture}/library/audio-library/music-library/artists/{artistId}/api-delete-artist"; + public const string RESTORE_ARTIST = "{culture}/library/audio-library/music-library/artists/{artistId}/api-restore-artist"; public const string GET_ARTIST_ALBUMS = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/api-get-albums"; public const string ALBUM = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}"; public const string GET_ALBUM = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/api-get-album"; public const string SAVE_ALBUM = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/api-save-album"; public const string UPDATE_ALBUM_COVER = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/api-update-cover"; public const string DELETE_ALBUM = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/api-delete-album"; + public const string RESTORE_ALBUM = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/api-restore-album"; public const string GET_ALBUM_TRACKS = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/api-get-tracks"; public const string SHUFFLE_TRACKS = "{culture}/library/audio-library/music-library/tracks/api-shuffle-tracks"; public const string TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; public const string GET_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-get-track"; public const string SAVE_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-save-track"; public const string DELETE_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-delete-track"; + public const string RESTORE_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-restore-track"; public const string STREAM_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track"; public const string STREAM_TRACK_SEGMENT = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track-segment/{deliveryId}/{segmentIndex}"; public const string GET_PLAYBACK_MANIFEST = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-get-playback-manifest"; diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteMusicAlbum/DeleteMusicAlbumEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteMusicAlbum/DeleteMusicAlbumEndpointSummary.cs index 3386ca71..e4a1fcef 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteMusicAlbum/DeleteMusicAlbumEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteMusicAlbum/DeleteMusicAlbumEndpointSummary.cs @@ -17,7 +17,7 @@ public class DeleteMusicAlbumEndpointSummary : Summary public DeleteMusicAlbumEndpointSummary() { Summary = "Deletes a music album."; - Description = "Deletes the music album identified by the route, together with its tracks."; + Description = "Soft deletes the music album identified by the route, so its metadata, artwork and track paths are kept and the album can be restored."; Response(200, "The music album was deleted."); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpoint.cs new file mode 100644 index 00000000..5a8b036a --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpoint.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreMusicAlbum; + +/// +/// API endpoint for the /{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/api-restore-album route. +/// +public class RestoreMusicAlbumEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public RestoreMusicAlbumEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Music.RESTORE_ALBUM); + DontAutoTag(); + Options(options => options.WithTags("Music")); + EnableAntiforgery(); + } + + /// + /// Restores the deleted music album identified by the route. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The album is identified by the {artistId} and {albumId} route values and the owning library by the {libraryId} query string; + // all ids are normalized to Guids before they are substituted into the upstream URL, so that a crafted value can never escape its URL segment. + string routeArtistId = HttpContext.Request.RouteValues["artistId"]?.ToString() ?? string.Empty; + string artistId = Guid.TryParse(routeArtistId, out Guid parsedArtistId) ? parsedArtistId.ToString() : Guid.Empty.ToString(); + string routeAlbumId = HttpContext.Request.RouteValues["albumId"]?.ToString() ?? string.Empty; + string albumId = Guid.TryParse(routeAlbumId, out Guid parsedAlbumId) ? parsedAlbumId.ToString() : Guid.Empty.ToString(); + string queryLibraryId = HttpContext.Request.Query["libraryId"].ToString(); + string libraryId = Guid.TryParse(queryLibraryId, out Guid parsedLibraryId) ? parsedLibraryId.ToString() : Guid.Empty.ToString(); + + await _apiHttpClient.PostAsync( + ApiRoutes.Music.RESTORE_ALBUM.Replace("{libraryId}", libraryId).Replace("{artistId}", artistId).Replace("{albumId}", albumId), + new Web.Common.Requests.Common.EmptyRequest(), + cancellationToken).ConfigureAwait(false); + return JsonSuccess(new { isRestored = true }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpointSummary.cs new file mode 100644 index 00000000..c4a3d1fe --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpointSummary.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreMusicAlbum; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class RestoreMusicAlbumEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public RestoreMusicAlbumEndpointSummary() + { + Summary = "Restores a deleted music album."; + Description = "Restores the deleted music album identified by the route, together with the metadata and artwork kept for it."; + + Response(200, "The music album was restored."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteMusicArtist/DeleteMusicArtistEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteMusicArtist/DeleteMusicArtistEndpointSummary.cs index 9a1db23b..2e869bbc 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteMusicArtist/DeleteMusicArtistEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteMusicArtist/DeleteMusicArtistEndpointSummary.cs @@ -17,7 +17,7 @@ public class DeleteMusicArtistEndpointSummary : Summary +/// API endpoint for the /{culture}/library/audio-library/music-library/artists/{artistId}/api-restore-artist route. +/// +public class RestoreMusicArtistEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public RestoreMusicArtistEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Music.RESTORE_ARTIST); + DontAutoTag(); + Options(options => options.WithTags("Music")); + EnableAntiforgery(); + } + + /// + /// Restores the deleted music artist identified by the route. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The artist is identified by the {artistId} route value and the owning library by the {libraryId} query string; both ids are + // normalized to Guids before they are substituted into the upstream URL, so that a crafted value can never escape its URL segment. + string routeArtistId = HttpContext.Request.RouteValues["artistId"]?.ToString() ?? string.Empty; + string artistId = Guid.TryParse(routeArtistId, out Guid parsedArtistId) ? parsedArtistId.ToString() : Guid.Empty.ToString(); + string queryLibraryId = HttpContext.Request.Query["libraryId"].ToString(); + string libraryId = Guid.TryParse(queryLibraryId, out Guid parsedLibraryId) ? parsedLibraryId.ToString() : Guid.Empty.ToString(); + + await _apiHttpClient.PostAsync( + ApiRoutes.Music.RESTORE_ARTIST.Replace("{libraryId}", libraryId).Replace("{artistId}", artistId), + new Web.Common.Requests.Common.EmptyRequest(), + cancellationToken).ConfigureAwait(false); + return JsonSuccess(new { isRestored = true }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpointSummary.cs new file mode 100644 index 00000000..d1254794 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpointSummary.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreMusicArtist; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class RestoreMusicArtistEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public RestoreMusicArtistEndpointSummary() + { + Summary = "Restores a deleted music artist."; + Description = "Restores the deleted music artist identified by the route, together with the metadata and artwork kept for it."; + + Response(200, "The music artist was restored."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/DeletedMusicItems/DeletedMusicItemsViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/DeletedMusicItems/DeletedMusicItemsViewEndpoint.cs new file mode 100644 index 00000000..5e6c64c0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/DeletedMusicItems/DeletedMusicItemsViewEndpoint.cs @@ -0,0 +1,143 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Lumina.Presentation.Web.Core.Themes; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.DeletedMusicItems; + +/// +/// API endpoint for the /{culture}/library/audio-library/music-library/deleted-items route. +/// +public class DeletedMusicItemsViewEndpoint : BaseEndpoint +{ + // The resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath. + private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Library.AudioLibrary.MusicLibrary.DeletedItems"; + private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web"; + // The page key mirrors the path of the Razor view under Core/Views, so that theme templates can override it at the page, section or default scope. + private const string VIEW_PAGE_KEY = "library/audio-library/music-library/deleted-items"; + + private static readonly JsonSerializerOptions s_camelCaseJsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Converters = { new JsonStringEnumConverter() } + }; + + private readonly IApiHttpClient _apiHttpClient; + private readonly IUrlService _urlService; + private readonly ThemePageRenderer _themePageRenderer; + private readonly IAntiforgery _antiforgery; + private readonly IStringLocalizer _localizer; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + /// Injected service for generating URLs from action and controller names, with localization. + /// Injected service for rendering themed pages. + /// Injected service for anti-forgery token handling. + /// Injected factory used to create the localizer of the view resources. + public DeletedMusicItemsViewEndpoint(IApiHttpClient apiHttpClient, IUrlService urlService, ThemePageRenderer themePageRenderer, IAntiforgery antiforgery, IStringLocalizerFactory stringLocalizerFactory) + { + _apiHttpClient = apiHttpClient; + _urlService = urlService; + _themePageRenderer = themePageRenderer; + _antiforgery = antiforgery; + _localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION); + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Music.DELETED_MUSIC_ITEMS); + DontAutoTag(); + Options(options => options.WithTags("Music")); + } + + /// + /// Displays the deleted music items of a media library, rendered by the active theme with a fallback to the Razor view. + /// + /// The request containing the Id of the media library whose deleted music items are shown. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetMusicArtistsViewRequest request, CancellationToken cancellationToken) + { + if (request.LibraryId is null) + return Results.Redirect(_urlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED)!); + + LibraryDto library = await _apiHttpClient.GetAsync( + ApiRoutes.Libraries.GET_LIBRARY_BY_ID.Replace("{id}", request.LibraryId.Value.ToString()), cancellationToken).ConfigureAwait(false); + DeletedMusicArtistDto[] deletedArtists = await _apiHttpClient.GetAsync( + ApiRoutes.Music.GET_DELETED_ARTISTS.Replace("{libraryId}", request.LibraryId.Value.ToString()), cancellationToken).ConfigureAwait(false); + DeletedMusicAlbumDto[] deletedAlbums = await _apiHttpClient.GetAsync( + ApiRoutes.Music.GET_DELETED_ALBUMS.Replace("{libraryId}", request.LibraryId.Value.ToString()), cancellationToken).ConfigureAwait(false); + DeletedMusicTrackDto[] deletedTracks = await _apiHttpClient.GetAsync( + ApiRoutes.Music.GET_DELETED_TRACKS.Replace("{libraryId}", request.LibraryId.Value.ToString()), cancellationToken).ConfigureAwait(false); + + // The page restores music items, which submit through the form anti-forgery token, so a fresh token must be issued for it. + AntiforgeryTokenSet antiforgeryTokens = _antiforgery.GetAndStoreTokens(HttpContext); + + string title = _localizer["Title"].Value; + string backUrl = (_urlService.GetAbsoluteUrl(WebRoutes.Music.ARTISTS_INDEX) ?? string.Empty) + "?libraryId=" + request.LibraryId.Value; + Dictionary strings = ThemePageDataFactory.CreateLocalizedStrings(_localizer); + // The themed page script reads the localized strings through camel case keys, and they are serialized as JSON so that quotes and + // apostrophes in translations never terminate the JavaScript string literals of the template. + string stringsJson = JsonSerializer.Serialize(strings.ToDictionary( + entry => JsonNamingPolicy.CamelCase.ConvertName(entry.Key), + entry => entry.Value)); + + ThemePageDto pageModel = new() + { + PageKey = VIEW_PAGE_KEY, + Title = title, + Description = string.Empty, + PageData = new Dictionary + { + ["libraryId"] = request.LibraryId.Value.ToString(), + ["libraryTitle"] = library.Title ?? string.Empty, + ["deletedArtistsJson"] = JsonSerializer.Serialize(deletedArtists, s_camelCaseJsonOptions), + ["deletedAlbumsJson"] = JsonSerializer.Serialize(deletedAlbums, s_camelCaseJsonOptions), + ["deletedTracksJson"] = JsonSerializer.Serialize(deletedTracks, s_camelCaseJsonOptions), + ["artistRestoreUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.RESTORE_ARTIST, new { artistId = default(Guid) }) ?? string.Empty, + ["albumRestoreUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.RESTORE_ALBUM, new { artistId = default(Guid), albumId = default(Guid) }) ?? string.Empty, + ["trackRestoreUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.RESTORE_TRACK, new { artistId = default(Guid), albumId = default(Guid), trackId = default(Guid) }) ?? string.Empty, + ["backUrl"] = backUrl, + ["antiforgeryToken"] = antiforgeryTokens.RequestToken, + ["strings"] = strings, + ["stringsJson"] = stringsJson + } + }; + + Result sectionResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false); + if (sectionResult.IsFailure) + return View("/Core/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.cshtml", + new DeletedMusicItemsPageDto(library, deletedArtists, deletedAlbums, deletedTracks), + new Dictionary { ["Title"] = title }); + + return View( + "/Core/Views/Shared/_ThemedView.cshtml", + new ThemeViewDto(sectionResult.Value.Content, sectionResult.Value.Script), + new Dictionary { ["Title"] = title }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/DeletedMusicItems/DeletedMusicItemsViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/DeletedMusicItems/DeletedMusicItemsViewEndpointSummary.cs new file mode 100644 index 00000000..f8742b6e --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/DeletedMusicItems/DeletedMusicItemsViewEndpointSummary.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.DeletedMusicItems; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class DeletedMusicItemsViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public DeletedMusicItemsViewEndpointSummary() + { + Summary = "Renders the deleted items page of a music library."; + Description = "Renders the page that lists the artists, albums and tracks the user deleted from a music library and lets the user restore them."; + + Response(200, "The deleted items page is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteMusicTrack/DeleteMusicTrackEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteMusicTrack/DeleteMusicTrackEndpointSummary.cs index a4d49a30..86e8dfb0 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteMusicTrack/DeleteMusicTrackEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteMusicTrack/DeleteMusicTrackEndpointSummary.cs @@ -17,7 +17,7 @@ public class DeleteMusicTrackEndpointSummary : Summary public DeleteMusicTrackEndpointSummary() { Summary = "Deletes a music track."; - Description = "Deletes the music track identified by the route, together with its metadata."; + Description = "Soft deletes the music track identified by the route, so its metadata, artwork and file path are kept and the track can be restored."; Response(200, "The music track was deleted."); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpoint.cs new file mode 100644 index 00000000..e79985a0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpoint.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreMusicTrack; + +/// +/// API endpoint for the /{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-restore-track route. +/// +public class RestoreMusicTrackEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public RestoreMusicTrackEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Music.RESTORE_TRACK); + DontAutoTag(); + Options(options => options.WithTags("Music")); + EnableAntiforgery(); + } + + /// + /// Restores the deleted music track identified by the route. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The track is identified by the {artistId}, {albumId} and {trackId} route values and the owning library by the {libraryId} query string; + // all ids are normalized to Guids before they are substituted into the upstream URL, so that a crafted value can never escape its URL segment. + string routeArtistId = HttpContext.Request.RouteValues["artistId"]?.ToString() ?? string.Empty; + string artistId = Guid.TryParse(routeArtistId, out Guid parsedArtistId) ? parsedArtistId.ToString() : Guid.Empty.ToString(); + string routeAlbumId = HttpContext.Request.RouteValues["albumId"]?.ToString() ?? string.Empty; + string albumId = Guid.TryParse(routeAlbumId, out Guid parsedAlbumId) ? parsedAlbumId.ToString() : Guid.Empty.ToString(); + string routeTrackId = HttpContext.Request.RouteValues["trackId"]?.ToString() ?? string.Empty; + string trackId = Guid.TryParse(routeTrackId, out Guid parsedTrackId) ? parsedTrackId.ToString() : Guid.Empty.ToString(); + string queryLibraryId = HttpContext.Request.Query["libraryId"].ToString(); + string libraryId = Guid.TryParse(queryLibraryId, out Guid parsedLibraryId) ? parsedLibraryId.ToString() : Guid.Empty.ToString(); + + await _apiHttpClient.PostAsync( + ApiRoutes.Music.RESTORE_TRACK.Replace("{libraryId}", libraryId).Replace("{artistId}", artistId).Replace("{albumId}", albumId).Replace("{trackId}", trackId), + new Web.Common.Requests.Common.EmptyRequest(), + cancellationToken).ConfigureAwait(false); + return JsonSuccess(new { isRestored = true }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpointSummary.cs new file mode 100644 index 00000000..1729857d --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpointSummary.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreMusicTrack; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class RestoreMusicTrackEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public RestoreMusicTrackEndpointSummary() + { + Summary = "Restores a deleted music track."; + Description = "Restores the deleted music track identified by the route, together with the metadata and artwork kept for it."; + + Response(200, "The music track was restored."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ar-SA.resx index 51c3d569..cda25573 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ar-SA.resx @@ -69,4 +69,7 @@ إضافة إلى قائمة التشغيل + + العناصر المحذوفة + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.de-DE.resx index 9629c2e8..d78660b5 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.de-DE.resx @@ -69,4 +69,7 @@ Zur Wiedergabeliste hinzufügen + + Gelöschte Elemente + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.en-US.resx index 70edc6b1..57ef5557 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.en-US.resx @@ -69,4 +69,7 @@ Add to playlist + + Deleted items + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.es-ES.resx index ef56aa55..7b55ec97 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.es-ES.resx @@ -69,4 +69,7 @@ Añadir a la lista de reproducción + + Elementos eliminados + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.fr-FR.resx index 54a1c039..6d49846e 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.fr-FR.resx @@ -69,4 +69,7 @@ Ajouter à la liste de lecture + + Éléments supprimés + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.it-IT.resx index 3a94a7da..598d92a2 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.it-IT.resx @@ -69,4 +69,7 @@ Aggiungi alla playlist + + Elementi eliminati + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ja-JP.resx index e1f3718d..3bf5fa61 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ja-JP.resx @@ -69,4 +69,7 @@ プレイリストに追加 + + 削除済みアイテム + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.resx index 70edc6b1..57ef5557 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.resx @@ -69,4 +69,7 @@ Add to playlist + + Deleted items + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ro-RO.resx index 4860c230..21de7027 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ro-RO.resx @@ -69,4 +69,7 @@ Adaugă în listă de redare + + Elemente șterse + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.uk-UA.resx index 9ceafb1b..a6f79ffc 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.uk-UA.resx @@ -69,4 +69,7 @@ Додати до списку відтворення + + Видалені елементи + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.zh-CN.resx index 18859dc1..e2ac2657 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.zh-CN.resx @@ -69,4 +69,7 @@ 添加到播放列表 + + 已删除项目 + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.ar-SA.resx new file mode 100644 index 00000000..a8f01382 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.ar-SA.resx @@ -0,0 +1,57 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + العناصر المحذوفة + + + العودة إلى المكتبة + + + لا توجد عناصر محذوفة في هذه المكتبة. + + + الفنانون + + + الألبومات + + + المقاطع + + + الاسم + + + الفنان + + + ألبوم + + + العنوان + + + تاريخ الحذف + + + استعادة + + + تمت استعادة العنصر. + + + تعذرت استعادة العنصر. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.de-DE.resx new file mode 100644 index 00000000..1da61850 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.de-DE.resx @@ -0,0 +1,57 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Gelöschte Elemente + + + Zurück zur Bibliothek + + + In dieser Bibliothek gibt es keine gelöschten Elemente. + + + Künstler + + + Alben + + + Titel + + + Name + + + Künstler + + + Album + + + Titel + + + Gelöscht am + + + Wiederherstellen + + + Das Element wurde wiederhergestellt. + + + Das Element konnte nicht wiederhergestellt werden. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.en-US.resx new file mode 100644 index 00000000..bdd00e94 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.en-US.resx @@ -0,0 +1,57 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Deleted items + + + Back to library + + + There are no deleted items in this library. + + + Artists + + + Albums + + + Tracks + + + Name + + + Artist + + + Album + + + Title + + + Deleted on + + + Restore + + + The item was restored. + + + The item could not be restored. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.es-ES.resx new file mode 100644 index 00000000..a6fec297 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.es-ES.resx @@ -0,0 +1,57 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Elementos eliminados + + + Volver a la biblioteca + + + No hay elementos eliminados en esta biblioteca. + + + Artistas + + + Álbumes + + + Pistas + + + Nombre + + + Artista + + + Álbum + + + Título + + + Eliminado el + + + Restaurar + + + El elemento se ha restaurado. + + + El elemento no se ha podido restaurar. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.fr-FR.resx new file mode 100644 index 00000000..487636f3 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.fr-FR.resx @@ -0,0 +1,57 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Éléments supprimés + + + Retour à la bibliothèque + + + Cette bibliothèque ne contient aucun élément supprimé. + + + Artistes + + + Albums + + + Pistes + + + Nom + + + Artiste + + + Album + + + Titre + + + Supprimé le + + + Restaurer + + + L'élément a été restauré. + + + L'élément n'a pas pu être restauré. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.it-IT.resx new file mode 100644 index 00000000..0b39abec --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.it-IT.resx @@ -0,0 +1,57 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Elementi eliminati + + + Torna alla biblioteca + + + Non ci sono elementi eliminati in questa biblioteca. + + + Artisti + + + Album + + + Tracce + + + Nome + + + Artista + + + Album + + + Titolo + + + Eliminato il + + + Ripristina + + + L'elemento è stato ripristinato. + + + Non è stato possibile ripristinare l'elemento. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.ja-JP.resx new file mode 100644 index 00000000..132a475a --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.ja-JP.resx @@ -0,0 +1,57 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 削除済みアイテム + + + ライブラリに戻る + + + このライブラリに削除済みアイテムはありません。 + + + アーティスト + + + アルバム + + + トラック + + + 名前 + + + アーティスト + + + アルバム + + + タイトル + + + 削除日 + + + 復元 + + + 項目を復元しました。 + + + 項目を復元できませんでした。 + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.resx new file mode 100644 index 00000000..bdd00e94 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.resx @@ -0,0 +1,57 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Deleted items + + + Back to library + + + There are no deleted items in this library. + + + Artists + + + Albums + + + Tracks + + + Name + + + Artist + + + Album + + + Title + + + Deleted on + + + Restore + + + The item was restored. + + + The item could not be restored. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.ro-RO.resx new file mode 100644 index 00000000..5fc5665f --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.ro-RO.resx @@ -0,0 +1,57 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Elemente șterse + + + Înapoi la bibliotecă + + + Nu există elemente șterse în această bibliotecă. + + + Artiști + + + Albume + + + Piese + + + Nume + + + Artist + + + Album + + + Titlu + + + Șters la + + + Restaurează + + + Elementul a fost restaurat. + + + Elementul nu a putut fi restaurat. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.uk-UA.resx new file mode 100644 index 00000000..0e8e579a --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.uk-UA.resx @@ -0,0 +1,57 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Видалені елементи + + + Повернутися до бібліотеки + + + У цій бібліотеці немає видалених елементів. + + + Виконавці + + + Альбоми + + + Треки + + + Ім'я + + + Виконавець + + + Альбом + + + Назва + + + Видалено + + + Відновити + + + Елемент відновлено. + + + Не вдалося відновити елемент. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.zh-CN.resx new file mode 100644 index 00000000..7be22492 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.zh-CN.resx @@ -0,0 +1,57 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 已删除项目 + + + 返回图书馆 + + + 此库中没有已删除项目。 + + + 艺术家 + + + 专辑 + + + 曲目 + + + 名称 + + + 艺术家 + + + 专辑 + + + 标题 + + + 删除时间 + + + 恢复 + + + 项目已恢复。 + + + 无法恢复项目。 + + diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.cshtml index 54d04c59..553c86f3 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.cshtml @@ -46,6 +46,8 @@ + +
@@ -89,6 +91,8 @@ const prevPageButton = document.getElementById('prev-page'); const nextPageButton = document.getElementById('next-page'); const pageIndicator = document.getElementById('page-indicator'); + const deletedItemsButton = document.getElementById('deleted-items-button'); + const deletedItemsUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Music.DELETED_MUSIC_ITEMS)'; // The special alpha keys for numbers and symbols, followed by the letters. const alphaKeys = ['#', '*', ...Array.from({ length: 26 }, (_, index) => String.fromCharCode(65 + index))]; @@ -492,6 +496,10 @@ loadItemsAsync(); } + async function handleDeletedItemsClick() { + await updateContentAsync(`${deletedItemsUrl}?libraryId=${encodeURIComponent(libraryId)}`, true); + } + async function loadSettingsAsync() { const data = await callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS)'); if (data) { @@ -515,6 +523,7 @@ bindEventHandler(sortToggle, 'click', handleSortToggle); bindEventHandler(prevPageButton, 'click', handlePrevPageClick); bindEventHandler(nextPageButton, 'click', handleNextPageClick); + bindEventHandler(deletedItemsButton, 'click', handleDeletedItemsClick); document.addEventListener('keydown', handleAlphaKeydown); document.addEventListener('click', handleCardMenuDismiss); document.addEventListener('keydown', handleCardMenuDismiss); @@ -526,6 +535,7 @@ unbindEventHandler(sortToggle, 'click', handleSortToggle); unbindEventHandler(prevPageButton, 'click', handlePrevPageClick); unbindEventHandler(nextPageButton, 'click', handleNextPageClick); + unbindEventHandler(deletedItemsButton, 'click', handleDeletedItemsClick); document.removeEventListener('keydown', handleAlphaKeydown); document.removeEventListener('click', handleCardMenuDismiss); document.removeEventListener('keydown', handleCardMenuDismiss); diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.cshtml new file mode 100644 index 00000000..24de668b --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.cshtml @@ -0,0 +1,220 @@ +@* + FALLBACK DELETED ITEMS VIEW - READ BEFORE EDITING + + This view is the application fallback of the deleted items page of a music library, rendered only when the + active theme does not provide its own template for the page. It keeps the DOM contract and the client script + the theme template mirrors, so that restoring a deleted artist, album or track keeps working even without the theme. + + /library/audio-library/music-library/deleted-items?libraryId=... +*@ + +@using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary +@using Lumina.Presentation.Web.Common.Services +@using Microsoft.AspNetCore.Mvc.Localization + +@{ + // Generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler. + var scriptId = ScriptIdentifierHelper.GenerateScriptId(); + var libraryId = Model.Library.Id?.ToString() ?? string.Empty; +} + +@inject IViewLocalizer _localizer +@inject IUrlService _urlService + +@model DeletedMusicItemsPageDto + +@Html.AntiForgeryToken() + +
+
+
+
+
+ +
+
+

@_localizer["Title"]

+
+

@_localizer["NoDeletedItems"]

+ +
+

@_localizer["Artists"]

+ + + + + + + + + + @foreach (DeletedMusicArtistDto artist in Model.DeletedArtists) + { + + + + + + } + +
@_localizer["Name"]@_localizer["DeletedOn"]
@artist.Name@artist.DeletedOnUtc.ToString("g") + +
+
+ +
+

@_localizer["Albums"]

+ + + + + + + + + + + @foreach (DeletedMusicAlbumDto album in Model.DeletedAlbums) + { + + + + + + + } + +
@_localizer["Artist"]@_localizer["Album"]@_localizer["DeletedOn"]
@album.ArtistName@album.Title@album.DeletedOnUtc.ToString("g") + +
+
+ +
+

@_localizer["Tracks"]

+ + + + + + + + + + + + @foreach (DeletedMusicTrackDto track in Model.DeletedTracks) + { + + + + + + + + } + +
@_localizer["Artist"]@_localizer["Album"]@_localizer["TrackTitle"]@_localizer["DeletedOn"]
@track.ArtistName@track.AlbumTitle@track.Title@track.DeletedOnUtc.ToString("g") + +
+
+
+
+ +@section Scripts { + + +} diff --git a/src/Lumina.slnx b/src/Lumina.slnx index 25841efb..04bf0b64 100644 --- a/src/Lumina.slnx +++ b/src/Lumina.slnx @@ -191,6 +191,8 @@ + + @@ -202,6 +204,8 @@ + + @@ -210,6 +214,8 @@ + + diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumEntityFixture.cs index 511211c7..4e2e6efa 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumEntityFixture.cs @@ -55,10 +55,12 @@ public class AlbumEntityFixture /// Optional. The release status of the album. /// Optional. The total number of discs of the album. /// Optional. The media format of the album. - /// Optional. The catalog number of the album. + /// Optional. The catalog numbers of the album. /// Optional. The MusicBrainz release identifier of the album. /// Optional. The MusicBrainz release group identifier of the album. /// Optional. The MusicBrainz release artist identifier of the album. + /// Whether the album is soft deleted. + /// Optional. The date and time when the album was deleted. /// Whether the album should own a generated track, or no track at all. /// Whether the owned metadata collections (Tags, Genres, Contributors, Ratings) should be included, or forced to empty collections. /// Whether the original release date should be included, or forced to . @@ -78,6 +80,7 @@ public class AlbumEntityFixture /// Whether the MusicBrainz release identifier should be included, or forced to . /// Whether the MusicBrainz release group identifier should be included, or forced to . /// Whether the MusicBrainz release artist identifier should be included, or forced to . + /// Whether a deleted album should carry a deletion time, or . /// Optional. The metadata enrichment status of the album. /// The created . public AlbumEntity Create( @@ -107,6 +110,8 @@ public class AlbumEntityFixture Guid? musicBrainzReleaseId = null, Guid? musicBrainzReleaseGroupId = null, Guid? musicBrainzReleaseArtistId = null, + bool isDeleted = false, + DateTime? deletedOnUtc = null, bool includeTracks = true, bool includeMetadata = true, bool includeOriginalReleaseDate = true, @@ -126,6 +131,7 @@ public class AlbumEntityFixture bool includeMusicBrainzReleaseId = true, bool includeMusicBrainzReleaseGroupId = true, bool includeMusicBrainzReleaseArtistId = true, + bool includeDeletedOnUtc = true, MetadataStatus? metadataStatus = null) { Guid resolvedId = id ?? Guid.NewGuid(); @@ -182,6 +188,8 @@ public class AlbumEntityFixture .RuleFor(x => x.Contributors, f => includeMetadata ? _albumContributorEntityFixture.CreateMany(f.Random.Number(1, 3), albumId: resolvedId) : []) .RuleFor(x => x.Ratings, f => includeMetadata ? _audioRatingEntityFixture.CreateMany(f.Random.Number(1, 3)) : []) .RuleFor(x => x.Tracks, resolvedTracks) + .RuleFor(x => x.IsDeleted, isDeleted) + .RuleFor(x => x.DeletedOnUtc, f => isDeleted && includeDeletedOnUtc ? (deletedOnUtc ?? f.Date.Recent()) : null) .RuleFor(x => x.CreatedOnUtc, f => f.Date.Past()) .RuleFor(x => x.UpdatedOnUtc, f => f.Date.Recent()) .Generate(); diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistEntityFixture.cs index db9dedae..76357337 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistEntityFixture.cs @@ -27,11 +27,14 @@ public class ArtistEntityFixture /// Optional. The website of the artist. /// Optional. The MusicBrainz identifier of the artist. /// Optional. The albums of the artist. + /// Whether the artist is soft deleted. + /// Optional. The date and time when the artist was deleted. /// Whether the artist should own a generated album, or no album at all. /// Whether the website should be included, or forced to . /// Whether the MusicBrainz identifier should be included, or forced to . /// Whether the artist should own a generated media contributor, or none at all. /// Whether the owned metadata collections of the generated album should be included, or forced to empty collections. + /// Whether a deleted artist should carry a deletion time, or . /// The created . public ArtistEntity Create( Guid? id = null, @@ -40,11 +43,14 @@ public class ArtistEntityFixture string? website = null, Guid? musicBrainzArtistId = null, List? albums = null, + bool isDeleted = false, + DateTime? deletedOnUtc = null, bool includeAlbums = true, bool includeWebsite = true, bool includeMusicBrainzArtistId = true, bool includeContributors = true, - bool includeMetadata = true) + bool includeMetadata = true, + bool includeDeletedOnUtc = true) { Guid resolvedId = id ?? Guid.NewGuid(); Guid resolvedLibraryId = libraryId ?? Guid.NewGuid(); @@ -65,6 +71,8 @@ public class ArtistEntityFixture .RuleFor(x => x.MusicBrainzArtistId, f => includeMusicBrainzArtistId ? (musicBrainzArtistId ?? f.Random.Guid()) : null) .RuleFor(x => x.Albums, resolvedAlbums) .RuleFor(x => x.Contributors, f => includeContributors ? _artistContributorEntityFixture.CreateMany(f.Random.Number(1, 3), artistId: resolvedId) : []) + .RuleFor(x => x.IsDeleted, isDeleted) + .RuleFor(x => x.DeletedOnUtc, f => isDeleted && includeDeletedOnUtc ? (deletedOnUtc ?? f.Date.Recent()) : null) .RuleFor(x => x.CreatedOnUtc, f => f.Date.Past()) .RuleFor(x => x.UpdatedOnUtc, f => f.Date.Recent()) .Generate(); diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntityFixture.cs index d41b6e5a..7e885984 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntityFixture.cs @@ -44,6 +44,8 @@ public class TrackEntityFixture /// Optional. The original release year of the track. /// Optional. The re-release date of the track. /// Optional. The re-release year of the track. + /// Whether the track is soft deleted. + /// Optional. The date and time when the track was deleted. /// Whether the owned metadata collections (Tags, Genres, Moods, ISRCs, Contributors, Ratings) should be included, or forced to empty collections. /// Whether the original release date should be included, or forced to . /// Whether the original release year should be included, or forced to . @@ -58,6 +60,7 @@ public class TrackEntityFixture /// Optional. The ReplayGain album gain of the track, in decibels. /// Optional. The ReplayGain album peak of the track. /// Whether the ReplayGain values should be included, or forced to . + /// Whether a deleted track should carry a deletion time, or . /// The created . public TrackEntity Create( Guid? id = null, @@ -72,6 +75,8 @@ public class TrackEntityFixture int? originalReleaseYear = null, DateOnly? reReleaseDate = null, int? reReleaseYear = null, + bool isDeleted = false, + DateTime? deletedOnUtc = null, bool includeMetadata = true, bool includeOriginalReleaseDate = true, bool includeOriginalReleaseYear = true, @@ -85,7 +90,8 @@ public class TrackEntityFixture decimal? replayGainTrackPeak = null, decimal? replayGainAlbumGain = null, decimal? replayGainAlbumPeak = null, - bool includeReplayGain = true) + bool includeReplayGain = true, + bool includeDeletedOnUtc = true) { Guid resolvedId = id ?? Guid.NewGuid(); Guid resolvedAlbumId = albumId ?? Guid.NewGuid(); @@ -154,6 +160,8 @@ public class TrackEntityFixture .RuleFor(x => x.Isrcs, f => includeMetadata ? _trackIsrcEntityFixture.CreateMany(f.Random.Number(1, 3)) : []) .RuleFor(x => x.Contributors, f => includeMetadata ? _trackContributorEntityFixture.CreateMany(f.Random.Number(1, 3), trackId: resolvedId) : []) .RuleFor(x => x.Ratings, f => includeMetadata ? _audioRatingEntityFixture.CreateMany(f.Random.Number(1, 3)) : []) + .RuleFor(x => x.IsDeleted, isDeleted) + .RuleFor(x => x.DeletedOnUtc, f => isDeleted && includeDeletedOnUtc ? (deletedOnUtc ?? f.Date.Recent()) : null) .RuleFor(x => x.CreatedOnUtc, f => f.Date.Past()) .RuleFor(x => x.UpdatedOnUtc, f => f.Date.Recent()) .Generate(); diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/RestoreAlbum/RestoreAlbumCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/RestoreAlbum/RestoreAlbumCommandFixture.cs new file mode 100644 index 00000000..1bba8013 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/RestoreAlbum/RestoreAlbumCommandFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class RestoreAlbumCommandFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library the album belongs to, taken from the route. + /// Optional. The Id of the artist the album belongs to, taken from the route. + /// Optional. The Id of the deleted album to restore, taken from the route. + /// Whether the library Id should be included, or forced to . + /// Whether the artist Id should be included, or forced to . + /// Whether the album Id should be included, or forced to . + /// The created . + public RestoreAlbumCommand Create( + string? libraryId = null, + string? artistId = null, + string? albumId = null, + bool includeLibraryId = true, + bool includeArtistId = true, + bool includeAlbumId = true) + { + return new RestoreAlbumCommand( + includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null, + includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null, + includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null); + } + + /// + /// Creates a list of . + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetDeletedAlbums/GetDeletedAlbumsQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetDeletedAlbums/GetDeletedAlbumsQueryFixture.cs new file mode 100644 index 00000000..1ad315e6 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetDeletedAlbums/GetDeletedAlbumsQueryFixture.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedAlbumsQueryFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library whose deleted albums are retrieved, taken from the route. + /// Whether the library Id should be included, or forced to . + /// The created . + public GetDeletedAlbumsQuery Create( + string? libraryId = null, + bool includeLibraryId = true) + { + return new GetDeletedAlbumsQuery( + includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null); + } + + /// + /// Creates a list of . + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/RestoreArtist/RestoreArtistCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/RestoreArtist/RestoreArtistCommandFixture.cs new file mode 100644 index 00000000..411684da --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/RestoreArtist/RestoreArtistCommandFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class RestoreArtistCommandFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library the artist belongs to, taken from the route. + /// Optional. The Id of the deleted artist to restore, taken from the route. + /// Whether the library Id should be included, or forced to . + /// Whether the artist Id should be included, or forced to . + /// The created . + public RestoreArtistCommand Create( + string? libraryId = null, + string? artistId = null, + bool includeLibraryId = true, + bool includeArtistId = true) + { + return new RestoreArtistCommand( + includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null, + includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null); + } + + /// + /// Creates a list of . + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetDeletedArtists/GetDeletedArtistsQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetDeletedArtists/GetDeletedArtistsQueryFixture.cs new file mode 100644 index 00000000..3ae68369 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetDeletedArtists/GetDeletedArtistsQueryFixture.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedArtistsQueryFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library whose deleted artists are retrieved, taken from the route. + /// Whether the library Id should be included, or forced to . + /// The created . + public GetDeletedArtistsQuery Create( + string? libraryId = null, + bool includeLibraryId = true) + { + return new GetDeletedArtistsQuery( + includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null); + } + + /// + /// Creates a list of . + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/RestoreTrack/RestoreTrackCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/RestoreTrack/RestoreTrackCommandFixture.cs new file mode 100644 index 00000000..d5f007fc --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/RestoreTrack/RestoreTrackCommandFixture.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class RestoreTrackCommandFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library the track belongs to, taken from the route. + /// Optional. The Id of the artist the album of the track belongs to, taken from the route. + /// Optional. The Id of the album the track belongs to, taken from the route. + /// Optional. The Id of the deleted track to restore, taken from the route. + /// Whether the library Id should be included, or forced to . + /// Whether the artist Id should be included, or forced to . + /// Whether the album Id should be included, or forced to . + /// Whether the track Id should be included, or forced to . + /// The created . + public RestoreTrackCommand Create( + string? libraryId = null, + string? artistId = null, + string? albumId = null, + string? trackId = null, + bool includeLibraryId = true, + bool includeArtistId = true, + bool includeAlbumId = true, + bool includeTrackId = true) + { + return new RestoreTrackCommand( + includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null, + includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null, + includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null, + includeTrackId ? (trackId ?? Guid.NewGuid().ToString()) : null); + } + + /// + /// Creates a list of . + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetDeletedTracks/GetDeletedTracksQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetDeletedTracks/GetDeletedTracksQueryFixture.cs new file mode 100644 index 00000000..ba8bd4d3 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetDeletedTracks/GetDeletedTracksQueryFixture.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedTracksQueryFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library whose deleted tracks are retrieved, taken from the route. + /// Whether the library Id should be included, or forced to . + /// The created . + public GetDeletedTracksQuery Create( + string? libraryId = null, + bool includeLibraryId = true) + { + return new GetDeletedTracksQuery( + includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null); + } + + /// + /// Creates a list of . + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/DeletedAlbumResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/DeletedAlbumResponseFixture.cs new file mode 100644 index 00000000..c3665f81 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/DeletedAlbumResponseFixture.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class DeletedAlbumResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the deleted album. + /// Optional. The Id of the media library the deleted album belongs to. + /// Optional. The Id of the artist the deleted album belongs to. + /// Optional. The name of the artist the deleted album belongs to. + /// Optional. The title of the deleted album. + /// Optional. The date and time when the album was deleted. + /// Optional. The path of the cover image of the deleted album. + /// Whether the cover path should be included, or forced to . + /// The created . + public DeletedAlbumResponse Create( + Guid? id = null, + Guid? libraryId = null, + Guid? artistId = null, + string? artistName = null, + string? title = null, + DateTime? deletedOnUtc = null, + string? coverPath = null, + bool includeCoverPath = true) + { + return new DeletedAlbumResponse( + id ?? _faker.Random.Guid(), + libraryId ?? _faker.Random.Guid(), + artistId ?? _faker.Random.Guid(), + artistName ?? _faker.Name.FullName(), + title ?? _faker.Music.Genre(), + deletedOnUtc ?? _faker.Date.Recent().ToUniversalTime(), + includeCoverPath ? (coverPath ?? $"/covers/{_faker.Random.Guid()}.jpg") : null); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/DeletedArtistResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/DeletedArtistResponseFixture.cs new file mode 100644 index 00000000..c8d87a5e --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/DeletedArtistResponseFixture.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class DeletedArtistResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the deleted artist. + /// Optional. The Id of the media library the deleted artist belongs to. + /// Optional. The name of the deleted artist. + /// Optional. The date and time when the artist was deleted. + /// Optional. The path of the cover image of the deleted artist. + /// Whether the cover path should be included, or forced to . + /// The created . + public DeletedArtistResponse Create( + Guid? id = null, + Guid? libraryId = null, + string? name = null, + DateTime? deletedOnUtc = null, + string? coverPath = null, + bool includeCoverPath = true) + { + return new DeletedArtistResponse( + id ?? _faker.Random.Guid(), + libraryId ?? _faker.Random.Guid(), + name ?? _faker.Name.FullName(), + deletedOnUtc ?? _faker.Date.Recent().ToUniversalTime(), + includeCoverPath ? (coverPath ?? $"/covers/{_faker.Random.Guid()}.jpg") : null); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/DeletedTrackResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/DeletedTrackResponseFixture.cs new file mode 100644 index 00000000..5614bdd6 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/DeletedTrackResponseFixture.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class DeletedTrackResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the deleted track. + /// Optional. The Id of the media library the deleted track belongs to. + /// Optional. The Id of the artist the deleted track belongs to. + /// Optional. The name of the artist the deleted track belongs to. + /// Optional. The Id of the album the deleted track belongs to. + /// Optional. The title of the album the deleted track belongs to. + /// Optional. The title of the deleted track. + /// Optional. The file system path of the deleted track. + /// Optional. The date and time when the track was deleted. + /// The created . + public DeletedTrackResponse Create( + Guid? id = null, + Guid? libraryId = null, + Guid? artistId = null, + string? artistName = null, + Guid? albumId = null, + string? albumTitle = null, + string? title = null, + string? path = null, + DateTime? deletedOnUtc = null) + { + return new DeletedTrackResponse( + id ?? _faker.Random.Guid(), + libraryId ?? _faker.Random.Guid(), + artistId ?? _faker.Random.Guid(), + artistName ?? _faker.Name.FullName(), + albumId ?? _faker.Random.Guid(), + albumTitle ?? _faker.Music.Genre(), + title ?? _faker.Music.Genre(), + path ?? $"/music/tracks/{_faker.Random.Guid()}.flac", + deletedOnUtc ?? _faker.Date.Recent().ToUniversalTime()); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/AudioLibrary/MusicLibrary/DeletedMusicAlbumDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/AudioLibrary/MusicLibrary/DeletedMusicAlbumDtoFixture.cs new file mode 100644 index 00000000..d1990ca0 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/AudioLibrary/MusicLibrary/DeletedMusicAlbumDtoFixture.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class DeletedMusicAlbumDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The Id of the deleted album. + /// Optional. The Id of the media library the deleted album belongs to. + /// Optional. The Id of the artist the deleted album belongs to. + /// Optional. The name of the artist the deleted album belongs to. + /// Optional. The title of the deleted album. + /// Optional. The date and time when the album was deleted. + /// Optional. The relative path of the stored cover image of the deleted album. + /// Whether the cover path should be included, or forced to . + /// The created . + public DeletedMusicAlbumDto Create( + Guid? id = null, + Guid? libraryId = null, + Guid? artistId = null, + string? artistName = null, + string? title = null, + DateTime? deletedOnUtc = null, + string? coverPath = null, + bool includeCoverPath = true) + { + return new DeletedMusicAlbumDto( + Id: id ?? _faker.Random.Guid(), + LibraryId: libraryId ?? _faker.Random.Guid(), + ArtistId: artistId ?? _faker.Random.Guid(), + ArtistName: artistName ?? _faker.Lorem.Word(), + Title: title ?? _faker.Lorem.Sentence(), + DeletedOnUtc: deletedOnUtc ?? _faker.Date.Recent(), + CoverPath: includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/AudioLibrary/MusicLibrary/DeletedMusicArtistDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/AudioLibrary/MusicLibrary/DeletedMusicArtistDtoFixture.cs new file mode 100644 index 00000000..921a9214 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/AudioLibrary/MusicLibrary/DeletedMusicArtistDtoFixture.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class DeletedMusicArtistDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The Id of the deleted artist. + /// Optional. The Id of the media library the deleted artist belongs to. + /// Optional. The name of the deleted artist. + /// Optional. The date and time when the artist was deleted. + /// Optional. The relative path of the stored cover image of the deleted artist. + /// Whether the cover path should be included, or forced to . + /// The created . + public DeletedMusicArtistDto Create( + Guid? id = null, + Guid? libraryId = null, + string? name = null, + DateTime? deletedOnUtc = null, + string? coverPath = null, + bool includeCoverPath = true) + { + return new DeletedMusicArtistDto( + Id: id ?? _faker.Random.Guid(), + LibraryId: libraryId ?? _faker.Random.Guid(), + Name: name ?? _faker.Lorem.Word(), + DeletedOnUtc: deletedOnUtc ?? _faker.Date.Recent(), + CoverPath: includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/AudioLibrary/MusicLibrary/DeletedMusicItemsPageDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/AudioLibrary/MusicLibrary/DeletedMusicItemsPageDtoFixture.cs new file mode 100644 index 00000000..949a985a --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/AudioLibrary/MusicLibrary/DeletedMusicItemsPageDtoFixture.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class DeletedMusicItemsPageDtoFixture +{ + private readonly Faker _faker = new(); + private readonly LibraryDtoFixture _libraryDtoFixture = new(); + private readonly DeletedMusicArtistDtoFixture _deletedMusicArtistDtoFixture = new(); + private readonly DeletedMusicAlbumDtoFixture _deletedMusicAlbumDtoFixture = new(); + private readonly DeletedMusicTrackDtoFixture _deletedMusicTrackDtoFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The media library whose deleted music items are shown. + /// Optional. The deleted artists of the media library. + /// Optional. The deleted albums of the media library. + /// Optional. The deleted tracks of the media library. + /// The created . + public DeletedMusicItemsPageDto Create( + LibraryDto? library = null, + IReadOnlyList? deletedArtists = null, + IReadOnlyList? deletedAlbums = null, + IReadOnlyList? deletedTracks = null) + { + return new DeletedMusicItemsPageDto( + Library: library ?? _libraryDtoFixture.Create(), + DeletedArtists: deletedArtists ?? _deletedMusicArtistDtoFixture.CreateMany(_faker.Random.Number(1, 3)), + DeletedAlbums: deletedAlbums ?? _deletedMusicAlbumDtoFixture.CreateMany(_faker.Random.Number(1, 3)), + DeletedTracks: deletedTracks ?? _deletedMusicTrackDtoFixture.CreateMany(_faker.Random.Number(1, 3)) + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/AudioLibrary/MusicLibrary/DeletedMusicTrackDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/AudioLibrary/MusicLibrary/DeletedMusicTrackDtoFixture.cs new file mode 100644 index 00000000..a091e978 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/AudioLibrary/MusicLibrary/DeletedMusicTrackDtoFixture.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class DeletedMusicTrackDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The Id of the deleted track. + /// Optional. The Id of the media library the deleted track belongs to. + /// Optional. The Id of the artist the deleted track belongs to. + /// Optional. The name of the artist the deleted track belongs to. + /// Optional. The Id of the album the deleted track belongs to. + /// Optional. The title of the album the deleted track belongs to. + /// Optional. The title of the deleted track. + /// Optional. The file system path of the deleted track. + /// Optional. The date and time when the track was deleted. + /// The created . + public DeletedMusicTrackDto Create( + Guid? id = null, + Guid? libraryId = null, + Guid? artistId = null, + string? artistName = null, + Guid? albumId = null, + string? albumTitle = null, + string? title = null, + string? path = null, + DateTime? deletedOnUtc = null) + { + return new DeletedMusicTrackDto( + Id: id ?? _faker.Random.Guid(), + LibraryId: libraryId ?? _faker.Random.Guid(), + ArtistId: artistId ?? _faker.Random.Guid(), + ArtistName: artistName ?? _faker.Lorem.Word(), + AlbumId: albumId ?? _faker.Random.Guid(), + AlbumTitle: albumTitle ?? _faker.Lorem.Sentence(), + Title: title ?? _faker.Lorem.Sentence(), + Path: path ?? _faker.System.FilePath(), + DeletedOnUtc: deletedOnUtc ?? _faker.Date.Recent() + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Favorites/FavoriteRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Favorites/FavoriteRepositoryTests.cs index 2e8dcc4f..a7facc05 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Favorites/FavoriteRepositoryTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Favorites/FavoriteRepositoryTests.cs @@ -52,6 +52,7 @@ public class FavoriteRepositoryTests private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); private readonly BookContributorEntityFixture _bookContributorEntityFixture = new(); private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new(); + private readonly DateTime _deletedOnUtc = new(2026, 11, 14, 10, 30, 0, DateTimeKind.Utc); [Fact] public async Task InsertAsync_WhenTheFavoriteIsNew_ShouldReturnCreatedAndPersistEveryField() @@ -1119,6 +1120,59 @@ public class FavoriteRepositoryTests Assert.Empty(result.Value); } + [Theory] + [InlineData(FavoriteMediaKind.MusicArtist, false)] // the artist itself is soft deleted + [InlineData(FavoriteMediaKind.MusicAlbum, false)] // the album itself is soft deleted + [InlineData(FavoriteMediaKind.MusicAlbum, true)] // the album's artist is soft deleted + [InlineData(FavoriteMediaKind.MusicTrack, false)] // the track itself is soft deleted + [InlineData(FavoriteMediaKind.MusicTrack, true)] // the track's album is soft deleted + public async Task GetMediaItemLibraryIdAsync_WhenTheMusicItemIsSoftDeleted_ShouldReturnSuccessWithNull(FavoriteMediaKind mediaKind, bool isAncestorDeleted) + { + // Arrange + using SqliteConnection anchorConnection = CreateAnchorConnection($"library-id-deleted-music-{(int)mediaKind}-{isAncestorDeleted}"); + using LuminaDbContext context = CreateContext(anchorConnection); + FavoriteRepository sut = new(context); + Guid mediaItemId = await SeedSoftDeletedMusicItemAsync(context, mediaKind, isAncestorDeleted); + + // Act + Result result = await sut.GetMediaItemLibraryIdAsync(mediaKind, mediaItemId, CancellationToken.None); + + // Assert + // A deleted music item, or one hidden by a deleted ancestor, is not part of the catalogue, so adding it to favorites is rejected as if it did not exist. + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Theory] + [InlineData(FavoriteMediaKind.MusicArtist, false)] // the artist itself is soft deleted + [InlineData(FavoriteMediaKind.MusicAlbum, false)] // the album itself is soft deleted + [InlineData(FavoriteMediaKind.MusicAlbum, true)] // the album's artist is soft deleted + [InlineData(FavoriteMediaKind.MusicTrack, false)] // the track itself is soft deleted + [InlineData(FavoriteMediaKind.MusicTrack, true)] // the track's album is soft deleted + public async Task GetAllForUserAsync_WhenTheFavoritedMusicItemIsSoftDeleted_ShouldKeepTheFavoriteWithoutDisplayData(FavoriteMediaKind mediaKind, bool isAncestorDeleted) + { + // Arrange + using SqliteConnection anchorConnection = CreateAnchorConnection($"list-deleted-music-{(int)mediaKind}-{isAncestorDeleted}"); + using LuminaDbContext context = CreateContext(anchorConnection); + FavoriteRepository sut = new(context); + Guid userId = Guid.NewGuid(); + context.Users.Add(_userEntityFixture.Create(id: userId)); + Guid mediaItemId = await SeedSoftDeletedMusicItemAsync(context, mediaKind, isAncestorDeleted); + FavoriteEntity favorite = CreateFavorite(userId, mediaKind, mediaItemId); + context.Favorites.Add(favorite); + await context.SaveChangesAsync(); + + // Act + Result> result = await sut.GetAllForUserAsync(userId, mediaKind, paginationData: null, cancellationToken: CancellationToken.None); + + // Assert + // A deleted item is hidden from the catalogue, so its favorite must fall back to the unavailable state instead of exposing its display data. + Assert.False(result.IsFailure); + FavoriteItemDto item = Assert.Single(result.Value.Data); + Assert.Equal(favorite.Id, item.Favorite.Id); + Assert.Null(item.Display); + } + /// /// Creates an open in-memory SQLite anchor connection with a database name unique to the test. /// @@ -1193,6 +1247,66 @@ public class FavoriteRepositoryTests includeUpdatedBy: false); } + /// + /// Seeds an artist, an album of that artist and a track of that album, and soft deletes the requested music item or one of its ancestors. + /// + /// The context the catalogue is persisted through. + /// The kind of the media item that must be hidden from the catalogue. + /// Whether an ancestor of the item is soft deleted instead of the item itself. + /// The Id of the hidden media item. + private async Task SeedSoftDeletedMusicItemAsync(LuminaDbContext context, FavoriteMediaKind mediaKind, bool isAncestorDeleted) + { + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + context.Artists.Add(artist); + await context.SaveChangesAsync(); + + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + context.Albums.Add(album); + await context.SaveChangesAsync(); + + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + context.Tracks.Add(track); + await context.SaveChangesAsync(); + + switch (mediaKind) + { + case FavoriteMediaKind.MusicArtist: + artist.IsDeleted = true; + artist.DeletedOnUtc = _deletedOnUtc; + await context.SaveChangesAsync(); + return artist.Id; + case FavoriteMediaKind.MusicAlbum: + if (isAncestorDeleted) + { + artist.IsDeleted = true; + artist.DeletedOnUtc = _deletedOnUtc; + } + else + { + album.IsDeleted = true; + album.DeletedOnUtc = _deletedOnUtc; + } + await context.SaveChangesAsync(); + return album.Id; + case FavoriteMediaKind.MusicTrack: + if (isAncestorDeleted) + { + album.IsDeleted = true; + album.DeletedOnUtc = _deletedOnUtc; + } + else + { + track.IsDeleted = true; + track.DeletedOnUtc = _deletedOnUtc; + } + await context.SaveChangesAsync(); + return track.Id; + default: + throw new ArgumentOutOfRangeException(nameof(mediaKind), mediaKind, "The fixture only hides music items."); + } + } + /// /// Seeds one artist, one album of that artist, one track of that album and one book, each in its own library. /// diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/AlbumRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/AlbumRepositoryTests.cs index e65ef9a3..4d69c2da 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/AlbumRepositoryTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/AlbumRepositoryTests.cs @@ -47,6 +47,16 @@ public class AlbumRepositoryTests private readonly ArtistEntityFixture _artistEntityFixture = new(); private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new(); private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new(); + private readonly IDateTimeProvider _mockDateTimeProvider; + + /// + /// Initializes a new instance of the class. + /// + public AlbumRepositoryTests() + { + _mockDateTimeProvider = Substitute.For(); + _mockDateTimeProvider.UtcNow.Returns(new DateTime(2026, 11, 14, 10, 30, 0, DateTimeKind.Utc)); + } [Fact] public async Task InsertAsync_WhenCalledWithAValidAlbum_ShouldPersistTheAlbumAndItsAggregate() @@ -709,14 +719,482 @@ public class AlbumRepositoryTests Assert.Equal("covers/opera.jpg", row.CoverPath); } + [Fact] + public async Task GetByIdAsync_WhenTheAlbumIsSoftDeleted_ShouldReturnNull() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-getbyid-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id, "Deleted Album"); + album.IsDeleted = true; + album.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + await context.SaveChangesAsync(); + + // Act + Result result = await sut.GetByIdAsync(album.Id, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetByIdAsync_WhenItsArtistIsSoftDeleted_ShouldReturnNull() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-getbyid-deleted-artist-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id, "Album Of Deleted Artist"); + artist.IsDeleted = true; + artist.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + await context.SaveChangesAsync(); + + // Act + Result result = await sut.GetByIdAsync(album.Id, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetByIdAsync_WhenATrackIsSoftDeleted_ShouldExcludeItFromTheGraph() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-getbyid-deleted-track-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity album = BuildFullAlbum(artist.Id, libraryId, "Album"); + TrackEntity activeTrack = album.Tracks[0]; + TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + album.Tracks = [activeTrack, deletedTrack]; + context.Albums.Add(album); + await context.SaveChangesAsync(); + context.ChangeTracker.Clear(); + + // Act + Result result = await sut.GetByIdAsync(album.Id, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(activeTrack.Id, Assert.Single(result.Value!.Tracks).Id); + } + + [Fact] + public async Task GetByArtistIdAsync_WhenAnAlbumIsSoftDeleted_ShouldExcludeIt() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-getbyartist-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity activeAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Active Album"); + AlbumEntity deletedAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Deleted Album"); + deletedAlbum.IsDeleted = true; + deletedAlbum.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + await context.SaveChangesAsync(); + + // Act + Result> result = await sut.GetByArtistIdAsync(artist.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(activeAlbum.Id, Assert.Single(result.Value).Id); + } + + [Fact] + public async Task GetByArtistIdIncludingDeletedAsync_WhenCalled_ShouldReturnEveryAlbumOfTheArtistOrdered() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-getbyartist-including-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity betaAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Beta"); + AlbumEntity deletedAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Alpha"); + deletedAlbum.IsDeleted = true; + deletedAlbum.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + ArtistEntity otherArtist = await SeedArtistAsync(context, libraryId); + AlbumEntity albumOfAnotherArtist = await SeedAlbumAsync(context, libraryId, otherArtist.Id, "Gamma"); + await context.SaveChangesAsync(); + + // Act + Result> result = await sut.GetByArtistIdIncludingDeletedAsync(artist.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal([deletedAlbum.Id, betaAlbum.Id], result.Value.Select(album => album.Id)); + Assert.DoesNotContain(result.Value, album => album.Id == albumOfAnotherArtist.Id); + } + + [Fact] + public async Task GetIncludingDeletedByIdAsync_WhenTheAlbumIsSoftDeleted_ShouldReturnIt() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-get-including-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id, "Deleted Album"); + album.IsDeleted = true; + album.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + await context.SaveChangesAsync(); + + // Act + Result result = await sut.GetIncludingDeletedByIdAsync(album.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(album.Id, result.Value!.Id); + Assert.True(result.Value.IsDeleted); + } + + [Fact] + public async Task GetSoftDeletedByLibraryIdAsync_WhenCalled_ShouldReturnOnlyDeletedAlbumsOfVisibleArtistsOrdered() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-getdeleted-library-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + DateTime deletedOnUtc = _mockDateTimeProvider.UtcNow; + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity olderDeletion = await SeedAlbumAsync(context, libraryId, artist.Id, "Older"); + olderDeletion.IsDeleted = true; + olderDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-2); + AlbumEntity newerDeletion = await SeedAlbumAsync(context, libraryId, artist.Id, "Newer"); + newerDeletion.IsDeleted = true; + newerDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-1); + AlbumEntity activeAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Active"); + ArtistEntity deletedArtist = await SeedArtistAsync(context, libraryId); + AlbumEntity deletedAlbumOfDeletedArtist = await SeedAlbumAsync(context, libraryId, deletedArtist.Id, "Hidden"); + deletedAlbumOfDeletedArtist.IsDeleted = true; + deletedAlbumOfDeletedArtist.DeletedOnUtc = deletedOnUtc; + deletedArtist.IsDeleted = true; + deletedArtist.DeletedOnUtc = deletedOnUtc; + await context.SaveChangesAsync(); + + // Act + Result> result = await sut.GetSoftDeletedByLibraryIdAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal([newerDeletion.Id, olderDeletion.Id], result.Value.Select(album => album.Id)); + Assert.DoesNotContain(result.Value, album => album.Id == deletedAlbumOfDeletedArtist.Id); + } + + [Fact] + public async Task SoftDeleteByIdAsync_WhenAnotherVisibleAlbumOfTheArtistRemains_ShouldPersistTheDeletionStateAndProviderTime() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-softdelete-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id, "Album"); + await SeedAlbumAsync(context, libraryId, artist.Id, "Kept Album"); + + // Act + Result result = await sut.SoftDeleteByIdAsync(album.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + AlbumEntity storedAlbum = await context.Albums.AsNoTracking().SingleAsync(candidate => candidate.Id == album.Id); + Assert.True(storedAlbum.IsDeleted); + Assert.Equal(_mockDateTimeProvider.UtcNow, storedAlbum.DeletedOnUtc); + } + + [Fact] + public async Task SoftDeleteByIdAsync_WhenAlbumIsTheOnlyVisibleAlbumOfTheArtist_ShouldReturnArtistMustHaveAtLeastOneAlbumAndKeepItVisible() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-softdelete-last-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id, "Album"); + + // Act + Result result = await sut.SoftDeleteByIdAsync(album.Id, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError); + AlbumEntity storedAlbum = await context.Albums.AsNoTracking().SingleAsync(candidate => candidate.Id == album.Id); + Assert.False(storedAlbum.IsDeleted); + Assert.Null(storedAlbum.DeletedOnUtc); + } + + [Fact] + public async Task SoftDeleteByIdAsync_WhenTheOtherAlbumsOfTheArtistAreDeleted_ShouldReturnArtistMustHaveAtLeastOneAlbum() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-softdelete-deleted-siblings-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id, "Album"); + AlbumEntity deletedAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Deleted Album"); + deletedAlbum.IsDeleted = true; + deletedAlbum.DeletedOnUtc = _mockDateTimeProvider.UtcNow.AddHours(-1); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.SoftDeleteByIdAsync(album.Id, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError); + AlbumEntity storedAlbum = await context.Albums.AsNoTracking().SingleAsync(candidate => candidate.Id == album.Id); + Assert.False(storedAlbum.IsDeleted); + } + + [Fact] + public async Task SoftDeleteByIdAsync_WhenAlbumIsAlreadyDeleted_ShouldReturnAlbumNotFound() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-softdelete-already-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id, "Album"); + await SeedAlbumAsync(context, libraryId, artist.Id, "Visible Album"); + DateTime storedDeletedOnUtc = _mockDateTimeProvider.UtcNow.AddHours(-1); + album.IsDeleted = true; + album.DeletedOnUtc = storedDeletedOnUtc; + await context.SaveChangesAsync(); + + // Act + Result result = await sut.SoftDeleteByIdAsync(album.Id, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + AlbumEntity storedAlbum = await context.Albums.AsNoTracking().SingleAsync(candidate => candidate.Id == album.Id); + Assert.Equal(storedDeletedOnUtc, storedAlbum.DeletedOnUtc); + } + + [Fact] + public async Task SoftDeleteByIdAsync_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFound() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-softdelete-missing-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + // Act + Result result = await sut.SoftDeleteByIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + } + + [Fact] + public async Task SoftDeleteByIdAsync_WhenAnotherWriterAlreadyDeletedTheOtherLastAlbum_ShouldReturnArtistMustHaveAtLeastOneAlbum() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-softdelete-race-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext firstContext = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + firstContext.Database.EnsureCreated(); + using LuminaDbContext secondContext = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + AlbumRepository firstRepository = CreateAlbumRepository(firstContext); + AlbumRepository secondRepository = CreateAlbumRepository(secondContext); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(firstContext, libraryId); + AlbumEntity firstAlbum = await SeedAlbumAsync(firstContext, libraryId, artist.Id, "First Album"); + AlbumEntity secondAlbum = await SeedAlbumAsync(firstContext, libraryId, artist.Id, "Second Album"); + + // The second writer reads the state a preceding check would have seen: both albums visible. The write must not trust that read. + int visibleAlbumsSeenBySecondWriter = await secondContext.Albums.CountAsync(album => album.ArtistId == artist.Id && !album.IsDeleted); + Assert.Equal(2, visibleAlbumsSeenBySecondWriter); + + // Act + Result firstResult = await firstRepository.SoftDeleteByIdAsync(firstAlbum.Id, CancellationToken.None); + Result secondResult = await secondRepository.SoftDeleteByIdAsync(secondAlbum.Id, CancellationToken.None); + + // Assert + Assert.False(firstResult.IsFailure); + Assert.True(secondResult.IsFailure); + Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, secondResult.FirstError); + int remainingVisibleAlbums = await secondContext.Albums.CountAsync(album => album.ArtistId == artist.Id && !album.IsDeleted); + Assert.Equal(1, remainingVisibleAlbums); + } + + [Fact] + public async Task RestoreSoftDeletedByIdAsync_WhenCalled_ShouldPersistTheClearedDeletionState() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-restore-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id, "Album"); + album.IsDeleted = true; + album.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + await context.SaveChangesAsync(); + + // Act + Result result = await sut.RestoreSoftDeletedByIdAsync(album.Id, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + AlbumEntity storedAlbum = await context.Albums.AsNoTracking().SingleAsync(candidate => candidate.Id == album.Id); + Assert.False(storedAlbum.IsDeleted); + Assert.Null(storedAlbum.DeletedOnUtc); + } + + [Fact] + public async Task UpdateAsync_WhenTheAlbumIsSoftDeleted_ShouldReturnAlbumNotFound() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-update-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id, "Album"); + album.IsDeleted = true; + album.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + await context.SaveChangesAsync(); + + AlbumEntity data = _albumEntityFixture.Create(id: album.Id, artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + + // Act + Result result = await sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + } + + [Fact] + public async Task UpdateAsync_WhenItsArtistIsSoftDeleted_ShouldReturnAlbumNotFound() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-update-deleted-artist-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id, "Album"); + artist.IsDeleted = true; + artist.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + await context.SaveChangesAsync(); + + AlbumEntity data = _albumEntityFixture.Create(id: album.Id, artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + + // Act + Result result = await sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + } + + [Fact] + public async Task UpdateAsync_WhenIncomingDataIsMarkedDeleted_ShouldPreserveTheActiveRowsDeletionState() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-update-preserve-deletion-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id, "Album"); + AlbumEntity data = await LoadDetachedAlbumAsync(context, album.Id); + data.Title = "A Night at the Opera"; + data.IsDeleted = true; + data.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + + // Act + Result result = await sut.UpdateAsync(data, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + AlbumEntity storedAlbum = await context.Albums.AsNoTracking().SingleAsync(candidate => candidate.Id == album.Id); + Assert.Equal("A Night at the Opera", storedAlbum.Title); + Assert.False(storedAlbum.IsDeleted); + Assert.Null(storedAlbum.DeletedOnUtc); + } + /// /// Creates an album repository backed by the provided context, wiring the real track repository. /// /// The context the repository operates on. /// The created repository. - private static AlbumRepository CreateAlbumRepository(LuminaDbContext context) + private AlbumRepository CreateAlbumRepository(LuminaDbContext context) { - return new AlbumRepository(context, new TrackRepository(context)); + return new AlbumRepository(context, new TrackRepository(context, _mockDateTimeProvider), _mockDateTimeProvider); } /// diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/ArtistRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/ArtistRepositoryTests.cs index 7baeee66..5574c05f 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/ArtistRepositoryTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/ArtistRepositoryTests.cs @@ -53,6 +53,16 @@ public class ArtistRepositoryTests private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new(); private readonly LibraryFilterDtoFixture _libraryFilterDtoFixture = new(); private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new(); + private readonly IDateTimeProvider _mockDateTimeProvider; + + /// + /// Initializes a new instance of the class. + /// + public ArtistRepositoryTests() + { + _mockDateTimeProvider = Substitute.For(); + _mockDateTimeProvider.UtcNow.Returns(new DateTime(2026, 11, 14, 10, 30, 0, DateTimeKind.Utc)); + } [Fact] public async Task InsertAsync_WhenCalledWithAValidArtist_ShouldPersistTheArtistAndItsAggregate() @@ -1332,6 +1342,447 @@ public class ArtistRepositoryTests Assert.Equal("covers/queen.jpg", row.CoverPath); } + [Fact] + public async Task InsertAsync_WhenOnlyASoftDeletedArtistHasTheSameName_ShouldPersistTheNewArtist() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-insert-deleted-name-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity deletedArtist = await SeedArtistAsync(context, libraryId, "Queen"); + deletedArtist.IsDeleted = true; + deletedArtist.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + await context.SaveChangesAsync(); + + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false); + + // Act + Result result = await sut.InsertAsync(artist, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + // The unique artist name index only covers the visible artists, so a new file of a deleted artist materializes as a new visible artist. + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + Assert.Equal(2, await context.Artists.AsNoTracking().CountAsync(candidate => candidate.LibraryId == libraryId && candidate.Name == "Queen")); + Assert.Single(await context.Artists.AsNoTracking().Where(candidate => candidate.LibraryId == libraryId && candidate.Name == "Queen" && !candidate.IsDeleted).ToListAsync()); + } + + [Fact] + public async Task GetByIdAsync_WhenTheArtistIsSoftDeleted_ShouldReturnNull() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-getbyid-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); + artist.IsDeleted = true; + artist.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + await context.SaveChangesAsync(); + + // Act + Result result = await sut.GetByIdAsync(artist.Id, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetByIdAsync_WhenAnAlbumAndATrackAreSoftDeleted_ShouldExcludeThemFromTheGraph() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-getbyid-deleted-children-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + AlbumEntity activeAlbum = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + TrackEntity activeTrack = _trackEntityFixture.Create(albumId: activeAlbum.Id, libraryId: libraryId, includeMetadata: false); + TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: activeAlbum.Id, libraryId: libraryId, includeMetadata: false); + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + activeAlbum.Tracks = [activeTrack, deletedTrack]; + AlbumEntity deletedAlbum = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + deletedAlbum.IsDeleted = true; + deletedAlbum.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + deletedAlbum.Tracks = [_trackEntityFixture.Create(albumId: deletedAlbum.Id, libraryId: libraryId, includeMetadata: false)]; + artist.Albums = [activeAlbum, deletedAlbum]; + context.Artists.Add(artist); + await context.SaveChangesAsync(); + context.ChangeTracker.Clear(); + + // Act + Result result = await sut.GetByIdAsync(artist.Id, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + ArtistEntity retrievedArtist = result.Value!; + AlbumEntity retrievedAlbum = Assert.Single(retrievedArtist.Albums); + Assert.Equal(activeAlbum.Id, retrievedAlbum.Id); + Assert.Equal(activeTrack.Id, Assert.Single(retrievedAlbum.Tracks).Id); + } + + [Fact] + public async Task GetAllAsync_WhenTheArtistIsSoftDeleted_ShouldExcludeIt() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-getall-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity activeArtist = await SeedArtistAsync(context, libraryId, "Queen"); + ArtistEntity deletedArtist = await SeedArtistAsync(context, libraryId, "Deleted Artist"); + deletedArtist.IsDeleted = true; + deletedArtist.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + await context.SaveChangesAsync(); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await sut.GetAllAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(activeArtist.Id, Assert.Single(result.Value.Data).Id); + } + + [Fact] + public async Task GetSoftDeletedByIdAsync_WhenCalled_ShouldReturnThePersistedDeletionState() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-getdeleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); + DateTime deletedOnUtc = _mockDateTimeProvider.UtcNow; + artist.IsDeleted = true; + artist.DeletedOnUtc = deletedOnUtc; + await context.SaveChangesAsync(); + + // Act + Result result = await sut.GetSoftDeletedByIdAsync(artist.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(deletedOnUtc, result.Value!.DeletedOnUtc); + } + + [Fact] + public async Task GetSoftDeletedByLibraryIdAsync_WhenCalled_ShouldReturnOnlyTheDeletedArtistsOrderedByDeletionTime() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-getdeleted-library-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + DateTime deletedOnUtc = _mockDateTimeProvider.UtcNow; + ArtistEntity olderDeletion = await SeedArtistAsync(context, libraryId, "Older"); + olderDeletion.IsDeleted = true; + olderDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-2); + ArtistEntity newerDeletion = await SeedArtistAsync(context, libraryId, "Newer"); + newerDeletion.IsDeleted = true; + newerDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-1); + ArtistEntity activeArtist = await SeedArtistAsync(context, libraryId, "Active"); + ArtistEntity otherLibraryDeletion = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + otherLibraryDeletion.IsDeleted = true; + otherLibraryDeletion.DeletedOnUtc = deletedOnUtc; + context.Artists.Add(otherLibraryDeletion); + await context.SaveChangesAsync(); + + // Act + Result> result = await sut.GetSoftDeletedByLibraryIdAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal([newerDeletion.Id, olderDeletion.Id], result.Value.Select(artist => artist.Id)); + } + + [Fact] + public async Task SoftDeleteByIdAsync_WhenCalled_ShouldPersistTheDeletionStateAndProviderTime() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-softdelete-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); + + // Act + Result result = await sut.SoftDeleteByIdAsync(artist.Id, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + ArtistEntity storedArtist = await context.Artists.AsNoTracking().SingleAsync(candidate => candidate.Id == artist.Id); + Assert.True(storedArtist.IsDeleted); + Assert.Equal(_mockDateTimeProvider.UtcNow, storedArtist.DeletedOnUtc); + } + + [Fact] + public async Task RestoreSoftDeletedByIdAsync_WhenCalled_ShouldPersistTheClearedDeletionState() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-restore-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); + artist.IsDeleted = true; + artist.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + await context.SaveChangesAsync(); + + // Act + Result result = await sut.RestoreSoftDeletedByIdAsync(artist.Id, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + ArtistEntity storedArtist = await context.Artists.AsNoTracking().SingleAsync(candidate => candidate.Id == artist.Id); + Assert.False(storedArtist.IsDeleted); + Assert.Null(storedArtist.DeletedOnUtc); + } + + [Fact] + public async Task UpdateAsync_WhenTheArtistIsSoftDeleted_ShouldReturnArtistNotFound() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); + artist.IsDeleted = true; + artist.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + await context.SaveChangesAsync(); + + ArtistEntity data = _artistEntityFixture.Create(id: artist.Id, includeAlbums: false, includeContributors: false); + + // Act + Result result = await sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + } + + [Fact] + public async Task UpdateAsync_WhenIncomingDataIsMarkedDeleted_ShouldPreserveTheActiveRowsDeletionState() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-preserve-deletion-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); + ArtistEntity data = await LoadDetachedArtistAsync(context, artist.Id); + data.Name = "Freddie Mercury"; + data.IsDeleted = true; + data.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + + // Act + Result result = await sut.UpdateAsync(data, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + ArtistEntity storedArtist = await context.Artists.AsNoTracking().SingleAsync(candidate => candidate.Id == artist.Id); + Assert.Equal("Freddie Mercury", storedArtist.Name); + Assert.False(storedArtist.IsDeleted); + Assert.Null(storedArtist.DeletedOnUtc); + } + + [Fact] + public async Task UpdateAsync_WhenAnAlbumIsSoftDeleted_ShouldKeepItAndItsTracks() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-keeps-deleted-album-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedFullArtistAsync(context, libraryId); + AlbumEntity deletedAlbum = artist.Albums[0]; + TrackEntity trackOfDeletedAlbum = deletedAlbum.Tracks[0]; + deletedAlbum.IsDeleted = true; + deletedAlbum.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + await context.SaveChangesAsync(); + + ArtistEntity data = _artistEntityFixture.Create(id: artist.Id, includeAlbums: false, includeContributors: false); + + // Act + Result result = await sut.UpdateAsync(data, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + AlbumEntity storedAlbum = await context.Albums.AsNoTracking().SingleAsync(candidate => candidate.Id == deletedAlbum.Id); + Assert.True(storedAlbum.IsDeleted); + TrackEntity storedTrack = await context.Tracks.AsNoTracking().SingleAsync(candidate => candidate.Id == trackOfDeletedAlbum.Id); + Assert.False(storedTrack.IsDeleted); + } + + [Fact] + public async Task UpdateAsync_WhenATrackIsSoftDeleted_ShouldKeepIt() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-keeps-deleted-track-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedFullArtistAsync(context, libraryId); + TrackEntity deletedTrack = artist.Albums[0].Tracks[0]; + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + await context.SaveChangesAsync(); + + AlbumEntity incomingAlbum = _albumEntityFixture.Create( + id: artist.Albums[0].Id, + artistId: artist.Id, + libraryId: libraryId, + title: artist.Albums[0].Title, + includeTracks: false, + includeMetadata: false); + ArtistEntity data = _artistEntityFixture.Create(id: artist.Id, includeAlbums: false, includeContributors: false); + data.Albums = [incomingAlbum]; + + // Act + Result result = await sut.UpdateAsync(data, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + TrackEntity storedTrack = await context.Tracks.AsNoTracking().SingleAsync(candidate => candidate.Id == deletedTrack.Id); + Assert.True(storedTrack.IsDeleted); + } + + [Fact] + public async Task UpdateAsync_WhenIncomingAlbumMatchesASoftDeletedAlbum_ShouldReturnAlbumNotFoundWithoutEditingIt() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-rejects-deleted-album-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedFullArtistAsync(context, libraryId); + AlbumEntity deletedAlbum = artist.Albums[0]; + string originalTitle = deletedAlbum.Title; + deletedAlbum.IsDeleted = true; + deletedAlbum.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + await context.SaveChangesAsync(); + + AlbumEntity incomingAlbum = _albumEntityFixture.Create( + id: deletedAlbum.Id, + artistId: artist.Id, + libraryId: libraryId, + title: "Edited Hidden Album", + includeTracks: false, + includeMetadata: false); + ArtistEntity data = _artistEntityFixture.Create(id: artist.Id, includeAlbums: false, includeContributors: false); + data.Albums = [incomingAlbum]; + + // Act + Result result = await sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + AlbumEntity storedAlbum = await context.Albums.AsNoTracking().SingleAsync(candidate => candidate.Id == deletedAlbum.Id); + Assert.Equal(originalTitle, storedAlbum.Title); + Assert.True(storedAlbum.IsDeleted); + } + + [Fact] + public async Task UpdateAsync_WhenIncomingTrackMatchesASoftDeletedTrack_ShouldReturnTrackNotFoundWithoutEditingIt() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-rejects-deleted-track-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedFullArtistAsync(context, libraryId); + AlbumEntity storedAlbum = artist.Albums[0]; + TrackEntity deletedTrack = storedAlbum.Tracks[0]; + string originalTitle = deletedTrack.Title; + string originalPath = deletedTrack.Path; + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + await context.SaveChangesAsync(); + + AlbumEntity incomingAlbum = _albumEntityFixture.Create( + id: storedAlbum.Id, + artistId: artist.Id, + libraryId: libraryId, + title: storedAlbum.Title, + includeTracks: false, + includeMetadata: false); + TrackEntity incomingTrack = _trackEntityFixture.Create( + id: deletedTrack.Id, + albumId: storedAlbum.Id, + libraryId: libraryId, + title: "Edited Hidden Track", + path: "/music/moved-hidden-track.flac", + includeMetadata: false); + incomingAlbum.Tracks = [incomingTrack]; + ArtistEntity data = _artistEntityFixture.Create(id: artist.Id, includeAlbums: false, includeContributors: false); + data.Albums = [incomingAlbum]; + + // Act + Result result = await sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + TrackEntity storedTrack = await context.Tracks.AsNoTracking().SingleAsync(candidate => candidate.Id == deletedTrack.Id); + Assert.Equal(originalTitle, storedTrack.Title); + Assert.Equal(originalPath, storedTrack.Path); + Assert.True(storedTrack.IsDeleted); + } + /// /// Seeds an artist that owns the requested number of albums, each with the requested number of tracks, all of them with distinct shared reference names. /// @@ -1371,11 +1822,11 @@ public class ArtistRepositoryTests /// /// The context the repository operates on. /// The created repository. - private static ArtistRepository CreateArtistRepository(LuminaDbContext context) + private ArtistRepository CreateArtistRepository(LuminaDbContext context) { - TrackRepository trackRepository = new(context); - AlbumRepository albumRepository = new(context, trackRepository); - return new ArtistRepository(context, albumRepository, trackRepository); + TrackRepository trackRepository = new(context, _mockDateTimeProvider); + AlbumRepository albumRepository = new(context, trackRepository, _mockDateTimeProvider); + return new ArtistRepository(context, albumRepository, trackRepository, _mockDateTimeProvider); } /// diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/TrackRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/TrackRepositoryTests.cs index c1e2301f..6488a341 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/TrackRepositoryTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/TrackRepositoryTests.cs @@ -49,6 +49,16 @@ public class TrackRepositoryTests private readonly ArtistEntityFixture _artistEntityFixture = new(); private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new(); private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new(); + private readonly IDateTimeProvider _mockDateTimeProvider; + + /// + /// Initializes a new instance of the class. + /// + public TrackRepositoryTests() + { + _mockDateTimeProvider = Substitute.For(); + _mockDateTimeProvider.UtcNow.Returns(new DateTime(2026, 11, 14, 10, 30, 0, DateTimeKind.Utc)); + } [Fact] public async Task InsertAsync_WhenCalledWithAValidTrack_ShouldPersistTheTrackAndItsChildren() @@ -58,7 +68,7 @@ public class TrackRepositoryTests anchorConnection.Open(); using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); context.Database.EnsureCreated(); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); AlbumEntity album = await SeedAlbumAsync(context, libraryId); @@ -107,7 +117,7 @@ public class TrackRepositoryTests anchorConnection.Open(); using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); context.Database.EnsureCreated(); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); AlbumEntity album = await SeedAlbumAsync(context, libraryId); @@ -133,7 +143,7 @@ public class TrackRepositoryTests anchorConnection.Open(); using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); context.Database.EnsureCreated(); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid firstLibraryId = Guid.NewGuid(); AlbumEntity firstAlbum = await SeedAlbumAsync(context, firstLibraryId); @@ -165,7 +175,7 @@ public class TrackRepositoryTests anchorConnection.Open(); using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); context.Database.EnsureCreated(); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); AlbumEntity album = await SeedAlbumAsync(context, libraryId); @@ -198,7 +208,7 @@ public class TrackRepositoryTests anchorConnection.Open(); using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); context.Database.EnsureCreated(); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); AlbumEntity album = await SeedAlbumAsync(context, libraryId); @@ -226,7 +236,7 @@ public class TrackRepositoryTests Guid userId = Guid.NewGuid(); DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); AlbumEntity album = await SeedAlbumAsync(context, libraryId); @@ -275,7 +285,7 @@ public class TrackRepositoryTests Guid userId = Guid.NewGuid(); DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); AlbumEntity album = await SeedAlbumAsync(context, libraryId); @@ -319,7 +329,7 @@ public class TrackRepositoryTests Guid userId = Guid.NewGuid(); DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); AlbumEntity album = await SeedAlbumAsync(context, libraryId); @@ -360,7 +370,7 @@ public class TrackRepositoryTests Guid userId = Guid.NewGuid(); DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); AlbumEntity album = await SeedAlbumAsync(context, libraryId); @@ -402,7 +412,7 @@ public class TrackRepositoryTests Guid userId = Guid.NewGuid(); DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); AlbumEntity album = await SeedAlbumAsync(context, libraryId); @@ -444,7 +454,7 @@ public class TrackRepositoryTests Guid userId = Guid.NewGuid(); DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); AlbumEntity album = await SeedAlbumAsync(context, libraryId); @@ -504,7 +514,7 @@ public class TrackRepositoryTests anchorConnection.Open(); using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); context.Database.EnsureCreated(); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); AlbumEntity album = await SeedAlbumAsync(context, libraryId); @@ -545,7 +555,7 @@ public class TrackRepositoryTests anchorConnection.Open(); using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); context.Database.EnsureCreated(); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); AlbumEntity album = await SeedAlbumAsync(context, libraryId); @@ -572,7 +582,7 @@ public class TrackRepositoryTests anchorConnection.Open(); using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); context.Database.EnsureCreated(); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); AlbumEntity album = await SeedAlbumAsync(context, libraryId); @@ -626,7 +636,7 @@ public class TrackRepositoryTests anchorConnection.Open(); using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); context.Database.EnsureCreated(); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); AlbumEntity album = await SeedAlbumAsync(context, libraryId); @@ -675,7 +685,7 @@ public class TrackRepositoryTests anchorConnection.Open(); using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); context.Database.EnsureCreated(); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); AlbumEntity album = await SeedAlbumAsync(context, libraryId); @@ -707,7 +717,7 @@ public class TrackRepositoryTests anchorConnection.Open(); using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); context.Database.EnsureCreated(); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); AlbumEntity album = await SeedAlbumAsync(context, libraryId); @@ -752,7 +762,7 @@ public class TrackRepositoryTests anchorConnection.Open(); using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); context.Database.EnsureCreated(); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); AlbumEntity album = await SeedAlbumAsync(context, libraryId); @@ -780,7 +790,7 @@ public class TrackRepositoryTests anchorConnection.Open(); using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); context.Database.EnsureCreated(); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); AlbumEntity album = await SeedAlbumAsync(context, libraryId); @@ -805,7 +815,7 @@ public class TrackRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyids-empty-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); AlbumEntity album = await SeedAlbumAsync(context, libraryId); context.Tracks.Add(_trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false)); @@ -827,7 +837,7 @@ public class TrackRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyids-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); AlbumEntity album = await SeedAlbumAsync(context, libraryId); TrackEntity firstTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/first.flac", includeMetadata: false); @@ -855,7 +865,7 @@ public class TrackRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyids-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); AlbumEntity album = await SeedAlbumAsync(context, libraryId); TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/hidden.flac", includeMetadata: false); @@ -897,7 +907,7 @@ public class TrackRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyids-include-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); AlbumEntity album = await SeedAlbumAsync(context, libraryId, includeMetadata: true); ArtistEntity artist = await context.Artists.AsNoTracking().FirstAsync(candidate => candidate.Id == album.ArtistId); @@ -941,7 +951,7 @@ public class TrackRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyids-chunks-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); AlbumEntity album = await SeedAlbumAsync(context, libraryId); const int TRACK_COUNT = 501; @@ -969,7 +979,7 @@ public class TrackRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-library-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera"); @@ -998,7 +1008,7 @@ public class TrackRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-artist-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); AlbumEntity artistAlbum = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera"); @@ -1026,7 +1036,7 @@ public class TrackRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-album-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera"); @@ -1053,7 +1063,7 @@ public class TrackRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-bothfilters-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera"); @@ -1083,7 +1093,7 @@ public class TrackRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-excluded-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera"); @@ -1109,7 +1119,7 @@ public class TrackRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-count-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera"); @@ -1132,7 +1142,7 @@ public class TrackRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-fewertracks-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera"); @@ -1155,7 +1165,7 @@ public class TrackRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-nomatch-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera"); @@ -1178,7 +1188,7 @@ public class TrackRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-projection-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera"); @@ -1214,7 +1224,7 @@ public class TrackRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-cover-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera"); @@ -1239,7 +1249,7 @@ public class TrackRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-nocover-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera"); @@ -1262,7 +1272,7 @@ public class TrackRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-noncover-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera"); @@ -1286,7 +1296,7 @@ public class TrackRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-othercover-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - TrackRepository sut = new(context); + TrackRepository sut = CreateTrackRepository(context); Guid libraryId = Guid.NewGuid(); ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera"); @@ -1304,8 +1314,607 @@ public class TrackRepositoryTests Assert.Null(row.CoverPath); } + [Fact] + public async Task InsertAsync_WhenATrackWithTheSamePathIsSoftDeleted_ShouldReturnTrackAlreadyExists() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-insert-deleted-path-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + TrackRepository sut = CreateTrackRepository(context); + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/deleted.flac", includeMetadata: false); + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + context.Tracks.Add(deletedTrack); + await context.SaveChangesAsync(); + + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/deleted.flac", includeMetadata: false); + + // Act + Result result = await sut.InsertAsync(track, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError); + } + + [Fact] + public async Task GetExistingPathsAsync_WhenTheOnlyTrackIsSoftDeleted_ShouldStillReportThePath() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-existing-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + TrackRepository sut = CreateTrackRepository(context); + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/deleted.flac", includeMetadata: false); + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + context.Tracks.Add(deletedTrack); + await context.SaveChangesAsync(); + + // Act + Result> result = await sut.GetExistingPathsAsync(libraryId, ["/music/queen/deleted.flac"], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(["/music/queen/deleted.flac"], result.Value); + } + + [Fact] + public async Task GetByPathAsync_WhenTheTrackIsSoftDeleted_ShouldReturnIt() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbypath-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + TrackRepository sut = CreateTrackRepository(context); + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/deleted.flac", includeMetadata: false); + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + context.Tracks.Add(deletedTrack); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.GetByPathAsync(libraryId, "/music/queen/deleted.flac", CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(deletedTrack.Id, result.Value!.Id); + Assert.True(result.Value.IsDeleted); + } + + [Fact] + public async Task GetByIdAsync_WhenTheTrackIsSoftDeleted_ShouldReturnNull() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyid-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + TrackRepository sut = CreateTrackRepository(context); + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + track.IsDeleted = true; + track.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + context.Tracks.Add(track); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.GetByIdAsync(track.Id, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Theory] + [InlineData(true)] // The album of the track is soft deleted. + [InlineData(false)] // The artist of the album is soft deleted. + public async Task GetByIdAsync_WhenAnAncestorIsSoftDeleted_ShouldReturnNull(bool isAlbumDeleted) + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyid-deleted-ancestor-{isAlbumDeleted}-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + TrackRepository sut = CreateTrackRepository(context); + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); + AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera"); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + context.Tracks.Add(track); + if (isAlbumDeleted) + album.IsDeleted = true; + else + artist.IsDeleted = true; + await context.SaveChangesAsync(); + + // Act + Result result = await sut.GetByIdAsync(track.Id, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetByAlbumIdAsync_WhenTracksAreSoftDeleted_ShouldExcludeThem() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyalbum-deleted-tracks-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + TrackRepository sut = CreateTrackRepository(context); + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + TrackEntity activeTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + context.Tracks.AddRange(activeTrack, deletedTrack); + await context.SaveChangesAsync(); + + // Act + Result> result = await sut.GetByAlbumIdAsync(album.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(activeTrack.Id, Assert.Single(result.Value).Id); + } + + [Fact] + public async Task GetByAlbumIdAsync_WhenTheAlbumIsSoftDeleted_ShouldReturnEmpty() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyalbum-deleted-album-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + TrackRepository sut = CreateTrackRepository(context); + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + context.Tracks.Add(track); + album.IsDeleted = true; + album.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + await context.SaveChangesAsync(); + + // Act + Result> result = await sut.GetByAlbumIdAsync(album.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task GetByAlbumIdIncludingDeletedAsync_WhenCalled_ShouldReturnEveryTrackOfTheAlbumOrdered() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyalbum-including-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + TrackRepository sut = CreateTrackRepository(context); + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + TrackEntity activeTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, trackNumber: 2, includeMetadata: false); + activeTrack.DiscNumber = 1; + TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, trackNumber: 1, includeMetadata: false); + deletedTrack.DiscNumber = 1; + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + context.Tracks.AddRange(activeTrack, deletedTrack); + await context.SaveChangesAsync(); + + // Act + Result> result = await sut.GetByAlbumIdIncludingDeletedAsync(album.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal([deletedTrack.Id, activeTrack.Id], result.Value.Select(track => track.Id)); + } + + [Fact] + public async Task GetShuffleTracksLiteAsync_WhenTracksOrAncestorsAreSoftDeleted_ShouldExcludeThem() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + TrackRepository sut = CreateTrackRepository(context); + Guid libraryId = Guid.NewGuid(); + ArtistEntity visibleArtist = await SeedArtistAsync(context, libraryId, "Queen"); + AlbumEntity visibleAlbum = await SeedAlbumForArtistAsync(context, libraryId, visibleArtist.Id, "A Night at the Opera"); + TrackEntity visibleTrack = _trackEntityFixture.Create(albumId: visibleAlbum.Id, libraryId: libraryId, includeMetadata: false); + TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: visibleAlbum.Id, libraryId: libraryId, includeMetadata: false); + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + context.Tracks.AddRange(visibleTrack, deletedTrack); + + ArtistEntity artistOfDeletedAlbum = await SeedArtistAsync(context, libraryId, "Deleted Album Artist"); + AlbumEntity deletedAlbum = await SeedAlbumForArtistAsync(context, libraryId, artistOfDeletedAlbum.Id, "Deleted Album"); + context.Tracks.Add(_trackEntityFixture.Create(albumId: deletedAlbum.Id, libraryId: libraryId, includeMetadata: false)); + deletedAlbum.IsDeleted = true; + deletedAlbum.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + + ArtistEntity deletedArtist = await SeedArtistAsync(context, libraryId, "Deleted Artist"); + AlbumEntity albumOfDeletedArtist = await SeedAlbumForArtistAsync(context, libraryId, deletedArtist.Id, "Hidden Album"); + context.Tracks.Add(_trackEntityFixture.Create(albumId: albumOfDeletedArtist.Id, libraryId: libraryId, includeMetadata: false)); + deletedArtist.IsDeleted = true; + deletedArtist.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + await context.SaveChangesAsync(); + + // Act + Result> result = await sut.GetShuffleTracksLiteAsync(libraryId, null, null, [], 10, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(visibleTrack.Id, Assert.Single(result.Value).TrackId); + } + + [Theory] + [InlineData(true)] // The track itself is soft deleted. + [InlineData(false)] // An ancestor of the track is soft deleted. + public async Task GetTrackStreamInfoAsync_WhenTheTrackIsOrHasASoftDeletedAncestor_ShouldReturnNull(bool isTrackDeleted) + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-stream-deleted-{isTrackDeleted}-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + TrackRepository sut = CreateTrackRepository(context); + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); + AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera"); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + context.Tracks.Add(track); + if (isTrackDeleted) + track.IsDeleted = true; + else + album.IsDeleted = true; + await context.SaveChangesAsync(); + + // Act + Result result = await sut.GetTrackStreamInfoAsync(libraryId, album.Id, artist.Id, track.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Theory] + [InlineData(true)] // The track itself is soft deleted. + [InlineData(false)] // An ancestor of the track is soft deleted. + public async Task GetPlaybackManifestInfoAsync_WhenTheTrackIsOrHasASoftDeletedAncestor_ShouldReturnNull(bool isTrackDeleted) + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-manifest-deleted-{isTrackDeleted}-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + TrackRepository sut = CreateTrackRepository(context); + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); + AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera"); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + context.Tracks.Add(track); + if (isTrackDeleted) + track.IsDeleted = true; + else + artist.IsDeleted = true; + await context.SaveChangesAsync(); + + // Act + Result result = await sut.GetPlaybackManifestInfoAsync(libraryId, album.Id, artist.Id, track.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetAccessInfoByIdsAsync_WhenTracksOrAncestorsAreSoftDeleted_ShouldExcludeThem() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-access-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + TrackRepository sut = CreateTrackRepository(context); + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); + AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera"); + TrackEntity activeTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + context.Tracks.AddRange(activeTrack, deletedTrack); + + ArtistEntity deletedArtist = await SeedArtistAsync(context, libraryId, "Deleted Artist"); + AlbumEntity albumOfDeletedArtist = await SeedAlbumForArtistAsync(context, libraryId, deletedArtist.Id, "Hidden Album"); + TrackEntity trackOfDeletedArtist = _trackEntityFixture.Create(albumId: albumOfDeletedArtist.Id, libraryId: libraryId, includeMetadata: false); + context.Tracks.Add(trackOfDeletedArtist); + deletedArtist.IsDeleted = true; + deletedArtist.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + await context.SaveChangesAsync(); + + // Act + Result result = await sut.GetAccessInfoByIdsAsync([activeTrack.Id, deletedTrack.Id, trackOfDeletedArtist.Id], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(1, result.Value.TrackCount); + Assert.Equal([libraryId], result.Value.LibraryIds); + } + + [Fact] + public async Task GetByIdsAsync_WhenTracksOrAncestorsAreSoftDeleted_ShouldExcludeThem() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyids-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + TrackRepository sut = CreateTrackRepository(context); + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); + AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera"); + TrackEntity activeTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + context.Tracks.AddRange(activeTrack, deletedTrack); + + ArtistEntity artistOfDeletedAlbum = await SeedArtistAsync(context, libraryId, "Album Artist"); + AlbumEntity deletedAlbum = await SeedAlbumForArtistAsync(context, libraryId, artistOfDeletedAlbum.Id, "Deleted Album"); + TrackEntity trackOfDeletedAlbum = _trackEntityFixture.Create(albumId: deletedAlbum.Id, libraryId: libraryId, includeMetadata: false); + context.Tracks.Add(trackOfDeletedAlbum); + deletedAlbum.IsDeleted = true; + deletedAlbum.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + await context.SaveChangesAsync(); + + // Act + Result> result = await sut.GetByIdsAsync([activeTrack.Id, deletedTrack.Id, trackOfDeletedAlbum.Id], false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(activeTrack.Id, Assert.Single(result.Value).Id); + } + + [Fact] + public async Task GetTracksNeedingMetadataCountAsync_WhenATrackOrItsAncestorsAreSoftDeleted_ShouldNotCountIt() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-count-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + TrackRepository sut = CreateTrackRepository(context); + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); + AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera"); + TrackEntity pendingTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Pending); + TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Pending); + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + context.Tracks.AddRange(pendingTrack, deletedTrack); + + ArtistEntity artistOfDeletedAlbum = await SeedArtistAsync(context, libraryId, "Album Artist"); + AlbumEntity deletedAlbum = await SeedAlbumForArtistAsync(context, libraryId, artistOfDeletedAlbum.Id, "Deleted Album"); + context.Tracks.Add(_trackEntityFixture.Create( + albumId: deletedAlbum.Id, libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Pending)); + deletedAlbum.IsDeleted = true; + deletedAlbum.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + await context.SaveChangesAsync(); + + // Act + Result result = await sut.GetTracksNeedingMetadataCountAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(1, result.Value); + } + + [Fact] + public async Task SoftDeleteByIdAsync_WhenCalled_ShouldPersistTheDeletionStateAndProviderTime() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-softdelete-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + TrackRepository sut = CreateTrackRepository(context); + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + context.Tracks.Add(track); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.SoftDeleteByIdAsync(track.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + TrackEntity storedTrack = await context.Tracks.AsNoTracking().SingleAsync(candidate => candidate.Id == track.Id); + Assert.True(storedTrack.IsDeleted); + Assert.Equal(_mockDateTimeProvider.UtcNow, storedTrack.DeletedOnUtc); + } + + [Fact] + public async Task SoftDeleteByIdAsync_WhenTrackIsAlreadyDeleted_ShouldReturnTrackNotFound() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-softdelete-already-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + TrackRepository sut = CreateTrackRepository(context); + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + DateTime storedDeletedOnUtc = _mockDateTimeProvider.UtcNow.AddHours(-1); + track.IsDeleted = true; + track.DeletedOnUtc = storedDeletedOnUtc; + context.Tracks.Add(track); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.SoftDeleteByIdAsync(track.Id, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + TrackEntity storedTrack = await context.Tracks.AsNoTracking().SingleAsync(candidate => candidate.Id == track.Id); + Assert.Equal(storedDeletedOnUtc, storedTrack.DeletedOnUtc); + } + + [Fact] + public async Task SoftDeleteByIdAsync_WhenTrackDoesNotExist_ShouldReturnTrackNotFound() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-softdelete-missing-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + TrackRepository sut = CreateTrackRepository(context); + + // Act + Result result = await sut.SoftDeleteByIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + } + + [Fact] + public async Task RestoreSoftDeletedByIdAsync_WhenCalled_ShouldPersistTheClearedDeletionState() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-restore-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + TrackRepository sut = CreateTrackRepository(context); + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + track.IsDeleted = true; + track.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + context.Tracks.Add(track); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.RestoreSoftDeletedByIdAsync(track.Id, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + TrackEntity storedTrack = await context.Tracks.AsNoTracking().SingleAsync(candidate => candidate.Id == track.Id); + Assert.False(storedTrack.IsDeleted); + Assert.Null(storedTrack.DeletedOnUtc); + } + + [Fact] + public async Task GetSoftDeletedByLibraryIdAsync_WhenCalled_ShouldReturnOnlyDeletedTracksWithVisibleAncestorsOrdered() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getdeleted-library-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + TrackRepository sut = CreateTrackRepository(context); + Guid libraryId = Guid.NewGuid(); + DateTime deletedOnUtc = _mockDateTimeProvider.UtcNow; + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + TrackEntity olderDeletion = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, title: "Alpha", includeMetadata: false); + olderDeletion.IsDeleted = true; + olderDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-2); + TrackEntity newerDeletion = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, title: "Beta", includeMetadata: false); + newerDeletion.IsDeleted = true; + newerDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-1); + TrackEntity sameTimeDeletion = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, title: "Gamma", includeMetadata: false); + sameTimeDeletion.IsDeleted = true; + sameTimeDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-1); + context.Tracks.AddRange(olderDeletion, newerDeletion, sameTimeDeletion); + + ArtistEntity deletedArtist = await SeedArtistAsync(context, libraryId, "Deleted Artist"); + AlbumEntity albumOfDeletedArtist = await SeedAlbumForArtistAsync(context, libraryId, deletedArtist.Id, "Hidden Album"); + TrackEntity hiddenDeletedTrack = _trackEntityFixture.Create(albumId: albumOfDeletedArtist.Id, libraryId: libraryId, includeMetadata: false); + hiddenDeletedTrack.IsDeleted = true; + hiddenDeletedTrack.DeletedOnUtc = deletedOnUtc; + context.Tracks.Add(hiddenDeletedTrack); + deletedArtist.IsDeleted = true; + deletedArtist.DeletedOnUtc = deletedOnUtc; + await context.SaveChangesAsync(); + + TrackEntity[] expectedDeletedTracks = [olderDeletion, newerDeletion, sameTimeDeletion]; + Guid[] expectedOrder = [.. expectedDeletedTracks + .OrderByDescending(track => track.DeletedOnUtc) + .ThenByDescending(track => track.Title) + .ThenByDescending(track => track.Id) + .Select(track => track.Id)]; + + // Act + Result> result = await sut.GetSoftDeletedByLibraryIdAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(expectedOrder, result.Value.Select(track => track.Id)); + } + + [Fact] + public async Task UpdateAsync_WhenTheTrackIsSoftDeleted_ShouldReturnTrackNotFound() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-update-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + TrackRepository sut = CreateTrackRepository(context); + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + track.IsDeleted = true; + track.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + context.Tracks.Add(track); + await context.SaveChangesAsync(); + + TrackEntity data = _trackEntityFixture.Create(id: track.Id, albumId: album.Id, libraryId: libraryId, includeMetadata: false); + + // Act + Result result = await sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + } + + [Fact] + public async Task UpdateAsync_WhenIncomingDataIsMarkedDeleted_ShouldPreserveTheActiveRowsDeletionState() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-update-preserve-deletion-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + TrackRepository sut = CreateTrackRepository(context); + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + context.Tracks.Add(track); + await context.SaveChangesAsync(); + + TrackEntity data = await LoadDetachedTrackAsync(context, track.Id); + data.Title = "Somebody to Love"; + data.IsDeleted = true; + data.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + + // Act + Result result = await sut.UpdateAsync(data, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + TrackEntity storedTrack = await context.Tracks.AsNoTracking().SingleAsync(candidate => candidate.Id == track.Id); + Assert.Equal("Somebody to Love", storedTrack.Title); + Assert.False(storedTrack.IsDeleted); + Assert.Null(storedTrack.DeletedOnUtc); + } + /// - /// Creates a list of tracks with distinct paths and empty metadata collections, so that the chunked lookup can be exercised without extra graph data. + /// Creates a list of tracks of the provided album with distinct paths and empty metadata collections, so that the chunked lookup can be exercised without extra graph data. /// /// The number of tracks to create. /// The Id of the album that owns the tracks. @@ -1317,6 +1926,16 @@ public class TrackRepositoryTests albumId: albumId, libraryId: libraryId, path: $"/music/generated-{Guid.NewGuid():N}.flac", includeMetadata: false))]; } + /// + /// Creates a track repository backed by the provided context, using the deterministic time provider of the test class. + /// + /// The context the repository operates on. + /// The created repository. + private TrackRepository CreateTrackRepository(LuminaDbContext context) + { + return new TrackRepository(context, _mockDateTimeProvider); + } + /// /// Creates a real SQLite backed context, so that the stored values are read exactly as they were written. /// diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Playlists/PlaylistRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Playlists/PlaylistRepositoryTests.cs index 9d6b7a08..500c33e1 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Playlists/PlaylistRepositoryTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Playlists/PlaylistRepositoryTests.cs @@ -44,6 +44,16 @@ public class PlaylistRepositoryTests private readonly AlbumEntityFixture _albumEntityFixture = new(); private readonly TrackEntityFixture _trackEntityFixture = new(); private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new(); + private readonly IDateTimeProvider _mockDateTimeProvider; + + /// + /// Initializes a new instance of the class. + /// + public PlaylistRepositoryTests() + { + _mockDateTimeProvider = Substitute.For(); + _mockDateTimeProvider.UtcNow.Returns(new DateTime(2026, 11, 14, 10, 30, 0, DateTimeKind.Utc)); + } [Fact] public async Task UpdateAsync_WhenNoEditableValueChanged_ShouldNotModifyTheStoredPlaylist() @@ -741,6 +751,125 @@ public class PlaylistRepositoryTests Assert.Null(item.Display); } + [Fact] + public async Task AddScopeEntriesAsync_WhenTheScopeContainsSoftDeletedItems_ShouldAppendOnlyTheVisibleTracks() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-scope-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + PlaylistRepository sut = new(context); + Guid userId = Guid.NewGuid(); + context.Users.Add(_userEntityFixture.Create(id: userId)); + Guid libraryId = Guid.NewGuid(); + + ArtistEntity visibleArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Visible Artist", includeAlbums: false, includeContributors: false); + AlbumEntity visibleAlbum = _albumEntityFixture.Create(artistId: visibleArtist.Id, libraryId: libraryId, title: "Visible Album", includeTracks: false, includeMetadata: false); + TrackEntity visibleTrack = _trackEntityFixture.Create(albumId: visibleAlbum.Id, libraryId: libraryId, title: "Visible Track", includeMetadata: false); + TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: visibleAlbum.Id, libraryId: libraryId, title: "Deleted Track", includeMetadata: false); + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + context.Artists.Add(visibleArtist); + context.Albums.Add(visibleAlbum); + context.Tracks.AddRange(visibleTrack, deletedTrack); + + ArtistEntity artistOfDeletedAlbum = _artistEntityFixture.Create(libraryId: libraryId, name: "Album Artist", includeAlbums: false, includeContributors: false); + AlbumEntity deletedAlbum = _albumEntityFixture.Create(artistId: artistOfDeletedAlbum.Id, libraryId: libraryId, title: "Deleted Album", includeTracks: false, includeMetadata: false); + deletedAlbum.IsDeleted = true; + deletedAlbum.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + TrackEntity trackOfDeletedAlbum = _trackEntityFixture.Create(albumId: deletedAlbum.Id, libraryId: libraryId, title: "Deleted Album Track", includeMetadata: false); + context.Artists.Add(artistOfDeletedAlbum); + context.Albums.Add(deletedAlbum); + context.Tracks.Add(trackOfDeletedAlbum); + + ArtistEntity deletedArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Deleted Artist", includeAlbums: false, includeContributors: false); + deletedArtist.IsDeleted = true; + deletedArtist.DeletedOnUtc = _mockDateTimeProvider.UtcNow; + AlbumEntity albumOfDeletedArtist = _albumEntityFixture.Create(artistId: deletedArtist.Id, libraryId: libraryId, title: "Album Of Deleted Artist", includeTracks: false, includeMetadata: false); + TrackEntity trackOfDeletedArtist = _trackEntityFixture.Create(albumId: albumOfDeletedArtist.Id, libraryId: libraryId, title: "Deleted Artist Track", includeMetadata: false); + context.Artists.Add(deletedArtist); + context.Albums.Add(albumOfDeletedArtist); + context.Tracks.Add(trackOfDeletedArtist); + PlaylistEntity playlist = _playlistEntityFixture.Create(userId: userId, type: PlaylistType.Music, entryCount: 0, version: 0); + context.Playlists.Add(playlist); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.AddScopeEntriesAsync( + playlist.Id, + userId, + libraryId, + artistId: null, + albumId: null, + PlaylistMediaItemType.MusicTrack, + _mockDateTimeProvider.UtcNow, + CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(1, result.Value.AddedCount); + List storedMediaItemIds = await context.PlaylistEntries + .AsNoTracking() + .Where(entry => entry.PlaylistId == playlist.Id) + .Select(entry => entry.MediaItemId) + .ToListAsync(); + Assert.Equal([visibleTrack.Id], storedMediaItemIds); + } + + [Theory] + [InlineData(true)] // The track itself is soft deleted. + [InlineData(false)] // An ancestor of the track is soft deleted. + public async Task GetDetailsForUserAsync_WhenAnEntryReferencesASoftDeletedTrack_ShouldKeepTheEntryWithoutDisplayData(bool isTrackDeleted) + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-details-deleted-{isTrackDeleted}-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + PlaylistRepository sut = new(context); + Guid userId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + context.Users.Add(_userEntityFixture.Create(id: userId)); + (ArtistEntity artist, AlbumEntity album, TrackEntity track) = await SeedTrackAsync( + context, + libraryId, + artistName: "Deleted Track Artist", + albumTitle: "Deleted Track Album", + trackTitle: "Deleted Track", + coverFileName: "deleted-track-cover.jpg"); + if (isTrackDeleted) + track.IsDeleted = true; + else + album.IsDeleted = true; + await context.SaveChangesAsync(); + + Guid playlistId = Guid.NewGuid(); + PlaylistEntryEntity entry = _playlistEntryEntityFixture.Create( + playlistId: playlistId, + mediaItemId: track.Id, + mediaItemType: PlaylistMediaItemType.MusicTrack, + position: 1_000_000_000L); + PlaylistEntity playlist = _playlistEntityFixture.Create( + id: playlistId, + userId: userId, + type: PlaylistType.Music, + entries: [entry], + entryCount: 1, + version: 0); + context.Playlists.Add(playlist); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.GetDetailsForUserAsync(playlistId, userId, paginationData: null, CancellationToken.None); + + // Assert + // A deleted item keeps its entry so its owner can see and remove it, but its display data is no longer exposed. + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + PlaylistEntryDto item = Assert.Single(result.Value!.Entries.Data); + Assert.Equal(entry.Id, item.Entry.Id); + Assert.Null(item.Display); + } + /// /// Seeds a playlist of the given user with the requested number of entries, each referencing a different generated media item. /// diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs index 16dcb9c1..f87903df 100644 --- a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs @@ -82,6 +82,7 @@ public class MusicArtworkServiceTests Guid libraryId = Guid.NewGuid(); Guid albumId = Guid.NewGuid(); string libraryName = "Test Library"; + Guid artistId = Guid.NewGuid(); string artistName = "Test Artist"; string albumTitle = "Test Album"; @@ -92,7 +93,7 @@ public class MusicArtworkServiceTests _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(ImageType.JPEG)); - string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle); MockArtworkDirectoryStubs(artworkDirectoryPath); _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) @@ -104,7 +105,7 @@ public class MusicArtworkServiceTests .Returns(Result.From(renamedFileId)); // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -131,6 +132,7 @@ public class MusicArtworkServiceTests Guid libraryId = Guid.NewGuid(); Guid albumId = Guid.NewGuid(); string libraryName = "Test Library"; + Guid artistId = Guid.NewGuid(); string artistName = "Test Artist"; string albumTitle = "Test Album"; @@ -141,7 +143,7 @@ public class MusicArtworkServiceTests _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(ImageType.JPEG)); - string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle); MockArtworkDirectoryStubs(artworkDirectoryPath); _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) @@ -150,7 +152,7 @@ public class MusicArtworkServiceTests .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, expectedFileName)))); // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath, type: artworkType, ordinal: ordinal), null, CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath, type: artworkType, ordinal: ordinal), null, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -168,6 +170,7 @@ public class MusicArtworkServiceTests // Arrange Guid libraryId = Guid.NewGuid(); Guid albumId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); string libraryName = "Test Library"; string albumTitle = "Test Album"; @@ -178,7 +181,7 @@ public class MusicArtworkServiceTests _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(ImageType.JPEG)); - string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName: "Unknown", albumTitle); + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName: "Unknown", albumTitle); MockArtworkDirectoryStubs(artworkDirectoryPath); _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) @@ -187,11 +190,11 @@ public class MusicArtworkServiceTests .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName: " ", albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName: " ", albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); // Assert Assert.False(result.IsFailure); - _mockPathService.Received(1).SanitizeSegment("Unknown"); + _mockPathService.Received(1).SanitizeCompositeSegment("Unknown", artistId.ToString()); } finally { @@ -218,7 +221,7 @@ public class MusicArtworkServiceTests MockPathBuilding(); // Act - Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: linkPath), null, CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(localPath: linkPath), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -246,7 +249,7 @@ public class MusicArtworkServiceTests MockPathBuilding(); // Act - Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -272,7 +275,7 @@ public class MusicArtworkServiceTests MockPathBuilding(); // Act - Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -293,6 +296,7 @@ public class MusicArtworkServiceTests Guid libraryId = Guid.NewGuid(); Guid albumId = Guid.NewGuid(); string libraryName = "Test Library"; + Guid artistId = Guid.NewGuid(); string artistName = "Test Artist"; string albumTitle = "Test Album"; @@ -300,7 +304,7 @@ public class MusicArtworkServiceTests _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(ImageType.JPEG)); - string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle); MockArtworkDirectoryStubs(artworkDirectoryPath); _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) @@ -309,7 +313,7 @@ public class MusicArtworkServiceTests .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), null, CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), null, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -327,7 +331,7 @@ public class MusicArtworkServiceTests MockPathBuilding(); // Act - Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), null, CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -342,7 +346,7 @@ public class MusicArtworkServiceTests MockPathBuilding(); // Act - Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), null, CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -356,6 +360,7 @@ public class MusicArtworkServiceTests Guid libraryId = Guid.NewGuid(); Guid albumId = Guid.NewGuid(); string libraryName = "Test Library"; + Guid artistId = Guid.NewGuid(); string artistName = "Test Artist"; string albumTitle = "Test Album"; @@ -366,7 +371,7 @@ public class MusicArtworkServiceTests _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(ImageType.JPEG)); - string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle); MockArtworkDirectoryStubs(artworkDirectoryPath); _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) @@ -375,7 +380,7 @@ public class MusicArtworkServiceTests .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath, remoteUrl: "https://coverartarchive.org/cover.jpg"), null, CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath, remoteUrl: "https://coverartarchive.org/cover.jpg"), null, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -402,7 +407,7 @@ public class MusicArtworkServiceTests // Act async Task Act() { - await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), null, cancellationTokenSource.Token); + await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), null, cancellationTokenSource.Token); } // Assert @@ -422,7 +427,7 @@ public class MusicArtworkServiceTests MockPathBuilding(); // Act - Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -442,6 +447,7 @@ public class MusicArtworkServiceTests Guid libraryId = Guid.NewGuid(); Guid albumId = Guid.NewGuid(); string libraryName = "Test Library"; + Guid artistId = Guid.NewGuid(); string artistName = "Test Artist"; string albumTitle = "Test Album"; @@ -452,13 +458,13 @@ public class MusicArtworkServiceTests _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(ImageType.JPEG)); - string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle); MockArtworkDirectoryStubs(artworkDirectoryPath); _mockDirectoryProviderService.CreateDirectory(Arg.Any(), Arg.Any()) .Returns(Error.Failure("Directory.Error", "Failed to create the artwork directory")); // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -478,6 +484,7 @@ public class MusicArtworkServiceTests Guid libraryId = Guid.NewGuid(); Guid albumId = Guid.NewGuid(); string libraryName = "Test Library"; + Guid artistId = Guid.NewGuid(); string artistName = "Test Artist"; string albumTitle = "Test Album"; @@ -488,13 +495,13 @@ public class MusicArtworkServiceTests _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(ImageType.JPEG)); - string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle); MockArtworkDirectoryStubs(artworkDirectoryPath); _mockDirectoryProviderService.DirectoryExists(Arg.Any()) .Returns(Error.Failure("Directory.Error", "Failed to check the artwork directory")); // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -514,6 +521,7 @@ public class MusicArtworkServiceTests Guid libraryId = Guid.NewGuid(); Guid albumId = Guid.NewGuid(); string libraryName = "Test Library"; + Guid artistId = Guid.NewGuid(); string artistName = "Test Artist"; string albumTitle = "Test Album"; @@ -524,13 +532,13 @@ public class MusicArtworkServiceTests _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(ImageType.JPEG)); - string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle); MockArtworkDirectoryStubs(artworkDirectoryPath); _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) .Returns(Error.Failure("FileSystem.Error", "Failed to copy the artwork")); // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -550,6 +558,7 @@ public class MusicArtworkServiceTests Guid libraryId = Guid.NewGuid(); Guid albumId = Guid.NewGuid(); string libraryName = "Test Library"; + Guid artistId = Guid.NewGuid(); string artistName = "Test Artist"; string albumTitle = "Test Album"; @@ -560,7 +569,7 @@ public class MusicArtworkServiceTests _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(ImageType.JPEG)); - string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle); MockArtworkDirectoryStubs(artworkDirectoryPath); _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); @@ -568,7 +577,7 @@ public class MusicArtworkServiceTests .Returns(Error.Failure("FileSystem.Error", "Failed to rename the artwork")); // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -587,6 +596,7 @@ public class MusicArtworkServiceTests Guid libraryId = Guid.NewGuid(); Guid albumId = Guid.NewGuid(); string libraryName = "Test Library"; + Guid artistId = Guid.NewGuid(); string artistName = "Test Artist"; string albumTitle = "Test Album"; @@ -603,17 +613,18 @@ public class MusicArtworkServiceTests _mockPathService.CombinePath(mediaRoot, "music").Returns(Result.From(musicPath)); _mockPathService.CombinePath(Arg.Any(), Arg.Any()) .Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1)))); - _mockPathService.SanitizeSegment(Arg.Any()) + _mockPathService.SanitizeCompositeSegment(Arg.Any(), Arg.Any()) .Returns(callInfo => { - string name = callInfo.Arg(); - return name == $"{libraryName}-{libraryId}" - ? Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false)) - : Errors.FileSystemManagement.InvalidPath; + string name = callInfo.ArgAt(0); + string identifier = callInfo.ArgAt(1); + return name == artistName + ? Errors.FileSystemManagement.InvalidPath + : Result.From(_pathSegmentFixture.Create(name: $"{name}-{identifier}", isDirectory: true, isDrive: false)); }); // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -633,10 +644,11 @@ public class MusicArtworkServiceTests Guid libraryId = Guid.NewGuid(); Guid albumId = Guid.NewGuid(); string libraryName = "Test Library"; + Guid artistId = Guid.NewGuid(); string artistName = "Test Artist"; string albumTitle = "Test Album"; - string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle); MockArtworkDirectoryStubs(artworkDirectoryPath); _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(Result.From(true)); FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")); @@ -646,7 +658,7 @@ public class MusicArtworkServiceTests _mockFileProviderService.DeleteFile(Arg.Any()).Returns(Result.Deleted); // Act - Result result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistName, albumTitle); + Result result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistId, artistName, albumTitle); // Assert Assert.False(result.IsFailure); @@ -661,11 +673,12 @@ public class MusicArtworkServiceTests Guid libraryId = Guid.NewGuid(); Guid albumId = Guid.NewGuid(); string libraryName = "Test Library"; + Guid artistId = Guid.NewGuid(); string artistName = "Test Artist"; string albumTitle = "Test Album"; byte[] uploadedBytes = [10, 20, 30, 40, 50]; string libraryDirectoryPath = BuildLibraryDirectoryPath(libraryName, libraryId); - string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle); string expectedStoredPath = Path.Combine(artworkDirectoryPath, "cover.jpg"); string? temporaryUploadPath = null; MockRealFileSystemStubs(pathId => temporaryUploadPath = pathId.Path); @@ -675,7 +688,7 @@ public class MusicArtworkServiceTests try { // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, artworkStream, "cover.jpg", null, CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, artworkStream, "cover.jpg", null, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -699,11 +712,12 @@ public class MusicArtworkServiceTests { // Arrange Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); string libraryName = "Test Library"; string artistName = "Test Artist"; byte[] uploadedBytes = [60, 70, 80, 90]; string libraryDirectoryPath = BuildLibraryDirectoryPath(libraryName, libraryId); - string artworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName); + string artworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistId, artistName); string expectedStoredPath = Path.Combine(artworkDirectoryPath, "cover.png"); string? temporaryUploadPath = null; MockRealFileSystemStubs(pathId => temporaryUploadPath = pathId.Path); @@ -713,7 +727,7 @@ public class MusicArtworkServiceTests try { // Act - Result result = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, artistName, artworkStream, "cover.png", CancellationToken.None); + Result result = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, artistId, artistName, artworkStream, "cover.png", CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -732,6 +746,44 @@ public class MusicArtworkServiceTests } } + [Fact] + public async Task SaveArtistArtworkAsync_WhenTwoArtistsShareTheSameName_ShouldStoreTheirArtworkInDifferentDirectories() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid firstArtistId = Guid.NewGuid(); + Guid secondArtistId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Queen"; + string libraryDirectoryPath = BuildLibraryDirectoryPath(libraryName, libraryId); + string firstArtworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, firstArtistId, artistName); + string secondArtworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, secondArtistId, artistName); + MockRealFileSystemStubs(); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.PNG)); + await using MemoryStream firstArtworkStream = new([1, 2, 3]); + await using MemoryStream secondArtworkStream = new([4, 5, 6]); + try + { + // Act + Result firstResult = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, firstArtistId, artistName, firstArtworkStream, "cover.png", CancellationToken.None); + Result secondResult = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, secondArtistId, artistName, secondArtworkStream, "cover.png", CancellationToken.None); + + // Assert + // A visible artist and a deleted artist can share a name, so the artist Id keeps their artwork apart and replacing the cover of one never touches the file of the other. + Assert.False(firstResult.IsFailure); + Assert.False(secondResult.IsFailure); + Assert.NotEqual(firstResult.Value, secondResult.Value); + Assert.True(File.Exists(Path.Combine(firstArtworkDirectoryPath, "cover.png"))); + Assert.True(File.Exists(Path.Combine(secondArtworkDirectoryPath, "cover.png"))); + } + finally + { + if (Directory.Exists(libraryDirectoryPath)) + Directory.Delete(libraryDirectoryPath, recursive: true); + } + } + [Fact] public void DeleteStoredArtwork_WhenTheFileExists_ShouldDeleteTheRealFile() { @@ -853,6 +905,14 @@ public class MusicArtworkServiceTests return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false)); }); + _mockPathService.SanitizeCompositeSegment(Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + string name = callInfo.ArgAt(0); + string identifier = callInfo.ArgAt(1); + return Result.From(_pathSegmentFixture.Create(name: $"{name}-{identifier}", isDirectory: true, isDrive: false)); + }); + _mockPathService.CombinePath(Arg.Any(), Arg.Any()) .Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1)))); } @@ -881,17 +941,18 @@ public class MusicArtworkServiceTests /// The Id of the media library the album belongs to. /// The Id of the album. /// The name of the media library the album belongs to. + /// The Id of the artist of the album. /// The name of the artist of the album. /// The title of the album. /// The expected file system path of the album artwork directory. - private static string BuildArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle) + private static string BuildArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, Guid artistId, string artistName, string albumTitle) { return Path.Combine( AppContext.BaseDirectory, "media", "music", $"{libraryName}-{libraryId}", - artistName, + $"{artistName}-{artistId}", $"{albumTitle}-{albumId}"); } @@ -915,16 +976,17 @@ public class MusicArtworkServiceTests /// /// The Id of the media library the artist belongs to. /// The name of the media library the artist belongs to. + /// The Id of the artist. /// The name of the artist. /// The expected file system path of the artist artwork directory. - private static string BuildArtistArtworkDirectoryPath(Guid libraryId, string libraryName, string artistName) + private static string BuildArtistArtworkDirectoryPath(Guid libraryId, string libraryName, Guid artistId, string artistName) { return Path.Combine( AppContext.BaseDirectory, "media", "music", $"{libraryName}-{libraryId}", - artistName); + $"{artistName}-{artistId}"); } /// diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs index 5456488f..2e3fd448 100644 --- a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs @@ -561,14 +561,15 @@ public class BookArtworkServiceTests _mockPathService.CombinePath(mediaRoot, "books").Returns(Result.From(booksPath)); _mockPathService.CombinePath(Arg.Any(), Arg.Any()) .Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1)))); - _mockPathService.SanitizeSegment(Arg.Any()) + _mockPathService.SanitizeCompositeSegment(Arg.Any(), Arg.Any()) .Returns(callInfo => { - string name = callInfo.Arg(); - return name == $"{libraryName}-{libraryId}" - ? Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false)) - : Errors.FileSystemManagement.InvalidPath; + string name = callInfo.ArgAt(0); + string identifier = callInfo.ArgAt(1); + return Result.From(_pathSegmentFixture.Create(name: $"{name}-{identifier}", isDirectory: true, isDrive: false)); }); + _mockPathService.SanitizeSegment(Arg.Any()) + .Returns(Errors.FileSystemManagement.InvalidPath); // Act Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); @@ -602,6 +603,14 @@ public class BookArtworkServiceTests return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false)); }); + _mockPathService.SanitizeCompositeSegment(Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + string name = callInfo.ArgAt(0); + string identifier = callInfo.ArgAt(1); + return Result.From(_pathSegmentFixture.Create(name: $"{name}-{identifier}", isDirectory: true, isDrive: false)); + }); + _mockPathService.CombinePath(Arg.Any(), Arg.Any()) .Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1)))); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointTests.cs index 2749e900..8338422e 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointTests.cs @@ -61,7 +61,7 @@ public class DeleteAlbumEndpointTests : IClassFixture(); - Assert.Null(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId)); - // The sibling album of the artist is preserved. - Assert.NotNull(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == otherAlbumId)); + AlbumEntity? album = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId); + Assert.NotNull(album); + Assert.True(album!.IsDeleted); + Assert.NotNull(album.DeletedOnUtc); + // The sibling album of the artist is untouched. + AlbumEntity? otherAlbum = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == otherAlbumId); + Assert.NotNull(otherAlbum); + Assert.False(otherAlbum!.IsDeleted); } [Fact] - public async Task DeleteAlbum_WhenAlbumHasStoredArtwork_ShouldRemoveTheArtworkOfTheAlbumAndOfItsTracks() + public async Task DeleteAlbum_WhenAlbumHasStoredArtwork_ShouldKeepTheArtworkOfTheAlbumAndOfItsTracks() { // Arrange Guid userId = GetCurrentUserId(); @@ -97,9 +102,34 @@ public class DeleteAlbumEndpointTests : IClassFixture(); - // The artwork of the album and of its tracks does not cascade from the album row, so it is removed together with the album. - Assert.Null(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == albumId)); - Assert.Null(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Track && artwork.OwnerId == trackId)); + // The album is soft deleted, so its artwork and the artwork of its tracks stay available until the user restores it. + AlbumEntity? album = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId); + Assert.NotNull(album); + Assert.True(album!.IsDeleted); + Assert.NotNull(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == albumId)); + Assert.NotNull(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Track && artwork.OwnerId == trackId)); + } + + [Fact] + public async Task DeleteAlbum_WhenAlbumIsTheOnlyAlbumOfTheArtist_ShouldReturnForbiddenWithoutDeletingTheAlbum() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistWithSingleAlbumAsync(userId); + string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync(url); + + // Assert + await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Forbidden", "ArtistMustHaveAtLeastOneAlbum", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4"); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + AlbumEntity? album = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId); + Assert.NotNull(album); + Assert.False(album!.IsDeleted); + Assert.Null(album.DeletedOnUtc); } [Fact] @@ -287,6 +317,36 @@ public class DeleteAlbumEndpointTests : IClassFixture + /// Seeds a music library owned by , together with an artist that owns a single album. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library, artist and album. + private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistWithSingleAlbumAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create( + id: albumId, + artistId: artistId, + libraryId: libraryId, + title: "A Night at the Opera", + includeTracks: false, + includeMetadata: false, + includeBarcode: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId, albumId); + } + /// /// Seeds a music library owned by , together with an artist that owns two albums. /// diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetDeletedAlbums/GetDeletedAlbumsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetDeletedAlbums/GetDeletedAlbumsEndpointTests.cs new file mode 100644 index 00000000..76464402 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetDeletedAlbums/GetDeletedAlbumsEndpointTests.cs @@ -0,0 +1,250 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetDeletedAlbums; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetDeletedAlbums; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedAlbumsEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetDeletedAlbumsEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetDeletedAlbums_WhenLibraryHasDeletedAlbums_ShouldReturnOnlyTheDeletedAlbums() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + Guid artistId = await SeedArtistAsync(libraryId, name: "Queen"); + AlbumEntity deletedAlbum = await SeedAlbumAsync(libraryId, artistId, title: "A Night at the Opera", isDeleted: true); + await SeedAlbumAsync(libraryId, artistId, title: "News of the World", isDeleted: false); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/albums/deleted-items"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + DeletedAlbumResponse[]? albums = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(albums); + Assert.Single(albums); + Assert.Equal(deletedAlbum.Id, albums![0].Id); + Assert.Equal(libraryId, albums[0].LibraryId); + Assert.Equal(artistId, albums[0].ArtistId); + Assert.Equal("Queen", albums[0].ArtistName); + Assert.Equal("A Night at the Opera", albums[0].Title); + Assert.NotEqual(default, albums[0].DeletedOnUtc); + } + + [Fact] + public async Task GetDeletedAlbums_WhenAlbumBelongsToDeletedArtist_ShouldNotReturnIt() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + Guid artistId = await SeedArtistAsync(libraryId, name: "Queen"); + await SeedAlbumAsync(libraryId, artistId, title: "A Night at the Opera", isDeleted: true); + await SoftDeleteArtistAsync(artistId); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/albums/deleted-items"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + DeletedAlbumResponse[]? albums = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(albums); + Assert.Empty(albums); + } + + [Fact] + public async Task GetDeletedAlbums_WhenLibraryBelongsToAnotherUser_ShouldReturnForbidden() + { + // Arrange + Guid otherUserId = await SeedOtherUserAsync(); + Guid otherLibraryId = await SeedLibraryAsync(otherUserId); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{otherLibraryId}/albums/deleted-items"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + } + + [Fact] + public async Task GetDeletedAlbums_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/albums/deleted-items"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task GetDeletedAlbums_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/albums/deleted-items"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + } + + /// + /// Seeds a music library owned by . + /// + /// The Id of the user that owns the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [])); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds an artist in the provided library. + /// + /// The Id of the library that owns the artist. + /// The name of the artist. + /// The Id of the seeded artist. + private async Task SeedArtistAsync(Guid libraryId, string name) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false); + dbContext.Artists.Add(artist); + await dbContext.SaveChangesAsync(); + return artist.Id; + } + + /// + /// Seeds an album of the provided artist, in the requested deletion state. + /// + /// The Id of the library that owns the album. + /// The Id of the artist that owns the album. + /// The title of the album. + /// Whether the album is soft deleted. + /// The seeded album. + private async Task SeedAlbumAsync(Guid libraryId, Guid artistId, string title, bool isDeleted) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + AlbumEntity album = _albumEntityFixture.Create( + artistId: artistId, + libraryId: libraryId, + title: title, + includeTracks: false, + includeMetadata: false, + includeBarcode: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false); + album.IsDeleted = isDeleted; + album.DeletedOnUtc = isDeleted ? DateTime.UtcNow.AddMinutes(-5) : null; + dbContext.Albums.Add(album); + await dbContext.SaveChangesAsync(); + return album; + } + + /// + /// Soft deletes the artist identified by . + /// + /// The Id of the artist to soft delete. + /// A task representing the asynchronous operation. + private async Task SoftDeleteArtistAsync(Guid artistId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + ArtistEntity artist = await dbContext.Artists.FirstAsync(artist => artist.Id == artistId); + artist.IsDeleted = true; + artist.DeletedOnUtc = DateTime.UtcNow.AddMinutes(-5); + await dbContext.SaveChangesAsync(); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + return userId; + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreAlbum/RestoreAlbumEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreAlbum/RestoreAlbumEndpointTests.cs new file mode 100644 index 00000000..1ac05453 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreAlbum/RestoreAlbumEndpointTests.cs @@ -0,0 +1,246 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreAlbum; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreAlbum; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreAlbumEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public RestoreAlbumEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task RestoreAlbum_WhenDeletedAlbumBelongsToAnOwnedArtist_ShouldRestoreTheAlbum() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, isDeleted: true); + + // Act + HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + AlbumEntity? album = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId); + Assert.NotNull(album); + Assert.False(album!.IsDeleted); + Assert.Null(album.DeletedOnUtc); + } + + [Fact] + public async Task RestoreAlbum_WhenAlbumIsNotDeleted_ShouldReturnAlbumNotFoundProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, isDeleted: false); + + // Act + HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task RestoreAlbum_WhenAlbumIsRestoredThroughDifferentLibrary_ShouldReturnAlbumNotFoundProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + (_, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, isDeleted: true); + + // Act + HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/albums/{albumId}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task RestoreAlbum_WhenAlbumIsRestoredThroughDifferentArtist_ShouldReturnAlbumNotFoundProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, _, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, isDeleted: true); + + // Act + HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{albumId}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task RestoreAlbum_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem() + { + // Arrange + Guid otherUserId = await SeedOtherUserAsync(); + (Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId) = await SeedLibraryArtistAndAlbumAsync(otherUserId, isDeleted: true); + + // Act + HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + } + + [Fact] + public async Task RestoreAlbum_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + + // Act + HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task RestoreAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task RestoreAlbum_WhenIdsAreNotParseable_ShouldReturnUnprocessableEntity() + { + // Act + HttpResponseMessage response = await _client.PostAsync("/api/v1/libraries/not-a-guid/artists/not-a-guid/albums/not-a-guid/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + } + + /// + /// Seeds a music library owned by . + /// + /// The Id of the user that owns the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [])); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a music library owned by , an artist of it and an album of the artist, in the requested deletion state. + /// + /// The Id of the user that owns the library. + /// Whether the seeded album is soft deleted. + /// The Ids of the seeded library, artist and album. + private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId, bool isDeleted) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create( + artistId: artistId, + libraryId: libraryId, + title: "A Night at the Opera", + includeTracks: false, + includeMetadata: false, + includeBarcode: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false); + album.IsDeleted = isDeleted; + album.DeletedOnUtc = isDeleted ? DateTime.UtcNow.AddMinutes(-5) : null; + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId, album.Id); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + return userId; + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointTests.cs index 2d6c3dbd..1fb9b770 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointTests.cs @@ -61,7 +61,7 @@ public class DeleteArtistEndpointTests : IClassFixture(); - Assert.Null(await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId)); + ArtistEntity? artist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId); + Assert.NotNull(artist); + Assert.True(artist!.IsDeleted); + Assert.NotNull(artist.DeletedOnUtc); } [Fact] - public async Task DeleteArtist_WhenArtistHasStoredArtwork_ShouldRemoveTheArtworkOfTheArtistAndOfItsChildren() + public async Task DeleteArtist_WhenArtistHasStoredArtwork_ShouldKeepTheArtworkOfTheArtistAndOfItsChildren() { // Arrange Guid userId = GetCurrentUserId(); @@ -96,13 +99,15 @@ public class DeleteArtistEndpointTests : IClassFixture(); - // The artist takes its albums and their tracks with it, and the artwork of all of them does not cascade, so it is removed together with the artist. - Assert.Null(await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId)); - Assert.Null(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId)); - Assert.Null(await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId)); - Assert.Null(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Artist && artwork.OwnerId == artistId)); - Assert.Null(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == albumId)); - Assert.Null(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Track && artwork.OwnerId == trackId)); + // The artist is soft deleted, so its albums, tracks and artwork stay available until the user restores it. + ArtistEntity? artist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId); + Assert.NotNull(artist); + Assert.True(artist!.IsDeleted); + Assert.NotNull(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId)); + Assert.NotNull(await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId)); + Assert.NotNull(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Artist && artwork.OwnerId == artistId)); + Assert.NotNull(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == albumId)); + Assert.NotNull(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Track && artwork.OwnerId == trackId)); } [Fact] diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetDeletedArtists/GetDeletedArtistsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetDeletedArtists/GetDeletedArtistsEndpointTests.cs new file mode 100644 index 00000000..531c8df5 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetDeletedArtists/GetDeletedArtistsEndpointTests.cs @@ -0,0 +1,183 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetDeletedArtists; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetDeletedArtists; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedArtistsEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetDeletedArtistsEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetDeletedArtists_WhenLibraryHasDeletedArtists_ShouldReturnOnlyTheDeletedArtists() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + ArtistEntity deletedArtist = await SeedArtistAsync(libraryId, name: "Queen", isDeleted: true); + await SeedArtistAsync(libraryId, name: "David Bowie", isDeleted: false); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/deleted-items"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + DeletedArtistResponse[]? artists = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(artists); + Assert.Single(artists); + Assert.Equal(deletedArtist.Id, artists![0].Id); + Assert.Equal(libraryId, artists[0].LibraryId); + Assert.Equal("Queen", artists[0].Name); + Assert.NotEqual(default, artists[0].DeletedOnUtc); + } + + [Fact] + public async Task GetDeletedArtists_WhenLibraryBelongsToAnotherUser_ShouldReturnForbidden() + { + // Arrange + Guid otherUserId = await SeedOtherUserAsync(); + Guid otherLibraryId = await SeedLibraryAsync(otherUserId); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{otherLibraryId}/artists/deleted-items"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + } + + [Fact] + public async Task GetDeletedArtists_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/deleted-items"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task GetDeletedArtists_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/artists/deleted-items"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + } + + /// + /// Seeds a music library owned by . + /// + /// The Id of the user that owns the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [])); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds an artist in the provided library, in the requested deletion state. + /// + /// The Id of the library that owns the artist. + /// The name of the artist. + /// Whether the artist is soft deleted. + /// The seeded artist. + private async Task SeedArtistAsync(Guid libraryId, string name, bool isDeleted) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false); + artist.IsDeleted = isDeleted; + artist.DeletedOnUtc = isDeleted ? DateTime.UtcNow.AddMinutes(-5) : null; + dbContext.Artists.Add(artist); + await dbContext.SaveChangesAsync(); + return artist; + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + return userId; + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreArtist/RestoreArtistEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreArtist/RestoreArtistEndpointTests.cs new file mode 100644 index 00000000..15b7f460 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreArtist/RestoreArtistEndpointTests.cs @@ -0,0 +1,220 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreArtist; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreArtist; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreArtistEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public RestoreArtistEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task RestoreArtist_WhenDeletedArtistBelongsToAnOwnedLibrary_ShouldRestoreTheArtist() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(userId, isDeleted: true); + + // Act + HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + ArtistEntity? artist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId); + Assert.NotNull(artist); + Assert.False(artist!.IsDeleted); + Assert.Null(artist.DeletedOnUtc); + } + + [Fact] + public async Task RestoreArtist_WhenArtistIsNotDeleted_ShouldReturnArtistNotFoundProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(userId, isDeleted: false); + + // Act + HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task RestoreArtist_WhenArtistIsRestoredThroughDifferentLibrary_ShouldReturnArtistNotFoundProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + (_, Guid artistId) = await SeedLibraryAndArtistAsync(userId, isDeleted: true); + + // Act + HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task RestoreArtist_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem() + { + // Arrange + Guid otherUserId = await SeedOtherUserAsync(); + (Guid otherLibraryId, Guid otherArtistId) = await SeedLibraryAndArtistAsync(otherUserId, isDeleted: true); + + // Act + HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + } + + [Fact] + public async Task RestoreArtist_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + + // Act + HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task RestoreArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task RestoreArtist_WhenIdsAreNotParseable_ShouldReturnUnprocessableEntity() + { + // Act + HttpResponseMessage response = await _client.PostAsync("/api/v1/libraries/not-a-guid/artists/not-a-guid/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + } + + /// + /// Seeds a music library owned by . + /// + /// The Id of the user that owns the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [])); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a music library owned by and an artist of it, in the requested deletion state. + /// + /// The Id of the user that owns the library. + /// Whether the seeded artist is soft deleted. + /// The Ids of the seeded library and artist. + private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId, bool isDeleted) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false); + artist.IsDeleted = isDeleted; + artist.DeletedOnUtc = isDeleted ? DateTime.UtcNow.AddMinutes(-5) : null; + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(artist); + await dbContext.SaveChangesAsync(); + return (libraryId, artist.Id); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + return userId; + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpointTests.cs index 6133c9c9..c9ab40db 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpointTests.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; @@ -64,7 +63,7 @@ public class DeleteTrackEndpointTests : IClassFixture(); - Assert.Null(await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId)); - // The album and the artist that contained the track are preserved. - Assert.NotNull(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId)); - Assert.NotNull(await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId)); + TrackEntity? track = await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId); + Assert.NotNull(track); + Assert.True(track!.IsDeleted); + Assert.NotNull(track.DeletedOnUtc); + // The album and the artist that contained the track are untouched. + AlbumEntity? album = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId); + ArtistEntity? artist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId); + Assert.NotNull(album); + Assert.False(album!.IsDeleted); + Assert.NotNull(artist); + Assert.False(artist!.IsDeleted); } [Fact] - public async Task DeleteTrack_WhenTrackHasStoredArtwork_ShouldRemoveItsArtworkRecords() + public async Task DeleteTrack_WhenTrackHasStoredArtwork_ShouldKeepItsArtworkRecords() { // Arrange Guid userId = GetCurrentUserId(); @@ -100,8 +106,11 @@ public class DeleteTrackEndpointTests : IClassFixture(); - // The artwork of the track does not cascade from the track row, so it is removed together with the track. - Assert.Null(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Track && artwork.OwnerId == trackId)); + // The track is soft deleted, so its artwork stays available until the user restores it. + TrackEntity? track = await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId); + Assert.NotNull(track); + Assert.True(track!.IsDeleted); + Assert.NotNull(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Track && artwork.OwnerId == trackId)); } [Fact] diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetDeletedTracks/GetDeletedTracksEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetDeletedTracks/GetDeletedTracksEndpointTests.cs new file mode 100644 index 00000000..1d392623 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetDeletedTracks/GetDeletedTracksEndpointTests.cs @@ -0,0 +1,264 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetDeletedTracks; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetDeletedTracks; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedTracksEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetDeletedTracksEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetDeletedTracks_WhenLibraryHasDeletedTracks_ShouldReturnOnlyTheDeletedTracks() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId); + TrackEntity deletedTrack = await SeedTrackAsync(libraryId, albumId, title: "Bohemian Rhapsody", path: $"/music/queen/{Guid.NewGuid():N}.flac", isDeleted: true); + await SeedTrackAsync(libraryId, albumId, title: "Love of My Life", path: $"/music/queen/{Guid.NewGuid():N}.flac", isDeleted: false); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/tracks/deleted-items"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + DeletedTrackResponse[]? tracks = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(tracks); + Assert.Single(tracks); + Assert.Equal(deletedTrack.Id, tracks![0].Id); + Assert.Equal(libraryId, tracks[0].LibraryId); + Assert.Equal(artistId, tracks[0].ArtistId); + Assert.Equal("Queen", tracks[0].ArtistName); + Assert.Equal(albumId, tracks[0].AlbumId); + Assert.Equal("A Night at the Opera", tracks[0].AlbumTitle); + Assert.Equal("Bohemian Rhapsody", tracks[0].Title); + Assert.Equal(deletedTrack.Path, tracks[0].Path); + Assert.NotEqual(default, tracks[0].DeletedOnUtc); + } + + [Fact] + public async Task GetDeletedTracks_WhenTrackBelongsToDeletedAlbum_ShouldNotReturnIt() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, _, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId); + await SeedTrackAsync(libraryId, albumId, title: "Bohemian Rhapsody", path: $"/music/queen/{Guid.NewGuid():N}.flac", isDeleted: true); + await SoftDeleteAlbumAsync(albumId); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/tracks/deleted-items"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + DeletedTrackResponse[]? tracks = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(tracks); + Assert.Empty(tracks); + } + + [Fact] + public async Task GetDeletedTracks_WhenLibraryBelongsToAnotherUser_ShouldReturnForbidden() + { + // Arrange + Guid otherUserId = await SeedOtherUserAsync(); + Guid otherLibraryId = await SeedLibraryAsync(otherUserId); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{otherLibraryId}/tracks/deleted-items"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + } + + [Fact] + public async Task GetDeletedTracks_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/tracks/deleted-items"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task GetDeletedTracks_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/tracks/deleted-items"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + } + + /// + /// Seeds a music library owned by . + /// + /// The Id of the user that owns the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [])); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a music library owned by , an artist of it and an album of the artist. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library, artist and album. + private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create( + artistId: artistId, + libraryId: libraryId, + title: "A Night at the Opera", + includeTracks: false, + includeMetadata: false, + includeBarcode: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId, album.Id); + } + + /// + /// Seeds a track of the provided album, in the requested deletion state. + /// + /// The Id of the library that owns the track. + /// The Id of the album that owns the track. + /// The title of the track. + /// The file system path of the track. + /// Whether the track is soft deleted. + /// The seeded track. + private async Task SeedTrackAsync(Guid libraryId, Guid albumId, string title, string path, bool isDeleted) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + TrackEntity track = _trackEntityFixture.Create( + albumId: albumId, + libraryId: libraryId, + path: path, + title: title, + includeMetadata: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false); + track.IsDeleted = isDeleted; + track.DeletedOnUtc = isDeleted ? DateTime.UtcNow.AddMinutes(-5) : null; + dbContext.Tracks.Add(track); + await dbContext.SaveChangesAsync(); + return track; + } + + /// + /// Soft deletes the album identified by . + /// + /// The Id of the album to soft delete. + /// A task representing the asynchronous operation. + private async Task SoftDeleteAlbumAsync(Guid albumId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + AlbumEntity album = await dbContext.Albums.FirstAsync(album => album.Id == albumId); + album.IsDeleted = true; + album.DeletedOnUtc = DateTime.UtcNow.AddMinutes(-5); + await dbContext.SaveChangesAsync(); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + return userId; + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreTrack/RestoreTrackEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreTrack/RestoreTrackEndpointTests.cs new file mode 100644 index 00000000..041f0b88 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreTrack/RestoreTrackEndpointTests.cs @@ -0,0 +1,258 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreTrack; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreTrack; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreTrackEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public RestoreTrackEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task RestoreTrack_WhenDeletedTrackBelongsToAnOwnedAlbum_ShouldRestoreTheTrack() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, isDeleted: true); + + // Act + HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + TrackEntity? track = await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId); + Assert.NotNull(track); + Assert.False(track!.IsDeleted); + Assert.Null(track.DeletedOnUtc); + } + + [Fact] + public async Task RestoreTrack_WhenTrackIsNotDeleted_ShouldReturnTrackNotFoundProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, isDeleted: false); + + // Act + HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task RestoreTrack_WhenTrackIsRestoredThroughDifferentLibrary_ShouldReturnTrackNotFoundProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + (_, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, isDeleted: true); + + // Act + HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task RestoreTrack_WhenTrackIsRestoredThroughDifferentAlbum_ShouldReturnTrackNotFoundProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid artistId, _, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, isDeleted: true); + + // Act + HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/tracks/{trackId}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task RestoreTrack_WhenTrackBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem() + { + // Arrange + Guid otherUserId = await SeedOtherUserAsync(); + (Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId, Guid otherTrackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId, isDeleted: true); + + // Act + HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}/tracks/{otherTrackId}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + } + + [Fact] + public async Task RestoreTrack_WhenTrackDoesNotExist_ShouldReturnTrackNotFoundProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + + // Act + HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task RestoreTrack_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task RestoreTrack_WhenIdsAreNotParseable_ShouldReturnUnprocessableEntity() + { + // Act + HttpResponseMessage response = await _client.PostAsync("/api/v1/libraries/not-a-guid/artists/not-a-guid/albums/not-a-guid/tracks/not-a-guid/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + } + + /// + /// Seeds a music library owned by . + /// + /// The Id of the user that owns the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [])); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a music library owned by , an artist of it, an album of the artist and a track of the album, in the requested deletion state. + /// + /// The Id of the user that owns the library. + /// Whether the seeded track is soft deleted. + /// The Ids of the seeded library, artist, album and track. + private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId, bool isDeleted) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + TrackEntity track = _trackEntityFixture.Create( + albumId: albumId, + libraryId: libraryId, + path: $"/music/queen/{Guid.NewGuid():N}.flac", + title: "Bohemian Rhapsody", + includeMetadata: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false); + track.IsDeleted = isDeleted; + track.DeletedOnUtc = isDeleted ? DateTime.UtcNow.AddMinutes(-5) : null; + AlbumEntity album = _albumEntityFixture.Create( + artistId: artistId, + libraryId: libraryId, + title: "A Night at the Opera", + tracks: [track], + includeMetadata: false, + includeBarcode: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId, album.Id, track.Id); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + return userId; + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs index deb99adf..54015acc 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs @@ -87,6 +87,34 @@ public class GetThemeTemplateEndpointTests : IClassFixture(_jsonOptions); + Assert.NotNull(result); + Assert.Equal(themeId, result!.Theme.ThemeId); + Assert.Contains("deleted-artists-table", result.Template); + Assert.Contains("deleted-albums-table", result.Template); + Assert.Contains("deleted-tracks-table", result.Template); + Assert.Contains("btn-restore-artist", result.Template); + Assert.Contains("btn-restore-album", result.Template); + Assert.Contains("btn-restore-track", result.Template); + Assert.Contains("pageData.artistRestoreUrl", result.Template); + Assert.Contains("pageData.albumRestoreUrl", result.Template); + Assert.Contains("pageData.trackRestoreUrl", result.Template); + } + [Fact] public async Task GetThemeTemplate_WhenThemeDoesNotExist_ShouldReturnNotFound() { diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpointTests.cs new file mode 100644 index 00000000..d62636e0 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpointTests.cs @@ -0,0 +1,113 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreMusicAlbum; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreMusicAlbum; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreMusicAlbumEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RestoreMusicAlbumEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task RestoreMusicAlbum_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardPostAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage restoreRequest = CreateRestoreRequest(artistId, albumId, libraryId); + restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.True(json.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean()); + Assert.Contains($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(postRequest => postRequest.Endpoint)); + } + + [Fact] + public async Task RestoreMusicAlbum_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + _apiFactory.ApiClientStub.Reset(); + HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.PostRequests); + } + + [Fact] + public async Task RestoreMusicAlbum_WhenNotAuthenticated_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()); + + // Act + HttpResponseMessage response = await anonymousClient.SendAsync(restoreRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.PostRequests); + } + + /// + /// Builds the restore request for the album identified by the route, with the owning library passed through the query string. + /// + /// The route Id of the artist the album belongs to. + /// The route Id of the album to restore. + /// The Id of the media library the album belongs to. + /// The configured restore request. + private static HttpRequestMessage CreateRestoreRequest(Guid artistId, Guid albumId, Guid libraryId) + { + HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/api-restore-album?libraryId={libraryId}") + { + // The front-end sends the JSON content type even for bodyless POST requests, which triggers the antiforgery validation. + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return restoreRequest; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpointTests.cs new file mode 100644 index 00000000..fce2e3ea --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpointTests.cs @@ -0,0 +1,111 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreMusicArtist; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreMusicArtist; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreMusicArtistEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RestoreMusicArtistEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task RestoreMusicArtist_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardPostAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{libraryId}/artists/{artistId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage restoreRequest = CreateRestoreRequest(artistId, libraryId); + restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.True(json.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean()); + Assert.Contains($"libraries/{libraryId}/artists/{artistId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(postRequest => postRequest.Endpoint)); + } + + [Fact] + public async Task RestoreMusicArtist_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + _apiFactory.ApiClientStub.Reset(); + HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid(), Guid.NewGuid()); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.PostRequests); + } + + [Fact] + public async Task RestoreMusicArtist_WhenNotAuthenticated_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid(), Guid.NewGuid()); + + // Act + HttpResponseMessage response = await anonymousClient.SendAsync(restoreRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.PostRequests); + } + + /// + /// Builds the restore request for the artist identified by the route, with the owning library passed through the query string. + /// + /// The route Id of the artist to restore. + /// The Id of the media library the artist belongs to. + /// The configured restore request. + private static HttpRequestMessage CreateRestoreRequest(Guid artistId, Guid libraryId) + { + HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/library/audio-library/music-library/artists/{artistId}/api-restore-artist?libraryId={libraryId}") + { + // The front-end sends the JSON content type even for bodyless POST requests, which triggers the antiforgery validation. + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return restoreRequest; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/DeletedMusicItems/DeletedMusicItemsViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/DeletedMusicItems/DeletedMusicItemsViewEndpointTests.cs new file mode 100644 index 00000000..9904c706 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/DeletedMusicItems/DeletedMusicItemsViewEndpointTests.cs @@ -0,0 +1,148 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.DeletedMusicItems; +using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.DeletedMusicItems; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeletedMusicItemsViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly LibraryDtoFixture _libraryDtoFixture = new(); + private readonly DeletedMusicArtistDtoFixture _deletedMusicArtistDtoFixture = new(); + private readonly DeletedMusicAlbumDtoFixture _deletedMusicAlbumDtoFixture = new(); + private readonly DeletedMusicTrackDtoFixture _deletedMusicTrackDtoFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public DeletedMusicItemsViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task DeletedMusicItemsView_WhenCalledByAuthenticatedUserWithLibraryId_ShouldRenderDeletedMusicItemsPage() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + LibraryDto library = _libraryDtoFixture.Create(id: libraryId, title: "Music"); + DeletedMusicArtistDto deletedArtist = _deletedMusicArtistDtoFixture.Create(libraryId: libraryId, id: artistId, name: "Deleted Artist"); + DeletedMusicAlbumDto deletedAlbum = _deletedMusicAlbumDtoFixture.Create(libraryId: libraryId, id: albumId, artistId: artistId, artistName: "Deleted Artist", title: "Deleted Album"); + DeletedMusicTrackDto deletedTrack = _deletedMusicTrackDtoFixture.Create(libraryId: libraryId, artistId: artistId, artistName: "Deleted Artist", albumId: albumId, albumTitle: "Deleted Album", title: "Deleted Track"); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", library); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/deleted-items", new[] { deletedArtist }); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/albums/deleted-items", new[] { deletedAlbum }); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/tracks/deleted-items", new[] { deletedTrack }); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/deleted-items?libraryId={libraryId}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + Assert.Contains("deleted-artists-table", content); + Assert.Contains("deleted-albums-table", content); + Assert.Contains("deleted-tracks-table", content); + Assert.Contains("btn-restore-artist", content); + Assert.Contains("btn-restore-album", content); + Assert.Contains("btn-restore-track", content); + Assert.Contains("Deleted Artist", content); + Assert.Contains("Deleted Album", content); + Assert.Contains("Deleted Track", content); + Assert.Contains($"libraries/{libraryId}", _apiFactory.ApiClientStub.GetEndpointsCalled); + Assert.Contains($"libraries/{libraryId}/artists/deleted-items", _apiFactory.ApiClientStub.GetEndpointsCalled); + Assert.Contains($"libraries/{libraryId}/albums/deleted-items", _apiFactory.ApiClientStub.GetEndpointsCalled); + Assert.Contains($"libraries/{libraryId}/tracks/deleted-items", _apiFactory.ApiClientStub.GetEndpointsCalled); + } + + [Fact] + public async Task DeletedMusicItemsView_WhenDeletedItemNamesContainMarkup_ShouldEncodeThem() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + LibraryDto library = _libraryDtoFixture.Create(id: libraryId, title: "Music"); + DeletedMusicArtistDto deletedArtist = _deletedMusicArtistDtoFixture.Create(libraryId: libraryId, name: ""); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", library); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/deleted-items", new[] { deletedArtist }); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/albums/deleted-items", Array.Empty()); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/tracks/deleted-items", Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/deleted-items?libraryId={libraryId}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Contains("<script>alert", content); + Assert.DoesNotContain("", content); + } + + [Fact] + public async Task DeletedMusicItemsView_WhenTheApiReturnsForbidden_ShouldRedirectWithoutLeakingDetails() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + LibraryDto library = _libraryDtoFixture.Create(id: libraryId, title: "Music"); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", library); + string endpoint = $"libraries/{libraryId}/artists/deleted-items"; + _apiFactory.ApiClientStub.RegisterGetException(endpoint, new ApiException( + _problemDetailsDtoFixture.Create(title: "General.Unauthorized", detail: "NotAuthorized"), + HttpStatusCode.Forbidden, + endpoint)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/deleted-items?libraryId={libraryId}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // A browser navigation that the API forbids is redirected to the access denied page, without rendering any of the forbidden data. + Assert.Equal(HttpStatusCode.Found, response.StatusCode); + Assert.NotNull(response.Headers.Location); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task DeletedMusicItemsView_WhenCalledWithoutLibraryId_ShouldRedirectToHome() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/library/audio-library/music-library/deleted-items"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("/en-us", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpointTests.cs new file mode 100644 index 00000000..76f7dc12 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpointTests.cs @@ -0,0 +1,115 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreMusicTrack; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreMusicTrack; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreMusicTrackEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RestoreMusicTrackEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task RestoreMusicTrack_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardPostAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage restoreRequest = CreateRestoreRequest(artistId, albumId, trackId, libraryId); + restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.True(json.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean()); + Assert.Contains($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(postRequest => postRequest.Endpoint)); + } + + [Fact] + public async Task RestoreMusicTrack_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + _apiFactory.ApiClientStub.Reset(); + HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.PostRequests); + } + + [Fact] + public async Task RestoreMusicTrack_WhenNotAuthenticated_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()); + + // Act + HttpResponseMessage response = await anonymousClient.SendAsync(restoreRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.PostRequests); + } + + /// + /// Builds the restore request for the track identified by the route, with the owning library passed through the query string. + /// + /// The route Id of the artist the track belongs to. + /// The route Id of the album the track belongs to. + /// The route Id of the track to restore. + /// The Id of the media library the track belongs to. + /// The configured restore request. + private static HttpRequestMessage CreateRestoreRequest(Guid artistId, Guid albumId, Guid trackId, Guid libraryId) + { + HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-restore-track?libraryId={libraryId}") + { + // The front-end sends the JSON content type even for bodyless POST requests, which triggers the antiforgery validation. + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return restoreRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetDeletedAlbums/GetDeletedAlbumsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetDeletedAlbums/GetDeletedAlbumsEndpointTests.cs new file mode 100644 index 00000000..0a18409c --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetDeletedAlbums/GetDeletedAlbumsEndpointTests.cs @@ -0,0 +1,157 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetDeletedAlbums; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetDeletedAlbums; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedAlbumsEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + private readonly List _seededUsernames = []; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetDeletedAlbumsEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task GetDeletedAlbums_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/albums/deleted-items"; + + // Act + HttpResponseMessage response = await _client.GetAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Albums; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetDeletedAlbums_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/albums/deleted-items"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + } + + [Fact] + public async Task GetDeletedAlbums_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenAndNotLeakTheDeletedAlbum() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + HttpClient victimClient = _apiFactory.CreateClient(); + (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient); + _seededUsernames.Add(victimUsername); + const string TITLE = "Secret Deleted Album"; + const string COVER_PATH = "/private/deleted-album-cover.jpg"; + Guid libraryId = await SeedLibraryAndDeletedAlbumAsync(victimUserId, TITLE, COVER_PATH); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{libraryId}/albums/deleted-items"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.DoesNotContain(TITLE, content, StringComparison.Ordinal); + Assert.DoesNotContain(COVER_PATH, content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Seeds a music library owned by , together with a deleted album, its artist and its cover. + /// + /// The Id of the user that owns the library. + /// The title of the deleted album. + /// The stored cover path of the deleted album. + /// The Id of the seeded library. + private async Task SeedLibraryAndDeletedAlbumAsync(Guid userId, string title, string coverPath) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create( + artistId: artistId, + libraryId: libraryId, + title: title, + includeTracks: false, + includeMetadata: false, + includeBarcode: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false); + album.IsDeleted = true; + album.DeletedOnUtc = DateTime.UtcNow.AddMinutes(-5); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Victim Artist", albums: [album], includeContributors: false)); + dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: album.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: coverPath)); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Removes the users created by the tests. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreAlbum/RestoreAlbumEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreAlbum/RestoreAlbumEndpointTests.cs new file mode 100644 index 00000000..6a663051 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreAlbum/RestoreAlbumEndpointTests.cs @@ -0,0 +1,241 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreAlbum; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreAlbum; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreAlbumEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + private readonly List _seededUsernames = []; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public RestoreAlbumEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task RestoreAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/restore"; + + // Act + HttpResponseMessage response = await _client.PostAsync(url, null); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Albums; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task RestoreAlbum_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/restore", null); + + // Assert + await AssertRejectedInjectionAttemptAsync(response); + } + + [Theory] + [InlineData("'; DROP TABLE Albums; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task RestoreAlbum_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/restore", null); + + // Assert + await AssertRejectedInjectionAttemptAsync(response); + } + + [Theory] + [InlineData("'; DROP TABLE Albums; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task RestoreAlbum_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/restore", null); + + // Assert + await AssertRejectedInjectionAttemptAsync(response); + } + + [Fact] + public async Task RestoreAlbum_WhenAlbumBelongsToAnotherUser_ShouldReturnForbiddenAndKeepItDeleted() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + HttpClient victimClient = _apiFactory.CreateClient(); + (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient); + _seededUsernames.Add(victimUsername); + (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndDeletedAlbumAsync(victimUserId); + + // Act + HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/restore", null); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + AlbumEntity? album = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId); + Assert.NotNull(album); + Assert.True(album!.IsDeleted); + } + + [Fact] + public async Task RestoreAlbum_WhenAlbumIsRestoredThroughAnotherLibrary_ShouldReturnNotFoundAndKeepItDeleted() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(actingUsername); + Guid ownLibraryId = await SeedLibraryAsync(actingUserId); + HttpClient victimClient = _apiFactory.CreateClient(); + (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient); + _seededUsernames.Add(victimUsername); + (_, Guid victimArtistId, Guid victimAlbumId) = await SeedLibraryArtistAndDeletedAlbumAsync(victimUserId); + + // Act + HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}/restore", null); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + AlbumEntity? victimAlbum = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == victimAlbumId); + Assert.NotNull(victimAlbum); + Assert.True(victimAlbum!.IsDeleted); + } + + /// + /// Asserts that a route parameter carrying an injection payload is rejected as a validation error, without leaking internal details. + /// + /// The HTTP response to assert on. + private async Task AssertRejectedInjectionAttemptAsync(HttpResponseMessage response) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + } + + /// + /// Seeds a music library owned by . + /// + /// The Id of the user that owns the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Acting Library", libraryType: LibraryType.Music, contentLocations: [])); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a music library owned by , together with an artist and a deleted album of that artist. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library, artist and album. + private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndDeletedAlbumAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create( + artistId: artistId, + libraryId: libraryId, + title: "Victim Album", + includeTracks: false, + includeMetadata: false, + includeBarcode: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false); + album.IsDeleted = true; + album.DeletedOnUtc = DateTime.UtcNow.AddMinutes(-5); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Victim Artist", albums: [album], includeContributors: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId, album.Id); + } + + /// + /// Removes the users created by the tests. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetDeletedArtists/GetDeletedArtistsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetDeletedArtists/GetDeletedArtistsEndpointTests.cs new file mode 100644 index 00000000..2ce9e4ec --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetDeletedArtists/GetDeletedArtistsEndpointTests.cs @@ -0,0 +1,145 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetDeletedArtists; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetDeletedArtists; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedArtistsEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + private readonly List _seededUsernames = []; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetDeletedArtistsEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task GetDeletedArtists_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/deleted-items"; + + // Act + HttpResponseMessage response = await _client.GetAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetDeletedArtists_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/deleted-items"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + } + + [Fact] + public async Task GetDeletedArtists_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenAndNotLeakTheDeletedArtist() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + HttpClient victimClient = _apiFactory.CreateClient(); + (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient); + _seededUsernames.Add(victimUsername); + const string NAME = "Secret Deleted Artist"; + const string COVER_PATH = "/private/deleted-artist-cover.jpg"; + Guid libraryId = await SeedLibraryAndDeletedArtistAsync(victimUserId, NAME, COVER_PATH); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{libraryId}/artists/deleted-items"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.DoesNotContain(NAME, content, StringComparison.Ordinal); + Assert.DoesNotContain(COVER_PATH, content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Seeds a music library owned by , together with a deleted artist and its cover. + /// + /// The Id of the user that owns the library. + /// The name of the deleted artist. + /// The stored cover path of the deleted artist. + /// The Id of the seeded library. + private async Task SeedLibraryAndDeletedArtistAsync(Guid userId, string name, string coverPath) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false); + artist.IsDeleted = true; + artist.DeletedOnUtc = DateTime.UtcNow.AddMinutes(-5); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(artist); + dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artist.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: coverPath)); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Removes the users created by the tests. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreArtist/RestoreArtistEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreArtist/RestoreArtistEndpointTests.cs new file mode 100644 index 00000000..89af99f8 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreArtist/RestoreArtistEndpointTests.cs @@ -0,0 +1,207 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreArtist; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreArtist; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreArtistEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + private readonly List _seededUsernames = []; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public RestoreArtistEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task RestoreArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/restore"; + + // Act + HttpResponseMessage response = await _client.PostAsync(url, null); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task RestoreArtist_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task RestoreArtist_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + } + + [Fact] + public async Task RestoreArtist_WhenArtistBelongsToAnotherUser_ShouldReturnForbiddenAndKeepItDeleted() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + HttpClient victimClient = _apiFactory.CreateClient(); + (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient); + _seededUsernames.Add(victimUsername); + (Guid libraryId, Guid artistId) = await SeedLibraryAndDeletedArtistAsync(victimUserId); + + // Act + HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/restore", null); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + ArtistEntity? artist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId); + Assert.NotNull(artist); + Assert.True(artist!.IsDeleted); + } + + [Fact] + public async Task RestoreArtist_WhenArtistIsRestoredThroughAnotherLibrary_ShouldReturnNotFoundAndKeepItDeleted() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(actingUsername); + Guid ownLibraryId = await SeedLibraryAsync(actingUserId); + HttpClient victimClient = _apiFactory.CreateClient(); + (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient); + _seededUsernames.Add(victimUsername); + (_, Guid victimArtistId) = await SeedLibraryAndDeletedArtistAsync(victimUserId); + + // Act + HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/restore", null); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + ArtistEntity? victimArtist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == victimArtistId); + Assert.NotNull(victimArtist); + Assert.True(victimArtist!.IsDeleted); + } + + /// + /// Seeds a music library owned by . + /// + /// The Id of the user that owns the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Acting Library", libraryType: LibraryType.Music, contentLocations: [])); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a music library owned by , together with a deleted artist. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library and artist. + private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndDeletedArtistAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: "Victim Artist", includeAlbums: false, includeContributors: false); + artist.IsDeleted = true; + artist.DeletedOnUtc = DateTime.UtcNow.AddMinutes(-5); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(artist); + await dbContext.SaveChangesAsync(); + return (libraryId, artist.Id); + } + + /// + /// Removes the users created by the tests. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetDeletedTracks/GetDeletedTracksEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetDeletedTracks/GetDeletedTracksEndpointTests.cs new file mode 100644 index 00000000..b29ddcec --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetDeletedTracks/GetDeletedTracksEndpointTests.cs @@ -0,0 +1,166 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetDeletedTracks; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetDeletedTracks; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedTracksEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + private readonly List _seededUsernames = []; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetDeletedTracksEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task GetDeletedTracks_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/tracks/deleted-items"; + + // Act + HttpResponseMessage response = await _client.GetAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetDeletedTracks_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/tracks/deleted-items"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + } + + [Fact] + public async Task GetDeletedTracks_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenAndNotLeakTheDeletedTrack() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + HttpClient victimClient = _apiFactory.CreateClient(); + (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient); + _seededUsernames.Add(victimUsername); + const string TITLE = "Secret Deleted Track"; + const string PATH = "/private/secret-deleted-track.flac"; + Guid libraryId = await SeedLibraryAndDeletedTrackAsync(victimUserId, TITLE, PATH); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{libraryId}/tracks/deleted-items"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.DoesNotContain(TITLE, content, StringComparison.Ordinal); + Assert.DoesNotContain(PATH, content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Seeds a music library owned by , together with a deleted track, its album and its artist. + /// + /// The Id of the user that owns the library. + /// The title of the deleted track. + /// The file system path of the deleted track. + /// The Id of the seeded library. + private async Task SeedLibraryAndDeletedTrackAsync(Guid userId, string title, string path) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + TrackEntity track = _trackEntityFixture.Create( + albumId: albumId, + libraryId: libraryId, + path: path, + title: title, + includeMetadata: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false); + track.IsDeleted = true; + track.DeletedOnUtc = DateTime.UtcNow.AddMinutes(-5); + AlbumEntity album = _albumEntityFixture.Create( + artistId: artistId, + libraryId: libraryId, + title: "Victim Album", + tracks: [track], + includeMetadata: false, + includeBarcode: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Victim Artist", albums: [album], includeContributors: false)); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Removes the users created by the tests. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreTrack/RestoreTrackEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreTrack/RestoreTrackEndpointTests.cs new file mode 100644 index 00000000..cd5c3607 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreTrack/RestoreTrackEndpointTests.cs @@ -0,0 +1,271 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreTrack; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreTrack; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreTrackEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + private readonly List _seededUsernames = []; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public RestoreTrackEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task RestoreTrack_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/restore"; + + // Act + HttpResponseMessage response = await _client.PostAsync(url, null); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task RestoreTrack_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/restore", null); + + // Assert + await AssertRejectedInjectionAttemptAsync(response); + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task RestoreTrack_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/restore", null); + + // Assert + await AssertRejectedInjectionAttemptAsync(response); + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task RestoreTrack_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/tracks/{Guid.NewGuid()}/restore", null); + + // Assert + await AssertRejectedInjectionAttemptAsync(response); + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task RestoreTrack_WithSQLInjectionInTrackId_ShouldNotCorruptOrLeakData(string maliciousTrackId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Uri.EscapeDataString(maliciousTrackId)}/restore", null); + + // Assert + await AssertRejectedInjectionAttemptAsync(response); + } + + [Fact] + public async Task RestoreTrack_WhenTrackBelongsToAnotherUser_ShouldReturnForbiddenAndKeepItDeleted() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + HttpClient victimClient = _apiFactory.CreateClient(); + (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient); + _seededUsernames.Add(victimUsername); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndDeletedTrackAsync(victimUserId); + + // Act + HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore", null); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + TrackEntity? track = await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId); + Assert.NotNull(track); + Assert.True(track!.IsDeleted); + } + + [Fact] + public async Task RestoreTrack_WhenTrackIsRestoredThroughAnotherLibrary_ShouldReturnNotFoundAndKeepItDeleted() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(actingUsername); + Guid ownLibraryId = await SeedLibraryAsync(actingUserId); + HttpClient victimClient = _apiFactory.CreateClient(); + (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient); + _seededUsernames.Add(victimUsername); + (_, Guid victimArtistId, Guid victimAlbumId, Guid victimTrackId) = await SeedLibraryArtistAlbumAndDeletedTrackAsync(victimUserId); + + // Act + HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}/tracks/{victimTrackId}/restore", null); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + TrackEntity? victimTrack = await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == victimTrackId); + Assert.NotNull(victimTrack); + Assert.True(victimTrack!.IsDeleted); + } + + /// + /// Asserts that a route parameter carrying an injection payload is rejected as a validation error, without leaking internal details. + /// + /// The HTTP response to assert on. + private async Task AssertRejectedInjectionAttemptAsync(HttpResponseMessage response) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + } + + /// + /// Seeds a music library owned by . + /// + /// The Id of the user that owns the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Acting Library", libraryType: LibraryType.Music, contentLocations: [])); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a music library owned by , together with an artist, an album and a deleted track of that album. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library, artist, album and track. + private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndDeletedTrackAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + TrackEntity track = _trackEntityFixture.Create( + albumId: albumId, + libraryId: libraryId, + path: $"/music/victim/{Guid.NewGuid():N}.flac", + title: "Victim Track", + includeMetadata: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false); + track.IsDeleted = true; + track.DeletedOnUtc = DateTime.UtcNow.AddMinutes(-5); + AlbumEntity album = _albumEntityFixture.Create( + artistId: artistId, + libraryId: libraryId, + title: "Victim Album", + tracks: [track], + includeMetadata: false, + includeBarcode: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Victim Artist", albums: [album], includeContributors: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId, album.Id, track.Id); + } + + /// + /// Removes the users created by the tests. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpointTests.cs new file mode 100644 index 00000000..05cc74b6 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpointTests.cs @@ -0,0 +1,139 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreMusicAlbum; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreMusicAlbum; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreMusicAlbumEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RestoreMusicAlbumEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Theory] + [InlineData("'; DROP TABLE Albums; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task RestoreMusicAlbum_WithSQLInjectionInRouteId_ShouldNormalizeTheIdAndNeverRestoreAnotherAlbum(string maliciousId) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + string normalizedId = Guid.Empty.ToString(); + _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage restoreRequest = CreateRestoreRequest(maliciousId, maliciousId, libraryId.ToString()); + restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase); + Assert.Contains($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(postRequest => postRequest.Endpoint)); + } + + [Theory] + [InlineData("'; DROP TABLE Albums; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task RestoreMusicAlbum_WithSQLInjectionInLibraryQueryId_ShouldNormalizeTheLibraryId(string maliciousLibraryId) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string normalizedId = Guid.Empty.ToString(); + _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{normalizedId}/artists/{artistId}/albums/{albumId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage restoreRequest = CreateRestoreRequest(artistId.ToString(), albumId.ToString(), maliciousLibraryId); + restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase); + Assert.Contains($"libraries/{normalizedId}/artists/{artistId}/albums/{albumId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(postRequest => postRequest.Endpoint)); + } + + [Fact] + public async Task RestoreMusicAlbum_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + _apiFactory.ApiClientStub.Reset(); + HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.PostRequests); + } + + [Fact] + public async Task RestoreMusicAlbum_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); + + // Act + HttpResponseMessage response = await anonymousClient.SendAsync(restoreRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.PostRequests); + } + + /// + /// Builds the restore request for the album identified by the route, with the owning library passed through the query string. + /// + /// The raw route value of the artist Id. + /// The raw route value of the album Id. + /// The raw query value of the library Id. + /// The configured restore request. + private static HttpRequestMessage CreateRestoreRequest(string artistId, string albumId, string libraryId) + { + HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/library/audio-library/music-library/artists/{Uri.EscapeDataString(artistId)}/albums/{Uri.EscapeDataString(albumId)}/api-restore-album?libraryId={Uri.EscapeDataString(libraryId)}") + { + // The front-end sends the JSON content type even for bodyless POST requests, which triggers the antiforgery validation. + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return restoreRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpointTests.cs new file mode 100644 index 00000000..9dbe7890 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpointTests.cs @@ -0,0 +1,137 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreMusicArtist; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreMusicArtist; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreMusicArtistEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RestoreMusicArtistEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task RestoreMusicArtist_WithSQLInjectionInRouteId_ShouldNormalizeTheIdAndNeverRestoreAnotherArtist(string maliciousId) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + string normalizedId = Guid.Empty.ToString(); + _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{libraryId}/artists/{normalizedId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage restoreRequest = CreateRestoreRequest(maliciousId, libraryId.ToString()); + restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase); + Assert.Contains($"libraries/{libraryId}/artists/{normalizedId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(postRequest => postRequest.Endpoint)); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task RestoreMusicArtist_WithSQLInjectionInLibraryQueryId_ShouldNormalizeTheLibraryId(string maliciousLibraryId) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid artistId = Guid.NewGuid(); + string normalizedId = Guid.Empty.ToString(); + _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{normalizedId}/artists/{artistId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage restoreRequest = CreateRestoreRequest(artistId.ToString(), maliciousLibraryId); + restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase); + Assert.Contains($"libraries/{normalizedId}/artists/{artistId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(postRequest => postRequest.Endpoint)); + } + + [Fact] + public async Task RestoreMusicArtist_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + _apiFactory.ApiClientStub.Reset(); + HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.PostRequests); + } + + [Fact] + public async Task RestoreMusicArtist_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); + + // Act + HttpResponseMessage response = await anonymousClient.SendAsync(restoreRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.PostRequests); + } + + /// + /// Builds the restore request for the artist identified by the route, with the owning library passed through the query string. + /// + /// The raw route value of the artist Id. + /// The raw query value of the library Id. + /// The configured restore request. + private static HttpRequestMessage CreateRestoreRequest(string artistId, string libraryId) + { + HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/library/audio-library/music-library/artists/{Uri.EscapeDataString(artistId)}/api-restore-artist?libraryId={Uri.EscapeDataString(libraryId)}") + { + // The front-end sends the JSON content type even for bodyless POST requests, which triggers the antiforgery validation. + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return restoreRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/DeletedMusicItems/DeletedMusicItemsViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/DeletedMusicItems/DeletedMusicItemsViewEndpointTests.cs new file mode 100644 index 00000000..8360913a --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/DeletedMusicItems/DeletedMusicItemsViewEndpointTests.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.DeletedMusicItems; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.DeletedMusicItems; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeletedMusicItemsViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public DeletedMusicItemsViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task DeletedMusicItemsView_WhenNotAuthenticated_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/deleted-items?libraryId={Guid.NewGuid()}"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled); + } + + [Theory] + [InlineData("'; DROP TABLE Libraries; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task DeletedMusicItemsView_WithSQLInjectionInLibraryQueryId_ShouldNeverForwardTheMaliciousIdToTheApi(string maliciousLibraryId) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/deleted-items?libraryId={Uri.EscapeDataString(maliciousLibraryId)}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLibraryId, string.Join(",", _apiFactory.ApiClientStub.GetEndpointsCalled), StringComparison.Ordinal); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpointTests.cs new file mode 100644 index 00000000..fb234057 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpointTests.cs @@ -0,0 +1,141 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreMusicTrack; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreMusicTrack; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreMusicTrackEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RestoreMusicTrackEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task RestoreMusicTrack_WithSQLInjectionInRouteId_ShouldNormalizeTheIdAndNeverRestoreAnotherTrack(string maliciousId) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + string normalizedId = Guid.Empty.ToString(); + _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/tracks/{normalizedId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage restoreRequest = CreateRestoreRequest(maliciousId, maliciousId, maliciousId, libraryId.ToString()); + restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase); + Assert.Contains($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/tracks/{normalizedId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(postRequest => postRequest.Endpoint)); + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task RestoreMusicTrack_WithSQLInjectionInLibraryQueryId_ShouldNormalizeTheLibraryId(string maliciousLibraryId) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + string normalizedId = Guid.Empty.ToString(); + _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{normalizedId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage restoreRequest = CreateRestoreRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), maliciousLibraryId); + restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase); + Assert.Contains($"libraries/{normalizedId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(postRequest => postRequest.Endpoint)); + } + + [Fact] + public async Task RestoreMusicTrack_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + _apiFactory.ApiClientStub.Reset(); + HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.PostRequests); + } + + [Fact] + public async Task RestoreMusicTrack_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); + + // Act + HttpResponseMessage response = await anonymousClient.SendAsync(restoreRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.PostRequests); + } + + /// + /// Builds the restore request for the track identified by the route, with the owning library passed through the query string. + /// + /// The raw route value of the artist Id. + /// The raw route value of the album Id. + /// The raw route value of the track Id. + /// The raw query value of the library Id. + /// The configured restore request. + private static HttpRequestMessage CreateRestoreRequest(string artistId, string albumId, string trackId, string libraryId) + { + HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/library/audio-library/music-library/artists/{Uri.EscapeDataString(artistId)}/albums/{Uri.EscapeDataString(albumId)}/tracks/{Uri.EscapeDataString(trackId)}/api-restore-track?libraryId={Uri.EscapeDataString(libraryId)}") + { + // The front-end sends the JSON content type even for bodyless POST requests, which triggers the antiforgery validation. + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return restoreRequest; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandHandlerTests.cs index 30a809ea..aa462094 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandHandlerTests.cs @@ -9,14 +9,12 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum; -using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum; using Lumina.Domain.Common.Primitives; using NSubstitute; using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; @@ -35,8 +33,8 @@ public class DeleteAlbumCommandHandlerTests { private readonly IUnitOfWork _mockUnitOfWork; private readonly IArtistRepository _mockArtistRepository; + private readonly IAlbumRepository _mockAlbumRepository; private readonly ILibraryRepository _mockLibraryRepository; - private readonly IMusicArtworkCleanupService _mockMusicArtworkCleanupService; private readonly IAuthorizationService _mockAuthorizationService; private readonly ICurrentUserService _mockCurrentUserService; private readonly IValidator _mockValidator; @@ -54,42 +52,41 @@ public class DeleteAlbumCommandHandlerTests { _mockUnitOfWork = Substitute.For(); _mockArtistRepository = Substitute.For(); + _mockAlbumRepository = Substitute.For(); _mockLibraryRepository = Substitute.For(); _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); - _mockMusicArtworkCleanupService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockValidator = Substitute.For>(); _userId = Guid.NewGuid(); - // Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the library exists, the artist update succeeds, the artwork cleanup succeeds and saving changes succeeds. + // Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the artist, the library + // and the album exist, marking the album as deleted succeeds, and saving changes succeeds. _mockValidator.Validate(Arg.Any()).Returns([]); _mockCurrentUserService.UserId.Returns(_userId); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(true); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(_artistEntityFixture.Create(includeAlbums: false, includeContributors: false))); _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(_ => Result.From(_libraryEntityFixture.Create())); - _mockMusicArtworkCleanupService.DeleteAlbumArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Deleted); - _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + _mockAlbumRepository.SoftDeleteByIdAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); _mockUnitOfWork.SaveChangesAsync(Arg.Any()) .Returns(Result.Success); - _sut = new DeleteAlbumCommandHandler(_mockUnitOfWork, _mockMusicArtworkCleanupService, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + _sut = new DeleteAlbumCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); } [Fact] - public async Task HandleAsync_WhenAlbumExists_ShouldRemoveAlbumFromArtistAndReturnDeleted() + public async Task HandleAsync_WhenAlbumExists_ShouldSoftDeleteAlbumAndReturnDeleted() { // Arrange DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); - Guid libraryId = Guid.Parse(command.LibraryId!); - Guid artistId = Guid.Parse(command.ArtistId!); - Guid albumId = Guid.Parse(command.AlbumId!); - ArtistEntity artist = CreateArtistWithAlbums(libraryId, artistId, albumId, Guid.NewGuid()); - StubExistingArtist(artist); + (Guid libraryId, Guid artistId, Guid albumId) = GetCommandIds(command); + StubArtistAndLibrary(libraryId, artistId, albumId, Guid.NewGuid()); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -97,30 +94,51 @@ public class DeleteAlbumCommandHandlerTests // Assert Assert.False(result.IsFailure); Assert.Equal(Result.Deleted, result.Value); - // The artwork of the album and of its tracks is removed before the album is removed from the artist aggregate, so that no artwork is orphaned. - await _mockMusicArtworkCleanupService.Received(1).DeleteAlbumArtworkAsync(albumId, Arg.Any()); - Received.InOrder(() => - { - _mockMusicArtworkCleanupService.DeleteAlbumArtworkAsync(albumId, Arg.Any()); - _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()); - }); - await _mockArtistRepository.Received(1).UpdateAsync( - Arg.Is(updatedArtist => - updatedArtist.Id == artistId && - updatedArtist.Albums.Count == 1 && - updatedArtist.Albums.All(album => album.Id != albumId)), - Arg.Any()); + // The album is only marked as deleted, so its metadata, artwork and track paths stay available for a later restore. + await _mockAlbumRepository.Received(1).SoftDeleteByIdAsync(albumId, Arg.Any()); + await _mockAlbumRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenCalled_ShouldLoadTheArtistAggregateAndTheLibraryWithoutTracking() + { + // Arrange + DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); + (Guid libraryId, Guid artistId, Guid albumId) = GetCommandIds(command); + StubArtistAndLibrary(libraryId, artistId, albumId, Guid.NewGuid()); + + // Act + await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + // The album is a child of the artist aggregate, so it is loaded with the aggregate and not with a separate album read. + await _mockArtistRepository.Received(1).GetByIdAsync( + artistId, + shouldIncludeNavigationProperties: true, + shouldTrackEntities: false, + cancellationToken: Arg.Any()); + await _mockLibraryRepository.Received(1).GetByIdAsync( + libraryId, + shouldIncludeNavigationProperties: true, + shouldTrackEntities: false, + cancellationToken: Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetByIdAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository() { // Arrange DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); - _mockValidator.Validate(Arg.Any()).Returns([DomainErrors.Music.AlbumIdCannotBeEmpty]); + _mockValidator.Validate(Arg.Any()) + .Returns([DomainErrors.Music.AlbumIdCannotBeEmpty]); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -129,8 +147,8 @@ public class DeleteAlbumCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Music.AlbumIdCannotBeEmpty, result.FirstError); await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - await _mockMusicArtworkCleanupService.DidNotReceive().DeleteAlbumArtworkAsync(Arg.Any(), Arg.Any()); - await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -148,7 +166,9 @@ public class DeleteAlbumCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } [Fact] @@ -165,7 +185,7 @@ public class DeleteAlbumCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); - await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -192,10 +212,10 @@ public class DeleteAlbumCommandHandlerTests { // Arrange DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); - Guid artistId = Guid.Parse(command.ArtistId!); - Guid albumId = Guid.Parse(command.AlbumId!); - ArtistEntity artist = CreateArtistWithAlbums(Guid.NewGuid(), artistId, albumId, Guid.NewGuid()); - StubExistingArtist(artist); + (_, Guid artistId, _) = GetCommandIds(command); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: Guid.NewGuid(), includeAlbums: false, includeContributors: false); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -213,10 +233,8 @@ public class DeleteAlbumCommandHandlerTests { // Arrange DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); - Guid libraryId = Guid.Parse(command.LibraryId!); - Guid artistId = Guid.Parse(command.ArtistId!); - Guid albumId = Guid.Parse(command.AlbumId!); - StubExistingArtist(CreateArtistWithAlbums(libraryId, artistId, albumId, Guid.NewGuid())); + (Guid libraryId, Guid artistId, _) = GetCommandIds(command); + StubArtist(libraryId, artistId); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(false); @@ -229,26 +247,7 @@ public class DeleteAlbumCommandHandlerTests await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenAlbumDoesNotExistInArtist_ShouldReturnAlbumNotFoundError() - { - // Arrange - DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); - Guid libraryId = Guid.Parse(command.LibraryId!); - Guid artistId = Guid.Parse(command.ArtistId!); - StubExistingArtist(CreateArtistWithAlbums(libraryId, artistId, Guid.NewGuid(), Guid.NewGuid())); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(DomainErrors.Music.AlbumNotFound, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -257,10 +256,8 @@ public class DeleteAlbumCommandHandlerTests { // Arrange DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); - Guid libraryId = Guid.Parse(command.LibraryId!); - Guid artistId = Guid.Parse(command.ArtistId!); - Guid albumId = Guid.Parse(command.AlbumId!); - StubExistingArtist(CreateArtistWithAlbums(libraryId, artistId, albumId, Guid.NewGuid())); + (Guid libraryId, Guid artistId, _) = GetCommandIds(command); + StubArtist(libraryId, artistId); _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); @@ -270,7 +267,8 @@ public class DeleteAlbumCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); - await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } [Fact] @@ -278,10 +276,8 @@ public class DeleteAlbumCommandHandlerTests { // Arrange DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); - Guid libraryId = Guid.Parse(command.LibraryId!); - Guid artistId = Guid.Parse(command.ArtistId!); - Guid albumId = Guid.Parse(command.AlbumId!); - StubExistingArtist(CreateArtistWithAlbums(libraryId, artistId, albumId, Guid.NewGuid())); + (Guid libraryId, Guid artistId, _) = GetCommandIds(command); + StubArtist(libraryId, artistId); _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(_ => Result.From(null)); @@ -291,44 +287,39 @@ public class DeleteAlbumCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError); - await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } [Fact] - public async Task HandleAsync_WhenArtistDomainConversionFails_ShouldReturnError() + public async Task HandleAsync_WhenAlbumIsTheOnlyAlbumOfTheArtist_ShouldReturnArtistMustHaveAtLeastOneAlbumWithoutDeleting() { // Arrange DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); - Guid libraryId = Guid.Parse(command.LibraryId!); - Guid artistId = Guid.Parse(command.ArtistId!); - Guid albumId = Guid.Parse(command.AlbumId!); - AlbumEntity firstAlbum = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false); - AlbumEntity secondAlbum = _albumEntityFixture.Create(id: Guid.NewGuid(), artistId: artistId, libraryId: libraryId, includeTracks: false); - // An empty name is rejected by the artist aggregate invariant, so the repository entity fails to convert to a domain entity. - ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: string.Empty, albums: [firstAlbum, secondAlbum]); - StubExistingArtist(artist); + (Guid libraryId, Guid artistId, Guid albumId) = GetCommandIds(command); + StubArtistAndLibrary(libraryId, artistId, albumId); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert + // The domain rejects the last album before the write is reached. Assert.True(result.IsFailure); - Assert.Equal(DomainErrors.Music.ArtistNameCannotBeEmpty, result.FirstError); - await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + Assert.Equal(DomainErrors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError); + await _mockAlbumRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } [Fact] - public async Task HandleAsync_WhenRemovingTheLastAlbumOfTheArtistFails_ShouldReturnErrorWithoutSaving() + public async Task HandleAsync_WhenTheLastAlbumCheckRacesWithAnotherDelete_ShouldReturnTheStorageFallbackError() { // Arrange DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); - Guid libraryId = Guid.Parse(command.LibraryId!); - Guid artistId = Guid.Parse(command.ArtistId!); - Guid albumId = Guid.Parse(command.AlbumId!); - // The artist owns a single album, which the aggregate forbids removing. - ArtistEntity artist = CreateArtistWithAlbums(libraryId, artistId, albumId); - StubExistingArtist(artist); + (Guid libraryId, Guid artistId, Guid albumId) = GetCommandIds(command); + StubArtistAndLibrary(libraryId, artistId, albumId, Guid.NewGuid()); + // The aggregate still sees a sibling album, but the storage write finds that the sibling was deleted by a concurrent request. + _mockAlbumRepository.SoftDeleteByIdAsync(albumId, Arg.Any()) + .Returns(DomainErrors.Music.ArtistMustHaveAtLeastOneAlbum); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -336,44 +327,56 @@ public class DeleteAlbumCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError); - await _mockMusicArtworkCleanupService.DidNotReceive().DeleteAlbumArtworkAsync(Arg.Any(), Arg.Any()); - await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockAlbumRepository.Received(1).SoftDeleteByIdAsync(albumId, Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } [Fact] - public async Task HandleAsync_WhenArtworkCleanupFails_ShouldReturnErrorWithoutUpdatingTheArtist() + public async Task HandleAsync_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundError() { // Arrange DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); - Guid libraryId = Guid.Parse(command.LibraryId!); - Guid artistId = Guid.Parse(command.ArtistId!); - Guid albumId = Guid.Parse(command.AlbumId!); - StubExistingArtist(CreateArtistWithAlbums(libraryId, artistId, albumId, Guid.NewGuid())); - Error error = Error.Failure(description: "Failed to delete the artwork"); - _mockMusicArtworkCleanupService.DeleteAlbumArtworkAsync(albumId, Arg.Any()) - .Returns(error); + (Guid libraryId, Guid artistId, _) = GetCommandIds(command); + // The artist owns an album, but not the requested one, so the aggregate graph does not contain it. + StubArtistAndLibrary(libraryId, artistId, Guid.NewGuid()); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsFailure); - Assert.Equal(error, result.FirstError); - await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + Assert.Equal(DomainErrors.Music.AlbumNotFound, result.FirstError); + await _mockAlbumRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } [Fact] - public async Task HandleAsync_WhenUpdateArtistFails_ShouldReturnErrorWithoutSaving() + public async Task HandleAsync_WhenAlbumBelongsToAnotherArtist_ShouldReturnAlbumNotFoundError() { // Arrange DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); - Guid libraryId = Guid.Parse(command.LibraryId!); - Guid artistId = Guid.Parse(command.ArtistId!); - Guid albumId = Guid.Parse(command.AlbumId!); - StubExistingArtist(CreateArtistWithAlbums(libraryId, artistId, albumId, Guid.NewGuid())); - _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + (Guid libraryId, Guid artistId, _) = GetCommandIds(command); + // The route artist owns a different album, and the requested album belongs to another artist, so the aggregate graph does not contain it. + StubArtistAndLibrary(libraryId, artistId, Guid.NewGuid()); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.AlbumNotFound, result.FirstError); + await _mockAlbumRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSoftDeleteFails_ShouldReturnErrorWithoutSaving() + { + // Arrange + DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); + (Guid libraryId, Guid artistId, Guid albumId) = GetCommandIds(command); + StubArtistAndLibrary(libraryId, artistId, albumId, Guid.NewGuid()); + _mockAlbumRepository.SoftDeleteByIdAsync(Arg.Any(), Arg.Any()) .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); // Act @@ -382,6 +385,7 @@ public class DeleteAlbumCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockAlbumRepository.Received(1).SoftDeleteByIdAsync(albumId, Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -390,10 +394,8 @@ public class DeleteAlbumCommandHandlerTests { // Arrange DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); - Guid libraryId = Guid.Parse(command.LibraryId!); - Guid artistId = Guid.Parse(command.ArtistId!); - Guid albumId = Guid.Parse(command.AlbumId!); - StubExistingArtist(CreateArtistWithAlbums(libraryId, artistId, albumId, Guid.NewGuid())); + (Guid libraryId, Guid artistId, Guid albumId) = GetCommandIds(command); + StubArtistAndLibrary(libraryId, artistId, albumId, Guid.NewGuid()); _mockUnitOfWork.SaveChangesAsync(Arg.Any()) .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); @@ -403,29 +405,48 @@ public class DeleteAlbumCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); - await _mockArtistRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockAlbumRepository.Received(1).SoftDeleteByIdAsync(albumId, Arg.Any()); } /// - /// Creates an artist that owns the provided albums. + /// Extracts the parsed identifiers carried by . + /// + /// The command whose route identifiers are extracted. + /// The parsed library, artist and album identifiers. + private static (Guid libraryId, Guid artistId, Guid albumId) GetCommandIds(DeleteAlbumCommand command) + { + return ( + Guid.Parse(command.LibraryId!), + Guid.Parse(command.ArtistId!), + Guid.Parse(command.AlbumId!)); + } + + /// + /// Stubs the artist repository so that the handler finds an artist that belongs to . /// /// The Id of the media library the artist belongs to. /// The Id of the artist. - /// The Ids of the albums the artist owns. - /// The created artist entity. - private ArtistEntity CreateArtistWithAlbums(Guid libraryId, Guid artistId, params Guid[] albumIds) + /// The Ids of the albums the artist owns. + private ArtistEntity StubArtist(Guid libraryId, Guid artistId, params Guid[] ownedAlbumIds) { - List albums = [.. albumIds.Select(albumId => _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false, includeMetadata: true))]; - return _artistEntityFixture.Create(id: artistId, libraryId: libraryId, albums: albums, includeContributors: true); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + artist.Albums = [.. ownedAlbumIds.Select(albumId => _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false))]; + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + return artist; } /// - /// Stubs the artist repository so that the artist read returns . + /// Stubs the artist and library repositories so that the handler finds the artist, its albums and its library. /// - /// The artist returned by the artist repository. - private void StubExistingArtist(ArtistEntity artist) + /// The Id of the media library the artist belongs to. + /// The Id of the artist. + /// The Ids of the albums the artist owns. + private void StubArtistAndLibrary(Guid libraryId, Guid artistId, params Guid[] ownedAlbumIds) { - _mockArtistRepository.GetByIdAsync(artist.Id, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) - .Returns(Result.From(artist)); + StubArtist(libraryId, artistId, ownedAlbumIds); + LibraryEntity library = _libraryEntityFixture.Create(id: libraryId); + _mockLibraryRepository.GetByIdAsync(libraryId, Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/RestoreAlbum/RestoreAlbumCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/RestoreAlbum/RestoreAlbumCommandHandlerTests.cs new file mode 100644 index 00000000..2b4ce143 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/RestoreAlbum/RestoreAlbumCommandHandlerTests.cs @@ -0,0 +1,299 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreAlbumCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IAlbumRepository _mockAlbumRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly RestoreAlbumCommandHandler _sut; + private readonly Guid _userId; + private readonly RestoreAlbumCommandFixture _restoreAlbumCommandFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public RestoreAlbumCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockAlbumRepository = Substitute.For(); + _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the restoration, restoring the deleted + // album succeeds, and saving changes succeeds. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockAlbumRepository.RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(Result.Success); + + _sut = new RestoreAlbumCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenDeletedAlbumExists_ShouldRestoreAlbumAndReturnUpdated() + { + // Arrange + RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + Guid albumId = Guid.Parse(command.AlbumId!); + AlbumEntity album = MarkAsDeleted(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false)); + _mockAlbumRepository.GetSoftDeletedByIdAsync(albumId, Arg.Any()) + .Returns(Result.From(album)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + await _mockAlbumRepository.Received(1).RestoreSoftDeletedByIdAsync(albumId, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository() + { + // Arrange + RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([DomainErrors.Music.AlbumIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.AlbumIdCannotBeEmpty, result.FirstError); + await _mockAlbumRepository.DidNotReceive().GetSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAlbumRepository.DidNotReceive().GetSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumRepositoryFails_ShouldReturnFailureResultWithoutRestoring() + { + // Arrange + RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create(); + _mockAlbumRepository.GetSoftDeletedByIdAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockAlbumRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDeletedAlbumDoesNotExist_ShouldReturnAlbumNotFoundError() + { + // Arrange + RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create(); + _mockAlbumRepository.GetSoftDeletedByIdAsync(Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.AlbumNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumBelongsToAnotherLibrary_ShouldReturnAlbumNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create(); + Guid artistId = Guid.Parse(command.ArtistId!); + Guid albumId = Guid.Parse(command.AlbumId!); + AlbumEntity album = MarkAsDeleted(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: Guid.NewGuid(), includeTracks: false)); + _mockAlbumRepository.GetSoftDeletedByIdAsync(albumId, Arg.Any()) + .Returns(Result.From(album)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + // Resource scoping is enforced before authorization, and the mismatch is reported as not found, without disclosing that the album exists in another library. + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.AlbumNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumBelongsToAnotherArtist_ShouldReturnAlbumNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid albumId = Guid.Parse(command.AlbumId!); + AlbumEntity album = MarkAsDeleted(_albumEntityFixture.Create(id: albumId, artistId: Guid.NewGuid(), libraryId: libraryId, includeTracks: false)); + _mockAlbumRepository.GetSoftDeletedByIdAsync(albumId, Arg.Any()) + .Returns(Result.From(album)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + // Resource scoping is enforced before authorization, and the mismatch is reported as not found, without disclosing that the album exists under another artist. + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.AlbumNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + Guid albumId = Guid.Parse(command.AlbumId!); + AlbumEntity album = MarkAsDeleted(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false)); + _mockAlbumRepository.GetSoftDeletedByIdAsync(albumId, Arg.Any()) + .Returns(Result.From(album)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenRestoreFails_ShouldReturnErrorWithoutSaving() + { + // Arrange + RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + Guid albumId = Guid.Parse(command.AlbumId!); + AlbumEntity album = MarkAsDeleted(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false)); + _mockAlbumRepository.GetSoftDeletedByIdAsync(albumId, Arg.Any()) + .Returns(Result.From(album)); + _mockAlbumRepository.RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockAlbumRepository.Received(1).RestoreSoftDeletedByIdAsync(albumId, Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnError() + { + // Arrange + RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + Guid albumId = Guid.Parse(command.AlbumId!); + AlbumEntity album = MarkAsDeleted(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false)); + _mockAlbumRepository.GetSoftDeletedByIdAsync(albumId, Arg.Any()) + .Returns(Result.From(album)); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockAlbumRepository.Received(1).RestoreSoftDeletedByIdAsync(albumId, Arg.Any()); + } + + /// + /// Marks as soft deleted, the way the album repository returns it to the restore handler. + /// + /// The album to mark as soft deleted. + /// The same instance, marked as soft deleted. + private static AlbumEntity MarkAsDeleted(AlbumEntity album) + { + album.IsDeleted = true; + album.DeletedOnUtc = DateTime.UtcNow; + return album; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/RestoreAlbum/RestoreAlbumCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/RestoreAlbum/RestoreAlbumCommandValidatorTests.cs new file mode 100644 index 00000000..1e0d6b37 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/RestoreAlbum/RestoreAlbumCommandValidatorTests.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreAlbumCommandValidatorTests +{ + private readonly RestoreAlbumCommandFixture _restoreAlbumCommandFixture = new(); + private readonly RestoreAlbumCommandValidator _validator = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-artist-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId) + { + // Arrange + RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create(artistId: artistId, includeArtistId: artistId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-album-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenAlbumIdIsEmptyOrInvalid_ShouldHaveValidationError(string? albumId) + { + // Arrange + RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create(albumId: albumId, includeAlbumId: albumId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create(artistId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create(albumId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandHandlerTests.cs index 72575f3d..bb61e4c6 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandHandlerTests.cs @@ -89,12 +89,14 @@ public class UpdateAlbumCoverCommandHandlerTests _mockPathService.PathSeparator.Returns('/'); _mockPathService.SanitizeSegment(Arg.Any()) .Returns(callInfo => PathSegment.Create(callInfo.Arg(), isDirectory: true, isDrive: false)); + _mockPathService.SanitizeCompositeSegment(Arg.Any(), Arg.Any()) + .Returns(callInfo => PathSegment.Create($"{callInfo.ArgAt(0)}-{callInfo.ArgAt(1)}", isDirectory: true, isDrive: false)); _mockMusicArtworkRepository.GetByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From>([])); _mockMusicArtworkRepository.UpsertCoverAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From(Result.Updated)); _mockMusicArtworkService.SaveAlbumArtworkAsync( - Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From(STORED_COVER_PATH)); _mockMusicArtworkService.DeleteStoredArtwork(Arg.Any()).Returns(Result.From(Result.Deleted)); @@ -119,7 +121,7 @@ public class UpdateAlbumCoverCommandHandlerTests await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockMusicArtworkRepository.DidNotReceive().GetByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -137,7 +139,7 @@ public class UpdateAlbumCoverCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); - await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -156,7 +158,7 @@ public class UpdateAlbumCoverCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); - await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -195,7 +197,7 @@ public class UpdateAlbumCoverCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -216,7 +218,7 @@ public class UpdateAlbumCoverCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -236,7 +238,7 @@ public class UpdateAlbumCoverCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); - await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -256,7 +258,7 @@ public class UpdateAlbumCoverCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); - await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -275,7 +277,7 @@ public class UpdateAlbumCoverCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError); - await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -296,7 +298,7 @@ public class UpdateAlbumCoverCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); await _mockMusicArtworkRepository.DidNotReceive().GetByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -316,7 +318,7 @@ public class UpdateAlbumCoverCommandHandlerTests // Assert Assert.False(result.IsFailure); await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync( - Arg.Any(), Arg.Any(), Arg.Any(), string.Empty, Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), string.Empty, Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); } @@ -337,7 +339,7 @@ public class UpdateAlbumCoverCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); - await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); await _mockMusicArtworkRepository.DidNotReceive().UpsertCoverAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -351,7 +353,7 @@ public class UpdateAlbumCoverCommandHandlerTests SetupExistingLibrary(command); SetupExistingArtist(command); _mockMusicArtworkService.SaveAlbumArtworkAsync( - Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Errors.FileSystemManagement.FileTooLarge); @@ -382,7 +384,7 @@ public class UpdateAlbumCoverCommandHandlerTests // Assert Assert.False(result.IsFailure); await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync( - Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), "Ep", Arg.Any()); } @@ -392,11 +394,11 @@ public class UpdateAlbumCoverCommandHandlerTests // Arrange UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); // The artist is named "Live", which is also a release type name, but the album uses no release type, so the segment right before the album - // directory is the artist directory and must not be mistaken for a release type directory. - SetupExistingAlbum(command, includeReleaseType: false); + // directory is the artist directory ({artistName}-{artistId}) and must not be mistaken for a release type directory. + AlbumEntity existingAlbum = SetupExistingAlbum(command, includeReleaseType: false); SetupExistingLibrary(command); SetupExistingArtist(command, name: "Live"); - SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, artworkType: ArtworkType.Cover, fileName: "/media/music/library/Live/album/cover.jpg")); + SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, artworkType: ArtworkType.Cover, fileName: $"/media/music/library/Live-{existingAlbum.ArtistId}/album/cover.jpg")); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -404,7 +406,7 @@ public class UpdateAlbumCoverCommandHandlerTests // Assert Assert.False(result.IsFailure); await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync( - Arg.Any(), Arg.Any(), Arg.Any(), "Live", Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), "Live", Arg.Any(), Arg.Any(), Arg.Any(), Arg.Is(releaseTypeName => releaseTypeName == null), Arg.Any()); } @@ -425,7 +427,7 @@ public class UpdateAlbumCoverCommandHandlerTests // Assert Assert.False(result.IsFailure); await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync( - Arg.Any(), Arg.Any(), Arg.Any(), "Album", Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), "Album", Arg.Any(), Arg.Any(), Arg.Any(), "Ep", Arg.Any()); } @@ -445,7 +447,7 @@ public class UpdateAlbumCoverCommandHandlerTests // Assert Assert.False(result.IsFailure); await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync( - Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), "Single", Arg.Any()); } @@ -466,7 +468,7 @@ public class UpdateAlbumCoverCommandHandlerTests // Assert Assert.False(result.IsFailure); await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync( - Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), "Single", Arg.Any()); } @@ -485,7 +487,7 @@ public class UpdateAlbumCoverCommandHandlerTests // Assert Assert.False(result.IsFailure); await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync( - Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), "Single", Arg.Any()); } @@ -504,7 +506,7 @@ public class UpdateAlbumCoverCommandHandlerTests // Assert Assert.False(result.IsFailure); await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync( - Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Is(releaseTypeName => releaseTypeName == null), Arg.Any()); } @@ -649,6 +651,7 @@ public class UpdateAlbumCoverCommandHandlerTests existingAlbum.LibraryId, existingAlbum.Id, library.Title, + existingAlbum.ArtistId, artist.Name, existingAlbum.Title, Arg.Any(), diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetDeletedAlbums/GetDeletedAlbumsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetDeletedAlbums/GetDeletedAlbumsQueryHandlerTests.cs new file mode 100644 index 00000000..fa8be496 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetDeletedAlbums/GetDeletedAlbumsQueryHandlerTests.cs @@ -0,0 +1,238 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedAlbumsQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IAlbumRepository _mockAlbumRepository; + private readonly IMusicArtworkRepository _mockMusicArtworkRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly GetDeletedAlbumsQueryHandler _sut; + private readonly Guid _userId; + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new(); + private readonly GetDeletedAlbumsQueryFixture _getDeletedAlbumsQueryFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetDeletedAlbumsQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockAlbumRepository = Substitute.For(); + _mockMusicArtworkRepository = Substitute.For(); + _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); + _mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the query is valid, the current user is authenticated, the library ownership policy allows access, there are no deleted + // albums and none of them has stored artwork. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockAlbumRepository.GetSoftDeletedByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _mockMusicArtworkRepository.GetByOwnersAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); + + _sut = new GetDeletedAlbumsQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenDeletedAlbumsExist_ShouldReturnTheirMappedResponsesWithCoverPaths() + { + // Arrange + GetDeletedAlbumsQuery query = _getDeletedAlbumsQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + string coverFileName = $"covers/{Guid.NewGuid()}.jpg"; + DateTime firstDeletedOnUtc = new(2026, 2, 20, 18, 45, 0, DateTimeKind.Utc); + AlbumEntity firstAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false); + firstAlbum.IsDeleted = true; + firstAlbum.DeletedOnUtc = firstDeletedOnUtc; + firstAlbum.Artist = _artistEntityFixture.Create(id: firstAlbum.ArtistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + // A deleted album without a recorded deletion time falls back to its creation time, so the history never shows a default date. + AlbumEntity secondAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false); + secondAlbum.IsDeleted = true; + secondAlbum.DeletedOnUtc = null; + secondAlbum.Artist = _artistEntityFixture.Create(id: secondAlbum.ArtistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + _mockAlbumRepository.GetSoftDeletedByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([firstAlbum, secondAlbum])); + _mockMusicArtworkRepository.GetByOwnersAsync(MusicArtworkOwnerType.Album, Arg.Any>(), Arg.Any()) + .Returns(Result.From>( + [ + // A cover row whose stored file is not resolved yet is skipped, so it cannot hide the resolved cover of the same album. + _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: firstAlbum.Id, artworkType: ArtworkType.Cover, ordinal: 1, includeFileName: false), + _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: firstAlbum.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: coverFileName), + // Non cover artwork is not used as the cover of the deleted album. + _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: firstAlbum.Id, artworkType: ArtworkType.Booklet, ordinal: 0) + ])); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count); + Assert.Equal(firstAlbum.Id, result.Value[0].Id); + Assert.Equal(firstAlbum.LibraryId, result.Value[0].LibraryId); + Assert.Equal(firstAlbum.ArtistId, result.Value[0].ArtistId); + Assert.Equal(firstAlbum.Artist.Name, result.Value[0].ArtistName); + Assert.Equal(firstAlbum.Title, result.Value[0].Title); + Assert.Equal(firstDeletedOnUtc, result.Value[0].DeletedOnUtc); + Assert.Equal(coverFileName, result.Value[0].CoverPath); + Assert.Equal(secondAlbum.Id, result.Value[1].Id); + Assert.Equal(secondAlbum.Artist.Name, result.Value[1].ArtistName); + Assert.Equal(secondAlbum.CreatedOnUtc, result.Value[1].DeletedOnUtc); + Assert.Null(result.Value[1].CoverPath); + await _mockMusicArtworkRepository.Received(1).GetByOwnersAsync( + MusicArtworkOwnerType.Album, + Arg.Is>(ownerIds => ownerIds.Count == 2 && ownerIds.Contains(firstAlbum.Id) && ownerIds.Contains(secondAlbum.Id)), + Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThereAreNoDeletedAlbums_ShouldReturnAnEmptyCollection() + { + // Arrange + GetDeletedAlbumsQuery query = _getDeletedAlbumsQueryFixture.Create(); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository() + { + // Arrange + GetDeletedAlbumsQuery query = _getDeletedAlbumsQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([DomainErrors.Library.LibraryIdCannotBeEmpty]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockAlbumRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockMusicArtworkRepository.DidNotReceive().GetByOwnersAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetDeletedAlbumsQuery query = _getDeletedAlbumsQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAlbumRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + GetDeletedAlbumsQuery query = _getDeletedAlbumsQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockMusicArtworkRepository.DidNotReceive().GetByOwnersAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumRepositoryFails_ShouldReturnFailureResult() + { + // Arrange + GetDeletedAlbumsQuery query = _getDeletedAlbumsQueryFixture.Create(); + _mockAlbumRepository.GetSoftDeletedByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockMusicArtworkRepository.DidNotReceive().GetByOwnersAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtworkRepositoryFails_ShouldReturnFailureResult() + { + // Arrange + GetDeletedAlbumsQuery query = _getDeletedAlbumsQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + AlbumEntity album = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false); + album.IsDeleted = true; + album.DeletedOnUtc = DateTime.UtcNow; + _mockAlbumRepository.GetSoftDeletedByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([album])); + _mockMusicArtworkRepository.GetByOwnersAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetDeletedAlbums/GetDeletedAlbumsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetDeletedAlbums/GetDeletedAlbumsQueryValidatorTests.cs new file mode 100644 index 00000000..d7c2a8de --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetDeletedAlbums/GetDeletedAlbumsQueryValidatorTests.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedAlbumsQueryValidatorTests +{ + private readonly GetDeletedAlbumsQueryFixture _getDeletedAlbumsQueryFixture = new(); + private readonly GetDeletedAlbumsQueryValidator _validator = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + GetDeletedAlbumsQuery query = _getDeletedAlbumsQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetDeletedAlbumsQuery query = _getDeletedAlbumsQueryFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + GetDeletedAlbumsQuery query = _getDeletedAlbumsQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandlerTests.cs index c387ff71..a5bc7bb8 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandlerTests.cs @@ -9,7 +9,6 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist; -using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist; @@ -34,7 +33,6 @@ public class DeleteArtistCommandHandlerTests private readonly IUnitOfWork _mockUnitOfWork; private readonly IArtistRepository _mockArtistRepository; private readonly ILibraryRepository _mockLibraryRepository; - private readonly IMusicArtworkCleanupService _mockMusicArtworkCleanupService; private readonly IAuthorizationService _mockAuthorizationService; private readonly ICurrentUserService _mockCurrentUserService; private readonly IValidator _mockValidator; @@ -54,31 +52,31 @@ public class DeleteArtistCommandHandlerTests _mockLibraryRepository = Substitute.For(); _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); - _mockMusicArtworkCleanupService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockValidator = Substitute.For>(); _userId = Guid.NewGuid(); - // Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the library exists, the artist deletion succeeds, the artwork cleanup succeeds and saving changes succeeds. + // Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the artist and the + // library exist, marking the artist as deleted succeeds, and saving changes succeeds. _mockValidator.Validate(Arg.Any()).Returns([]); _mockCurrentUserService.UserId.Returns(_userId); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(true); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(_artistEntityFixture.Create(includeAlbums: false, includeContributors: false))); _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(_ => Result.From(_libraryEntityFixture.Create())); - _mockMusicArtworkCleanupService.DeleteArtistArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Deleted); - _mockArtistRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Deleted); + _mockArtistRepository.SoftDeleteByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); _mockUnitOfWork.SaveChangesAsync(Arg.Any()) .Returns(Result.Success); - _sut = new DeleteArtistCommandHandler(_mockUnitOfWork, _mockMusicArtworkCleanupService, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + _sut = new DeleteArtistCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); } [Fact] - public async Task HandleAsync_WhenArtistExists_ShouldDeleteArtistAndReturnDeleted() + public async Task HandleAsync_WhenArtistExists_ShouldSoftDeleteArtistAndReturnDeleted() { // Arrange DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); @@ -87,6 +85,8 @@ public class DeleteArtistCommandHandlerTests ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) .Returns(Result.From(artist)); + _mockLibraryRepository.GetByIdAsync(libraryId, Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(id: libraryId))); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -94,19 +94,43 @@ public class DeleteArtistCommandHandlerTests // Assert Assert.False(result.IsFailure); Assert.Equal(Result.Deleted, result.Value); - // The artwork of the artist and of its albums and tracks is removed before the artist row, so that no artwork is orphaned. - await _mockMusicArtworkCleanupService.Received(1).DeleteArtistArtworkAsync(artistId, Arg.Any()); - Received.InOrder(() => - { - _mockMusicArtworkCleanupService.DeleteArtistArtworkAsync(artistId, Arg.Any()); - _mockArtistRepository.DeleteByIdAsync(artistId, Arg.Any()); - }); - await _mockArtistRepository.Received(1).DeleteByIdAsync(artistId, Arg.Any()); + // The artist is only marked as deleted, so its metadata, artwork and paths stay available for a later restore. + await _mockArtistRepository.Received(1).SoftDeleteByIdAsync(artistId, Arg.Any()); + await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenCalled_ShouldLoadTheArtistAndTheLibraryWithoutNavigationPropertiesOrTracking() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockLibraryRepository.GetByIdAsync(libraryId, Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(id: libraryId))); + + // Act + await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + await _mockArtistRepository.Received(1).GetByIdAsync( + artistId, + shouldIncludeNavigationProperties: false, + shouldTrackEntities: false, + cancellationToken: Arg.Any()); + await _mockLibraryRepository.Received(1).GetByIdAsync( + libraryId, + shouldIncludeNavigationProperties: true, + shouldTrackEntities: false, + cancellationToken: Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository() { @@ -122,8 +146,7 @@ public class DeleteArtistCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Music.ArtistIdCannotBeEmpty, result.FirstError); await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - await _mockMusicArtworkCleanupService.DidNotReceive().DeleteArtistArtworkAsync(Arg.Any(), Arg.Any()); - await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -141,7 +164,9 @@ public class DeleteArtistCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } [Fact] @@ -158,7 +183,7 @@ public class DeleteArtistCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); - await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -177,6 +202,7 @@ public class DeleteArtistCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Music.ArtistNotFound, result.FirstError); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -198,6 +224,7 @@ public class DeleteArtistCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Music.ArtistNotFound, result.FirstError); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -223,7 +250,7 @@ public class DeleteArtistCommandHandlerTests await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -246,7 +273,8 @@ public class DeleteArtistCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); - await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } [Fact] @@ -268,12 +296,12 @@ public class DeleteArtistCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError); - await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } [Fact] - public async Task HandleAsync_WhenArtworkCleanupFails_ShouldReturnErrorWithoutDeletingTheArtist() + public async Task HandleAsync_WhenSoftDeleteFails_ShouldReturnErrorWithoutSaving() { // Arrange DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); @@ -282,31 +310,9 @@ public class DeleteArtistCommandHandlerTests ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) .Returns(Result.From(artist)); - Error error = Error.Failure(description: "Failed to delete the artwork"); - _mockMusicArtworkCleanupService.DeleteArtistArtworkAsync(artistId, Arg.Any()) - .Returns(error); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(error, result.FirstError); - await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenDeleteArtistFails_ShouldReturnErrorWithoutSaving() - { - // Arrange - DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); - Guid libraryId = Guid.Parse(command.LibraryId!); - Guid artistId = Guid.Parse(command.ArtistId!); - ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); - _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) - .Returns(Result.From(artist)); - _mockArtistRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(libraryId, Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(id: libraryId))); + _mockArtistRepository.SoftDeleteByIdAsync(Arg.Any(), Arg.Any()) .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); // Act @@ -315,7 +321,7 @@ public class DeleteArtistCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); - await _mockArtistRepository.Received(1).DeleteByIdAsync(artistId, Arg.Any()); + await _mockArtistRepository.Received(1).SoftDeleteByIdAsync(artistId, Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -329,6 +335,8 @@ public class DeleteArtistCommandHandlerTests ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) .Returns(Result.From(artist)); + _mockLibraryRepository.GetByIdAsync(libraryId, Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(id: libraryId))); _mockUnitOfWork.SaveChangesAsync(Arg.Any()) .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); @@ -338,6 +346,6 @@ public class DeleteArtistCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); - await _mockArtistRepository.Received(1).DeleteByIdAsync(artistId, Arg.Any()); + await _mockArtistRepository.Received(1).SoftDeleteByIdAsync(artistId, Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/RestoreArtist/RestoreArtistCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/RestoreArtist/RestoreArtistCommandHandlerTests.cs new file mode 100644 index 00000000..e422dd63 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/RestoreArtist/RestoreArtistCommandHandlerTests.cs @@ -0,0 +1,324 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreArtistCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly RestoreArtistCommandHandler _sut; + private readonly Guid _userId; + private readonly RestoreArtistCommandFixture _restoreArtistCommandFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public RestoreArtistCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockArtistRepository = Substitute.For(); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the restoration, restoring the deleted + // artist succeeds, no visible artist took over its name, and saving changes succeeds. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockArtistRepository.GetByNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + _mockArtistRepository.RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(Result.Success); + + _sut = new RestoreArtistCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenDeletedArtistExists_ShouldRestoreArtistAndReturnUpdated() + { + // Arrange + RestoreArtistCommand command = _restoreArtistCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = MarkAsDeleted(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false)); + _mockArtistRepository.GetSoftDeletedByIdAsync(artistId, Arg.Any()) + .Returns(Result.From(artist)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + await _mockArtistRepository.Received(1).RestoreSoftDeletedByIdAsync(artistId, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockArtistRepository.Received(1).GetByNameAsync(libraryId, artist.Name, Arg.Any()); + await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository() + { + // Arrange + RestoreArtistCommand command = _restoreArtistCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([DomainErrors.Music.ArtistIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.ArtistIdCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + RestoreArtistCommand command = _restoreArtistCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResultWithoutRestoring() + { + // Arrange + RestoreArtistCommand command = _restoreArtistCommandFixture.Create(); + _mockArtistRepository.GetSoftDeletedByIdAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDeletedArtistDoesNotExist_ShouldReturnArtistNotFoundError() + { + // Arrange + RestoreArtistCommand command = _restoreArtistCommandFixture.Create(); + _mockArtistRepository.GetSoftDeletedByIdAsync(Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + RestoreArtistCommand command = _restoreArtistCommandFixture.Create(); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = MarkAsDeleted(_artistEntityFixture.Create(id: artistId, libraryId: Guid.NewGuid(), includeAlbums: false, includeContributors: false)); + _mockArtistRepository.GetSoftDeletedByIdAsync(artistId, Arg.Any()) + .Returns(Result.From(artist)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + // Resource scoping is enforced before authorization, and the mismatch is reported as not found, without disclosing that the artist exists in another library. + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().GetByNameAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + RestoreArtistCommand command = _restoreArtistCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = MarkAsDeleted(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false)); + _mockArtistRepository.GetSoftDeletedByIdAsync(artistId, Arg.Any()) + .Returns(Result.From(artist)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockArtistRepository.DidNotReceive().GetByNameAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenVisibleArtistTookOverTheName_ShouldReturnArtistAlreadyExistsError() + { + // Arrange + RestoreArtistCommand command = _restoreArtistCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = MarkAsDeleted(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false)); + ArtistEntity artistWithSameName = _artistEntityFixture.Create(libraryId: libraryId, name: artist.Name, includeAlbums: false, includeContributors: false); + _mockArtistRepository.GetSoftDeletedByIdAsync(artistId, Arg.Any()) + .Returns(Result.From(artist)); + _mockArtistRepository.GetByNameAsync(libraryId, artist.Name, Arg.Any()) + .Returns(Result.From(artistWithSameName)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + // The name of a visible artist is unique within a library, so the deleted artist cannot be restored until it is renamed. + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.ArtistAlreadyExists, result.FirstError); + await _mockArtistRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetArtistByNameFails_ShouldReturnFailureResultWithoutRestoring() + { + // Arrange + RestoreArtistCommand command = _restoreArtistCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = MarkAsDeleted(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false)); + _mockArtistRepository.GetSoftDeletedByIdAsync(artistId, Arg.Any()) + .Returns(Result.From(artist)); + _mockArtistRepository.GetByNameAsync(libraryId, artist.Name, Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenRestoreFails_ShouldReturnErrorWithoutSaving() + { + // Arrange + RestoreArtistCommand command = _restoreArtistCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = MarkAsDeleted(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false)); + _mockArtistRepository.GetSoftDeletedByIdAsync(artistId, Arg.Any()) + .Returns(Result.From(artist)); + _mockArtistRepository.RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.Received(1).RestoreSoftDeletedByIdAsync(artistId, Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnError() + { + // Arrange + RestoreArtistCommand command = _restoreArtistCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = MarkAsDeleted(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false)); + _mockArtistRepository.GetSoftDeletedByIdAsync(artistId, Arg.Any()) + .Returns(Result.From(artist)); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.Received(1).RestoreSoftDeletedByIdAsync(artistId, Arg.Any()); + } + + /// + /// Marks as soft deleted, the way the artist repository returns it to the restore handler. + /// + /// The artist to mark as soft deleted. + /// The same instance, marked as soft deleted. + private static ArtistEntity MarkAsDeleted(ArtistEntity artist) + { + artist.IsDeleted = true; + artist.DeletedOnUtc = DateTime.UtcNow; + return artist; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/RestoreArtist/RestoreArtistCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/RestoreArtist/RestoreArtistCommandValidatorTests.cs new file mode 100644 index 00000000..270fda1c --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/RestoreArtist/RestoreArtistCommandValidatorTests.cs @@ -0,0 +1,97 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreArtistCommandValidatorTests +{ + private readonly RestoreArtistCommandFixture _restoreArtistCommandFixture = new(); + private readonly RestoreArtistCommandValidator _validator = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + RestoreArtistCommand command = _restoreArtistCommandFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-artist-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId) + { + // Arrange + RestoreArtistCommand command = _restoreArtistCommandFixture.Create(artistId: artistId, includeArtistId: artistId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + RestoreArtistCommand command = _restoreArtistCommandFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + RestoreArtistCommand command = _restoreArtistCommandFixture.Create(artistId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + RestoreArtistCommand command = _restoreArtistCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandHandlerTests.cs index 4de61fa1..d84221a0 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandHandlerTests.cs @@ -82,7 +82,7 @@ public class UpdateArtistCoverCommandHandlerTests _mockMusicArtworkRepository.UpsertCoverAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From(Result.Updated)); _mockMusicArtworkService.SaveArtistArtworkAsync( - Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From(STORED_COVER_PATH)); _mockMusicArtworkService.DeleteStoredArtwork(Arg.Any()).Returns(Result.From(Result.Deleted)); @@ -106,7 +106,7 @@ public class UpdateArtistCoverCommandHandlerTests await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockMusicArtworkRepository.DidNotReceive().GetByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -124,7 +124,7 @@ public class UpdateArtistCoverCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); - await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -143,7 +143,7 @@ public class UpdateArtistCoverCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); - await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -182,7 +182,7 @@ public class UpdateArtistCoverCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -202,7 +202,7 @@ public class UpdateArtistCoverCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); - await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -222,7 +222,7 @@ public class UpdateArtistCoverCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); await _mockMusicArtworkRepository.DidNotReceive().GetByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -241,7 +241,7 @@ public class UpdateArtistCoverCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError); - await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -261,7 +261,7 @@ public class UpdateArtistCoverCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); - await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); await _mockMusicArtworkRepository.DidNotReceive().UpsertCoverAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -274,7 +274,7 @@ public class UpdateArtistCoverCommandHandlerTests SetupExistingArtist(command); SetupExistingLibrary(command); _mockMusicArtworkService.SaveArtistArtworkAsync( - Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Errors.FileSystemManagement.FileTooLarge); @@ -421,6 +421,7 @@ public class UpdateArtistCoverCommandHandlerTests await _mockMusicArtworkService.Received(1).SaveArtistArtworkAsync( existingArtist.LibraryId, library.Title, + existingArtist.Id, existingArtist.Name, Arg.Any(), command.FileName!, diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetDeletedArtists/GetDeletedArtistsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetDeletedArtists/GetDeletedArtistsQueryHandlerTests.cs new file mode 100644 index 00000000..002d71e5 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetDeletedArtists/GetDeletedArtistsQueryHandlerTests.cs @@ -0,0 +1,232 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedArtistsQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly IMusicArtworkRepository _mockMusicArtworkRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly GetDeletedArtistsQueryHandler _sut; + private readonly Guid _userId; + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new(); + private readonly GetDeletedArtistsQueryFixture _getDeletedArtistsQueryFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetDeletedArtistsQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockArtistRepository = Substitute.For(); + _mockMusicArtworkRepository = Substitute.For(); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the query is valid, the current user is authenticated, the library ownership policy allows access, there are no deleted + // artists and none of them has stored artwork. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockArtistRepository.GetSoftDeletedByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _mockMusicArtworkRepository.GetByOwnersAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); + + _sut = new GetDeletedArtistsQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenDeletedArtistsExist_ShouldReturnTheirMappedResponsesWithCoverPaths() + { + // Arrange + GetDeletedArtistsQuery query = _getDeletedArtistsQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + string coverFileName = $"covers/{Guid.NewGuid()}.jpg"; + DateTime firstDeletedOnUtc = new(2026, 1, 15, 10, 30, 0, DateTimeKind.Utc); + ArtistEntity firstArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + firstArtist.IsDeleted = true; + firstArtist.DeletedOnUtc = firstDeletedOnUtc; + // A deleted artist without a recorded deletion time falls back to its creation time, so the history never shows a default date. + ArtistEntity secondArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + secondArtist.IsDeleted = true; + secondArtist.DeletedOnUtc = null; + _mockArtistRepository.GetSoftDeletedByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([firstArtist, secondArtist])); + _mockMusicArtworkRepository.GetByOwnersAsync(MusicArtworkOwnerType.Artist, Arg.Any>(), Arg.Any()) + .Returns(Result.From>( + [ + // A cover row whose stored file is not resolved yet is skipped, so it cannot hide the resolved cover of the same artist. + _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: firstArtist.Id, artworkType: ArtworkType.Cover, ordinal: 1, includeFileName: false), + _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: firstArtist.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: coverFileName), + // Non cover artwork is not used as the cover of the deleted artist. + _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: firstArtist.Id, artworkType: ArtworkType.Back, ordinal: 0) + ])); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count); + Assert.Equal(firstArtist.Id, result.Value[0].Id); + Assert.Equal(firstArtist.LibraryId, result.Value[0].LibraryId); + Assert.Equal(firstArtist.Name, result.Value[0].Name); + Assert.Equal(firstDeletedOnUtc, result.Value[0].DeletedOnUtc); + Assert.Equal(coverFileName, result.Value[0].CoverPath); + Assert.Equal(secondArtist.Id, result.Value[1].Id); + Assert.Equal(secondArtist.CreatedOnUtc, result.Value[1].DeletedOnUtc); + Assert.Null(result.Value[1].CoverPath); + await _mockMusicArtworkRepository.Received(1).GetByOwnersAsync( + MusicArtworkOwnerType.Artist, + Arg.Is>(ownerIds => ownerIds.Count == 2 && ownerIds.Contains(firstArtist.Id) && ownerIds.Contains(secondArtist.Id)), + Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThereAreNoDeletedArtists_ShouldReturnAnEmptyCollection() + { + // Arrange + GetDeletedArtistsQuery query = _getDeletedArtistsQueryFixture.Create(); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository() + { + // Arrange + GetDeletedArtistsQuery query = _getDeletedArtistsQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([DomainErrors.Library.LibraryIdCannotBeEmpty]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockMusicArtworkRepository.DidNotReceive().GetByOwnersAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetDeletedArtistsQuery query = _getDeletedArtistsQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + GetDeletedArtistsQuery query = _getDeletedArtistsQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockArtistRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockMusicArtworkRepository.DidNotReceive().GetByOwnersAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResult() + { + // Arrange + GetDeletedArtistsQuery query = _getDeletedArtistsQueryFixture.Create(); + _mockArtistRepository.GetSoftDeletedByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockMusicArtworkRepository.DidNotReceive().GetByOwnersAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtworkRepositoryFails_ShouldReturnFailureResult() + { + // Arrange + GetDeletedArtistsQuery query = _getDeletedArtistsQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + artist.IsDeleted = true; + artist.DeletedOnUtc = DateTime.UtcNow; + _mockArtistRepository.GetSoftDeletedByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([artist])); + _mockMusicArtworkRepository.GetByOwnersAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetDeletedArtists/GetDeletedArtistsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetDeletedArtists/GetDeletedArtistsQueryValidatorTests.cs new file mode 100644 index 00000000..b050c8aa --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetDeletedArtists/GetDeletedArtistsQueryValidatorTests.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedArtistsQueryValidatorTests +{ + private readonly GetDeletedArtistsQueryFixture _getDeletedArtistsQueryFixture = new(); + private readonly GetDeletedArtistsQueryValidator _validator = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + GetDeletedArtistsQuery query = _getDeletedArtistsQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetDeletedArtistsQuery query = _getDeletedArtistsQueryFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + GetDeletedArtistsQuery query = _getDeletedArtistsQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkCleanupServiceTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkCleanupServiceTests.cs deleted file mode 100644 index a6beb96e..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkCleanupServiceTests.cs +++ /dev/null @@ -1,324 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; -using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; -using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; -using NSubstitute; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -#endregion - -namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class MusicArtworkCleanupServiceTests -{ - private readonly IUnitOfWork _mockUnitOfWork; - private readonly IAlbumRepository _mockAlbumRepository; - private readonly ITrackRepository _mockTrackRepository; - private readonly IMusicArtworkRepository _mockMusicArtworkRepository; - private readonly IMusicArtworkService _mockMusicArtworkService; - private readonly MusicArtworkCleanupService _sut; - private readonly AlbumEntityFixture _albumEntityFixture = new(); - private readonly TrackEntityFixture _trackEntityFixture = new(); - private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - public MusicArtworkCleanupServiceTests() - { - _mockUnitOfWork = Substitute.For(); - _mockAlbumRepository = Substitute.For(); - _mockTrackRepository = Substitute.For(); - _mockMusicArtworkRepository = Substitute.For(); - _mockMusicArtworkService = Substitute.For(); - _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); - _mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository); - _mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository); - - // Default stubs: every owner has no artwork, deleting the records succeeds, deleting a stored file succeeds. - _mockAlbumRepository.GetByArtistIdAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From>([])); - _mockTrackRepository.GetByAlbumIdAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From>([])); - _mockMusicArtworkRepository.GetByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From>([])); - _mockMusicArtworkRepository.DeleteByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.Deleted); - _mockMusicArtworkService.DeleteStoredArtwork(Arg.Any()).Returns(Result.Deleted); - - _sut = new MusicArtworkCleanupService(_mockUnitOfWork, _mockMusicArtworkService); - } - - [Fact] - public async Task DeleteArtistArtworkAsync_WhenArtistHasAlbumsAndTracks_ShouldRemoveTheArtworkOfTheChildrenBeforeTheArtistArtwork() - { - // Arrange - Guid artistId = Guid.NewGuid(); - Guid firstAlbumId = Guid.NewGuid(); - Guid secondAlbumId = Guid.NewGuid(); - Guid firstTrackId = Guid.NewGuid(); - Guid secondTrackId = Guid.NewGuid(); - Guid thirdTrackId = Guid.NewGuid(); - AlbumEntity firstAlbum = _albumEntityFixture.Create(id: firstAlbumId, includeTracks: false); - AlbumEntity secondAlbum = _albumEntityFixture.Create(id: secondAlbumId, includeTracks: false); - TrackEntity firstTrack = _trackEntityFixture.Create(id: firstTrackId, albumId: firstAlbumId); - TrackEntity secondTrack = _trackEntityFixture.Create(id: secondTrackId, albumId: firstAlbumId); - TrackEntity thirdTrack = _trackEntityFixture.Create(id: thirdTrackId, albumId: secondAlbumId); - MusicArtworkEntity firstTrackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: firstTrackId, fileName: "/media/music/first-track.jpg"); - MusicArtworkEntity secondTrackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: secondTrackId, fileName: "/media/music/second-track.jpg"); - MusicArtworkEntity thirdTrackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: thirdTrackId, fileName: "/media/music/third-track.jpg"); - MusicArtworkEntity firstAlbumArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: firstAlbumId, fileName: "/media/music/first-album.jpg"); - MusicArtworkEntity secondAlbumArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: secondAlbumId, fileName: "/media/music/second-album.jpg"); - MusicArtworkEntity artistArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artistId, fileName: "/media/music/artist.jpg"); - _mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any()) - .Returns(Result.From>([firstAlbum, secondAlbum])); - _mockTrackRepository.GetByAlbumIdAsync(firstAlbumId, Arg.Any()) - .Returns(Result.From>([firstTrack, secondTrack])); - _mockTrackRepository.GetByAlbumIdAsync(secondAlbumId, Arg.Any()) - .Returns(Result.From>([thirdTrack])); - _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, firstTrackId, Arg.Any()) - .Returns(Result.From>([firstTrackArtwork])); - _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, secondTrackId, Arg.Any()) - .Returns(Result.From>([secondTrackArtwork])); - _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, thirdTrackId, Arg.Any()) - .Returns(Result.From>([thirdTrackArtwork])); - _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, firstAlbumId, Arg.Any()) - .Returns(Result.From>([firstAlbumArtwork])); - _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, secondAlbumId, Arg.Any()) - .Returns(Result.From>([secondAlbumArtwork])); - _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any()) - .Returns(Result.From>([artistArtwork])); - - // Act - Result result = await _sut.DeleteArtistArtworkAsync(artistId, CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - _mockMusicArtworkService.Received(1).DeleteStoredArtwork(firstTrackArtwork.FileName!); - _mockMusicArtworkService.Received(1).DeleteStoredArtwork(secondTrackArtwork.FileName!); - _mockMusicArtworkService.Received(1).DeleteStoredArtwork(thirdTrackArtwork.FileName!); - _mockMusicArtworkService.Received(1).DeleteStoredArtwork(firstAlbumArtwork.FileName!); - _mockMusicArtworkService.Received(1).DeleteStoredArtwork(secondAlbumArtwork.FileName!); - _mockMusicArtworkService.Received(1).DeleteStoredArtwork(artistArtwork.FileName!); - // Every owner of the artwork is removed from the innermost children outwards, so that no artwork is orphaned. - Received.InOrder(() => - { - _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, firstTrackId, Arg.Any()); - _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, secondTrackId, Arg.Any()); - _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, firstAlbumId, Arg.Any()); - _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, thirdTrackId, Arg.Any()); - _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, secondAlbumId, Arg.Any()); - _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any()); - }); - } - - [Fact] - public async Task DeleteArtistArtworkAsync_WhenGetAlbumsFails_ShouldReturnTheErrorWithoutDeletingAnyArtwork() - { - // Arrange - Guid artistId = Guid.NewGuid(); - _mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any()) - .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); - - // Act - Result result = await _sut.DeleteArtistArtworkAsync(artistId, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); - await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()); - _mockMusicArtworkService.DidNotReceive().DeleteStoredArtwork(Arg.Any()); - } - - [Fact] - public async Task DeleteArtistArtworkAsync_WhenAChildArtworkCleanupFails_ShouldReturnTheErrorWithoutDeletingTheArtistArtwork() - { - // Arrange - Guid artistId = Guid.NewGuid(); - Guid albumId = Guid.NewGuid(); - AlbumEntity album = _albumEntityFixture.Create(id: albumId, includeTracks: false); - _mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any()) - .Returns(Result.From>([album])); - _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) - .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); - - // Act - Result result = await _sut.DeleteArtistArtworkAsync(artistId, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); - await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task DeleteAlbumArtworkAsync_WhenAlbumHasTracks_ShouldRemoveTheArtworkOfTheTracksBeforeTheAlbumArtwork() - { - // Arrange - Guid albumId = Guid.NewGuid(); - Guid firstTrackId = Guid.NewGuid(); - Guid secondTrackId = Guid.NewGuid(); - TrackEntity firstTrack = _trackEntityFixture.Create(id: firstTrackId, albumId: albumId); - TrackEntity secondTrack = _trackEntityFixture.Create(id: secondTrackId, albumId: albumId); - MusicArtworkEntity firstTrackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: firstTrackId, fileName: "/media/music/first-track.jpg"); - MusicArtworkEntity secondTrackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: secondTrackId, fileName: "/media/music/second-track.jpg"); - MusicArtworkEntity albumArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, fileName: "/media/music/album.jpg"); - _mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any()) - .Returns(Result.From>([firstTrack, secondTrack])); - _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, firstTrackId, Arg.Any()) - .Returns(Result.From>([firstTrackArtwork])); - _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, secondTrackId, Arg.Any()) - .Returns(Result.From>([secondTrackArtwork])); - _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) - .Returns(Result.From>([albumArtwork])); - - // Act - Result result = await _sut.DeleteAlbumArtworkAsync(albumId, CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - _mockMusicArtworkService.Received(1).DeleteStoredArtwork(firstTrackArtwork.FileName!); - _mockMusicArtworkService.Received(1).DeleteStoredArtwork(secondTrackArtwork.FileName!); - _mockMusicArtworkService.Received(1).DeleteStoredArtwork(albumArtwork.FileName!); - Received.InOrder(() => - { - _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, firstTrackId, Arg.Any()); - _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, secondTrackId, Arg.Any()); - _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()); - }); - } - - [Fact] - public async Task DeleteAlbumArtworkAsync_WhenGetTracksFails_ShouldReturnTheErrorWithoutDeletingAnyArtwork() - { - // Arrange - Guid albumId = Guid.NewGuid(); - _mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any()) - .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); - - // Act - Result result = await _sut.DeleteAlbumArtworkAsync(albumId, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); - await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task DeleteAlbumArtworkAsync_WhenGetArtworkFails_ShouldReturnTheErrorWithoutDeletingTheRecords() - { - // Arrange - Guid albumId = Guid.NewGuid(); - _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) - .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); - - // Act - Result result = await _sut.DeleteAlbumArtworkAsync(albumId, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); - await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task DeleteAlbumArtworkAsync_WhenDeletingTheArtworkRecordsFails_ShouldReturnTheError() - { - // Arrange - Guid albumId = Guid.NewGuid(); - _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) - .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); - - // Act - Result result = await _sut.DeleteAlbumArtworkAsync(albumId, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); - } - - [Fact] - public async Task DeleteAlbumArtworkAsync_WhenDeletingAStoredArtworkFileFails_ShouldReturnTheErrorWithoutDeletingTheRecords() - { - // Arrange - Guid albumId = Guid.NewGuid(); - MusicArtworkEntity albumArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, fileName: "/media/music/album.jpg"); - _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) - .Returns(Result.From>([albumArtwork])); - _mockMusicArtworkService.DeleteStoredArtwork(albumArtwork.FileName!) - .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); - - // Act - Result result = await _sut.DeleteAlbumArtworkAsync(albumId, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); - await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task DeleteAlbumArtworkAsync_WhenArtworkHasNoStoredFile_ShouldSkipTheFileDeletionButDeleteTheRecords() - { - // Arrange - Guid albumId = Guid.NewGuid(); - // An artwork whose file has not been resolved yet has no file to remove, but its record still has to be removed. - MusicArtworkEntity unresolvedArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, includeFileName: false); - _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) - .Returns(Result.From>([unresolvedArtwork])); - - // Act - Result result = await _sut.DeleteAlbumArtworkAsync(albumId, CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - _mockMusicArtworkService.DidNotReceive().DeleteStoredArtwork(Arg.Any()); - await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()); - } - - [Fact] - public async Task DeleteTrackArtworkAsync_WhenArtworkExists_ShouldDeleteTheStoredFilesAndTheRecords() - { - // Arrange - Guid trackId = Guid.NewGuid(); - MusicArtworkEntity trackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: trackId, fileName: "/media/music/track.jpg"); - _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, trackId, Arg.Any()) - .Returns(Result.From>([trackArtwork])); - - // Act - Result result = await _sut.DeleteTrackArtworkAsync(trackId, CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - _mockMusicArtworkService.Received(1).DeleteStoredArtwork(trackArtwork.FileName!); - await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Track, trackId, Arg.Any()); - } - - [Fact] - public async Task DeleteTrackArtworkAsync_WhenNoArtworkExists_ShouldStillDeleteTheRecords() - { - // Arrange - Guid trackId = Guid.NewGuid(); - - // Act - Result result = await _sut.DeleteTrackArtworkAsync(trackId, CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - _mockMusicArtworkService.DidNotReceive().DeleteStoredArtwork(Arg.Any()); - await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Track, trackId, Arg.Any()); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandHandlerTests.cs index 4a6bb5f3..7f1d0ba2 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandHandlerTests.cs @@ -8,7 +8,6 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; -using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; @@ -33,8 +32,9 @@ public class DeleteTrackCommandHandlerTests { private readonly IUnitOfWork _mockUnitOfWork; private readonly IArtistRepository _mockArtistRepository; + private readonly IAlbumRepository _mockAlbumRepository; + private readonly ITrackRepository _mockTrackRepository; private readonly ILibraryRepository _mockLibraryRepository; - private readonly IMusicArtworkCleanupService _mockMusicArtworkCleanupService; private readonly IAuthorizationService _mockAuthorizationService; private readonly ICurrentUserService _mockCurrentUserService; private readonly IValidator _mockValidator; @@ -53,38 +53,51 @@ public class DeleteTrackCommandHandlerTests { _mockUnitOfWork = Substitute.For(); _mockArtistRepository = Substitute.For(); + _mockAlbumRepository = Substitute.For(); + _mockTrackRepository = Substitute.For(); _mockLibraryRepository = Substitute.For(); _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); + _mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); - _mockMusicArtworkCleanupService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockValidator = Substitute.For>(); _userId = Guid.NewGuid(); - // Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the artist update succeeds, the artwork cleanup succeeds and saving changes succeeds. + // Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the artist, the library, + // the album and the track exist, marking the track as deleted succeeds, and saving changes succeeds. _mockValidator.Validate(Arg.Any()).Returns([]); _mockCurrentUserService.UserId.Returns(_userId); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(true); - _mockMusicArtworkCleanupService.DeleteTrackArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Deleted); - _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(_artistEntityFixture.Create(includeAlbums: false, includeContributors: false))); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(_libraryEntityFixture.Create())); + _mockAlbumRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(_albumEntityFixture.Create(includeTracks: false))); + _mockTrackRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(_trackEntityFixture.Create(includeMetadata: false))); + _mockTrackRepository.SoftDeleteByIdAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); _mockUnitOfWork.SaveChangesAsync(Arg.Any()) .Returns(Result.Success); - _sut = new DeleteTrackCommandHandler(_mockUnitOfWork, _mockMusicArtworkCleanupService, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + _sut = new DeleteTrackCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); } [Fact] - public async Task HandleAsync_WhenTrackExists_ShouldRemoveTrackFromAlbumAndReturnDeleted() + public async Task HandleAsync_WhenTrackExists_ShouldSoftDeleteTrackAndReturnDeleted() { // Arrange DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); - ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId); - StubArtistAndLibrary(artist, libraryId); + StubArtistAndLibrary(libraryId, artistId); + StubAlbum(libraryId, artistId, albumId); + TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, includeMetadata: false); + _mockTrackRepository.GetByIdAsync(trackId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(track)); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -92,31 +105,25 @@ public class DeleteTrackCommandHandlerTests // Assert Assert.False(result.IsFailure); Assert.Equal(Result.Deleted, result.Value); - // The artwork of the track is removed before the track is removed from the artist aggregate, so that no artwork is orphaned. - await _mockMusicArtworkCleanupService.Received(1).DeleteTrackArtworkAsync(trackId, Arg.Any()); - Received.InOrder(() => - { - _mockMusicArtworkCleanupService.DeleteTrackArtworkAsync(trackId, Arg.Any()); - _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()); - }); - await _mockArtistRepository.Received(1).UpdateAsync( - Arg.Is(updatedArtist => - updatedArtist.Id == artistId && - updatedArtist.Albums.Count == 1 && - updatedArtist.Albums[0].Id == albumId && - updatedArtist.Albums[0].Tracks.Count == 0), - Arg.Any()); + // The track is only marked as deleted, so its metadata, artwork and path stay available for a later restore. + await _mockTrackRepository.Received(1).SoftDeleteByIdAsync(trackId, Arg.Any()); + await _mockTrackRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); } [Fact] - public async Task HandleAsync_WhenCalled_ShouldLoadTheArtistWithNavigationPropertiesAndTheLibraryWithoutTracking() + public async Task HandleAsync_WhenCalled_ShouldLoadTheScopingRowsWithoutNavigationPropertiesOrTracking() { // Arrange DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); - ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId); - StubArtistAndLibrary(artist, libraryId); + StubArtistAndLibrary(libraryId, artistId); + StubAlbum(libraryId, artistId, albumId); + TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, includeMetadata: false); + _mockTrackRepository.GetByIdAsync(trackId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(track)); // Act await _sut.HandleAsync(command, CancellationToken.None); @@ -124,17 +131,24 @@ public class DeleteTrackCommandHandlerTests // Assert await _mockArtistRepository.Received(1).GetByIdAsync( artistId, - shouldIncludeNavigationProperties: true, + shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()); await _mockLibraryRepository.Received(1).GetByIdAsync( libraryId, + shouldIncludeNavigationProperties: true, + shouldTrackEntities: false, + cancellationToken: Arg.Any()); + await _mockAlbumRepository.Received(1).GetByIdAsync( + albumId, + shouldIncludeNavigationProperties: false, + shouldTrackEntities: false, + cancellationToken: Arg.Any()); + await _mockTrackRepository.Received(1).GetByIdAsync( + trackId, + shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()); - await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( - _userId, - Arg.Is(context => context.LibraryId == libraryId), - Arg.Any()); } [Fact] @@ -153,13 +167,14 @@ public class DeleteTrackCommandHandlerTests Assert.Equal(DomainErrors.Music.TrackIdCannotBeEmpty, result.FirstError); await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - await _mockMusicArtworkCleanupService.DidNotReceive().DeleteTrackArtworkAsync(Arg.Any(), Arg.Any()); - await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockTrackRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } [Fact] - public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedError() + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() { // Arrange DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); @@ -172,27 +187,26 @@ public class DeleteTrackCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } [Fact] - public async Task HandleAsync_WhenGetArtistFails_ShouldReturnError() + public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResultWithoutDeleting() { // Arrange DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); - (_, Guid artistId, _, _) = GetCommandIds(command); - Error error = Error.Failure(description: "Failed to get artist"); - _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) - .Returns(error); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsFailure); - Assert.Equal(error, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -201,9 +215,8 @@ public class DeleteTrackCommandHandlerTests { // Arrange DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); - (_, Guid artistId, _, _) = GetCommandIds(command); - _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) - .Returns(Result.From(null)); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -211,18 +224,18 @@ public class DeleteTrackCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Music.ArtistNotFound, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } [Fact] - public async Task HandleAsync_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundErrorWithoutEvaluatingThePolicy() + public async Task HandleAsync_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundWithoutEvaluatingThePolicy() { // Arrange DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); - (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); - ArtistEntity artist = CreateArtistWithAlbumAndTrack(Guid.NewGuid(), artistId, albumId, trackId); - _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + (_, Guid artistId, _, _) = GetCommandIds(command); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: Guid.NewGuid(), includeAlbums: false, includeContributors: false); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) .Returns(Result.From(artist)); // Act @@ -233,7 +246,6 @@ public class DeleteTrackCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Music.ArtistNotFound, result.FirstError); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -242,10 +254,8 @@ public class DeleteTrackCommandHandlerTests { // Arrange DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); - (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); - ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId); - _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) - .Returns(Result.From(artist)); + (Guid libraryId, Guid artistId, _, _) = GetCommandIds(command); + StubArtist(libraryId, artistId); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(false); @@ -255,72 +265,30 @@ public class DeleteTrackCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } [Fact] - public async Task HandleAsync_WhenAlbumDoesNotExistInArtist_ShouldReturnAlbumNotFoundError() + public async Task HandleAsync_WhenLibraryRepositoryFails_ShouldReturnFailureResultWithoutDeleting() { // Arrange DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); - (Guid libraryId, Guid artistId, _, Guid trackId) = GetCommandIds(command); - Guid otherAlbumId = Guid.NewGuid(); - ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, otherAlbumId, trackId); - _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) - .Returns(Result.From(artist)); + (Guid libraryId, Guid artistId, _, _) = GetCommandIds(command); + StubArtist(libraryId, artistId); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsFailure); - Assert.Equal(DomainErrors.Music.AlbumNotFound, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenTrackDoesNotExistInAlbum_ShouldReturnTrackNotFoundError() - { - // Arrange - DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); - (Guid libraryId, Guid artistId, Guid albumId, _) = GetCommandIds(command); - ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, Guid.NewGuid()); - _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) - .Returns(Result.From(artist)); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(DomainErrors.Music.TrackNotFound, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenGetLibraryFails_ShouldReturnError() - { - // Arrange - DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); - (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); - ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId); - _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) - .Returns(Result.From(artist)); - Error error = Error.Failure(description: "Failed to get library"); - _mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: Arg.Any()) - .Returns(error); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(error, result.FirstError); - await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -329,12 +297,10 @@ public class DeleteTrackCommandHandlerTests { // Arrange DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); - (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); - ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId); - _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) - .Returns(Result.From(artist)); - _mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: Arg.Any()) - .Returns(Result.From(null)); + (Guid libraryId, Guid artistId, _, _) = GetCommandIds(command); + StubArtist(libraryId, artistId); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -342,77 +308,156 @@ public class DeleteTrackCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError); - await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } [Fact] - public async Task HandleAsync_WhenArtistDomainConversionFails_ShouldReturnError() + public async Task HandleAsync_WhenAlbumRepositoryFails_ShouldReturnFailureResultWithoutDeleting() { // Arrange DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); - (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); - // An empty name is rejected by the artist aggregate invariant, so the repository entity fails to convert to a domain entity. - AlbumEntity album = CreateAlbumWithTrack(libraryId, artistId, albumId, trackId); - ArtistEntity artist = _artistEntityFixture.Create( - id: artistId, - libraryId: libraryId, - name: string.Empty, - albums: [album], - includeContributors: false, - includeMetadata: false); - StubArtistAndLibrary(artist, libraryId); + (Guid libraryId, Guid artistId, _, _) = GetCommandIds(command); + StubArtistAndLibrary(libraryId, artistId); + _mockAlbumRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsFailure); - Assert.Equal(DomainErrors.Music.ArtistNameCannotBeEmpty, result.FirstError); - await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } [Fact] - public async Task HandleAsync_WhenArtworkCleanupFails_ShouldReturnErrorWithoutUpdatingTheArtist() + public async Task HandleAsync_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundError() { // Arrange DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); - (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); - ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId); - StubArtistAndLibrary(artist, libraryId); - Error error = Error.Failure(description: "Failed to delete the artwork"); - _mockMusicArtworkCleanupService.DeleteTrackArtworkAsync(trackId, Arg.Any()) - .Returns(error); + (Guid libraryId, Guid artistId, _, _) = GetCommandIds(command); + StubArtistAndLibrary(libraryId, artistId); + _mockAlbumRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsFailure); - Assert.Equal(error, result.FirstError); - await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + Assert.Equal(DomainErrors.Music.AlbumNotFound, result.FirstError); + await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } [Fact] - public async Task HandleAsync_WhenUpdateArtistFails_ShouldReturnErrorWithoutSaving() + public async Task HandleAsync_WhenAlbumBelongsToAnotherArtist_ShouldReturnAlbumNotFoundError() { // Arrange DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); - (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); - ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId); - StubArtistAndLibrary(artist, libraryId); - Error error = Error.Failure(description: "Failed to update artist"); - _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) - .Returns(error); + (Guid libraryId, Guid artistId, Guid albumId, _) = GetCommandIds(command); + StubArtistAndLibrary(libraryId, artistId); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: Guid.NewGuid(), libraryId: libraryId, includeTracks: false); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(album)); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsFailure); - Assert.Equal(error, result.FirstError); + Assert.Equal(DomainErrors.Music.AlbumNotFound, result.FirstError); + await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTrackRepositoryFails_ShouldReturnFailureResultWithoutDeleting() + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); + (Guid libraryId, Guid artistId, Guid albumId, _) = GetCommandIds(command); + StubArtistAndLibrary(libraryId, artistId); + StubAlbum(libraryId, artistId, albumId); + _mockTrackRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTrackDoesNotExist_ShouldReturnTrackNotFoundError() + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); + (Guid libraryId, Guid artistId, Guid albumId, _) = GetCommandIds(command); + StubArtistAndLibrary(libraryId, artistId); + StubAlbum(libraryId, artistId, albumId); + _mockTrackRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.TrackNotFound, result.FirstError); + await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTrackBelongsToAnotherAlbum_ShouldReturnTrackNotFoundError() + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); + StubArtistAndLibrary(libraryId, artistId); + StubAlbum(libraryId, artistId, albumId); + TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: Guid.NewGuid(), libraryId: libraryId, includeMetadata: false); + _mockTrackRepository.GetByIdAsync(trackId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(track)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.TrackNotFound, result.FirstError); + await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSoftDeleteFails_ShouldReturnErrorWithoutSaving() + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); + StubArtistAndLibrary(libraryId, artistId); + StubAlbum(libraryId, artistId, albumId); + TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, includeMetadata: false); + _mockTrackRepository.GetByIdAsync(trackId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(track)); + _mockTrackRepository.SoftDeleteByIdAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockTrackRepository.Received(1).SoftDeleteByIdAsync(trackId, Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -422,19 +467,21 @@ public class DeleteTrackCommandHandlerTests // Arrange DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); - ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId); - StubArtistAndLibrary(artist, libraryId); - Error error = Error.Failure(description: "Failed to save changes"); + StubArtistAndLibrary(libraryId, artistId); + StubAlbum(libraryId, artistId, albumId); + TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, includeMetadata: false); + _mockTrackRepository.GetByIdAsync(trackId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(track)); _mockUnitOfWork.SaveChangesAsync(Arg.Any()) - .Returns(error); + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsFailure); - Assert.Equal(error, result.FirstError); - await _mockArtistRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockTrackRepository.Received(1).SoftDeleteByIdAsync(trackId, Arg.Any()); } /// @@ -452,67 +499,40 @@ public class DeleteTrackCommandHandlerTests } /// - /// Creates an artist that contains a single album, which in turn contains a single track. + /// Stubs the artist repository so that the handler finds an artist that belongs to . /// /// The Id of the media library the artist belongs to. /// The Id of the artist. - /// The Id of the album. - /// The Id of the track. - /// The created artist entity, with its album and track graph. - private ArtistEntity CreateArtistWithAlbumAndTrack(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) + private void StubArtist(Guid libraryId, Guid artistId) { - AlbumEntity album = CreateAlbumWithTrack(libraryId, artistId, albumId, trackId); - return _artistEntityFixture.Create( - id: artistId, - libraryId: libraryId, - albums: [album], - includeContributors: false, - includeMetadata: false); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); } /// - /// Creates an album that contains a single track. + /// Stubs the album repository so that the handler finds an album of . /// /// The Id of the media library the album belongs to. /// The Id of the artist the album belongs to. /// The Id of the album. - /// The Id of the track. - /// The created album entity, with its track. - private AlbumEntity CreateAlbumWithTrack(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) + private void StubAlbum(Guid libraryId, Guid artistId, Guid albumId) { - TrackEntity track = _trackEntityFixture.Create( - id: trackId, - albumId: albumId, - libraryId: libraryId, - includeMetadata: false, - includeOriginalReleaseDate: false, - includeOriginalReleaseYear: false, - includeReReleaseDate: false, - includeReReleaseYear: false); - return _albumEntityFixture.Create( - id: albumId, - artistId: artistId, - libraryId: libraryId, - tracks: [track], - includeMetadata: false, - includeBarcode: false, - includeOriginalReleaseDate: false, - includeOriginalReleaseYear: false, - includeReReleaseDate: false, - includeReReleaseYear: false); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(album)); } /// - /// Stubs the artist and library repositories so that the handler finds the artist and the library. + /// Stubs the artist and library repositories so that the handler finds the artist and its library. /// - /// The artist returned by the artist repository. - /// The Id of the media library returned by the library repository. - private void StubArtistAndLibrary(ArtistEntity artist, Guid libraryId) + /// The Id of the media library the artist belongs to. + /// The Id of the artist. + private void StubArtistAndLibrary(Guid libraryId, Guid artistId) { - _mockArtistRepository.GetByIdAsync(artist.Id, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) - .Returns(Result.From(artist)); + StubArtist(libraryId, artistId); LibraryEntity library = _libraryEntityFixture.Create(id: libraryId); - _mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: Arg.Any()) + _mockLibraryRepository.GetByIdAsync(libraryId, Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()) .Returns(Result.From(library)); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/RestoreTrack/RestoreTrackCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/RestoreTrack/RestoreTrackCommandHandlerTests.cs new file mode 100644 index 00000000..63ec1a53 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/RestoreTrack/RestoreTrackCommandHandlerTests.cs @@ -0,0 +1,389 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreTrackCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ITrackRepository _mockTrackRepository; + private readonly IAlbumRepository _mockAlbumRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly RestoreTrackCommandHandler _sut; + private readonly Guid _userId; + private readonly RestoreTrackCommandFixture _restoreTrackCommandFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public RestoreTrackCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockTrackRepository = Substitute.For(); + _mockAlbumRepository = Substitute.For(); + _mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository); + _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the restoration, restoring the deleted + // track succeeds, and saving changes succeeds. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockTrackRepository.RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(Result.Success); + + _sut = new RestoreTrackCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenDeletedTrackExists_ShouldRestoreTrackAndReturnUpdated() + { + // Arrange + RestoreTrackCommand command = _restoreTrackCommandFixture.Create(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); + TrackEntity track = MarkAsDeleted(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, includeMetadata: false)); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false); + _mockTrackRepository.GetSoftDeletedByIdAsync(trackId, Arg.Any()) + .Returns(Result.From(track)); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(album)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + await _mockTrackRepository.Received(1).RestoreSoftDeletedByIdAsync(trackId, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockTrackRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository() + { + // Arrange + RestoreTrackCommand command = _restoreTrackCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([DomainErrors.Music.TrackIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.TrackIdCannotBeEmpty, result.FirstError); + await _mockTrackRepository.DidNotReceive().GetSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockTrackRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + RestoreTrackCommand command = _restoreTrackCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockTrackRepository.DidNotReceive().GetSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockTrackRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTrackRepositoryFails_ShouldReturnFailureResultWithoutRestoring() + { + // Arrange + RestoreTrackCommand command = _restoreTrackCommandFixture.Create(); + _mockTrackRepository.GetSoftDeletedByIdAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockTrackRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDeletedTrackDoesNotExist_ShouldReturnTrackNotFoundError() + { + // Arrange + RestoreTrackCommand command = _restoreTrackCommandFixture.Create(); + _mockTrackRepository.GetSoftDeletedByIdAsync(Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.TrackNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockTrackRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTrackBelongsToAnotherLibrary_ShouldReturnTrackNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + RestoreTrackCommand command = _restoreTrackCommandFixture.Create(); + (_, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); + TrackEntity track = MarkAsDeleted(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: Guid.NewGuid(), includeMetadata: false)); + _mockTrackRepository.GetSoftDeletedByIdAsync(trackId, Arg.Any()) + .Returns(Result.From(track)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + // Resource scoping is enforced before authorization, and the mismatch is reported as not found, without disclosing that the track exists in another library. + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.TrackNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockTrackRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTrackBelongsToAnotherAlbum_ShouldReturnTrackNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + RestoreTrackCommand command = _restoreTrackCommandFixture.Create(); + (Guid libraryId, _, Guid albumId, Guid trackId) = GetCommandIds(command); + TrackEntity track = MarkAsDeleted(_trackEntityFixture.Create(id: trackId, albumId: Guid.NewGuid(), libraryId: libraryId, includeMetadata: false)); + _mockTrackRepository.GetSoftDeletedByIdAsync(trackId, Arg.Any()) + .Returns(Result.From(track)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + // Resource scoping is enforced before authorization, and the mismatch is reported as not found, without disclosing that the track exists under another album. + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.TrackNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockTrackRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + RestoreTrackCommand command = _restoreTrackCommandFixture.Create(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); + TrackEntity track = MarkAsDeleted(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, includeMetadata: false)); + _mockTrackRepository.GetSoftDeletedByIdAsync(trackId, Arg.Any()) + .Returns(Result.From(track)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockTrackRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumRepositoryFails_ShouldReturnFailureResultWithoutRestoring() + { + // Arrange + RestoreTrackCommand command = _restoreTrackCommandFixture.Create(); + (Guid libraryId, _, Guid albumId, Guid trackId) = GetCommandIds(command); + TrackEntity track = MarkAsDeleted(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, includeMetadata: false)); + _mockTrackRepository.GetSoftDeletedByIdAsync(trackId, Arg.Any()) + .Returns(Result.From(track)); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockTrackRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumDoesNotExist_ShouldReturnTrackNotFoundError() + { + // Arrange + RestoreTrackCommand command = _restoreTrackCommandFixture.Create(); + (Guid libraryId, _, Guid albumId, Guid trackId) = GetCommandIds(command); + TrackEntity track = MarkAsDeleted(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, includeMetadata: false)); + _mockTrackRepository.GetSoftDeletedByIdAsync(trackId, Arg.Any()) + .Returns(Result.From(track)); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + // The deleted track is only restorable while its album is visible, so a missing album is reported as a missing track. + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.TrackNotFound, result.FirstError); + await _mockTrackRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumBelongsToAnotherArtist_ShouldReturnTrackNotFoundError() + { + // Arrange + RestoreTrackCommand command = _restoreTrackCommandFixture.Create(); + (Guid libraryId, _, Guid albumId, Guid trackId) = GetCommandIds(command); + TrackEntity track = MarkAsDeleted(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, includeMetadata: false)); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: Guid.NewGuid(), libraryId: libraryId, includeTracks: false); + _mockTrackRepository.GetSoftDeletedByIdAsync(trackId, Arg.Any()) + .Returns(Result.From(track)); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(album)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.TrackNotFound, result.FirstError); + await _mockTrackRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenRestoreFails_ShouldReturnErrorWithoutSaving() + { + // Arrange + RestoreTrackCommand command = _restoreTrackCommandFixture.Create(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); + TrackEntity track = MarkAsDeleted(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, includeMetadata: false)); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false); + _mockTrackRepository.GetSoftDeletedByIdAsync(trackId, Arg.Any()) + .Returns(Result.From(track)); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(album)); + _mockTrackRepository.RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockTrackRepository.Received(1).RestoreSoftDeletedByIdAsync(trackId, Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnError() + { + // Arrange + RestoreTrackCommand command = _restoreTrackCommandFixture.Create(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); + TrackEntity track = MarkAsDeleted(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, includeMetadata: false)); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false); + _mockTrackRepository.GetSoftDeletedByIdAsync(trackId, Arg.Any()) + .Returns(Result.From(track)); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(album)); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockTrackRepository.Received(1).RestoreSoftDeletedByIdAsync(trackId, Arg.Any()); + } + + /// + /// Extracts the parsed identifiers carried by . + /// + /// The command whose route identifiers are extracted. + /// The parsed library, artist, album and track identifiers. + private static (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) GetCommandIds(RestoreTrackCommand command) + { + return ( + Guid.Parse(command.LibraryId!), + Guid.Parse(command.ArtistId!), + Guid.Parse(command.AlbumId!), + Guid.Parse(command.TrackId!)); + } + + /// + /// Marks as soft deleted, the way the track repository returns it to the restore handler. + /// + /// The track to mark as soft deleted. + /// The same instance, marked as soft deleted. + private static TrackEntity MarkAsDeleted(TrackEntity track) + { + track.IsDeleted = true; + track.DeletedOnUtc = DateTime.UtcNow; + return track; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/RestoreTrack/RestoreTrackCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/RestoreTrack/RestoreTrackCommandValidatorTests.cs new file mode 100644 index 00000000..bf4da2e5 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/RestoreTrack/RestoreTrackCommandValidatorTests.cs @@ -0,0 +1,159 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreTrackCommandValidatorTests +{ + private readonly RestoreTrackCommandFixture _restoreTrackCommandFixture = new(); + private readonly RestoreTrackCommandValidator _validator = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + RestoreTrackCommand command = _restoreTrackCommandFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-artist-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId) + { + // Arrange + RestoreTrackCommand command = _restoreTrackCommandFixture.Create(artistId: artistId, includeArtistId: artistId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-album-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenAlbumIdIsEmptyOrInvalid_ShouldHaveValidationError(string? albumId) + { + // Arrange + RestoreTrackCommand command = _restoreTrackCommandFixture.Create(albumId: albumId, includeAlbumId: albumId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-track-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenTrackIdIsEmptyOrInvalid_ShouldHaveValidationError(string? trackId) + { + // Arrange + RestoreTrackCommand command = _restoreTrackCommandFixture.Create(trackId: trackId, includeTrackId: trackId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + RestoreTrackCommand command = _restoreTrackCommandFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + RestoreTrackCommand command = _restoreTrackCommandFixture.Create(artistId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + RestoreTrackCommand command = _restoreTrackCommandFixture.Create(albumId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + RestoreTrackCommand command = _restoreTrackCommandFixture.Create(trackId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + RestoreTrackCommand command = _restoreTrackCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetDeletedTracks/GetDeletedTracksQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetDeletedTracks/GetDeletedTracksQueryHandlerTests.cs new file mode 100644 index 00000000..7869f5d4 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetDeletedTracks/GetDeletedTracksQueryHandlerTests.cs @@ -0,0 +1,196 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedTracksQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ITrackRepository _mockTrackRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly GetDeletedTracksQueryHandler _sut; + private readonly Guid _userId; + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly GetDeletedTracksQueryFixture _getDeletedTracksQueryFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetDeletedTracksQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockTrackRepository = Substitute.For(); + _mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the query is valid, the current user is authenticated, the library ownership policy allows access and there are no deleted tracks. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockTrackRepository.GetSoftDeletedByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + + _sut = new GetDeletedTracksQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenDeletedTracksExist_ShouldReturnTheirMappedResponses() + { + // Arrange + GetDeletedTracksQuery query = _getDeletedTracksQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + DateTime firstDeletedOnUtc = new(2026, 3, 10, 9, 15, 0, DateTimeKind.Utc); + AlbumEntity firstAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false); + ArtistEntity firstArtist = _artistEntityFixture.Create(id: firstAlbum.ArtistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + firstAlbum.Artist = firstArtist; + TrackEntity firstTrack = _trackEntityFixture.Create(albumId: firstAlbum.Id, libraryId: libraryId, includeMetadata: false); + firstTrack.IsDeleted = true; + firstTrack.DeletedOnUtc = firstDeletedOnUtc; + firstTrack.Album = firstAlbum; + AlbumEntity secondAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false); + ArtistEntity secondArtist = _artistEntityFixture.Create(id: secondAlbum.ArtistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + secondAlbum.Artist = secondArtist; + // A deleted track without a recorded deletion time falls back to its creation time, so the history never shows a default date. + TrackEntity secondTrack = _trackEntityFixture.Create(albumId: secondAlbum.Id, libraryId: libraryId, includeMetadata: false); + secondTrack.IsDeleted = true; + secondTrack.DeletedOnUtc = null; + secondTrack.Album = secondAlbum; + _mockTrackRepository.GetSoftDeletedByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([firstTrack, secondTrack])); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count); + Assert.Equal(firstTrack.Id, result.Value[0].Id); + Assert.Equal(firstTrack.LibraryId, result.Value[0].LibraryId); + Assert.Equal(firstArtist.Id, result.Value[0].ArtistId); + Assert.Equal(firstArtist.Name, result.Value[0].ArtistName); + Assert.Equal(firstAlbum.Id, result.Value[0].AlbumId); + Assert.Equal(firstAlbum.Title, result.Value[0].AlbumTitle); + Assert.Equal(firstTrack.Title, result.Value[0].Title); + Assert.Equal(firstTrack.Path, result.Value[0].Path); + Assert.Equal(firstDeletedOnUtc, result.Value[0].DeletedOnUtc); + Assert.Equal(secondTrack.Id, result.Value[1].Id); + Assert.Equal(secondTrack.CreatedOnUtc, result.Value[1].DeletedOnUtc); + } + + [Fact] + public async Task HandleAsync_WhenThereAreNoDeletedTracks_ShouldReturnAnEmptyCollection() + { + // Arrange + GetDeletedTracksQuery query = _getDeletedTracksQueryFixture.Create(); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository() + { + // Arrange + GetDeletedTracksQuery query = _getDeletedTracksQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([DomainErrors.Library.LibraryIdCannotBeEmpty]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockTrackRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetDeletedTracksQuery query = _getDeletedTracksQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockTrackRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + GetDeletedTracksQuery query = _getDeletedTracksQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockTrackRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTrackRepositoryFails_ShouldReturnFailureResult() + { + // Arrange + GetDeletedTracksQuery query = _getDeletedTracksQueryFixture.Create(); + _mockTrackRepository.GetSoftDeletedByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetDeletedTracks/GetDeletedTracksQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetDeletedTracks/GetDeletedTracksQueryValidatorTests.cs new file mode 100644 index 00000000..94fdc207 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetDeletedTracks/GetDeletedTracksQueryValidatorTests.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedTracksQueryValidatorTests +{ + private readonly GetDeletedTracksQueryFixture _getDeletedTracksQueryFixture = new(); + private readonly GetDeletedTracksQueryValidator _validator = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + GetDeletedTracksQuery query = _getDeletedTracksQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetDeletedTracksQuery query = _getDeletedTracksQueryFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + GetDeletedTracksQuery query = _getDeletedTracksQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategyTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategyTests.cs index 8a96de2f..24715550 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategyTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategyTests.cs @@ -2,12 +2,15 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; using Lumina.Application.Core.MediaLibrary.Management.Deletion; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Microsoft.Extensions.Logging; using NSubstitute; using System; using System.Collections.Generic; @@ -29,10 +32,13 @@ public class MusicMediaLibraryItemDeletionStrategyTests private readonly IAlbumRepository _mockAlbumRepository; private readonly IArtistRepository _mockArtistRepository; private readonly IMusicArtworkRepository _mockMusicArtworkRepository; + private readonly IMusicArtworkService _mockMusicArtworkService; + private readonly ILogger _mockLogger; private readonly MusicMediaLibraryItemDeletionStrategy _sut; private readonly LibraryIdFixture _libraryIdFixture = new(); private readonly TrackEntityFixture _trackEntityFixture = new(); private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -44,12 +50,18 @@ public class MusicMediaLibraryItemDeletionStrategyTests _mockAlbumRepository = Substitute.For(); _mockArtistRepository = Substitute.For(); _mockMusicArtworkRepository = Substitute.For(); + _mockMusicArtworkService = Substitute.For(); + _mockLogger = Substitute.For>(); _mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository); _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); _mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository); + _mockMusicArtworkRepository.GetByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _mockMusicArtworkService.DeleteStoredArtwork(Arg.Any()) + .Returns(Result.Deleted); - _sut = new MusicMediaLibraryItemDeletionStrategy(_mockUnitOfWork); + _sut = new MusicMediaLibraryItemDeletionStrategy(_mockUnitOfWork, _mockMusicArtworkService, _mockLogger); } [Fact] @@ -67,9 +79,9 @@ public class MusicMediaLibraryItemDeletionStrategyTests .Returns(Result.Deleted); _mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any()) .Returns(Result.From(Result.Deleted)); - _mockAlbumRepository.GetByIdAsync(albumId, Arg.Any(), Arg.Any(), Arg.Any()) + _mockAlbumRepository.GetIncludingDeletedByIdAsync(albumId, Arg.Any()) .Returns(Result.From(album)); - _mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any()) + _mockTrackRepository.GetByAlbumIdIncludingDeletedAsync(albumId, Arg.Any()) .Returns(Result.From>([otherTrack])); _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); @@ -80,6 +92,11 @@ public class MusicMediaLibraryItemDeletionStrategyTests Assert.True(result.IsSuccess); await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any()); await _mockTrackRepository.Received(1).DeleteByIdAsync(track.Id, Arg.Any()); + // The album and its remaining tracks are read including the soft deleted ones, so a hidden track still keeps the album alive. + await _mockAlbumRepository.Received(1).GetIncludingDeletedByIdAsync(albumId, Arg.Any()); + await _mockTrackRepository.Received(1).GetByAlbumIdIncludingDeletedAsync(albumId, Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockTrackRepository.DidNotReceive().GetByAlbumIdAsync(Arg.Any(), Arg.Any()); await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(MusicArtworkOwnerType.Album, Arg.Any(), Arg.Any()); await _mockAlbumRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); @@ -102,15 +119,15 @@ public class MusicMediaLibraryItemDeletionStrategyTests .Returns(Result.Deleted); _mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any()) .Returns(Result.From(Result.Deleted)); - _mockAlbumRepository.GetByIdAsync(albumId, Arg.Any(), Arg.Any(), Arg.Any()) + _mockAlbumRepository.GetIncludingDeletedByIdAsync(albumId, Arg.Any()) .Returns(Result.From(album)); - _mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any()) + _mockTrackRepository.GetByAlbumIdIncludingDeletedAsync(albumId, Arg.Any()) .Returns(Result.From>([track])); _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) .Returns(Result.Deleted); _mockAlbumRepository.DeleteByIdAsync(albumId, Arg.Any()) .Returns(Result.From(Result.Deleted)); - _mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any()) + _mockAlbumRepository.GetByArtistIdIncludingDeletedAsync(artistId, Arg.Any()) .Returns(Result.From>([otherAlbum])); _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); @@ -121,6 +138,9 @@ public class MusicMediaLibraryItemDeletionStrategyTests Assert.True(result.IsSuccess); await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()); await _mockAlbumRepository.Received(1).DeleteByIdAsync(albumId, Arg.Any()); + // The remaining albums of the artist are read including the soft deleted ones, so a hidden album still keeps the artist alive. + await _mockAlbumRepository.Received(1).GetByArtistIdIncludingDeletedAsync(artistId, Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetByArtistIdAsync(Arg.Any(), Arg.Any()); await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, Arg.Any(), Arg.Any()); await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); @@ -141,15 +161,15 @@ public class MusicMediaLibraryItemDeletionStrategyTests .Returns(Result.Deleted); _mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any()) .Returns(Result.From(Result.Deleted)); - _mockAlbumRepository.GetByIdAsync(albumId, Arg.Any(), Arg.Any(), Arg.Any()) + _mockAlbumRepository.GetIncludingDeletedByIdAsync(albumId, Arg.Any()) .Returns(Result.From(album)); - _mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any()) + _mockTrackRepository.GetByAlbumIdIncludingDeletedAsync(albumId, Arg.Any()) .Returns(Result.From>([track])); _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) .Returns(Result.Deleted); _mockAlbumRepository.DeleteByIdAsync(albumId, Arg.Any()) .Returns(Result.From(Result.Deleted)); - _mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any()) + _mockAlbumRepository.GetByArtistIdIncludingDeletedAsync(artistId, Arg.Any()) .Returns(Result.From>([album])); _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any()) .Returns(Result.Deleted); @@ -166,9 +186,113 @@ public class MusicMediaLibraryItemDeletionStrategyTests await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any()); await _mockAlbumRepository.Received(1).DeleteByIdAsync(albumId, Arg.Any()); await _mockArtistRepository.Received(1).DeleteByIdAsync(artistId, Arg.Any()); + // Every scoping read includes the soft deleted rows, so hidden siblings are never missed when deciding what to remove. + await _mockAlbumRepository.Received(1).GetIncludingDeletedByIdAsync(albumId, Arg.Any()); + await _mockTrackRepository.Received(1).GetByAlbumIdIncludingDeletedAsync(albumId, Arg.Any()); + await _mockAlbumRepository.Received(1).GetByArtistIdIncludingDeletedAsync(artistId, Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } + [Fact] + public async Task DeleteItemAsync_WhenEveryItemHasStoredArtwork_ShouldDeleteEveryStoredFileAndRow() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + Guid albumId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/deleted.flac"); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, includeTracks: false); + MusicArtworkEntity trackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: track.Id, fileName: "/media/music/track-cover.jpg"); + MusicArtworkEntity albumArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, fileName: "/media/music/album-cover.jpg"); + MusicArtworkEntity artistArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artistId, fileName: "/media/music/artist-cover.jpg"); + _mockTrackRepository.GetByPathAsync(libraryId.Value, track.Path, Arg.Any()) + .Returns(Result.From(track)); + _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any()) + .Returns(Result.From>([trackArtwork])); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any()) + .Returns(Result.Deleted); + _mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockAlbumRepository.GetIncludingDeletedByIdAsync(albumId, Arg.Any()) + .Returns(Result.From(album)); + _mockTrackRepository.GetByAlbumIdIncludingDeletedAsync(albumId, Arg.Any()) + .Returns(Result.From>([track])); + _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) + .Returns(Result.From>([albumArtwork])); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) + .Returns(Result.Deleted); + _mockAlbumRepository.DeleteByIdAsync(albumId, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockAlbumRepository.GetByArtistIdIncludingDeletedAsync(artistId, Arg.Any()) + .Returns(Result.From>([album])); + _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any()) + .Returns(Result.From>([artistArtwork])); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any()) + .Returns(Result.Deleted); + _mockArtistRepository.DeleteByIdAsync(artistId, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + + // Act + Result result = await _sut.DeleteItemAsync(libraryId.Value, track.Path, CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + _mockMusicArtworkService.Received(1).DeleteStoredArtwork(trackArtwork.FileName!); + _mockMusicArtworkService.Received(1).DeleteStoredArtwork(albumArtwork.FileName!); + _mockMusicArtworkService.Received(1).DeleteStoredArtwork(artistArtwork.FileName!); + await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any()); + await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()); + await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any()); + } + + [Fact] + public async Task DeleteItemAsync_WhenDeletingAStoredArtworkFileFails_ShouldLogAWarningAndStillDeleteTheRow() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + Guid albumId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/deleted.flac"); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, includeTracks: false); + AlbumEntity otherAlbum = _albumEntityFixture.Create(artistId: artistId, includeTracks: false); + MusicArtworkEntity trackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: track.Id, fileName: "/media/music/track-cover.jpg"); + _mockTrackRepository.GetByPathAsync(libraryId.Value, track.Path, Arg.Any()) + .Returns(Result.From(track)); + _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any()) + .Returns(Result.From>([trackArtwork])); + _mockMusicArtworkService.DeleteStoredArtwork(trackArtwork.FileName!) + .Returns(Errors.FileSystemManagement.FileNotFound); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any()) + .Returns(Result.Deleted); + _mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockAlbumRepository.GetIncludingDeletedByIdAsync(albumId, Arg.Any()) + .Returns(Result.From(album)); + _mockTrackRepository.GetByAlbumIdIncludingDeletedAsync(albumId, Arg.Any()) + .Returns(Result.From>([track])); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) + .Returns(Result.Deleted); + _mockAlbumRepository.DeleteByIdAsync(albumId, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockAlbumRepository.GetByArtistIdIncludingDeletedAsync(artistId, Arg.Any()) + .Returns(Result.From>([otherAlbum])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + + // Act + Result result = await _sut.DeleteItemAsync(libraryId.Value, track.Path, CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any()); + _mockLogger.Received(1).Log( + LogLevel.Warning, + Arg.Any(), + Arg.Is(state => state.ToString()!.Contains("Failed to delete the stored")), + Arg.Any(), + Arg.Any>()); + } + [Fact] public async Task DeleteItemAsync_WhenAlbumWasAlreadyRemoved_ShouldPersistTheTrackDeletion() { @@ -182,7 +306,7 @@ public class MusicMediaLibraryItemDeletionStrategyTests .Returns(Result.Deleted); _mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any()) .Returns(Result.From(Result.Deleted)); - _mockAlbumRepository.GetByIdAsync(albumId, Arg.Any(), Arg.Any(), Arg.Any()) + _mockAlbumRepository.GetIncludingDeletedByIdAsync(albumId, Arg.Any()) .Returns(Result.From(null)); _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); @@ -192,6 +316,8 @@ public class MusicMediaLibraryItemDeletionStrategyTests // Assert Assert.True(result.IsSuccess); await _mockTrackRepository.Received(1).DeleteByIdAsync(track.Id, Arg.Any()); + // A soft deleted album is still read, because its own tracks have to keep it alive until their files disappear too. + await _mockAlbumRepository.Received(1).GetIncludingDeletedByIdAsync(albumId, Arg.Any()); await _mockAlbumRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -271,9 +397,9 @@ public class MusicMediaLibraryItemDeletionStrategyTests .Returns(Result.Deleted); _mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any()) .Returns(Result.From(Result.Deleted)); - _mockAlbumRepository.GetByIdAsync(albumId, Arg.Any(), Arg.Any(), Arg.Any()) + _mockAlbumRepository.GetIncludingDeletedByIdAsync(albumId, Arg.Any()) .Returns(Result.From(album)); - _mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any()) + _mockTrackRepository.GetByAlbumIdIncludingDeletedAsync(albumId, Arg.Any()) .Returns(Result.From>([track])); _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) .Returns(error); @@ -304,15 +430,15 @@ public class MusicMediaLibraryItemDeletionStrategyTests .Returns(Result.Deleted); _mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any()) .Returns(Result.From(Result.Deleted)); - _mockAlbumRepository.GetByIdAsync(albumId, Arg.Any(), Arg.Any(), Arg.Any()) + _mockAlbumRepository.GetIncludingDeletedByIdAsync(albumId, Arg.Any()) .Returns(Result.From(album)); - _mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any()) + _mockTrackRepository.GetByAlbumIdIncludingDeletedAsync(albumId, Arg.Any()) .Returns(Result.From>([track])); _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) .Returns(Result.Deleted); _mockAlbumRepository.DeleteByIdAsync(albumId, Arg.Any()) .Returns(Result.From(Result.Deleted)); - _mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any()) + _mockAlbumRepository.GetByArtistIdIncludingDeletedAsync(artistId, Arg.Any()) .Returns(Result.From>([album])); _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any()) .Returns(error); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandlerTests.cs index 9513bdcd..d58fcdfa 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandlerTests.cs @@ -79,8 +79,8 @@ public class LibraryDeletedDomainEventHandlerTests // default stubs: all path combinations succeed, segments are sanitized to their input, the library directories exist and they are deleted successfully _mockPathService.CombinePath(Arg.Any(), Arg.Any()) .Returns(callInfo => Result.From(string.Concat(callInfo.ArgAt(0), callInfo.ArgAt(1)))); - _mockPathService.SanitizeSegment(Arg.Any()) - .Returns(callInfo => PathSegment.Create(callInfo.ArgAt(0), isDirectory: false, isDrive: false)); + _mockPathService.SanitizeCompositeSegment(Arg.Any(), Arg.Any()) + .Returns(callInfo => PathSegment.Create($"{callInfo.ArgAt(0)}-{callInfo.ArgAt(1)}", isDirectory: false, isDrive: false)); _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(Result.From(true)); _mockDirectoryProviderService.DeleteDirectory(Arg.Any()).Returns(Result.Deleted); @@ -234,14 +234,14 @@ public class LibraryDeletedDomainEventHandlerTests } [Fact] - public async Task HandleAsync_WhenSanitizeSegmentFails_ShouldThrowEventualConsistencyExceptionWithoutDeletingItemDirectories() + public async Task HandleAsync_WhenSanitizeCompositeSegmentFails_ShouldThrowEventualConsistencyExceptionWithoutDeletingItemDirectories() { // Arrange Guid libraryId = Guid.NewGuid(); Library library = _libraryFixture.Create(id: libraryId); LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library); Error error = Error.Failure(description: "Failed to sanitize segment"); - _mockPathService.SanitizeSegment(Arg.Any()).Returns(error); + _mockPathService.SanitizeCompositeSegment(Arg.Any(), Arg.Any()).Returns(error); // Act EventualConsistencyException exception = await Assert.ThrowsAsync( @@ -274,7 +274,7 @@ public class LibraryDeletedDomainEventHandlerTests await _sut.HandleAsync(domainEvent, CancellationToken.None); // Assert - _mockPathService.Received(1).SanitizeSegment(librarySegment); + _mockPathService.Received(1).SanitizeCompositeSegment(libraryTitle, libraryId.ToString()); _mockDirectoryProviderService.Received(1).DeleteDirectory(Arg.Is(path => path.Path == expectedLibrariesPath)); _mockDirectoryProviderService.Received(1).DeleteDirectory(Arg.Is(path => path.Path == expectedBooksPath)); _mockDirectoryProviderService.Received(1).DeleteDirectory(Arg.Is(path => path.Path == expectedMusicPath)); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/AlbumRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/AlbumRepositoryTests.cs index c015aae5..d747c8c7 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/AlbumRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/AlbumRepositoryTests.cs @@ -5,6 +5,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.Mu using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums; using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Application.Fixtures.Common.DTO.Pagination; @@ -36,6 +37,7 @@ public class AlbumRepositoryTests { private readonly LuminaDbContext _mockContext; private readonly ITrackRepository _mockTrackRepository; + private readonly IDateTimeProvider _mockDateTimeProvider; private readonly AlbumRepository _sut; private readonly AlbumEntityFixture _albumEntityFixture = new(); private readonly TrackEntityFixture _trackEntityFixture = new(); @@ -61,7 +63,9 @@ public class AlbumRepositoryTests _mockTrackRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); _mockTrackRepository.GetExistingPathsAsync(Arg.Any(), Arg.Any>(), Arg.Any()) .Returns(Result.From>([])); - _sut = new AlbumRepository(_mockContext, _mockTrackRepository); + _mockDateTimeProvider = Substitute.For(); + _mockDateTimeProvider.UtcNow.Returns(new DateTime(2026, 11, 14, 10, 30, 0, DateTimeKind.Utc)); + _sut = new AlbumRepository(_mockContext, _mockTrackRepository, _mockDateTimeProvider); } [Fact] @@ -270,6 +274,7 @@ public class AlbumRepositoryTests { // Arrange AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(storedAlbum); _mockContext.Albums.Add(storedAlbum); await _mockContext.SaveChangesAsync(); @@ -297,6 +302,7 @@ public class AlbumRepositoryTests Guid storedArtistId = Guid.NewGuid(); Guid storedLibraryId = Guid.NewGuid(); AlbumEntity storedAlbum = _albumEntityFixture.Create(artistId: storedArtistId, libraryId: storedLibraryId, includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(storedArtistId, storedLibraryId); _mockContext.Albums.Add(storedAlbum); await _mockContext.SaveChangesAsync(); @@ -328,6 +334,7 @@ public class AlbumRepositoryTests storedAlbum.CreatedBy = storedCreatedBy; storedAlbum.UpdatedOnUtc = null; storedAlbum.UpdatedBy = null; + await SeedVisibleArtistAsync(storedAlbum); _mockContext.Albums.Add(storedAlbum); await _mockContext.SaveChangesAsync(); @@ -365,6 +372,7 @@ public class AlbumRepositoryTests _audioRatingEntityFixture.Create(value: 5, maxValue: 5, source: AudioRatingSource.User, voteCount: 10), _audioRatingEntityFixture.Create(value: 2, maxValue: 5, source: AudioRatingSource.LastFm, voteCount: 20) ]; + await SeedVisibleArtistAsync(storedAlbum); _mockContext.Albums.Add(storedAlbum); await _mockContext.SaveChangesAsync(); @@ -402,6 +410,7 @@ public class AlbumRepositoryTests AlbumContributorEntity keptContributor = _albumContributorEntityFixture.Create( albumId: storedAlbum.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer); storedAlbum.Contributors = [keptContributor]; + await SeedVisibleArtistAsync(storedAlbum); _mockContext.Albums.Add(storedAlbum); await _mockContext.SaveChangesAsync(); @@ -437,6 +446,7 @@ public class AlbumRepositoryTests AlbumContributorEntity removedContributor = _albumContributorEntityFixture.Create( albumId: storedAlbum.Id, mediaContributorId: removedMediaContributorId, role: MediaContributorRole.Composer); storedAlbum.Contributors = [keptContributor, removedContributor]; + await SeedVisibleArtistAsync(storedAlbum); _mockContext.Albums.Add(storedAlbum); await _mockContext.SaveChangesAsync(); @@ -474,6 +484,7 @@ public class AlbumRepositoryTests AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); storedAlbum.Tags = [existingTag]; storedAlbum.Genres = [existingGenre]; + await SeedVisibleArtistAsync(storedAlbum); _mockContext.Albums.Add(storedAlbum); await _mockContext.SaveChangesAsync(); @@ -506,6 +517,7 @@ public class AlbumRepositoryTests { // Arrange AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false, catalogNumbers: ["EMC 3006", "OC 062 o 94519"]); + await SeedVisibleArtistAsync(storedAlbum); _mockContext.Albums.Add(storedAlbum); await _mockContext.SaveChangesAsync(); @@ -532,6 +544,7 @@ public class AlbumRepositoryTests { // Arrange AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(album); _mockContext.Albums.Add(album); await _mockContext.SaveChangesAsync(); @@ -595,6 +608,8 @@ public class AlbumRepositoryTests AlbumEntity secondAlphaAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Alpha", includeTracks: false, includeMetadata: false); AlbumEntity firstAlphaAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Alpha", includeTracks: false, includeMetadata: false); AlbumEntity albumOfAnotherArtist = _albumEntityFixture.Create(title: "Gamma", includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(artistId, betaAlbum.LibraryId); + await SeedVisibleArtistAsync(albumOfAnotherArtist); _mockContext.Albums.AddRange(betaAlbum, secondAlphaAlbum, firstAlphaAlbum, albumOfAnotherArtist); await _mockContext.SaveChangesAsync(); @@ -646,6 +661,8 @@ public class AlbumRepositoryTests AlbumEntity secondAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Album B", includeTracks: false, includeMetadata: false); AlbumEntity firstAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Album A", includeTracks: false, includeMetadata: false); AlbumEntity albumOfAnotherArtist = _albumEntityFixture.Create(title: "Album C", includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(artistId, secondAlbum.LibraryId); + await SeedVisibleArtistAsync(albumOfAnotherArtist); _mockContext.Albums.AddRange(secondAlbum, firstAlbum, albumOfAnotherArtist); await _mockContext.SaveChangesAsync(); @@ -679,6 +696,7 @@ public class AlbumRepositoryTests albums[index].Title = $"Album {index}"; albums[index].Tracks = []; } + await SeedVisibleArtistAsync(artistId, albums[0].LibraryId); _mockContext.Albums.AddRange(albums); await _mockContext.SaveChangesAsync(); @@ -704,6 +722,8 @@ public class AlbumRepositoryTests Guid artistId = Guid.NewGuid(); AlbumEntity albumOfArtist = _albumEntityFixture.Create(artistId: artistId, includeTracks: false, includeMetadata: false); AlbumEntity albumOfAnotherArtist = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(artistId, albumOfArtist.LibraryId); + await SeedVisibleArtistAsync(albumOfAnotherArtist); _mockContext.Albums.AddRange(albumOfArtist, albumOfAnotherArtist); await _mockContext.SaveChangesAsync(); @@ -726,6 +746,7 @@ public class AlbumRepositoryTests Guid artistId = Guid.NewGuid(); AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false); album.TotalTracks = 12; + await SeedVisibleArtistAsync(album); _mockContext.Albums.Add(album); await _mockContext.SaveChangesAsync(); @@ -749,6 +770,7 @@ public class AlbumRepositoryTests Guid artistId = Guid.NewGuid(); AlbumEntity album = _albumEntityFixture.Create( artistId: artistId, originalReleaseYear: 1975, reReleaseYear: 2011, includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(album); _mockContext.Albums.Add(album); await _mockContext.SaveChangesAsync(); @@ -770,6 +792,7 @@ public class AlbumRepositoryTests Guid artistId = Guid.NewGuid(); AlbumEntity album = _albumEntityFixture.Create( artistId: artistId, originalReleaseYear: 1975, includeReReleaseYear: false, includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(album); _mockContext.Albums.Add(album); await _mockContext.SaveChangesAsync(); @@ -791,6 +814,7 @@ public class AlbumRepositoryTests Guid artistId = Guid.NewGuid(); AlbumEntity album = _albumEntityFixture.Create( artistId: artistId, releaseType: MusicReleaseType.Single, includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(album); _mockContext.Albums.Add(album); await _mockContext.SaveChangesAsync(); @@ -812,6 +836,7 @@ public class AlbumRepositoryTests // Arrange Guid artistId = Guid.NewGuid(); AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(album); _mockContext.Albums.Add(album); _mockContext.MusicArtwork.Add( _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: album.Id, artworkType: ArtworkType.Cover, fileName: "covers/opera.jpg")); @@ -834,6 +859,7 @@ public class AlbumRepositoryTests // Arrange Guid artistId = Guid.NewGuid(); AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(album); _mockContext.Albums.Add(album); await _mockContext.SaveChangesAsync(); @@ -857,6 +883,10 @@ public class AlbumRepositoryTests AlbumEntity failedAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false, metadataStatus: MetadataStatus.Failed); AlbumEntity enrichedAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false, metadataStatus: MetadataStatus.Enriched); AlbumEntity albumOfAnotherLibrary = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false, metadataStatus: MetadataStatus.Pending); + await SeedVisibleArtistAsync(pendingAlbum); + await SeedVisibleArtistAsync(failedAlbum); + await SeedVisibleArtistAsync(enrichedAlbum); + await SeedVisibleArtistAsync(albumOfAnotherLibrary); _mockContext.Albums.AddRange(pendingAlbum, failedAlbum, enrichedAlbum, albumOfAnotherLibrary); await _mockContext.SaveChangesAsync(); @@ -868,6 +898,550 @@ public class AlbumRepositoryTests Assert.Equal(2, result.Value); } + [Fact] + public async Task GetByIdAsync_WhenAlbumIsSoftDeleted_ShouldReturnNull() + { + // Arrange + AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(album); + album.IsDeleted = true; + album.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Albums.Add(album); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByIdAsync(album.Id, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetByIdAsync_WhenItsArtistIsSoftDeleted_ShouldReturnNull() + { + // Arrange + AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + ArtistEntity artist = await SeedVisibleArtistAsync(album); + artist.IsDeleted = true; + artist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Albums.Add(album); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByIdAsync(album.Id, cancellationToken: CancellationToken.None); + + // Assert + // A deleted artist hides every album it owns, because the albums are only reachable through it. + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetByArtistIdAsync_WhenAnAlbumIsSoftDeleted_ShouldExcludeIt() + { + // Arrange + Guid artistId = Guid.NewGuid(); + AlbumEntity activeAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Active", includeTracks: false, includeMetadata: false); + AlbumEntity deletedAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Deleted", includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(artistId, activeAlbum.LibraryId); + deletedAlbum.IsDeleted = true; + deletedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Albums.AddRange(activeAlbum, deletedAlbum); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetByArtistIdAsync(artistId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(activeAlbum.Id, Assert.Single(result.Value).Id); + } + + [Fact] + public async Task GetByArtistIdAsync_WhenTheArtistIsSoftDeleted_ShouldReturnEmpty() + { + // Arrange + Guid artistId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, includeTracks: false, includeMetadata: false); + ArtistEntity artist = await SeedVisibleArtistAsync(artistId, album.LibraryId); + artist.IsDeleted = true; + artist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Albums.Add(album); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetByArtistIdAsync(artistId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task GetByArtistIdIncludingDeletedAsync_WhenCalled_ShouldReturnEveryAlbumOfTheArtistOrderedByTitleThenId() + { + // Arrange + Guid artistId = Guid.NewGuid(); + AlbumEntity betaAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Beta", includeTracks: false, includeMetadata: false); + AlbumEntity deletedAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Alpha", includeTracks: false, includeMetadata: false); + AlbumEntity albumOfAnotherArtist = _albumEntityFixture.Create(title: "Gamma", includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(artistId, betaAlbum.LibraryId); + await SeedVisibleArtistAsync(albumOfAnotherArtist); + deletedAlbum.IsDeleted = true; + deletedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Albums.AddRange(betaAlbum, deletedAlbum, albumOfAnotherArtist); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetByArtistIdIncludingDeletedAsync(artistId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal([deletedAlbum.Id, betaAlbum.Id], result.Value.Select(album => album.Id)); + } + + [Fact] + public async Task GetIncludingDeletedByIdAsync_WhenAlbumIsSoftDeleted_ShouldReturnIt() + { + // Arrange + AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(album); + album.IsDeleted = true; + album.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Albums.Add(album); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetIncludingDeletedByIdAsync(album.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(album.Id, result.Value!.Id); + Assert.True(result.Value.IsDeleted); + } + + [Fact] + public async Task GetIncludingDeletedByIdAsync_WhenAlbumDoesNotExist_ShouldReturnNull() + { + // Act + Result result = await _sut.GetIncludingDeletedByIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetAlbumsLiteByArtistIdAsync_WhenAnAlbumIsSoftDeleted_ShouldExcludeIt() + { + // Arrange + Guid artistId = Guid.NewGuid(); + AlbumEntity activeAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Active", includeTracks: false, includeMetadata: false); + AlbumEntity deletedAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Deleted", includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(artistId, activeAlbum.LibraryId); + deletedAlbum.IsDeleted = true; + deletedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Albums.AddRange(activeAlbum, deletedAlbum); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetAlbumsLiteByArtistIdAsync(artistId, null, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(activeAlbum.Id, Assert.Single(result.Value.Data).Id); + } + + [Fact] + public async Task GetByTitleAsync_WhenAlbumIsSoftDeleted_ShouldReturnNull() + { + // Arrange + Guid artistId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(artistId, album.LibraryId); + album.IsDeleted = true; + album.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Albums.Add(album); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByTitleAsync(artistId, "A Night at the Opera", CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetByTitleAsync_WhenItsArtistIsSoftDeleted_ShouldReturnNull() + { + // Arrange + Guid artistId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false); + ArtistEntity artist = await SeedVisibleArtistAsync(artistId, album.LibraryId); + artist.IsDeleted = true; + artist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Albums.Add(album); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByTitleAsync(artistId, "A Night at the Opera", CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetByTrackDirectoryAsync_WhenAlbumIsSoftDeleted_ShouldReturnNull() + { + // Arrange + Guid artistId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, includeTracks: false, includeMetadata: false); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, path: "/music/queen/a-night-at-the-opera/bohemian-rhapsody.flac", includeMetadata: false); + album.Tracks = [track]; + await SeedVisibleArtistAsync(artistId, album.LibraryId); + album.IsDeleted = true; + album.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Albums.Add(album); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByTrackDirectoryAsync(artistId, "/music/queen/a-night-at-the-opera", CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetSoftDeletedByIdAsync_WhenAlbumIsDeleted_ShouldReturnIt() + { + // Arrange + AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(album); + album.IsDeleted = true; + album.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Albums.Add(album); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetSoftDeletedByIdAsync(album.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(album.Id, result.Value!.Id); + } + + [Fact] + public async Task GetSoftDeletedByIdAsync_WhenItsArtistIsDeleted_ShouldReturnNull() + { + // Arrange + AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + ArtistEntity artist = await SeedVisibleArtistAsync(album); + artist.IsDeleted = true; + artist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + album.IsDeleted = true; + album.DeletedOnUtc = DateTime.UtcNow.AddHours(-2); + _mockContext.Albums.Add(album); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetSoftDeletedByIdAsync(album.Id, CancellationToken.None); + + // Assert + // A deleted artist hides its own deleted albums from the deleted items page, so the album is not offered for a restore that would stay hidden. + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetSoftDeletedByIdAsync_WhenAlbumIsNotDeleted_ShouldReturnNull() + { + // Arrange + AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(album); + _mockContext.Albums.Add(album); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetSoftDeletedByIdAsync(album.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetSoftDeletedByLibraryIdAsync_WhenCalled_ShouldReturnOnlyTheDeletedAlbumsOfVisibleArtists() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AlbumEntity deletedAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false); + ArtistEntity visibleArtist = await SeedVisibleArtistAsync(deletedAlbum); + AlbumEntity deletedAlbumOfDeletedArtist = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false); + ArtistEntity deletedArtist = await SeedVisibleArtistAsync(deletedAlbumOfDeletedArtist); + AlbumEntity activeAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(activeAlbum); + deletedAlbum.IsDeleted = true; + deletedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + deletedAlbumOfDeletedArtist.IsDeleted = true; + deletedAlbumOfDeletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-2); + deletedArtist.IsDeleted = true; + deletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-3); + _mockContext.Albums.AddRange(deletedAlbum, deletedAlbumOfDeletedArtist, activeAlbum); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetSoftDeletedByLibraryIdAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(deletedAlbum.Id, Assert.Single(result.Value).Id); + } + + [Fact] + public async Task GetSoftDeletedByLibraryIdAsync_WhenCalled_ShouldOrderByTheStoredDeletionTimeThenTitleAndId() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + DateTime deletedOnUtc = new(2026, 11, 14, 10, 0, 0, DateTimeKind.Utc); + AlbumEntity olderDeletion = _albumEntityFixture.Create(libraryId: libraryId, title: "Beta", includeTracks: false, includeMetadata: false); + AlbumEntity newerDeletion = _albumEntityFixture.Create(libraryId: libraryId, title: "Alpha", includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(olderDeletion); + await SeedVisibleArtistAsync(newerDeletion); + olderDeletion.IsDeleted = true; + olderDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-2); + olderDeletion.UpdatedOnUtc = deletedOnUtc; + newerDeletion.IsDeleted = true; + newerDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-1); + newerDeletion.UpdatedOnUtc = deletedOnUtc.AddDays(-5); + _mockContext.Albums.AddRange(olderDeletion, newerDeletion); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetSoftDeletedByLibraryIdAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal([newerDeletion.Id, olderDeletion.Id], result.Value.Select(album => album.Id)); + } + + [Fact] + public async Task RestoreSoftDeletedByIdAsync_WhenCalled_ShouldClearTheDeletionStateAndTime() + { + // Arrange + AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(album); + album.IsDeleted = true; + album.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Albums.Add(album); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.RestoreSoftDeletedByIdAsync(album.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.False(album.IsDeleted); + Assert.Null(album.DeletedOnUtc); + } + + [Fact] + public async Task RestoreSoftDeletedByIdAsync_WhenAlbumIsNotDeleted_ShouldReturnAlbumNotFound() + { + // Arrange + AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(album); + _mockContext.Albums.Add(album); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.RestoreSoftDeletedByIdAsync(album.Id, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + } + + [Fact] + public async Task RestoreSoftDeletedByIdAsync_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFound() + { + // Act + Result result = await _sut.RestoreSoftDeletedByIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + } + + [Fact] + public async Task UpdateAsync_WhenAlbumIsSoftDeleted_ShouldReturnAlbumNotFound() + { + // Arrange + AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(storedAlbum); + storedAlbum.IsDeleted = true; + storedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Albums.Add(storedAlbum); + await _mockContext.SaveChangesAsync(); + + AlbumEntity data = _albumEntityFixture.Create(id: storedAlbum.Id, includeTracks: false, includeMetadata: false); + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + } + + [Fact] + public async Task UpdateAsync_WhenItsArtistIsSoftDeleted_ShouldReturnAlbumNotFound() + { + // Arrange + AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + ArtistEntity artist = await SeedVisibleArtistAsync(storedAlbum); + artist.IsDeleted = true; + artist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Albums.Add(storedAlbum); + await _mockContext.SaveChangesAsync(); + + AlbumEntity data = _albumEntityFixture.Create(id: storedAlbum.Id, includeTracks: false, includeMetadata: false); + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + } + + [Fact] + public async Task UpdateAsync_WhenIncomingDeletionStateDiffers_ShouldPreserveTheActiveStateAndClearItsModifiedFlags() + { + // Arrange + AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(storedAlbum); + _mockContext.Albums.Add(storedAlbum); + await _mockContext.SaveChangesAsync(); + + AlbumEntity data = _albumEntityFixture.Create(id: storedAlbum.Id, includeTracks: false, includeMetadata: false); + data.Title = "A Night at the Opera"; + data.IsDeleted = true; + data.DeletedOnUtc = DateTime.UtcNow; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + EntityEntry entry = _mockContext.Entry(storedAlbum); + Assert.False(storedAlbum.IsDeleted); + Assert.Null(storedAlbum.DeletedOnUtc); + Assert.False(entry.Property(album => album.IsDeleted).IsModified); + Assert.False(entry.Property(album => album.DeletedOnUtc).IsModified); + } + + [Fact] + public async Task GetAlbumsNeedingMetadataCountAsync_WhenAnAlbumIsSoftDeleted_ShouldNotCountIt() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AlbumEntity pendingAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false, metadataStatus: MetadataStatus.Pending); + AlbumEntity deletedAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false, metadataStatus: MetadataStatus.Pending); + await SeedVisibleArtistAsync(pendingAlbum); + await SeedVisibleArtistAsync(deletedAlbum); + deletedAlbum.IsDeleted = true; + deletedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Albums.AddRange(pendingAlbum, deletedAlbum); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetAlbumsNeedingMetadataCountAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(1, result.Value); + } + + [Fact] + public async Task GetFirstTrackPathsByAlbumIdsAsync_WhenTheOnlyTrackIsSoftDeleted_ShouldNotReturnItsPath() + { + // Arrange + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(album); + TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: albumId, libraryId: album.LibraryId, path: "/music/queen/deleted.flac", includeMetadata: false); + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + album.Tracks = [deletedTrack]; + _mockContext.Albums.Add(album); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetFirstTrackPathsByAlbumIdsAsync([albumId], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task GetAlbumsNeedingArtworkCountAsync_WhenAnAlbumIsSoftDeleted_ShouldNotCountIt() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AlbumEntity activeAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false); + AlbumEntity deletedAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false); + await SeedVisibleArtistAsync(activeAlbum); + await SeedVisibleArtistAsync(deletedAlbum); + deletedAlbum.IsDeleted = true; + deletedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Albums.AddRange(activeAlbum, deletedAlbum); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetAlbumsNeedingArtworkCountAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(1, result.Value); + } + + /// + /// Seeds an artist with the identity of the provided album, so that the album is part of a visible catalogue and its ancestor filters pass. + /// + /// The album whose artist is seeded. + /// The persisted artist. + private Task SeedVisibleArtistAsync(AlbumEntity album) + { + return SeedVisibleArtistAsync(album.ArtistId, album.LibraryId); + } + + /// + /// Seeds the artist identified by , unless it is already stored, so that the albums owned by it are part of a visible catalogue. + /// + /// The Id of the artist to seed. + /// The Id of the library that owns the artist. + /// The persisted artist. + private async Task SeedVisibleArtistAsync(Guid artistId, Guid libraryId) + { + ArtistEntity? artist = await _mockContext.Artists.FirstOrDefaultAsync(candidate => candidate.Id == artistId); + if (artist is null) + { + artist = _artistEntityFixture.Create( + id: artistId, + libraryId: libraryId, + includeAlbums: false, + includeContributors: false); + _mockContext.Artists.Add(artist); + await _mockContext.SaveChangesAsync(); + } + return artist; + } + /// /// Creates an album that belongs to the artist identified by , with every related collection populated deterministically. /// diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/ArtistRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/ArtistRepositoryTests.cs index 6b22bd1f..7675753f 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/ArtistRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/ArtistRepositoryTests.cs @@ -5,6 +5,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.Mu using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists; using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Application.Fixtures.Common.DTO.Filtering; @@ -19,6 +20,7 @@ using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; +using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -36,6 +38,7 @@ namespace Lumina.DataAccess.UnitTests.Core.Repositories.MusicLibrary; public class ArtistRepositoryTests { private readonly LuminaDbContext _mockContext; + private readonly IDateTimeProvider _mockDateTimeProvider; private readonly AlbumRepository _albumRepository; private readonly TrackRepository _trackRepository; private readonly ArtistRepository _sut; @@ -61,9 +64,11 @@ public class ArtistRepositoryTests public ArtistRepositoryTests() { _mockContext = Create.MockedDbContextFor(); - _trackRepository = new TrackRepository(_mockContext); - _albumRepository = new AlbumRepository(_mockContext, _trackRepository); - _sut = new ArtistRepository(_mockContext, _albumRepository, _trackRepository); + _mockDateTimeProvider = Substitute.For(); + _mockDateTimeProvider.UtcNow.Returns(new DateTime(2026, 11, 14, 10, 30, 0, DateTimeKind.Utc)); + _trackRepository = new TrackRepository(_mockContext, _mockDateTimeProvider); + _albumRepository = new AlbumRepository(_mockContext, _trackRepository, _mockDateTimeProvider); + _sut = new ArtistRepository(_mockContext, _albumRepository, _trackRepository, _mockDateTimeProvider); } [Fact] @@ -1311,6 +1316,554 @@ public class ArtistRepositoryTests Assert.Equal(["Beneath the Surface", "The Beatles"], result.Value.Data.Select(row => row.Name)); } + [Fact] + public async Task GetByIdAsync_WhenArtistIsSoftDeleted_ShouldReturnNull() + { + // Arrange + ArtistEntity deletedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + deletedArtist.IsDeleted = true; + deletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Artists.Add(deletedArtist); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByIdAsync(deletedArtist.Id, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetAllAsync_WhenArtistsAreSoftDeleted_ShouldExcludeThem() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity activeArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + ArtistEntity deletedArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + deletedArtist.IsDeleted = true; + deletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Artists.AddRange(activeArtist, deletedArtist); + await _mockContext.SaveChangesAsync(); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(activeArtist.Id, Assert.Single(result.Value.Data).Id); + } + + [Fact] + public async Task GetAllLiteAsync_WhenArtistsAreSoftDeleted_ShouldExcludeThem() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity activeArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + ArtistEntity deletedArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + deletedArtist.IsDeleted = true; + deletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Artists.AddRange(activeArtist, deletedArtist); + await _mockContext.SaveChangesAsync(); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(activeArtist.Id, Assert.Single(result.Value.Data).Id); + } + + [Fact] + public async Task GetByNameAsync_WhenArtistIsActive_ShouldReturnIt() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false); + _mockContext.Artists.Add(artist); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByNameAsync(libraryId, "Queen", CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(artist.Id, result.Value!.Id); + } + + [Fact] + public async Task GetByNameAsync_WhenOnlyASoftDeletedArtistHasTheName_ShouldReturnNull() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity deletedArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false); + deletedArtist.IsDeleted = true; + deletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Artists.Add(deletedArtist); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByNameAsync(libraryId, "Queen", CancellationToken.None); + + // Assert + // A deleted artist keeps its name only for a restore, so a scan that finds the name again must materialize a new visible artist. + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task InsertAsync_WhenOnlyASoftDeletedArtistHasTheSameName_ShouldAddArtistAndReturnCreated() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity deletedArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false); + deletedArtist.IsDeleted = true; + deletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Artists.Add(deletedArtist); + await _mockContext.SaveChangesAsync(); + + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false); + + // Act + Result result = await _sut.InsertAsync(artist, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + Assert.Contains(_mockContext.ChangeTracker.Entries(), entry => entry.State == EntityState.Added && entry.Entity.Id == artist.Id); + } + + [Fact] + public async Task GetSoftDeletedByIdAsync_WhenArtistIsDeleted_ShouldReturnIt() + { + // Arrange + ArtistEntity deletedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + deletedArtist.IsDeleted = true; + deletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Artists.Add(deletedArtist); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetSoftDeletedByIdAsync(deletedArtist.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(deletedArtist.Id, result.Value!.Id); + } + + [Fact] + public async Task GetSoftDeletedByIdAsync_WhenArtistIsNotDeleted_ShouldReturnNull() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + _mockContext.Artists.Add(artist); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetSoftDeletedByIdAsync(artist.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetSoftDeletedByIdAsync_WhenArtistDoesNotExist_ShouldReturnNull() + { + // Act + Result result = await _sut.GetSoftDeletedByIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetSoftDeletedByLibraryIdAsync_WhenCalled_ShouldReturnOnlyTheDeletedArtistsOfTheLibrary() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity activeArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + ArtistEntity deletedArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + deletedArtist.IsDeleted = true; + deletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + ArtistEntity otherLibraryDeletedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + otherLibraryDeletedArtist.IsDeleted = true; + otherLibraryDeletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-2); + _mockContext.Artists.AddRange(activeArtist, deletedArtist, otherLibraryDeletedArtist); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetSoftDeletedByLibraryIdAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(deletedArtist.Id, Assert.Single(result.Value).Id); + } + + [Fact] + public async Task GetSoftDeletedByLibraryIdAsync_WhenCalled_ShouldOrderByTheStoredDeletionTimeThenNameAndId() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + DateTime deletedOnUtc = new(2026, 11, 14, 10, 0, 0, DateTimeKind.Utc); + ArtistEntity olderDeletion = _artistEntityFixture.Create(libraryId: libraryId, name: "Beta", includeAlbums: false, includeContributors: false); + olderDeletion.IsDeleted = true; + olderDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-2); + olderDeletion.UpdatedOnUtc = DateTime.UtcNow; + ArtistEntity newerDeletion = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha", includeAlbums: false, includeContributors: false); + newerDeletion.IsDeleted = true; + newerDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-1); + newerDeletion.UpdatedOnUtc = deletedOnUtc.AddDays(-5); + _mockContext.Artists.AddRange(olderDeletion, newerDeletion); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetSoftDeletedByLibraryIdAsync(libraryId, CancellationToken.None); + + // Assert + // A later write to a hidden row may change its update time, but it must not change the order of the deleted items. + Assert.False(result.IsFailure); + Assert.Equal([newerDeletion.Id, olderDeletion.Id], result.Value.Select(artist => artist.Id)); + } + + [Fact] + public async Task SoftDeleteByIdAsync_WhenCalled_ShouldSetTheDeletionStateAndTimeFromTheProvider() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + _mockContext.Artists.Add(artist); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.SoftDeleteByIdAsync(artist.Id, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + Assert.True(artist.IsDeleted); + Assert.Equal(_mockDateTimeProvider.UtcNow, artist.DeletedOnUtc); + } + + [Fact] + public async Task SoftDeleteByIdAsync_WhenArtistIsAlreadyDeleted_ShouldReturnArtistNotFound() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + DateTime storedDeletedOnUtc = DateTime.UtcNow.AddHours(-1); + artist.IsDeleted = true; + artist.DeletedOnUtc = storedDeletedOnUtc; + _mockContext.Artists.Add(artist); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.SoftDeleteByIdAsync(artist.Id, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + Assert.Equal(storedDeletedOnUtc, artist.DeletedOnUtc); + } + + [Fact] + public async Task SoftDeleteByIdAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFound() + { + // Act + Result result = await _sut.SoftDeleteByIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + } + + [Fact] + public async Task RestoreSoftDeletedByIdAsync_WhenCalled_ShouldClearTheDeletionStateAndTime() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + artist.IsDeleted = true; + artist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Artists.Add(artist); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.RestoreSoftDeletedByIdAsync(artist.Id, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + Assert.False(artist.IsDeleted); + Assert.Null(artist.DeletedOnUtc); + } + + [Fact] + public async Task RestoreSoftDeletedByIdAsync_WhenArtistIsNotDeleted_ShouldReturnArtistNotFound() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + _mockContext.Artists.Add(artist); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.RestoreSoftDeletedByIdAsync(artist.Id, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + } + + [Fact] + public async Task RestoreSoftDeletedByIdAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFound() + { + // Act + Result result = await _sut.RestoreSoftDeletedByIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + } + + [Fact] + public async Task UpdateAsync_WhenArtistIsSoftDeleted_ShouldReturnArtistNotFound() + { + // Arrange + ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + storedArtist.IsDeleted = true; + storedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + } + + [Fact] + public async Task UpdateAsync_WhenIncomingDeletionStateDiffers_ShouldPreserveTheActiveStateAndClearItsModifiedFlags() + { + // Arrange + ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + data.Name = "Freddie Mercury"; + data.IsDeleted = true; + data.DeletedOnUtc = DateTime.UtcNow; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + EntityEntry entry = _mockContext.Entry(storedArtist); + // The deletion state is owned by the explicit delete and restore operations, so an edit never writes it back. + Assert.False(storedArtist.IsDeleted); + Assert.Null(storedArtist.DeletedOnUtc); + Assert.False(entry.Property(artist => artist.IsDeleted).IsModified); + Assert.False(entry.Property(artist => artist.DeletedOnUtc).IsModified); + } + + [Fact] + public async Task UpdateAsync_WhenAnAlbumIsSoftDeleted_ShouldKeepItInsteadOfRemovingIt() + { + // Arrange + ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + AlbumEntity deletedAlbum = _albumEntityFixture.Create(artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + deletedAlbum.IsDeleted = true; + deletedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + storedArtist.Albums = [deletedAlbum]; + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + AlbumEntity? retrievedAlbum = await _mockContext.Albums.FirstOrDefaultAsync(album => album.Id == deletedAlbum.Id); + Assert.NotNull(retrievedAlbum); + Assert.True(retrievedAlbum!.IsDeleted); + Assert.NotNull(retrievedAlbum.DeletedOnUtc); + } + + [Fact] + public async Task UpdateAsync_WhenIncomingAlbumMatchesASoftDeletedAlbum_ShouldReturnAlbumNotFoundWithoutEditingIt() + { + // Arrange + ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + AlbumEntity deletedAlbum = _albumEntityFixture.Create(artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, title: "Hidden Album", includeTracks: false, includeMetadata: false); + deletedAlbum.IsDeleted = true; + deletedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + storedArtist.Albums = [deletedAlbum]; + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + AlbumEntity incomingAlbum = _albumEntityFixture.Create(id: deletedAlbum.Id, artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, title: "Edited Hidden Album", includeTracks: false, includeMetadata: false); + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + data.Albums = [incomingAlbum]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + AlbumEntity? retrievedAlbum = await _mockContext.Albums.FirstOrDefaultAsync(album => album.Id == deletedAlbum.Id); + Assert.NotNull(retrievedAlbum); + Assert.Equal("Hidden Album", retrievedAlbum!.Title); + Assert.True(retrievedAlbum.IsDeleted); + } + + [Fact] + public async Task UpdateAsync_WhenATrackIsSoftDeleted_ShouldKeepItInsteadOfRemovingIt() + { + // Arrange + ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + AlbumEntity storedAlbum = _albumEntityFixture.Create(artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, includeMetadata: false); + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + storedAlbum.Tracks = [deletedTrack]; + storedArtist.Albums = [storedAlbum]; + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + AlbumEntity incomingAlbum = _albumEntityFixture.Create(id: storedAlbum.Id, artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + data.Albums = [incomingAlbum]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + TrackEntity? retrievedTrack = await _mockContext.Tracks.FirstOrDefaultAsync(track => track.Id == deletedTrack.Id); + Assert.NotNull(retrievedTrack); + Assert.True(retrievedTrack!.IsDeleted); + } + + [Fact] + public async Task UpdateAsync_WhenIncomingTrackMatchesASoftDeletedTrack_ShouldReturnTrackNotFoundWithoutEditingIt() + { + // Arrange + ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + AlbumEntity storedAlbum = _albumEntityFixture.Create(artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, title: "Hidden Track", path: "/music/hidden.flac", includeMetadata: false); + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + storedAlbum.Tracks = [deletedTrack]; + storedArtist.Albums = [storedAlbum]; + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + AlbumEntity incomingAlbum = _albumEntityFixture.Create(id: storedAlbum.Id, artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + TrackEntity incomingTrack = _trackEntityFixture.Create(id: deletedTrack.Id, albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, title: "Edited Hidden Track", path: "/music/moved.flac", includeMetadata: false); + incomingAlbum.Tracks = [incomingTrack]; + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + data.Albums = [incomingAlbum]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + TrackEntity? retrievedTrack = await _mockContext.Tracks.FirstOrDefaultAsync(track => track.Id == deletedTrack.Id); + Assert.NotNull(retrievedTrack); + Assert.Equal("Hidden Track", retrievedTrack!.Title); + Assert.Equal("/music/hidden.flac", retrievedTrack.Path); + Assert.True(retrievedTrack.IsDeleted); + } + + [Fact] + public async Task UpdateAsync_WhenIncomingTrackMatchesASoftDeletedTrackOfAnotherAlbum_ShouldReturnTrackNotFoundWithoutEditingIt() + { + // Arrange + ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + AlbumEntity storedAlbum = _albumEntityFixture.Create(artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, title: "Hidden Track", path: "/music/hidden.flac", includeMetadata: false); + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + storedAlbum.Tracks = [deletedTrack]; + storedArtist.Albums = [storedAlbum]; + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + AlbumEntity newAlbum = _albumEntityFixture.Create(artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + TrackEntity incomingTrack = _trackEntityFixture.Create(id: deletedTrack.Id, albumId: newAlbum.Id, libraryId: storedArtist.LibraryId, title: "Moved Hidden Track", path: "/music/moved.flac", includeMetadata: false); + newAlbum.Tracks = [incomingTrack]; + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + data.Albums = [newAlbum]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + TrackEntity? retrievedTrack = await _mockContext.Tracks.FirstOrDefaultAsync(track => track.Id == deletedTrack.Id); + Assert.NotNull(retrievedTrack); + Assert.Equal("Hidden Track", retrievedTrack!.Title); + Assert.Equal("/music/hidden.flac", retrievedTrack.Path); + Assert.Equal(storedAlbum.Id, retrievedTrack.AlbumId); + } + + [Fact] + public async Task GetArtistsNeedingMetadataCountAsync_WhenAnArtistIsSoftDeleted_ShouldNotCountIt() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity pendingArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + pendingArtist.MetadataStatus = MetadataStatus.Pending; + ArtistEntity deletedArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + deletedArtist.MetadataStatus = MetadataStatus.Pending; + deletedArtist.IsDeleted = true; + deletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Artists.AddRange(pendingArtist, deletedArtist); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetArtistsNeedingMetadataCountAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(1, result.Value); + } + + [Fact] + public async Task GetArtistsNeedingArtworkCountAsync_WhenAnArtistIsSoftDeleted_ShouldNotCountIt() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity activeArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + ArtistEntity deletedArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + deletedArtist.IsDeleted = true; + deletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Artists.AddRange(activeArtist, deletedArtist); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetArtistsNeedingArtworkCountAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(1, result.Value); + } + /// /// Marks the provided artist, its albums and its tracks as enriched. /// diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/TrackRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/TrackRepositoryTests.cs index 0723e45e..753d8618 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/TrackRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/TrackRepositoryTests.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Application.Fixtures.Common.DTO.Pagination; @@ -16,6 +17,7 @@ using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; +using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -33,6 +35,7 @@ namespace Lumina.DataAccess.UnitTests.Core.Repositories.MusicLibrary; public class TrackRepositoryTests { private readonly LuminaDbContext _mockContext; + private readonly IDateTimeProvider _mockDateTimeProvider; private readonly TrackRepository _sut; private readonly TrackEntityFixture _trackEntityFixture = new(); private readonly TrackMoodEntityFixture _trackMoodEntityFixture = new(); @@ -51,7 +54,9 @@ public class TrackRepositoryTests public TrackRepositoryTests() { _mockContext = Create.MockedDbContextFor(); - _sut = new TrackRepository(_mockContext); + _mockDateTimeProvider = Substitute.For(); + _mockDateTimeProvider.UtcNow.Returns(new DateTime(2026, 11, 14, 10, 30, 0, DateTimeKind.Utc)); + _sut = new TrackRepository(_mockContext, _mockDateTimeProvider); } [Fact] @@ -279,6 +284,7 @@ public class TrackRepositoryTests { // Arrange TrackEntity storedTrack = _trackEntityFixture.Create(includeMetadata: false); + await SeedVisibleAncestorsAsync(storedTrack); _mockContext.Tracks.Add(storedTrack); await _mockContext.SaveChangesAsync(); @@ -320,6 +326,7 @@ public class TrackRepositoryTests Guid storedAlbumId = Guid.NewGuid(); Guid storedLibraryId = Guid.NewGuid(); TrackEntity storedTrack = _trackEntityFixture.Create(albumId: storedAlbumId, libraryId: storedLibraryId, includeMetadata: false); + await SeedVisibleAncestorsAsync(storedTrack); _mockContext.Tracks.Add(storedTrack); await _mockContext.SaveChangesAsync(); @@ -350,6 +357,7 @@ public class TrackRepositoryTests storedTrack.CreatedBy = storedCreatedBy; storedTrack.UpdatedOnUtc = null; storedTrack.UpdatedBy = null; + await SeedVisibleAncestorsAsync(storedTrack); _mockContext.Tracks.Add(storedTrack); await _mockContext.SaveChangesAsync(); @@ -385,6 +393,7 @@ public class TrackRepositoryTests TrackContributorEntity keptContributor = _trackContributorEntityFixture.Create( trackId: storedTrack.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Composer); storedTrack.Contributors = [keptContributor]; + await SeedVisibleAncestorsAsync(storedTrack); _mockContext.Tracks.Add(storedTrack); await _mockContext.SaveChangesAsync(); @@ -420,6 +429,7 @@ public class TrackRepositoryTests TrackContributorEntity removedContributor = _trackContributorEntityFixture.Create( trackId: storedTrack.Id, mediaContributorId: removedMediaContributorId, role: MediaContributorRole.Producer); storedTrack.Contributors = [keptContributor, removedContributor]; + await SeedVisibleAncestorsAsync(storedTrack); _mockContext.Tracks.Add(storedTrack); await _mockContext.SaveChangesAsync(); @@ -459,6 +469,7 @@ public class TrackRepositoryTests _audioRatingEntityFixture.Create(value: 5, maxValue: 5, source: AudioRatingSource.User, voteCount: 10), _audioRatingEntityFixture.Create(value: 2, maxValue: 5, source: AudioRatingSource.LastFm, voteCount: 20) ]; + await SeedVisibleAncestorsAsync(storedTrack); _mockContext.Tracks.Add(storedTrack); await _mockContext.SaveChangesAsync(); @@ -496,6 +507,7 @@ public class TrackRepositoryTests TrackEntity storedTrack = _trackEntityFixture.Create(includeMetadata: false); storedTrack.Tags = [existingTag]; storedTrack.Genres = [existingGenre]; + await SeedVisibleAncestorsAsync(storedTrack); _mockContext.Tracks.Add(storedTrack); await _mockContext.SaveChangesAsync(); @@ -530,6 +542,7 @@ public class TrackRepositoryTests TrackEntity storedTrack = _trackEntityFixture.Create(includeMetadata: false); storedTrack.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Energetic")]; storedTrack.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678"), _trackIsrcEntityFixture.Create(value: "GBAYE0000001")]; + await SeedVisibleAncestorsAsync(storedTrack); _mockContext.Tracks.Add(storedTrack); await _mockContext.SaveChangesAsync(); @@ -561,6 +574,7 @@ public class TrackRepositoryTests { // Arrange TrackEntity track = _trackEntityFixture.Create(includeMetadata: false); + await SeedVisibleAncestorsAsync(track); _mockContext.Tracks.Add(track); await _mockContext.SaveChangesAsync(); @@ -632,6 +646,7 @@ public class TrackRepositoryTests TrackEntity firstDiscFirstTieTrack = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/seven-seas-of-rhye.flac", trackNumber: 1, includeMetadata: false); firstDiscFirstTieTrack.DiscNumber = 1; TrackEntity trackOfAnotherAlbum = _trackEntityFixture.Create(path: "/music/queen/under-pressure.flac", includeMetadata: false); + await SeedVisibleAncestorsAsync(albumId, firstDiscFirstTrack.LibraryId); _mockContext.Tracks.AddRange(secondDiscTrack, firstDiscSecondTrack, firstDiscFirstTrack, firstDiscFirstTieTrack, trackOfAnotherAlbum); await _mockContext.SaveChangesAsync(); @@ -660,6 +675,7 @@ public class TrackRepositoryTests secondDiscTrack.DiscNumber = 2; TrackEntity firstDiscTrackWithoutDiscNumber = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/first-disc.flac", trackNumber: 2, includeMetadata: false); firstDiscTrackWithoutDiscNumber.DiscNumber = null; + await SeedVisibleAncestorsAsync(albumId, firstDiscTrackWithoutDiscNumber.LibraryId); _mockContext.Tracks.AddRange(secondDiscTrack, firstDiscTrackWithoutDiscNumber); await _mockContext.SaveChangesAsync(); @@ -684,6 +700,7 @@ public class TrackRepositoryTests track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678")]; track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)]; track.Contributors = [_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)]; + await SeedVisibleAncestorsAsync(albumId, track.LibraryId); _mockContext.Tracks.Add(track); await _mockContext.SaveChangesAsync(); @@ -711,6 +728,7 @@ public class TrackRepositoryTests TrackEntity firstTrack = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/i-want-to-break-free.flac", trackNumber: 1, title: "Bohemian Rhapsody", includeMetadata: false); firstTrack.DiscNumber = 1; TrackEntity trackOfAnotherAlbum = _trackEntityFixture.Create(path: "/music/queen/a-kind-of-magic.flac", includeMetadata: false); + await SeedVisibleAncestorsAsync(albumId, firstTrack.LibraryId); _mockContext.Tracks.AddRange(secondTrack, firstTrack, trackOfAnotherAlbum); await _mockContext.SaveChangesAsync(); @@ -737,6 +755,7 @@ public class TrackRepositoryTests thirdTrack.DiscNumber = 1; TrackEntity secondTrackWithoutDiscNumber = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/second.flac", trackNumber: 2, includeMetadata: false); secondTrackWithoutDiscNumber.DiscNumber = null; + await SeedVisibleAncestorsAsync(albumId, secondTrackWithoutDiscNumber.LibraryId); _mockContext.Tracks.AddRange(thirdTrack, secondTrackWithoutDiscNumber); await _mockContext.SaveChangesAsync(); @@ -771,6 +790,7 @@ public class TrackRepositoryTests tracks[index].Contributors = []; tracks[index].Ratings = []; } + await SeedVisibleAncestorsAsync(albumId, tracks[0].LibraryId); _mockContext.Tracks.AddRange(tracks); await _mockContext.SaveChangesAsync(); @@ -796,6 +816,7 @@ public class TrackRepositoryTests Guid albumId = Guid.NewGuid(); TrackEntity trackOfAlbum = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/youre-my-best-friend.flac", includeMetadata: false); TrackEntity trackOfAnotherAlbum = _trackEntityFixture.Create(path: "/music/queen/fat-bottomed-girls.flac", includeMetadata: false); + await SeedVisibleAncestorsAsync(albumId, trackOfAlbum.LibraryId); _mockContext.Tracks.AddRange(trackOfAlbum, trackOfAnotherAlbum); await _mockContext.SaveChangesAsync(); @@ -818,6 +839,7 @@ public class TrackRepositoryTests Guid albumId = Guid.NewGuid(); TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/bicycle-race.flac", title: "Killer Queen", trackNumber: 9, includeMetadata: false); track.DiscNumber = 3; + await SeedVisibleAncestorsAsync(albumId, track.LibraryId); _mockContext.Tracks.Add(track); await _mockContext.SaveChangesAsync(); @@ -843,6 +865,7 @@ public class TrackRepositoryTests Guid albumId = Guid.NewGuid(); TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/the-prophet-song.flac", includeMetadata: false); track.DurationInSeconds = 367; + await SeedVisibleAncestorsAsync(albumId, track.LibraryId); _mockContext.Tracks.Add(track); await _mockContext.SaveChangesAsync(); @@ -866,6 +889,7 @@ public class TrackRepositoryTests TrackEntity failedTrack = _trackEntityFixture.Create(libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Failed); TrackEntity enrichedTrack = _trackEntityFixture.Create(libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Enriched); TrackEntity trackOfAnotherLibrary = _trackEntityFixture.Create(includeMetadata: false, metadataStatus: MetadataStatus.Pending); + await SeedVisibleAncestorsAsync(pendingTrack, failedTrack, enrichedTrack, trackOfAnotherLibrary); _mockContext.Tracks.AddRange(pendingTrack, failedTrack, enrichedTrack, trackOfAnotherLibrary); await _mockContext.SaveChangesAsync(); @@ -901,6 +925,7 @@ public class TrackRepositoryTests TrackEntity firstTrack = _trackEntityFixture.Create(includeMetadata: false); TrackEntity secondTrack = _trackEntityFixture.Create(includeMetadata: false); TrackEntity thirdTrack = _trackEntityFixture.Create(includeMetadata: false); + await SeedVisibleAncestorsAsync(firstTrack, secondTrack, thirdTrack); _mockContext.Tracks.AddRange(firstTrack, secondTrack, thirdTrack); await _mockContext.SaveChangesAsync(); @@ -921,6 +946,7 @@ public class TrackRepositoryTests { // Arrange TrackEntity track = _trackEntityFixture.Create(includeMetadata: false); + await SeedVisibleAncestorsAsync(track); _mockContext.Tracks.Add(track); await _mockContext.SaveChangesAsync(); @@ -985,7 +1011,10 @@ public class TrackRepositoryTests { // Arrange const int TRACK_COUNT = 501; - List tracks = CreateTracks(TRACK_COUNT); + Guid albumId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + List tracks = CreateTracks(TRACK_COUNT, albumId, libraryId); + await SeedVisibleAncestorsAsync(albumId, libraryId); _mockContext.Tracks.AddRange(tracks); await _mockContext.SaveChangesAsync(); @@ -1001,14 +1030,801 @@ public class TrackRepositoryTests result.Value.Select(track => track.Id).OrderBy(id => id)); } + [Fact] + public async Task InsertAsync_WhenATrackWithTheSamePathIsSoftDeleted_ShouldReturnTrackAlreadyExists() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false); + await SeedVisibleAncestorsAsync(album.Id, libraryId); + TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false); + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Tracks.Add(deletedTrack); + await _mockContext.SaveChangesAsync(); + + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false); + + // Act + Result result = await _sut.InsertAsync(track, CancellationToken.None); + + // Assert + // A deleted track keeps its path reserved, so a scan must never materialize the deleted file back into the catalogue. + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError); + } + + [Fact] + public async Task GetExistingPathsAsync_WhenTrackIsSoftDeleted_ShouldStillReportItsPathAsExisting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + TrackEntity deletedTrack = _trackEntityFixture.Create(libraryId: libraryId, path: "/music/queen/deleted.flac", includeMetadata: false); + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Tracks.Add(deletedTrack); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetExistingPathsAsync(libraryId, ["/music/queen/deleted.flac"], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(["/music/queen/deleted.flac"], result.Value); + } + + [Fact] + public async Task GetByPathAsync_WhenTrackExists_ShouldReturnIt() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + TrackEntity track = _trackEntityFixture.Create(libraryId: libraryId, path: "/music/queen/love-of-my-life.flac", includeMetadata: false); + _mockContext.Tracks.Add(track); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByPathAsync(libraryId, "/music/queen/love-of-my-life.flac", CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(track.Id, result.Value!.Id); + } + + [Fact] + public async Task GetByPathAsync_WhenTrackIsSoftDeleted_ShouldReturnIt() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + TrackEntity deletedTrack = _trackEntityFixture.Create(libraryId: libraryId, path: "/music/queen/deleted.flac", includeMetadata: false); + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Tracks.Add(deletedTrack); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByPathAsync(libraryId, "/music/queen/deleted.flac", CancellationToken.None); + + // Assert + // The scan deletion strategy must be able to permanently remove a track that the user had already deleted. + Assert.False(result.IsFailure); + Assert.Equal(deletedTrack.Id, result.Value!.Id); + Assert.True(result.Value.IsDeleted); + } + + [Fact] + public async Task GetByIdAsync_WhenTrackIsSoftDeleted_ShouldReturnNull() + { + // Arrange + TrackEntity track = _trackEntityFixture.Create(includeMetadata: false); + await SeedVisibleAncestorsAsync(track); + track.IsDeleted = true; + track.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Tracks.Add(track); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByIdAsync(track.Id, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetByIdAsync_WhenItsAlbumIsSoftDeleted_ShouldReturnNull() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false); + AlbumEntity storedAlbum = await SeedVisibleAncestorsAsync(album.Id, libraryId); + storedAlbum.IsDeleted = true; + storedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + _mockContext.Tracks.Add(track); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByIdAsync(track.Id, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetByIdAsync_WhenItsArtistIsSoftDeleted_ShouldReturnNull() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + album.Artist = artist; + artist.IsDeleted = true; + artist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + album.IsDeleted = false; + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + album.Tracks = [track]; + artist.Albums = [album]; + _mockContext.Artists.Add(artist); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByIdAsync(track.Id, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetByAlbumIdAsync_WhenTracksAreSoftDeleted_ShouldExcludeThem() + { + // Arrange + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, includeTracks: false, includeMetadata: false); + await SeedVisibleAncestorsAsync(album.Id, album.LibraryId); + TrackEntity activeTrack = _trackEntityFixture.Create(albumId: albumId, libraryId: album.LibraryId, includeMetadata: false); + TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: albumId, libraryId: album.LibraryId, includeMetadata: false); + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Tracks.AddRange(activeTrack, deletedTrack); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetByAlbumIdAsync(albumId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(activeTrack.Id, Assert.Single(result.Value).Id); + } + + [Fact] + public async Task GetByAlbumIdAsync_WhenTheAlbumIsSoftDeleted_ShouldReturnEmpty() + { + // Arrange + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, includeTracks: false, includeMetadata: false); + AlbumEntity storedAlbum = await SeedVisibleAncestorsAsync(album.Id, album.LibraryId); + storedAlbum.IsDeleted = true; + storedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + TrackEntity track = _trackEntityFixture.Create(albumId: albumId, libraryId: album.LibraryId, includeMetadata: false); + _mockContext.Tracks.Add(track); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetByAlbumIdAsync(albumId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task GetByAlbumIdAsync_WhenTheArtistIsSoftDeleted_ShouldReturnEmpty() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + album.Artist = artist; + artist.IsDeleted = true; + artist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + album.Tracks = [track]; + artist.Albums = [album]; + _mockContext.Artists.Add(artist); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetByAlbumIdAsync(album.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task GetByAlbumIdIncludingDeletedAsync_WhenCalled_ShouldReturnActiveAndDeletedTracksOrdered() + { + // Arrange + Guid albumId = Guid.NewGuid(); + TrackEntity activeTrack = _trackEntityFixture.Create(albumId: albumId, libraryId: Guid.NewGuid(), trackNumber: 2, includeMetadata: false); + activeTrack.DiscNumber = 1; + TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: albumId, libraryId: activeTrack.LibraryId, trackNumber: 1, includeMetadata: false); + deletedTrack.DiscNumber = 1; + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Tracks.AddRange(activeTrack, deletedTrack); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetByAlbumIdIncludingDeletedAsync(albumId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal([deletedTrack.Id, activeTrack.Id], result.Value.Select(track => track.Id)); + } + + [Fact] + public async Task GetTracksLiteByAlbumIdAsync_WhenATrackIsSoftDeleted_ShouldExcludeIt() + { + // Arrange + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, includeTracks: false, includeMetadata: false); + await SeedVisibleAncestorsAsync(album.Id, album.LibraryId); + TrackEntity activeTrack = _trackEntityFixture.Create(albumId: albumId, libraryId: album.LibraryId, includeMetadata: false); + TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: albumId, libraryId: album.LibraryId, includeMetadata: false); + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Tracks.AddRange(activeTrack, deletedTrack); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetTracksLiteByAlbumIdAsync(albumId, null, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(activeTrack.Id, Assert.Single(result.Value.Data).Id); + } + + [Fact] + public async Task GetShuffleTracksLiteAsync_WhenTracksOrAncestorsAreSoftDeleted_ShouldExcludeThem() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity visibleArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + AlbumEntity visibleAlbum = _albumEntityFixture.Create(artistId: visibleArtist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + TrackEntity visibleTrack = _trackEntityFixture.Create(albumId: visibleAlbum.Id, libraryId: libraryId, includeMetadata: false); + TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: visibleAlbum.Id, libraryId: libraryId, includeMetadata: false); + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + visibleAlbum.Tracks = [visibleTrack, deletedTrack]; + visibleArtist.Albums = [visibleAlbum]; + + ArtistEntity artistOfDeletedAlbum = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + AlbumEntity deletedAlbum = _albumEntityFixture.Create(artistId: artistOfDeletedAlbum.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + deletedAlbum.IsDeleted = true; + deletedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + deletedAlbum.Tracks = [_trackEntityFixture.Create(albumId: deletedAlbum.Id, libraryId: libraryId, includeMetadata: false)]; + artistOfDeletedAlbum.Albums = [deletedAlbum]; + + ArtistEntity deletedArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + deletedArtist.IsDeleted = true; + deletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + AlbumEntity albumOfDeletedArtist = _albumEntityFixture.Create(artistId: deletedArtist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + albumOfDeletedArtist.Tracks = [_trackEntityFixture.Create(albumId: albumOfDeletedArtist.Id, libraryId: libraryId, includeMetadata: false)]; + deletedArtist.Albums = [albumOfDeletedArtist]; + _mockContext.Artists.AddRange(visibleArtist, artistOfDeletedAlbum, deletedArtist); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetShuffleTracksLiteAsync(libraryId, null, null, [], 10, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(visibleTrack.Id, Assert.Single(result.Value).TrackId); + } + + [Fact] + public async Task GetTrackStreamInfoAsync_WhenTrackIsSoftDeleted_ShouldReturnNull() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + album.Artist = artist; + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + track.IsDeleted = true; + track.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + album.Tracks = [track]; + artist.Albums = [album]; + _mockContext.Artists.Add(artist); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetTrackStreamInfoAsync(libraryId, album.Id, artist.Id, track.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetTrackStreamInfoAsync_WhenItsAlbumIsSoftDeleted_ShouldReturnNull() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + album.Artist = artist; + album.IsDeleted = true; + album.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + album.Tracks = [track]; + artist.Albums = [album]; + _mockContext.Artists.Add(artist); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetTrackStreamInfoAsync(libraryId, album.Id, artist.Id, track.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetPlaybackManifestInfoAsync_WhenItsArtistIsSoftDeleted_ShouldReturnNull() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + artist.IsDeleted = true; + artist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + album.Artist = artist; + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + album.Tracks = [track]; + artist.Albums = [album]; + _mockContext.Artists.Add(artist); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetPlaybackManifestInfoAsync(libraryId, album.Id, artist.Id, track.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetAccessInfoByIdsAsync_WhenTracksOrAncestorsAreSoftDeleted_ShouldExcludeThem() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + album.Artist = artist; + TrackEntity activeTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + album.Tracks = [activeTrack, deletedTrack]; + artist.Albums = [album]; + _mockContext.Artists.Add(artist); + + ArtistEntity deletedArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + deletedArtist.IsDeleted = true; + deletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + AlbumEntity albumOfDeletedArtist = _albumEntityFixture.Create(artistId: deletedArtist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + albumOfDeletedArtist.Artist = deletedArtist; + TrackEntity trackOfDeletedArtist = _trackEntityFixture.Create(albumId: albumOfDeletedArtist.Id, libraryId: libraryId, includeMetadata: false); + albumOfDeletedArtist.Tracks = [trackOfDeletedArtist]; + deletedArtist.Albums = [albumOfDeletedArtist]; + _mockContext.Artists.Add(deletedArtist); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetAccessInfoByIdsAsync([activeTrack.Id, deletedTrack.Id, trackOfDeletedArtist.Id], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(1, result.Value.TrackCount); + Assert.Equal([libraryId], result.Value.LibraryIds); + } + + [Fact] + public async Task GetByIdsAsync_WhenTracksOrAncestorsAreSoftDeleted_ShouldExcludeThem() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + album.Artist = artist; + TrackEntity activeTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + album.Tracks = [activeTrack, deletedTrack]; + artist.Albums = [album]; + _mockContext.Artists.Add(artist); + + ArtistEntity artistOfDeletedAlbum = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + AlbumEntity deletedAlbum = _albumEntityFixture.Create(artistId: artistOfDeletedAlbum.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + deletedAlbum.Artist = artistOfDeletedAlbum; + deletedAlbum.IsDeleted = true; + deletedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + TrackEntity trackOfDeletedAlbum = _trackEntityFixture.Create(albumId: deletedAlbum.Id, libraryId: libraryId, includeMetadata: false); + deletedAlbum.Tracks = [trackOfDeletedAlbum]; + artistOfDeletedAlbum.Albums = [deletedAlbum]; + _mockContext.Artists.Add(artistOfDeletedAlbum); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetByIdsAsync([activeTrack.Id, deletedTrack.Id, trackOfDeletedAlbum.Id], false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(activeTrack.Id, Assert.Single(result.Value).Id); + } + + [Fact] + public async Task GetSoftDeletedByIdAsync_WhenTrackIsDeleted_ShouldReturnIt() + { + // Arrange + TrackEntity track = _trackEntityFixture.Create(includeMetadata: false); + await SeedVisibleAncestorsAsync(track); + track.IsDeleted = true; + track.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Tracks.Add(track); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetSoftDeletedByIdAsync(track.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(track.Id, result.Value!.Id); + } + + [Fact] + public async Task GetSoftDeletedByIdAsync_WhenItsAlbumIsDeleted_ShouldReturnNull() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false); + AlbumEntity storedAlbum = await SeedVisibleAncestorsAsync(album.Id, libraryId); + storedAlbum.IsDeleted = true; + storedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + track.IsDeleted = true; + track.DeletedOnUtc = DateTime.UtcNow.AddHours(-2); + _mockContext.Tracks.Add(track); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetSoftDeletedByIdAsync(track.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetSoftDeletedByIdAsync_WhenItsArtistIsDeleted_ShouldReturnNull() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + album.Artist = artist; + artist.IsDeleted = true; + artist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + track.IsDeleted = true; + track.DeletedOnUtc = DateTime.UtcNow.AddHours(-2); + album.Tracks = [track]; + artist.Albums = [album]; + _mockContext.Artists.Add(artist); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetSoftDeletedByIdAsync(track.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetSoftDeletedByIdAsync_WhenTrackIsNotDeleted_ShouldReturnNull() + { + // Arrange + TrackEntity track = _trackEntityFixture.Create(includeMetadata: false); + await SeedVisibleAncestorsAsync(track); + _mockContext.Tracks.Add(track); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetSoftDeletedByIdAsync(track.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetSoftDeletedByLibraryIdAsync_WhenCalled_ShouldReturnOnlyVisibleDeletedTracksOrdered() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + album.Artist = artist; + DateTime deletedOnUtc = new(2026, 11, 14, 10, 0, 0, DateTimeKind.Utc); + TrackEntity olderDeletion = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, title: "Alpha", includeMetadata: false); + olderDeletion.IsDeleted = true; + olderDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-2); + olderDeletion.UpdatedOnUtc = deletedOnUtc; + TrackEntity newerDeletion = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, title: "Beta", includeMetadata: false); + newerDeletion.IsDeleted = true; + newerDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-1); + TrackEntity sameTimeDeletion = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, title: "Gamma", includeMetadata: false); + sameTimeDeletion.IsDeleted = true; + sameTimeDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-1); + album.Tracks = [olderDeletion, newerDeletion, sameTimeDeletion]; + artist.Albums = [album]; + _mockContext.Artists.Add(artist); + + ArtistEntity deletedArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + deletedArtist.IsDeleted = true; + deletedArtist.DeletedOnUtc = deletedOnUtc.AddHours(-1); + AlbumEntity albumOfDeletedArtist = _albumEntityFixture.Create(artistId: deletedArtist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + albumOfDeletedArtist.Artist = deletedArtist; + TrackEntity hiddenDeletedTrack = _trackEntityFixture.Create(albumId: albumOfDeletedArtist.Id, libraryId: libraryId, includeMetadata: false); + hiddenDeletedTrack.IsDeleted = true; + hiddenDeletedTrack.DeletedOnUtc = deletedOnUtc; + albumOfDeletedArtist.Tracks = [hiddenDeletedTrack]; + deletedArtist.Albums = [albumOfDeletedArtist]; + _mockContext.Artists.Add(deletedArtist); + await _mockContext.SaveChangesAsync(); + + TrackEntity[] expectedDeletedTracks = [olderDeletion, newerDeletion, sameTimeDeletion]; + Guid[] expectedOrder = [.. expectedDeletedTracks + .OrderByDescending(track => track.DeletedOnUtc) + .ThenByDescending(track => track.Title) + .ThenByDescending(track => track.Id) + .Select(track => track.Id)]; + + // Act + Result> result = await _sut.GetSoftDeletedByLibraryIdAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(expectedOrder, result.Value.Select(track => track.Id)); + } + + [Fact] + public async Task RestoreSoftDeletedByIdAsync_WhenCalled_ShouldClearTheDeletionStateAndTime() + { + // Arrange + TrackEntity track = _trackEntityFixture.Create(includeMetadata: false); + track.IsDeleted = true; + track.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Tracks.Add(track); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.RestoreSoftDeletedByIdAsync(track.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.False(track.IsDeleted); + Assert.Null(track.DeletedOnUtc); + } + + [Fact] + public async Task RestoreSoftDeletedByIdAsync_WhenTrackIsNotDeleted_ShouldReturnTrackNotFound() + { + // Arrange + TrackEntity track = _trackEntityFixture.Create(includeMetadata: false); + _mockContext.Tracks.Add(track); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.RestoreSoftDeletedByIdAsync(track.Id, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + } + + [Fact] + public async Task RestoreSoftDeletedByIdAsync_WhenTrackDoesNotExist_ShouldReturnTrackNotFound() + { + // Act + Result result = await _sut.RestoreSoftDeletedByIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + } + + [Fact] + public async Task UpdateAsync_WhenTrackIsSoftDeleted_ShouldReturnTrackNotFound() + { + // Arrange + TrackEntity storedTrack = _trackEntityFixture.Create(includeMetadata: false); + await SeedVisibleAncestorsAsync(storedTrack); + storedTrack.IsDeleted = true; + storedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + _mockContext.Tracks.Add(storedTrack); + await _mockContext.SaveChangesAsync(); + + TrackEntity data = _trackEntityFixture.Create(id: storedTrack.Id, albumId: storedTrack.AlbumId, libraryId: storedTrack.LibraryId, includeMetadata: false); + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + } + + [Fact] + public async Task UpdateAsync_WhenItsAlbumIsSoftDeleted_ShouldReturnTrackNotFound() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false); + AlbumEntity storedAlbum = await SeedVisibleAncestorsAsync(album.Id, libraryId); + storedAlbum.IsDeleted = true; + storedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + TrackEntity storedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + _mockContext.Tracks.Add(storedTrack); + await _mockContext.SaveChangesAsync(); + + TrackEntity data = _trackEntityFixture.Create(id: storedTrack.Id, albumId: storedTrack.AlbumId, libraryId: storedTrack.LibraryId, includeMetadata: false); + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + } + + [Fact] + public async Task UpdateAsync_WhenItsArtistIsSoftDeleted_ShouldReturnTrackNotFound() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + album.Artist = artist; + artist.IsDeleted = true; + artist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + TrackEntity storedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + _mockContext.Artists.Add(artist); + _mockContext.Tracks.Add(storedTrack); + await _mockContext.SaveChangesAsync(); + + TrackEntity data = _trackEntityFixture.Create(id: storedTrack.Id, albumId: storedTrack.AlbumId, libraryId: storedTrack.LibraryId, includeMetadata: false); + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + } + + [Fact] + public async Task UpdateAsync_WhenIncomingDeletionStateDiffers_ShouldPreserveTheActiveStateAndClearItsModifiedFlags() + { + // Arrange + TrackEntity storedTrack = _trackEntityFixture.Create(includeMetadata: false); + await SeedVisibleAncestorsAsync(storedTrack); + _mockContext.Tracks.Add(storedTrack); + await _mockContext.SaveChangesAsync(); + + TrackEntity data = _trackEntityFixture.Create(id: storedTrack.Id, albumId: storedTrack.AlbumId, libraryId: storedTrack.LibraryId, includeMetadata: false); + data.Title = "Somebody to Love"; + data.IsDeleted = true; + data.DeletedOnUtc = DateTime.UtcNow; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + EntityEntry entry = _mockContext.Entry(storedTrack); + Assert.False(storedTrack.IsDeleted); + Assert.Null(storedTrack.DeletedOnUtc); + Assert.False(entry.Property(track => track.IsDeleted).IsModified); + Assert.False(entry.Property(track => track.DeletedOnUtc).IsModified); + } + + [Fact] + public async Task GetTracksNeedingMetadataCountAsync_WhenATrackOrItsAncestorIsSoftDeleted_ShouldNotCountIt() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + album.Artist = artist; + TrackEntity pendingTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Pending); + TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Pending); + deletedTrack.IsDeleted = true; + deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + album.Tracks = [pendingTrack, deletedTrack]; + artist.Albums = [album]; + _mockContext.Artists.Add(artist); + + ArtistEntity artistOfDeletedAlbum = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + AlbumEntity deletedAlbum = _albumEntityFixture.Create(artistId: artistOfDeletedAlbum.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + deletedAlbum.Artist = artistOfDeletedAlbum; + deletedAlbum.IsDeleted = true; + deletedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1); + TrackEntity trackOfDeletedAlbum = _trackEntityFixture.Create(albumId: deletedAlbum.Id, libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Pending); + deletedAlbum.Tracks = [trackOfDeletedAlbum]; + artistOfDeletedAlbum.Albums = [deletedAlbum]; + _mockContext.Artists.Add(artistOfDeletedAlbum); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetTracksNeedingMetadataCountAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(1, result.Value); + } + /// - /// Creates a list of tracks with distinct paths and empty metadata collections, so that the chunked lookup can be exercised without extra graph data. + /// Seeds an active artist and the album identified by , so that the tracks of that album pass the ancestor filters of the repository. + /// + /// The Id of the album the tracks belong to. + /// The Id of the library the album belongs to. + /// The seeded album, already tracked by the context. + private async Task SeedVisibleAncestorsAsync(Guid albumId, Guid libraryId) + { + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create( + id: albumId, + artistId: artist.Id, + libraryId: libraryId, + includeTracks: false, + includeMetadata: false); + album.Artist = artist; + _mockContext.Albums.Add(album); + await _mockContext.SaveChangesAsync(); + return album; + } + + /// + /// Seeds an active artist and album for each of the provided tracks, so that every track passes the ancestor filters of the repository. + /// + /// The tracks whose ancestors are seeded. + /// A task representing the asynchronous operation. + private async Task SeedVisibleAncestorsAsync(params TrackEntity[] tracks) + { + foreach (TrackEntity track in tracks) + await SeedVisibleAncestorsAsync(track.AlbumId, track.LibraryId); + } + + /// + /// Creates a list of tracks of the provided album with distinct paths and empty metadata collections, so that the chunked lookup can be exercised without extra graph data. /// /// The number of tracks to create. + /// The Id of the album that owns the tracks. + /// The Id of the library that owns the tracks. /// The created tracks. - private List CreateTracks(int count) + private List CreateTracks(int count, Guid albumId, Guid libraryId) { return [.. Enumerable.Range(0, count).Select(_ => _trackEntityFixture.Create( - path: $"/music/generated-{Guid.NewGuid():N}.flac", includeMetadata: false))]; + albumId: albumId, + libraryId: libraryId, + path: $"/music/generated-{Guid.NewGuid():N}.flac", + includeMetadata: false))]; } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs index 18192ffa..94aa7d31 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs @@ -260,11 +260,12 @@ public class ErrorsTests { // Assert // The count assertion fails when an error is added or removed, reminding to update the assertions below. - Assert.Equal(20, typeof(DomainErrors.FileSystemManagement).GetProperties().Length); + Assert.Equal(21, typeof(DomainErrors.FileSystemManagement).GetProperties().Length); AssertError(DomainErrors.FileSystemManagement.ParentNodeCannotBeNull, ErrorType.Failure); AssertError(DomainErrors.FileSystemManagement.PathMustBeMaximum260CharactersLong, ErrorType.Failure); AssertError(DomainErrors.FileSystemManagement.FileCopyError, ErrorType.Failure); AssertError(DomainErrors.FileSystemManagement.FileMoveError, ErrorType.Failure); + AssertError(DomainErrors.FileSystemManagement.FileDeleteError, ErrorType.Failure); AssertError(DomainErrors.FileSystemManagement.DirectoryCopyError, ErrorType.Failure); AssertError(DomainErrors.FileSystemManagement.DirectoryMoveError, ErrorType.Failure); AssertError(DomainErrors.FileSystemManagement.FileNotFound, ErrorType.NotFound); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ArtistTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ArtistTests.cs index 02e0add9..f3ec3dc2 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ArtistTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ArtistTests.cs @@ -471,6 +471,38 @@ public class ArtistTests Assert.Single(artist.Albums); } + [Fact] + public void EnsureCanRemoveAlbum_WhenTheArtistHasAnotherAlbum_ShouldReturnSuccess() + { + // Arrange + Album firstAlbum = _albumFixture.Create(); + Album secondAlbum = _albumFixture.Create(); + Artist artist = _artistFixture.Create(albums: [firstAlbum, secondAlbum]); + + // Act + Result result = artist.CanRemoveAlbum(firstAlbum); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, artist.Albums.Count); + } + + [Fact] + public void EnsureCanRemoveAlbum_WhenAlbumIsTheOnlyAlbumOfTheArtist_ShouldReturnArtistMustHaveAtLeastOneAlbumError() + { + // Arrange + Album onlyAlbum = _albumFixture.Create(); + Artist artist = _artistFixture.Create(albums: [onlyAlbum]); + + // Act + Result result = artist.CanRemoveAlbum(onlyAlbum); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError); + Assert.Single(artist.Albums); + } + [Fact] public void UpdateContributors_WhenCalledWithNewContributors_ShouldReplaceThemInPlace() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs index b2a5066c..7a12418c 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs @@ -955,4 +955,42 @@ public class FileProviderServiceTests Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); _mockFileSystem.File.DidNotReceive().Delete(Arg.Any()); } + + [Fact] + public void DeleteFile_WhenTheFileIsLocked_ShouldReturnFileDeleteError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.Create( + s_isUnix ? "/LockedFileToDelete.txt" : @"C:\LockedFileToDelete.txt" + ); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete).Returns(true); + _mockFileSystem.File.When(file => file.Delete(path.Path)) + .Do(_ => throw new IOException("The file is locked by another process")); + + // Act + Result result = _sut.DeleteFile(path); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileDeleteError, result.FirstError); + } + + [Fact] + public void DeleteFile_WhenTheFileIsReadOnly_ShouldReturnUnauthorizedAccessError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.Create( + s_isUnix ? "/ReadOnlyFileToDelete.txt" : @"C:\ReadOnlyFileToDelete.txt" + ); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete).Returns(true); + _mockFileSystem.File.When(file => file.Delete(path.Path)) + .Do(_ => throw new UnauthorizedAccessException("The file is read-only")); + + // Act + Result result = _sut.DeleteFile(path); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError); + } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs index a61eca6c..01aeff31 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs @@ -7,6 +7,7 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using NSubstitute; +using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -772,6 +773,52 @@ public class PathServiceTests Assert.Equal(100, result.Value.Name.Length); } + [Fact] + public void SanitizeCompositeSegment_WhenTheNameFitsTheBudget_ShouldAppendTheIdentifier() + { + // Arrange + _mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']); + string identifier = Guid.NewGuid().ToString(); + + // Act + Result result = _sut.SanitizeCompositeSegment("Queen", identifier); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal($"Queen-{identifier}", result.Value.Name); + } + + [Fact] + public void SanitizeCompositeSegment_WhenTheNameExceedsTheBudget_ShouldTruncateOnlyTheName() + { + // Arrange + _mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']); + string identifier = Guid.NewGuid().ToString(); + + // Act + Result result = _sut.SanitizeCompositeSegment(new string('a', 99), identifier); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(100, result.Value.Name.Length); + Assert.EndsWith($"-{identifier}", result.Value.Name); + Assert.Equal(new string('a', 63), result.Value.Name[..^($"-{identifier}".Length)]); + } + + [Fact] + public void SanitizeCompositeSegment_WhenTheIdentifierLeavesNoRoomForTheName_ShouldReturnInvalidPath() + { + // Arrange + _mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']); + + // Act + Result result = _sut.SanitizeCompositeSegment("Queen", new string('a', 99)); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + } + [Fact] public void IsPathWithin_WhenBothPathsAreValid_ShouldCreatePathIdsAndDelegateToTheStrategy() { diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs index 9ca8eaa9..49eb9f2c 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs @@ -76,7 +76,7 @@ public class MusicArtworkServiceTests _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(false)); // Act - Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -91,7 +91,7 @@ public class MusicArtworkServiceTests MockPathBuilding(); // Act - Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(), null, CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -108,7 +108,7 @@ public class MusicArtworkServiceTests .Returns(Error.Failure("FileSystem.Error", "Failed to check the artwork file")); // Act - Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -121,18 +121,19 @@ public class MusicArtworkServiceTests // Arrange Guid libraryId = Guid.NewGuid(); Guid albumId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); string libraryName = "Test Library"; string artistName = "Test Artist"; string albumTitle = "Test Album"; - string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle); MockArtworkDirectoryStubs(artworkDirectoryPath); _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(Result.From(true)); _mockFileProviderService.GetFilePaths(Arg.Any(), true) .Returns(Error.Failure("FileSystem.Error", "Failed to list the artwork files")); // Act - Result result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistName, albumTitle); + Result result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistId, artistName, albumTitle); // Assert Assert.True(result.IsFailure); @@ -146,11 +147,12 @@ public class MusicArtworkServiceTests // Arrange Guid libraryId = Guid.NewGuid(); Guid albumId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); string libraryName = "Test Library"; string artistName = "Test Artist"; string albumTitle = "Test Album"; - string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle); MockArtworkDirectoryStubs(artworkDirectoryPath); _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(Result.From(true)); FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")); @@ -160,7 +162,7 @@ public class MusicArtworkServiceTests _mockFileProviderService.DeleteFile(Arg.Any()).Returns(Result.Deleted); // Act - Result result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistName, albumTitle); + Result result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistId, artistName, albumTitle); // Assert Assert.False(result.IsFailure); @@ -174,9 +176,11 @@ public class MusicArtworkServiceTests // Arrange _mockPathService.SanitizeSegment(Arg.Any()) .Returns(Errors.FileSystemManagement.InvalidPath); + _mockPathService.SanitizeCompositeSegment(Arg.Any(), Arg.Any()) + .Returns(Errors.FileSystemManagement.InvalidPath); // Act - Result result = _sut.DeleteAlbumArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album"); + Result result = _sut.DeleteAlbumArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album"); // Assert Assert.True(result.IsFailure); @@ -190,7 +194,7 @@ public class MusicArtworkServiceTests _mockPathService.CombinePath(AppContext.BaseDirectory, "media").Returns(Errors.FileSystemManagement.InvalidPath); // Act - Result result = _sut.DeleteAlbumArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album"); + Result result = _sut.DeleteAlbumArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album"); // Assert Assert.True(result.IsFailure); @@ -203,11 +207,12 @@ public class MusicArtworkServiceTests // Arrange Guid libraryId = Guid.NewGuid(); Guid albumId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); string libraryName = "Test Library"; string artistName = "Test Artist"; string albumTitle = "Test Album"; byte[] uploadedBytes = [1, 2, 3, 4, 5, 6, 7, 8]; - string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle); string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpg"); string? capturedTemporaryPath = null; byte[]? capturedBytes = null; @@ -227,7 +232,7 @@ public class MusicArtworkServiceTests await using MemoryStream artworkStream = new(uploadedBytes); // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, artworkStream, "cover.jpg", null, CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, artworkStream, "cover.jpg", null, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -246,11 +251,12 @@ public class MusicArtworkServiceTests // Arrange Guid libraryId = Guid.NewGuid(); Guid albumId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); string libraryName = "Test Library"; string artistName = "Test Artist"; string albumTitle = "Test Album"; string releaseTypeName = "Single"; - string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle, releaseTypeName); + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle, releaseTypeName); string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpg"); MockArtworkDirectoryStubs(artworkDirectoryPath); _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); @@ -263,7 +269,7 @@ public class MusicArtworkServiceTests await using MemoryStream artworkStream = new([1, 2, 3]); // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, artworkStream, "cover.jpg", releaseTypeName, CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, artworkStream, "cover.jpg", releaseTypeName, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -279,10 +285,11 @@ public class MusicArtworkServiceTests // Arrange Guid libraryId = Guid.NewGuid(); Guid albumId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); string libraryName = "Test Library"; string artistName = "Test Artist"; string albumTitle = "Test Album"; - string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle); string? capturedTemporaryPath = null; MockArtworkDirectoryStubs(artworkDirectoryPath); _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); @@ -297,7 +304,7 @@ public class MusicArtworkServiceTests await using MemoryStream artworkStream = new([1, 2, 3, 4]); // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, artworkStream, "cover.jpg", null, CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, artworkStream, "cover.jpg", null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -316,10 +323,11 @@ public class MusicArtworkServiceTests // Arrange Guid libraryId = Guid.NewGuid(); Guid albumId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); string libraryName = "Test Library"; string artistName = "Test Artist"; string albumTitle = "Test Album"; - string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle); string? capturedTemporaryPath = null; MockArtworkDirectoryStubs(artworkDirectoryPath); _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); @@ -336,7 +344,7 @@ public class MusicArtworkServiceTests await using MemoryStream artworkStream = new([1, 2, 3]); // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, artworkStream, fileName!, null, CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, artworkStream, fileName!, null, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -349,10 +357,11 @@ public class MusicArtworkServiceTests { // Arrange Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); string libraryName = "Test Library"; string artistName = "Test Artist"; byte[] uploadedBytes = [9, 8, 7, 6, 5]; - string artworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName); + string artworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistId, artistName); string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.png"); string? capturedTemporaryPath = null; byte[]? capturedBytes = null; @@ -372,7 +381,7 @@ public class MusicArtworkServiceTests await using MemoryStream artworkStream = new(uploadedBytes); // Act - Result result = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, artistName, artworkStream, "cover.png", CancellationToken.None); + Result result = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, artistId, artistName, artworkStream, "cover.png", CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -390,9 +399,10 @@ public class MusicArtworkServiceTests { // Arrange Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); string libraryName = "Test Library"; string artistName = "Test Artist"; - string artworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName); + string artworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistId, artistName); string? capturedTemporaryPath = null; MockArtworkDirectoryStubs(artworkDirectoryPath); _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); @@ -407,7 +417,7 @@ public class MusicArtworkServiceTests await using MemoryStream artworkStream = new([1, 2, 3]); // Act - Result result = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, artistName, artworkStream, "cover.png", CancellationToken.None); + Result result = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, artistId, artistName, artworkStream, "cover.png", CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -482,19 +492,21 @@ public class MusicArtworkServiceTests } [Fact] - public void DeleteStoredArtwork_WhenDeletingTheFileFails_ShouldReturnDeleted() + public void DeleteStoredArtwork_WhenDeletingTheFileFails_ShouldReturnTheError() { // Arrange string artworkRelativePath = "\\media\\music\\cover.jpg"; + Error error = Error.Failure("FileSystem.Error", "Failed to delete the artwork file"); _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); _mockFileProviderService.DeleteFile(Arg.Any()) - .Returns(Error.Failure("FileSystem.Error", "Failed to delete the artwork file")); + .Returns(error); // Act Result result = _sut.DeleteStoredArtwork(artworkRelativePath); // Assert - Assert.False(result.IsFailure); + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); _mockFileProviderService.Received(1).DeleteFile(Arg.Any()); } @@ -510,6 +522,14 @@ public class MusicArtworkServiceTests return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false)); }); + _mockPathService.SanitizeCompositeSegment(Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + string name = callInfo.ArgAt(0); + string identifier = callInfo.ArgAt(1); + return Result.From(_pathSegmentFixture.Create(name: $"{name}-{identifier}", isDirectory: true, isDrive: false)); + }); + _mockPathService.CombinePath(Arg.Any(), Arg.Any()) .Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1)))); } @@ -538,11 +558,12 @@ public class MusicArtworkServiceTests /// The Id of the media library the album belongs to. /// The Id of the album. /// The name of the media library the album belongs to. + /// The Id of the artist of the album. /// The name of the artist of the album. /// The title of the album. /// Optional. The name of the release type directory the album is stored under. /// The expected file system path of the album artwork directory. - private static string BuildArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, string? releaseTypeName = null) + private static string BuildArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, Guid artistId, string artistName, string albumTitle, string? releaseTypeName = null) { if (string.IsNullOrWhiteSpace(releaseTypeName)) { @@ -551,7 +572,7 @@ public class MusicArtworkServiceTests "media", "music", $"{libraryName}-{libraryId}", - artistName, + $"{artistName}-{artistId}", $"{albumTitle}-{albumId}"); } @@ -560,7 +581,7 @@ public class MusicArtworkServiceTests "media", "music", $"{libraryName}-{libraryId}", - artistName, + $"{artistName}-{artistId}", releaseTypeName, $"{albumTitle}-{albumId}"); } @@ -570,15 +591,16 @@ public class MusicArtworkServiceTests /// /// The Id of the media library the artist belongs to. /// The name of the media library the artist belongs to. + /// The Id of the artist. /// The name of the artist. /// The expected file system path of the artist artwork directory. - private static string BuildArtistArtworkDirectoryPath(Guid libraryId, string libraryName, string artistName) + private static string BuildArtistArtworkDirectoryPath(Guid libraryId, string libraryName, Guid artistId, string artistName) { return Path.Combine( AppContext.BaseDirectory, "media", "music", $"{libraryName}-{libraryId}", - artistName); + $"{artistName}-{artistId}"); } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricherTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricherTests.cs index a70367fc..a2c9a0d3 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricherTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricherTests.cs @@ -236,6 +236,7 @@ public class MusicMediaLibraryScanArtworkEnricherTests await _mockMusicArtworkService.Received(1).SaveArtistArtworkAsync( _libraryId.Value, Arg.Any(), + artist.Id, artist.Name, Arg.Is(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0), Arg.Any()); @@ -269,6 +270,7 @@ public class MusicMediaLibraryScanArtworkEnricherTests _libraryId.Value, album.Id, Arg.Any(), + album.ArtistId, Arg.Any(), album.Title, Arg.Is(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0), @@ -328,7 +330,7 @@ public class MusicMediaLibraryScanArtworkEnricherTests ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value); SetupArtists(artist); _artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]); - _mockMusicArtworkService.SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + _mockMusicArtworkService.SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Error.Failure("Artwork.Error", "Failed to store the artwork")); // Act @@ -347,7 +349,7 @@ public class MusicMediaLibraryScanArtworkEnricherTests ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value); SetupArtists(artist); _artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]); - _mockMusicArtworkService.DeleteArtistArtwork(Arg.Any(), Arg.Any(), Arg.Any()) + _mockMusicArtworkService.DeleteArtistArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Error.Failure("Artwork.Error", "Failed to clear the artwork files")); // Act @@ -551,12 +553,12 @@ public class MusicMediaLibraryScanArtworkEnricherTests /// private void SetupSuccessArtworkStorage() { - _mockMusicArtworkService.SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + _mockMusicArtworkService.SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From("/media/music/cover.jpg")); - _mockMusicArtworkService.SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + _mockMusicArtworkService.SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From("/media/music/cover.jpg")); - _mockMusicArtworkService.DeleteArtistArtwork(Arg.Any(), Arg.Any(), Arg.Any()).Returns(Result.Deleted); - _mockMusicArtworkService.DeleteAlbumArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()).Returns(Result.Deleted); + _mockMusicArtworkService.DeleteArtistArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()).Returns(Result.Deleted); + _mockMusicArtworkService.DeleteAlbumArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()).Returns(Result.Deleted); _mockMusicArtworkRepository.DeleteByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()).Returns(Result.Deleted); _mockMusicArtworkRepository.InsertRangeAsync(Arg.Any>(), Arg.Any()).Returns(Result.Created); _mockFileHashService.ComputeFileHash(Arg.Any()).Returns(123UL); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs index 7edeb01f..fee091cf 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs @@ -165,6 +165,8 @@ public class BookArtworkServiceTests // Arrange _mockPathService.SanitizeSegment(Arg.Any()) .Returns(Errors.FileSystemManagement.InvalidPath); + _mockPathService.SanitizeCompositeSegment(Arg.Any(), Arg.Any()) + .Returns(Errors.FileSystemManagement.InvalidPath); // Act Result result = _sut.DeleteBookArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title"); @@ -192,6 +194,14 @@ public class BookArtworkServiceTests return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false)); }); + _mockPathService.SanitizeCompositeSegment(Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + string name = callInfo.ArgAt(0); + string identifier = callInfo.ArgAt(1); + return Result.From(_pathSegmentFixture.Create(name: $"{name}-{identifier}", isDirectory: true, isDrive: false)); + }); + _mockPathService.CombinePath(Arg.Any(), Arg.Any()) .Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1)))); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetDeletedAlbums/GetDeletedAlbumsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetDeletedAlbums/GetDeletedAlbumsEndpointTests.cs new file mode 100644 index 00000000..58ce4d37 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetDeletedAlbums/GetDeletedAlbumsEndpointTests.cs @@ -0,0 +1,199 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums; +using Lumina.Contracts.Fixtures.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetDeletedAlbums; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetDeletedAlbums; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedAlbumsEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetDeletedAlbumsEndpoint _sut; + private readonly DeletedAlbumResponseFixture _deletedAlbumResponseFixture = new(); + private readonly GetDeletedAlbumsQueryFixture _getDeletedAlbumsQueryFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetDeletedAlbumsEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeletedAlbums() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + IReadOnlyList expectedAlbums = + [ + _deletedAlbumResponseFixture.Create( + libraryId: libraryId, + artistName: "Queen", + title: "A Night at the Opera", + includeCoverPath: false) + ]; + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedAlbums)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedAlbums, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = DomainErrors.Library.LibraryIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendTheRouteLibraryIdToTheHandler() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + GetDeletedAlbumsQuery expectedQuery = _getDeletedAlbumsQueryFixture.Create(libraryId: libraryId.ToString()); + await _mockHandler.Received(1).HandleAsync(expectedQuery, Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendQueryWithRawRouteValue() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + GetDeletedAlbumsQuery expectedQuery = _getDeletedAlbumsQueryFixture.Create(libraryId: "not-a-library-guid"); + await _mockHandler.Received(1).HandleAsync(expectedQuery, Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendQueryWithNullLibraryId() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + GetDeletedAlbumsQuery expectedQuery = _getDeletedAlbumsQueryFixture.Create(includeLibraryId: false); + await _mockHandler.Received(1).HandleAsync(expectedQuery, Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From>([]); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString(); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreAlbum/RestoreAlbumEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreAlbum/RestoreAlbumEndpointTests.cs new file mode 100644 index 00000000..e40403e8 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreAlbum/RestoreAlbumEndpointTests.cs @@ -0,0 +1,238 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreAlbum; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreAlbum; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreAlbumEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly RestoreAlbumEndpoint _sut; + private readonly RestoreAlbumCommandFixture _restoreAlbumCommandFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public RestoreAlbumEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithUpdated() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(Result.Updated, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Music.AlbumNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("AlbumNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = DomainErrors.Music.AlbumIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "AlbumIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendTheRouteIdsToTheHandler() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + RestoreAlbumCommand expectedCommand = _restoreAlbumCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artistId.ToString(), + albumId: albumId.ToString()); + await _mockHandler.Received(1).HandleAsync(expectedCommand, Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + _sut.HttpContext.Request.RouteValues["albumId"] = "not-an-album-guid"; + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + RestoreAlbumCommand expectedCommand = _restoreAlbumCommandFixture.Create( + libraryId: "not-a-library-guid", + artistId: "not-an-artist-guid", + albumId: "not-an-album-guid"); + await _mockHandler.Received(1).HandleAsync(expectedCommand, Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + _sut.HttpContext.Request.RouteValues.Remove("albumId"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + RestoreAlbumCommand expectedCommand = _restoreAlbumCommandFixture.Create( + includeLibraryId: false, + includeArtistId: false, + includeAlbumId: false); + await _mockHandler.Received(1).HandleAsync(expectedCommand, Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Updated); + }, callInfo.Arg())); + ConfigureRouteValues(); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Configures the route values of a valid restore request. + /// + private void ConfigureRouteValues() + { + _sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = Guid.NewGuid().ToString(); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetDeletedArtists/GetDeletedArtistsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetDeletedArtists/GetDeletedArtistsEndpointTests.cs new file mode 100644 index 00000000..71be75cf --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetDeletedArtists/GetDeletedArtistsEndpointTests.cs @@ -0,0 +1,198 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists; +using Lumina.Contracts.Fixtures.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetDeletedArtists; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetDeletedArtists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedArtistsEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetDeletedArtistsEndpoint _sut; + private readonly DeletedArtistResponseFixture _deletedArtistResponseFixture = new(); + private readonly GetDeletedArtistsQueryFixture _getDeletedArtistsQueryFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetDeletedArtistsEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeletedArtists() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + IReadOnlyList expectedArtists = + [ + _deletedArtistResponseFixture.Create( + libraryId: libraryId, + name: "Queen", + includeCoverPath: false) + ]; + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedArtists)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedArtists, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = DomainErrors.Library.LibraryIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendTheRouteLibraryIdToTheHandler() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + GetDeletedArtistsQuery expectedQuery = _getDeletedArtistsQueryFixture.Create(libraryId: libraryId.ToString()); + await _mockHandler.Received(1).HandleAsync(expectedQuery, Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendQueryWithRawRouteValue() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + GetDeletedArtistsQuery expectedQuery = _getDeletedArtistsQueryFixture.Create(libraryId: "not-a-library-guid"); + await _mockHandler.Received(1).HandleAsync(expectedQuery, Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendQueryWithNullLibraryId() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + GetDeletedArtistsQuery expectedQuery = _getDeletedArtistsQueryFixture.Create(includeLibraryId: false); + await _mockHandler.Received(1).HandleAsync(expectedQuery, Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From>([]); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString(); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreArtist/RestoreArtistEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreArtist/RestoreArtistEndpointTests.cs new file mode 100644 index 00000000..c0e7f9d7 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreArtist/RestoreArtistEndpointTests.cs @@ -0,0 +1,228 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreArtist; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreArtistEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly RestoreArtistEndpoint _sut; + private readonly RestoreArtistCommandFixture _restoreArtistCommandFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public RestoreArtistEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithUpdated() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(Result.Updated, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Music.ArtistNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("ArtistNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = DomainErrors.Music.ArtistIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "ArtistIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendTheRouteIdsToTheHandler() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + RestoreArtistCommand expectedCommand = _restoreArtistCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artistId.ToString()); + await _mockHandler.Received(1).HandleAsync(expectedCommand, Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + RestoreArtistCommand expectedCommand = _restoreArtistCommandFixture.Create( + libraryId: "not-a-library-guid", + artistId: "not-an-artist-guid"); + await _mockHandler.Received(1).HandleAsync(expectedCommand, Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + RestoreArtistCommand expectedCommand = _restoreArtistCommandFixture.Create(includeLibraryId: false, includeArtistId: false); + await _mockHandler.Received(1).HandleAsync(expectedCommand, Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Updated); + }, callInfo.Arg())); + ConfigureRouteValues(); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Configures the route values of a valid restore request. + /// + private void ConfigureRouteValues() + { + _sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = Guid.NewGuid().ToString(); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetDeletedTracks/GetDeletedTracksEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetDeletedTracks/GetDeletedTracksEndpointTests.cs new file mode 100644 index 00000000..463cb248 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetDeletedTracks/GetDeletedTracksEndpointTests.cs @@ -0,0 +1,199 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks; +using Lumina.Contracts.Fixtures.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetDeletedTracks; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetDeletedTracks; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedTracksEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetDeletedTracksEndpoint _sut; + private readonly DeletedTrackResponseFixture _deletedTrackResponseFixture = new(); + private readonly GetDeletedTracksQueryFixture _getDeletedTracksQueryFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetDeletedTracksEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeletedTracks() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + IReadOnlyList expectedTracks = + [ + _deletedTrackResponseFixture.Create( + libraryId: libraryId, + artistName: "Queen", + albumTitle: "A Night at the Opera", + title: "Bohemian Rhapsody") + ]; + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedTracks)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedTracks, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = DomainErrors.Library.LibraryIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendTheRouteLibraryIdToTheHandler() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + GetDeletedTracksQuery expectedQuery = _getDeletedTracksQueryFixture.Create(libraryId: libraryId.ToString()); + await _mockHandler.Received(1).HandleAsync(expectedQuery, Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendQueryWithRawRouteValue() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + GetDeletedTracksQuery expectedQuery = _getDeletedTracksQueryFixture.Create(libraryId: "not-a-library-guid"); + await _mockHandler.Received(1).HandleAsync(expectedQuery, Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendQueryWithNullLibraryId() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + GetDeletedTracksQuery expectedQuery = _getDeletedTracksQueryFixture.Create(includeLibraryId: false); + await _mockHandler.Received(1).HandleAsync(expectedQuery, Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From>([]); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString(); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreTrack/RestoreTrackEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreTrack/RestoreTrackEndpointTests.cs new file mode 100644 index 00000000..9ed10845 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreTrack/RestoreTrackEndpointTests.cs @@ -0,0 +1,246 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreTrack; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreTrack; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreTrackEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly RestoreTrackEndpoint _sut; + private readonly RestoreTrackCommandFixture _restoreTrackCommandFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public RestoreTrackEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithUpdated() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(Result.Updated, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Music.TrackNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("TrackNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = DomainErrors.Music.TrackIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "TrackIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendTheRouteIdsToTheHandler() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + _sut.HttpContext.Request.RouteValues["trackId"] = trackId.ToString(); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + RestoreTrackCommand expectedCommand = _restoreTrackCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artistId.ToString(), + albumId: albumId.ToString(), + trackId: trackId.ToString()); + await _mockHandler.Received(1).HandleAsync(expectedCommand, Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + _sut.HttpContext.Request.RouteValues["albumId"] = "not-an-album-guid"; + _sut.HttpContext.Request.RouteValues["trackId"] = "not-a-track-guid"; + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + RestoreTrackCommand expectedCommand = _restoreTrackCommandFixture.Create( + libraryId: "not-a-library-guid", + artistId: "not-an-artist-guid", + albumId: "not-an-album-guid", + trackId: "not-a-track-guid"); + await _mockHandler.Received(1).HandleAsync(expectedCommand, Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + _sut.HttpContext.Request.RouteValues.Remove("albumId"); + _sut.HttpContext.Request.RouteValues.Remove("trackId"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + RestoreTrackCommand expectedCommand = _restoreTrackCommandFixture.Create( + includeLibraryId: false, + includeArtistId: false, + includeAlbumId: false, + includeTrackId: false); + await _mockHandler.Received(1).HandleAsync(expectedCommand, Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Updated); + }, callInfo.Arg())); + ConfigureRouteValues(); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Configures the route values of a valid restore request. + /// + private void ConfigureRouteValues() + { + _sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["trackId"] = Guid.NewGuid().ToString(); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpointTests.cs new file mode 100644 index 00000000..3b212fa0 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpointTests.cs @@ -0,0 +1,225 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreMusicAlbum; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreMusicAlbum; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreMusicAlbumEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly RestoreMusicAlbumEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public RestoreMusicAlbumEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + // The restore endpoints forward a bodyless POST upstream; returning an empty request lets every test that is not about + // cancellation focus on the URL construction instead of repeating the upstream stub. + _mockApiHttpClient.PostAsync( + Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new Web.Common.Requests.Common.EmptyRequest()); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Theory] + [InlineData("D")] // Standard hyphenated format. + [InlineData("B")] // Braced format. + [InlineData("N")] // Compact format. + [InlineData("P")] // Parenthesized format. + public async Task ExecuteAsync_WhenCalled_ShouldRestoreAlbumViaApiWithNormalizedIdsAndReturnSuccessPayload(string guidFormat) + { + // Arrange + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + ConfigureRequest(artistId.ToString(guidFormat), albumId.ToString(guidFormat), libraryId.ToString(guidFormat)); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + BuildExpectedEndpoint(libraryId, artistId, albumId), + Arg.Any(), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean()); + } + + [Fact] + public async Task ExecuteAsync_WhenArtistRouteIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi() + { + // Arrange + Guid albumId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + ConfigureRequest("not-a-guid", albumId.ToString(), libraryId.ToString()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + BuildExpectedEndpoint(libraryId, Guid.Empty, albumId), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenArtistRouteIdIsMissing_ShouldForwardGuidEmptyArtistIdToApi() + { + // Arrange + Guid albumId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + ConfigureRequest(null, albumId.ToString(), libraryId.ToString()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + BuildExpectedEndpoint(libraryId, Guid.Empty, albumId), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenAlbumRouteIdIsNotParseable_ShouldForwardGuidEmptyAlbumIdToApi() + { + // Arrange + Guid artistId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + ConfigureRequest(artistId.ToString(), "not-a-guid", libraryId.ToString()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + BuildExpectedEndpoint(libraryId, artistId, Guid.Empty), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenAlbumRouteIdIsMissing_ShouldForwardGuidEmptyAlbumIdToApi() + { + // Arrange + Guid artistId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + ConfigureRequest(artistId.ToString(), null, libraryId.ToString()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + BuildExpectedEndpoint(libraryId, artistId, Guid.Empty), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi() + { + // Arrange + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ConfigureRequest(artistId.ToString(), albumId.ToString(), "not-a-guid"); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + BuildExpectedEndpoint(Guid.Empty, artistId, albumId), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryQueryIdIsMissing_ShouldForwardGuidEmptyLibraryIdToApi() + { + // Arrange + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ConfigureRequest(artistId.ToString(), albumId.ToString(), null); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + BuildExpectedEndpoint(Guid.Empty, artistId, albumId), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + ConfigureRequest(artistId.ToString(), albumId.ToString(), libraryId.ToString()); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + _mockApiHttpClient.PostAsync( + Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.FromCanceled(cancellationTokenSource.Token)); + + // Act & Assert + await Assert.ThrowsAnyAsync( + () => _sut.ExecuteAsync(EmptyRequest.Instance, cancellationTokenSource.Token)); + } + + /// + /// Sets the route and query values the endpoint reads the album identity from. + /// + /// The raw route value of the artist Id, or to leave the route value missing. + /// The raw route value of the album Id, or to leave the route value missing. + /// The raw query value of the library Id, or to leave the query string missing. + private void ConfigureRequest(string? artistId, string? albumId, string? libraryId) + { + if (artistId is not null) + _sut.HttpContext.Request.RouteValues["artistId"] = artistId; + if (albumId is not null) + _sut.HttpContext.Request.RouteValues["albumId"] = albumId; + if (libraryId is not null) + _sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}"); + } + + /// + /// Builds the upstream endpoint the album restoration is expected to be sent to. + /// + /// The normalized Id of the media library. + /// The normalized Id of the artist. + /// The normalized Id of the album. + /// The expected upstream endpoint. + private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId) + { + return ApiRoutes.Music.RESTORE_ALBUM + .Replace("{libraryId}", libraryId.ToString()) + .Replace("{artistId}", artistId.ToString()) + .Replace("{albumId}", albumId.ToString()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/Index/MusicArtistsIndexViewEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/Index/MusicArtistsIndexViewEndpointTests.cs index 9dc17eff..74dd622c 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/Index/MusicArtistsIndexViewEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/Index/MusicArtistsIndexViewEndpointTests.cs @@ -91,6 +91,7 @@ public class MusicArtistsIndexViewEndpointTests _mockUrlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS).Returns("http://localhost/en-us/tools/settings/api-get-user-settings"); _mockUrlService.GetAbsoluteUrl(WebRoutes.Music.ARTIST, Arg.Any()).Returns("http://localhost/en-us/library/audio-library/music-library/artists/00000000-0000-0000-0000-000000000000"); _mockUrlService.GetAbsoluteUrl(WebRoutes.Music.DELETE_ARTIST, Arg.Any()).Returns("http://localhost/en-us/library/audio-library/music-library/artists/00000000-0000-0000-0000-000000000000/api-delete-artist"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Music.DELETED_MUSIC_ITEMS).Returns("http://localhost/en-us/library/audio-library/music-library/deleted-items"); _mockThemePageRenderer.RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "
content
", script: ""))); @@ -120,6 +121,10 @@ public class MusicArtistsIndexViewEndpointTests string.Equals( page.PageData["deleteUrl"] as string, "http://localhost/en-us/library/audio-library/music-library/artists/00000000-0000-0000-0000-000000000000/api-delete-artist", + StringComparison.Ordinal) && + string.Equals( + page.PageData["deletedItemsUrl"] as string, + "http://localhost/en-us/library/audio-library/music-library/deleted-items", StringComparison.Ordinal)), Arg.Is(requestedThemeId => requestedThemeId == null), Arg.Any()); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpointTests.cs new file mode 100644 index 00000000..898b60b4 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpointTests.cs @@ -0,0 +1,178 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreMusicArtist; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreMusicArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreMusicArtistEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly RestoreMusicArtistEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public RestoreMusicArtistEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + // The restore endpoints forward a bodyless POST upstream; returning an empty request lets every test that is not about + // cancellation focus on the URL construction instead of repeating the upstream stub. + _mockApiHttpClient.PostAsync( + Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new Web.Common.Requests.Common.EmptyRequest()); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Theory] + [InlineData("D")] // Standard hyphenated format. + [InlineData("B")] // Braced format. + [InlineData("N")] // Compact format. + [InlineData("P")] // Parenthesized format. + public async Task ExecuteAsync_WhenCalled_ShouldRestoreArtistViaApiWithNormalizedIdsAndReturnSuccessPayload(string guidFormat) + { + // Arrange + Guid artistId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + ConfigureRequest(artistId.ToString(guidFormat), libraryId.ToString(guidFormat)); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + BuildExpectedEndpoint(libraryId, artistId), + Arg.Any(), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean()); + } + + [Fact] + public async Task ExecuteAsync_WhenArtistRouteIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ConfigureRequest("not-a-guid", libraryId.ToString()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + BuildExpectedEndpoint(libraryId, Guid.Empty), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenArtistRouteIdIsMissing_ShouldForwardGuidEmptyArtistIdToApi() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ConfigureRequest(null, libraryId.ToString()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + BuildExpectedEndpoint(libraryId, Guid.Empty), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi() + { + // Arrange + Guid artistId = Guid.NewGuid(); + ConfigureRequest(artistId.ToString(), "not-a-guid"); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + BuildExpectedEndpoint(Guid.Empty, artistId), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryQueryIdIsMissing_ShouldForwardGuidEmptyLibraryIdToApi() + { + // Arrange + Guid artistId = Guid.NewGuid(); + ConfigureRequest(artistId.ToString(), null); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + BuildExpectedEndpoint(Guid.Empty, artistId), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + Guid artistId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + ConfigureRequest(artistId.ToString(), libraryId.ToString()); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + _mockApiHttpClient.PostAsync( + Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.FromCanceled(cancellationTokenSource.Token)); + + // Act & Assert + await Assert.ThrowsAnyAsync( + () => _sut.ExecuteAsync(EmptyRequest.Instance, cancellationTokenSource.Token)); + } + + /// + /// Sets the route and query values the endpoint reads the artist identity from. + /// + /// The raw route value of the artist Id, or to leave the route value missing. + /// The raw query value of the library Id, or to leave the query string missing. + private void ConfigureRequest(string? artistId, string? libraryId) + { + if (artistId is not null) + _sut.HttpContext.Request.RouteValues["artistId"] = artistId; + if (libraryId is not null) + _sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}"); + } + + /// + /// Builds the upstream endpoint the artist restoration is expected to be sent to. + /// + /// The normalized Id of the media library. + /// The normalized Id of the artist. + /// The expected upstream endpoint. + private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId) + { + return ApiRoutes.Music.RESTORE_ARTIST + .Replace("{libraryId}", libraryId.ToString()) + .Replace("{artistId}", artistId.ToString()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/DeletedMusicItems/DeletedMusicItemsViewEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/DeletedMusicItems/DeletedMusicItemsViewEndpointTests.cs new file mode 100644 index 00000000..dc4a072b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/DeletedMusicItems/DeletedMusicItemsViewEndpointTests.cs @@ -0,0 +1,345 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.DeletedMusicItems; +using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.Extensions.Localization; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.DeletedMusicItems; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeletedMusicItemsViewEndpointTests +{ + private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000"; + + private readonly IApiHttpClient _mockApiHttpClient; + private readonly IUrlService _mockUrlService; + private readonly ThemePageRenderer _mockThemePageRenderer; + private readonly IAntiforgery _mockAntiforgery; + private readonly IStringLocalizerFactory _mockStringLocalizerFactory; + private readonly IStringLocalizer _mockStringLocalizer; + private readonly DeletedMusicItemsViewEndpoint _sut; + private readonly LibraryDtoFixture _libraryDtoFixture = new(); + private readonly DeletedMusicArtistDtoFixture _deletedMusicArtistDtoFixture = new(); + private readonly DeletedMusicAlbumDtoFixture _deletedMusicAlbumDtoFixture = new(); + private readonly DeletedMusicTrackDtoFixture _deletedMusicTrackDtoFixture = new(); + private readonly DeletedMusicItemsPageDtoFixture _deletedMusicItemsPageDtoFixture = new(); + private readonly GetMusicArtistsViewRequestFixture _getMusicArtistsViewRequestFixture = new(); + private readonly ThemePageRenderResultDtoFixture _themePageRenderResultDtoFixture = new(); + private readonly List _artistRestoreRouteValues = []; + private readonly List _albumRestoreRouteValues = []; + private readonly List _trackRestoreRouteValues = []; + + /// + /// Initializes a new instance of the class. + /// + public DeletedMusicItemsViewEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _mockUrlService = Substitute.For(); + _mockThemePageRenderer = Substitute.For(new ThemeService(_mockApiHttpClient), new ThemeTemplateEngine()); + _mockAntiforgery = Substitute.For(); + _mockAntiforgery.GetAndStoreTokens(Arg.Any()) + .Returns(new AntiforgeryTokenSet("request-token", "cookie-token", "__RequestVerificationToken", "RequestVerificationToken")); + _mockStringLocalizer = Substitute.For(); + _mockStringLocalizer[Arg.Any()].Returns(callInfo => new LocalizedString( + callInfo.Arg(), + callInfo.Arg() == "Title" ? "Deleted items" : $"Localized-{callInfo.Arg()}")); + _mockStringLocalizer.GetAllStrings(Arg.Any()).Returns( + [ + new("Title", "Deleted items"), + new("BackToLibrary", "Back to library"), + new("NoDeletedItems", "There are no deleted items in this library."), + new("Artists", "Artists"), + new("Albums", "Albums"), + new("Tracks", "Tracks"), + new("Name", "Name"), + new("Artist", "Artist"), + new("Album", "Album"), + new("TrackTitle", "Title"), + new("DeletedOn", "Deleted on"), + new("Restore", "Restore"), + new("Restored", "The item was restored."), + new("RestoreFailed", "The item could not be restored.") + ]); + _mockStringLocalizerFactory = Substitute.For(); + _mockStringLocalizerFactory.Create(Arg.Any(), Arg.Any()).Returns(_mockStringLocalizer); + _sut = Factory.Create(_mockApiHttpClient, _mockUrlService, _mockThemePageRenderer, _mockAntiforgery, _mockStringLocalizerFactory); + TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession()); + _sut.HttpContext.Request.Path = "/en-us/library/audio-library/music-library/deleted-items"; + + StubUrls(); + } + + [Fact] + public async Task ExecuteAsync_WhenThemeRenderingSucceeds_ShouldRenderThemedViewWithDocumentedPageData() + { + // Arrange + LibraryDto library = _libraryDtoFixture.Create(title: "Music"); + DeletedMusicArtistDto[] deletedArtists = [.. _deletedMusicArtistDtoFixture.CreateMany(2)]; + DeletedMusicAlbumDto[] deletedAlbums = [.. _deletedMusicAlbumDtoFixture.CreateMany(2)]; + DeletedMusicTrackDto[] deletedTracks = [.. _deletedMusicTrackDtoFixture.CreateMany(2)]; + Guid libraryId = library.Id!.Value; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()).Returns(library); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()).Returns(deletedArtists); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()).Returns(deletedAlbums); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()).Returns(deletedTracks); + _mockThemePageRenderer.RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "
deleted
", script: ""))); + + // Act + IResult result = await _sut.ExecuteAsync(_getMusicArtistsViewRequestFixture.Create(libraryId: libraryId), CancellationToken.None); + + // Assert + Assert.Equal("/Core/Views/Shared/_ThemedView.cshtml", GetRenderedViewName(result)); + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_BY_ID.Replace("{id}", libraryId.ToString())), + Arg.Any()); + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Music.GET_DELETED_ARTISTS.Replace("{libraryId}", libraryId.ToString())), + Arg.Any()); + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Music.GET_DELETED_ALBUMS.Replace("{libraryId}", libraryId.ToString())), + Arg.Any()); + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Music.GET_DELETED_TRACKS.Replace("{libraryId}", libraryId.ToString())), + Arg.Any()); + await _mockThemePageRenderer.Received(1).RenderAsync( + Arg.Is(page => + page.PageKey == "library/audio-library/music-library/deleted-items" && + page.Title == "Deleted items" && + page.Description == string.Empty && + string.Equals(page.PageData["libraryId"] as string, libraryId.ToString(), StringComparison.Ordinal) && + string.Equals(page.PageData["libraryTitle"] as string, "Music", StringComparison.Ordinal) && + string.Equals(page.PageData["artistRestoreUrl"] as string, $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/api-restore-artist", StringComparison.Ordinal) && + string.Equals(page.PageData["albumRestoreUrl"] as string, $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/{ZERO_GUID}/api-restore-album", StringComparison.Ordinal) && + string.Equals(page.PageData["trackRestoreUrl"] as string, $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/{ZERO_GUID}/tracks/{ZERO_GUID}/api-restore-track", StringComparison.Ordinal) && + string.Equals(page.PageData["backUrl"] as string, $"http://localhost/en-us/library/audio-library/music-library/artists?libraryId={libraryId}", StringComparison.Ordinal) && + string.Equals(page.PageData["antiforgeryToken"] as string, "request-token", StringComparison.Ordinal) && + HasDocumentedDeletedMusicItems(page, deletedArtists, deletedAlbums, deletedTracks) && + HasDocumentedLocalizedStrings(page)), + Arg.Is(requestedThemeId => requestedThemeId == null), + Arg.Any()); + _mockAntiforgery.Received(1).GetAndStoreTokens(_sut.HttpContext); + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryIdIsNull_ShouldRedirectToHome() + { + // Arrange + _mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us"); + + // Act + IResult result = await _sut.ExecuteAsync(_getMusicArtistsViewRequestFixture.Create(libraryId: null), CancellationToken.None); + + // Assert + RedirectHttpResult redirectResult = Assert.IsType(result); + Assert.Equal("http://localhost/en-us", redirectResult.Url); + await _mockApiHttpClient.DidNotReceive().GetAsync(Arg.Any(), Arg.Any()); + await _mockApiHttpClient.DidNotReceive().GetAsync(Arg.Any(), Arg.Any()); + await _mockApiHttpClient.DidNotReceive().GetAsync(Arg.Any(), Arg.Any()); + await _mockApiHttpClient.DidNotReceive().GetAsync(Arg.Any(), Arg.Any()); + await _mockThemePageRenderer.DidNotReceive().RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()); + _mockAntiforgery.DidNotReceive().GetAndStoreTokens(Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldFallBackToTheRazorViewWithTheDeletedMusicItems() + { + // Arrange + LibraryDto library = _libraryDtoFixture.Create(title: "Music"); + DeletedMusicArtistDto[] deletedArtists = [.. _deletedMusicArtistDtoFixture.CreateMany(2)]; + DeletedMusicAlbumDto[] deletedAlbums = [.. _deletedMusicAlbumDtoFixture.CreateMany(2)]; + DeletedMusicTrackDto[] deletedTracks = [.. _deletedMusicTrackDtoFixture.CreateMany(2)]; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()).Returns(library); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()).Returns(deletedArtists); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()).Returns(deletedAlbums); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()).Returns(deletedTracks); + _mockThemePageRenderer.RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.Failure(Error.Failure("Theme.Render", "The page could not be rendered."))); + + // Act + IResult result = await _sut.ExecuteAsync(_getMusicArtistsViewRequestFixture.Create(libraryId: library.Id), CancellationToken.None); + + // Assert + Assert.Equal("/Core/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.cshtml", GetRenderedViewName(result)); + DeletedMusicItemsPageDto expectedPage = _deletedMusicItemsPageDtoFixture.Create( + library: library, + deletedArtists: deletedArtists, + deletedAlbums: deletedAlbums, + deletedTracks: deletedTracks); + DeletedMusicItemsPageDto model = Assert.IsType(GetRenderedModel(result)); + Assert.Equal(expectedPage, model); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldUseTheAllZeroGuidTemplatesOfTheRestoreRoutes() + { + // Arrange + LibraryDto library = _libraryDtoFixture.Create(title: "Music"); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()).Returns(library); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()).Returns(Array.Empty()); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()).Returns(Array.Empty()); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()).Returns(Array.Empty()); + _mockThemePageRenderer.RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_themePageRenderResultDtoFixture.Create())); + + // Act + await _sut.ExecuteAsync(_getMusicArtistsViewRequestFixture.Create(libraryId: library.Id), CancellationToken.None); + + // Assert + // The themed page replaces each all-zero Guid placeholder of the restore URLs one at a time, so every route value must be an empty Guid. + Assert.Single(_artistRestoreRouteValues); + AssertRouteValueIsEmptyGuid(_artistRestoreRouteValues[0], "artistId"); + Assert.Single(_albumRestoreRouteValues); + AssertRouteValueIsEmptyGuid(_albumRestoreRouteValues[0], "artistId"); + AssertRouteValueIsEmptyGuid(_albumRestoreRouteValues[0], "albumId"); + Assert.Single(_trackRestoreRouteValues); + AssertRouteValueIsEmptyGuid(_trackRestoreRouteValues[0], "artistId"); + AssertRouteValueIsEmptyGuid(_trackRestoreRouteValues[0], "albumId"); + AssertRouteValueIsEmptyGuid(_trackRestoreRouteValues[0], "trackId"); + } + + /// + /// Stubs the absolute URLs that the endpoint resolves for the deleted music items page. + /// + private void StubUrls() + { + _mockUrlService.GetAbsoluteUrl(WebRoutes.Music.ARTISTS_INDEX).Returns("http://localhost/en-us/library/audio-library/music-library/artists"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Music.RESTORE_ARTIST, Arg.Any()) + .Returns(callInfo => + { + _artistRestoreRouteValues.Add(callInfo.ArgAt(1)); + return $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/api-restore-artist"; + }); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Music.RESTORE_ALBUM, Arg.Any()) + .Returns(callInfo => + { + _albumRestoreRouteValues.Add(callInfo.ArgAt(1)); + return $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/{ZERO_GUID}/api-restore-album"; + }); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Music.RESTORE_TRACK, Arg.Any()) + .Returns(callInfo => + { + _trackRestoreRouteValues.Add(callInfo.ArgAt(1)); + return $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/{ZERO_GUID}/tracks/{ZERO_GUID}/api-restore-track"; + }); + } + + /// + /// Reads the private view name of the rendered , which the result does not expose publicly. + /// + /// The result returned by the endpoint under test. + /// The name or path of the rendered view. + private static string GetRenderedViewName(IResult result) + { + RazorViewResult viewResult = Assert.IsType(result); + FieldInfo? viewNameField = typeof(RazorViewResult).GetField("_viewName", BindingFlags.Instance | BindingFlags.NonPublic); + Assert.NotNull(viewNameField); + return (string)viewNameField.GetValue(viewResult)!; + } + + /// + /// Reads the private model of the rendered , which the result does not expose publicly. + /// + /// The result returned by the endpoint under test. + /// The model passed to the rendered view. + private static object? GetRenderedModel(IResult result) + { + RazorViewResult viewResult = Assert.IsType(result); + FieldInfo? modelField = typeof(RazorViewResult).GetField("_model", BindingFlags.Instance | BindingFlags.NonPublic); + Assert.NotNull(modelField); + return modelField.GetValue(viewResult); + } + + /// + /// Determines whether the page data carries the serialized deleted music items of the page. + /// + /// The page model passed to the theme renderer. + /// The deleted artists expected in the page data. + /// The deleted albums expected in the page data. + /// The deleted tracks expected in the page data. + /// when the serialized deleted items match the expected ones; otherwise . + private static bool HasDocumentedDeletedMusicItems( + ThemePageDto page, + DeletedMusicArtistDto[] deletedArtists, + DeletedMusicAlbumDto[] deletedAlbums, + DeletedMusicTrackDto[] deletedTracks) + { + if (!page.PageData.TryGetValue("deletedArtistsJson", out object? artistsValue) || artistsValue is not string artistsJson) + return false; + if (!page.PageData.TryGetValue("deletedAlbumsJson", out object? albumsValue) || albumsValue is not string albumsJson) + return false; + if (!page.PageData.TryGetValue("deletedTracksJson", out object? tracksValue) || tracksValue is not string tracksJson) + return false; + + using JsonDocument artistsDocument = JsonDocument.Parse(artistsJson); + using JsonDocument albumsDocument = JsonDocument.Parse(albumsJson); + using JsonDocument tracksDocument = JsonDocument.Parse(tracksJson); + return artistsDocument.RootElement.GetArrayLength() == deletedArtists.Length + && string.Equals(artistsDocument.RootElement[0].GetProperty("name").GetString(), deletedArtists[0].Name, StringComparison.Ordinal) + && albumsDocument.RootElement.GetArrayLength() == deletedAlbums.Length + && string.Equals(albumsDocument.RootElement[0].GetProperty("title").GetString(), deletedAlbums[0].Title, StringComparison.Ordinal) + && tracksDocument.RootElement.GetArrayLength() == deletedTracks.Length + && string.Equals(tracksDocument.RootElement[0].GetProperty("albumTitle").GetString(), deletedTracks[0].AlbumTitle, StringComparison.Ordinal); + } + + /// + /// Determines whether the page data carries the localized strings of the deleted music items page, both raw and serialized. + /// + /// The page model passed to the theme renderer. + /// when the localized strings are exposed and serialized; otherwise . + private static bool HasDocumentedLocalizedStrings(ThemePageDto page) + { + if (!page.PageData.TryGetValue("strings", out object? value) || value is not Dictionary strings) + return false; + if (!page.PageData.TryGetValue("stringsJson", out object? jsonValue) || jsonValue is not string stringsJson) + return false; + + using JsonDocument stringsDocument = JsonDocument.Parse(stringsJson); + return string.Equals(strings["Title"] as string, "Deleted items", StringComparison.Ordinal) + && string.Equals(strings["NoDeletedItems"] as string, "There are no deleted items in this library.", StringComparison.Ordinal) + && string.Equals(stringsDocument.RootElement.GetProperty("title").GetString(), "Deleted items", StringComparison.Ordinal) + && string.Equals(stringsDocument.RootElement.GetProperty("noDeletedItems").GetString(), "There are no deleted items in this library.", StringComparison.Ordinal); + } + + /// + /// Asserts that the named property of an anonymous route values object is the empty Guid. + /// + /// The anonymous route values object passed to the URL service. + /// The name of the route value property to check. + private static void AssertRouteValueIsEmptyGuid(object? routeValues, string propertyName) + { + Assert.NotNull(routeValues); + PropertyInfo? property = routeValues!.GetType().GetProperty(propertyName); + Assert.NotNull(property); + Assert.Equal(Guid.Empty, (Guid)property!.GetValue(routeValues)!); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpointTests.cs new file mode 100644 index 00000000..a654bb87 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpointTests.cs @@ -0,0 +1,276 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreMusicTrack; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreMusicTrack; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreMusicTrackEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly RestoreMusicTrackEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public RestoreMusicTrackEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + // The restore endpoints forward a bodyless POST upstream; returning an empty request lets every test that is not about + // cancellation focus on the URL construction instead of repeating the upstream stub. + _mockApiHttpClient.PostAsync( + Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new Web.Common.Requests.Common.EmptyRequest()); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Theory] + [InlineData("D")] // Standard hyphenated format. + [InlineData("B")] // Braced format. + [InlineData("N")] // Compact format. + [InlineData("P")] // Parenthesized format. + public async Task ExecuteAsync_WhenCalled_ShouldRestoreTrackViaApiWithNormalizedIdsAndReturnSuccessPayload(string guidFormat) + { + // Arrange + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + ConfigureRequest(artistId.ToString(guidFormat), albumId.ToString(guidFormat), trackId.ToString(guidFormat), libraryId.ToString(guidFormat)); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + BuildExpectedEndpoint(libraryId, artistId, albumId, trackId), + Arg.Any(), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean()); + } + + [Fact] + public async Task ExecuteAsync_WhenArtistRouteIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi() + { + // Arrange + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + ConfigureRequest("not-a-guid", albumId.ToString(), trackId.ToString(), libraryId.ToString()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + BuildExpectedEndpoint(libraryId, Guid.Empty, albumId, trackId), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenArtistRouteIdIsMissing_ShouldForwardGuidEmptyArtistIdToApi() + { + // Arrange + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + ConfigureRequest(null, albumId.ToString(), trackId.ToString(), libraryId.ToString()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + BuildExpectedEndpoint(libraryId, Guid.Empty, albumId, trackId), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenAlbumRouteIdIsNotParseable_ShouldForwardGuidEmptyAlbumIdToApi() + { + // Arrange + Guid artistId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + ConfigureRequest(artistId.ToString(), "not-a-guid", trackId.ToString(), libraryId.ToString()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + BuildExpectedEndpoint(libraryId, artistId, Guid.Empty, trackId), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenAlbumRouteIdIsMissing_ShouldForwardGuidEmptyAlbumIdToApi() + { + // Arrange + Guid artistId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + ConfigureRequest(artistId.ToString(), null, trackId.ToString(), libraryId.ToString()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + BuildExpectedEndpoint(libraryId, artistId, Guid.Empty, trackId), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTrackRouteIdIsNotParseable_ShouldForwardGuidEmptyTrackIdToApi() + { + // Arrange + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + ConfigureRequest(artistId.ToString(), albumId.ToString(), "not-a-guid", libraryId.ToString()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + BuildExpectedEndpoint(libraryId, artistId, albumId, Guid.Empty), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTrackRouteIdIsMissing_ShouldForwardGuidEmptyTrackIdToApi() + { + // Arrange + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + ConfigureRequest(artistId.ToString(), albumId.ToString(), null, libraryId.ToString()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + BuildExpectedEndpoint(libraryId, artistId, albumId, Guid.Empty), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi() + { + // Arrange + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + ConfigureRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), "not-a-guid"); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + BuildExpectedEndpoint(Guid.Empty, artistId, albumId, trackId), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryQueryIdIsMissing_ShouldForwardGuidEmptyLibraryIdToApi() + { + // Arrange + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + ConfigureRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), null); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + BuildExpectedEndpoint(Guid.Empty, artistId, albumId, trackId), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + ConfigureRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), libraryId.ToString()); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + _mockApiHttpClient.PostAsync( + Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.FromCanceled(cancellationTokenSource.Token)); + + // Act & Assert + await Assert.ThrowsAnyAsync( + () => _sut.ExecuteAsync(EmptyRequest.Instance, cancellationTokenSource.Token)); + } + + /// + /// Sets the route and query values the endpoint reads the track identity from. + /// + /// The raw route value of the artist Id, or to leave the route value missing. + /// The raw route value of the album Id, or to leave the route value missing. + /// The raw route value of the track Id, or to leave the route value missing. + /// The raw query value of the library Id, or to leave the query string missing. + private void ConfigureRequest(string? artistId, string? albumId, string? trackId, string? libraryId) + { + if (artistId is not null) + _sut.HttpContext.Request.RouteValues["artistId"] = artistId; + if (albumId is not null) + _sut.HttpContext.Request.RouteValues["albumId"] = albumId; + if (trackId is not null) + _sut.HttpContext.Request.RouteValues["trackId"] = trackId; + if (libraryId is not null) + _sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}"); + } + + /// + /// Builds the upstream endpoint the track restoration is expected to be sent to. + /// + /// The normalized Id of the media library. + /// The normalized Id of the artist. + /// The normalized Id of the album. + /// The normalized Id of the track. + /// The expected upstream endpoint. + private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) + { + return ApiRoutes.Music.RESTORE_TRACK + .Replace("{libraryId}", libraryId.ToString()) + .Replace("{artistId}", artistId.ToString()) + .Replace("{albumId}", albumId.ToString()) + .Replace("{trackId}", trackId.ToString()); + } +}