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