Merge pull request #250 from BinaryAlley/feature/implement-music-library-web-client

Feature/implement music library web client
This commit is contained in:
BinaryAlley authored and GitHub committed 2026-10-13 13:58:20 +03:00
commit 728a879bb8
469 files changed
+72902 -1053

No files matched your search

+1
View File
@@ -108,6 +108,7 @@ Several icons used in this project were adapted from icons sourced from [svgrepo
- [`error.svg`](https://www.svgrepo.com/svg/486408/error-filled) (MIT License) - [`error.svg`](https://www.svgrepo.com/svg/486408/error-filled) (MIT License)
- [`trigger.svg`](https://www.svgrepo.com/svg/489497/lightning-1) (Public Domain License) - [`trigger.svg`](https://www.svgrepo.com/svg/489497/lightning-1) (Public Domain License)
- [`stop.svg`](https://www.svgrepo.com/svg/521862/stop) (CC Attribution License) - [`stop.svg`](https://www.svgrepo.com/svg/521862/stop) (CC Attribution License)
- [`music-placeholder.svg`](https://www.svgrepo.com/svg/446269/music) (CC Attribution License)
**I greatly appreciate the creators and contributors for providing these assets.** **I greatly appreciate the creators and contributors for providing these assets.**
+10 -3
View File
@@ -62,13 +62,20 @@ A book opens only through an enabled reader for its format. The EPUB and PDF rea
## Browsing your music ## Browsing your music
Opening a music library shows a page with the library title, a search box, an item count, a grid of artist cards, and pagination. Search filters the artists by name. Each artist is a card; selecting it opens the artist's page, and the card's actions menu offers **View details** and **Delete**. 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.
The artist page is also where you edit the artist. It holds the artist's general information, areas, aliases, contributors and ratings, and it lists the artist's albums as cards, each leading to its own album page. The album page holds the album's information and its tracks, and the track page holds the track's details. Deleting an artist, album or track removes it from Lumina's catalogue; your files are not touched. - **Search** filters the artists by name; press Enter or use the search button.
- **Sort** toggles between ascending and descending order.
- **The alpha picker** jumps to names starting with a chosen character. It offers All, then the number and symbol keys, then A to Z. You can also press a letter key to filter, and press Escape to clear the filter.
- **Pagination** splits the list into pages when you have it enabled, with previous and next buttons and a page indicator. When it is off, the whole list is shown and the count is the total.
Each artist is a card; selecting it opens the artist's page, and the card's actions menu offers **View details** and **Delete**.
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.
## Editing what is catalogued ## Editing what is catalogued
Both book and music pages double as editors for the items that were scanned in. A book's details page groups its fields into general and release information, language and original language, genres, tags, identifiers, ISBNs, contributors and ratings, and lets you replace its cover. An artist's page groups its fields into general information, areas, aliases, contributors and ratings. Album and track pages follow the same shape for their own fields. Saving sends the changes back to the server, and a confirmation or an error is shown in the corner of the screen. Both book and music pages double as editors for the items that were scanned in. A book's details page groups its fields into general and release information, language and original language, genres, tags, identifiers, ISBNs, contributors and ratings, and lets you replace its cover. An artist's page lists the artist's albums first, then groups its fields into general information, contributors, ratings, genres, tags, aliases, areas and identifiers, and lets you replace the artist's cover. An album page groups its fields into general information, contributors, ratings, genres, tags, release types, release information, language and original language, and identifiers, and lets you replace the album's cover. A track page groups its fields into general information, contributors, ratings, genres, tags, moods, release information, language and original language, work, ISRCs, identifiers and audio properties. Saving sends the changes back to the server, and a confirmation or an error is shown in the corner of the screen.
Changes you make here live in Lumina's catalogue. Changes you make here live in Lumina's catalogue.
@@ -17,6 +17,9 @@
- [Update Album](#update-album) - [Update Album](#update-album)
- [Update Album Request](#update-album-request) - [Update Album Request](#update-album-request)
- [Update Album Response](#update-album-response) - [Update Album Response](#update-album-response)
- [Update Album Cover](#update-album-cover)
- [Update Album Cover Request](#update-album-cover-request)
- [Update Album Cover Response](#update-album-cover-response)
- [Delete Album](#delete-album) - [Delete Album](#delete-album)
- [Get Album Tracks](#get-album-tracks) - [Get Album Tracks](#get-album-tracks)
- [Get Album Tracks Request](#get-album-tracks-request) - [Get Album Tracks Request](#get-album-tracks-request)
@@ -41,12 +44,12 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"title": "A Night at the Opera", "title": "A Night at the Opera",
"originalTitle": "A Night at the Opera", "originalTitle": "A Night at the Opera",
"description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.", "description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.",
"disambiguation": null, "disambiguation": "original release",
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-11-21", "originalReleaseDate": "1975-11-21",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
"reReleaseDate": null, "reReleaseDate": "2011-11-21",
"reReleaseYear": null, "reReleaseYear": 2011,
"releaseCountry": "GB", "releaseCountry": "GB",
"releaseVersion": "Remastered" "releaseVersion": "Remastered"
}, },
@@ -109,12 +112,12 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"disambiguation": null, "disambiguation": "album version",
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-10-31", "originalReleaseDate": "1975-10-31",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
"reReleaseDate": null, "reReleaseDate": "2011-11-21",
"reReleaseYear": null, "reReleaseYear": 2011,
"releaseCountry": "GB", "releaseCountry": "GB",
"releaseVersion": "Original" "releaseVersion": "Original"
}, },
@@ -161,7 +164,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"languages": [ "languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" } { "languageCode": "en", "languageName": "English", "nativeName": "English" }
], ],
"iswcs": [] "iswcs": ["T-010489707-6"]
}, },
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
@@ -197,12 +200,12 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"title": "You're My Best Friend", "title": "You're My Best Friend",
"originalTitle": "You're My Best Friend", "originalTitle": "You're My Best Friend",
"description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.", "description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.",
"disambiguation": null, "disambiguation": "album version",
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1976-06-18", "originalReleaseDate": "1976-06-18",
"originalReleaseYear": 1976, "originalReleaseYear": 1976,
"reReleaseDate": null, "reReleaseDate": "2011-11-21",
"reReleaseYear": null, "reReleaseYear": 2011,
"releaseCountry": "GB", "releaseCountry": "GB",
"releaseVersion": "Original" "releaseVersion": "Original"
}, },
@@ -231,11 +234,11 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"bitDepth": 16, "bitDepth": 16,
"audioCodec": "FLAC", "audioCodec": "FLAC",
"bitrate": 912, "bitrate": 912,
"acoustId": null, "acoustId": "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d",
"replayGainTrackGain": null, "replayGainTrackGain": -7.2,
"replayGainTrackPeak": null, "replayGainTrackPeak": 0.9812,
"replayGainAlbumGain": null, "replayGainAlbumGain": -6.5,
"replayGainAlbumPeak": null "replayGainAlbumPeak": 0.9987
}, },
"trackNumber": 7, "trackNumber": 7,
"discNumber": 1, "discNumber": 1,
@@ -249,7 +252,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"languages": [ "languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" } { "languageCode": "en", "languageName": "English", "nativeName": "English" }
], ],
"iswcs": [] "iswcs": ["T-010489707-6"]
}, },
"musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f", "musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f",
"musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
@@ -298,12 +301,12 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"title": "A Night at the Opera", "title": "A Night at the Opera",
"originalTitle": "A Night at the Opera", "originalTitle": "A Night at the Opera",
"description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.", "description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.",
"disambiguation": null, "disambiguation": "original release",
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-11-21", "originalReleaseDate": "1975-11-21",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
"reReleaseDate": null, "reReleaseDate": "2011-11-21",
"reReleaseYear": null, "reReleaseYear": 2011,
"releaseCountry": "GB", "releaseCountry": "GB",
"releaseVersion": "Remastered" "releaseVersion": "Remastered"
}, },
@@ -342,7 +345,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
"musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null, "updatedOnUtc": "2025-01-20T14:45:00.0000000Z",
"contributors": [ "contributors": [
{ {
"contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b", "contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b",
@@ -377,8 +380,8 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"disambiguation": null, "disambiguation": "album version",
"releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" }, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": "2011-11-21", "reReleaseYear": 2011, "releaseCountry": "GB", "releaseVersion": "Original" },
"language": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "language": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"tags": [ { "name": "classic" }, { "name": "epic" } ], "tags": [ { "name": "classic" }, { "name": "epic" } ],
@@ -408,12 +411,12 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"languages": [ "languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" } { "languageCode": "en", "languageName": "English", "nativeName": "English" }
], ],
"iswcs": [] "iswcs": ["T-010489707-6"]
}, },
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null, "updatedOnUtc": "2025-01-20T14:45:00.0000000Z",
"moods": [ "moods": [
{ "name": "dramatic" }, { "name": "dramatic" },
{ "name": "anxious" } { "name": "anxious" }
@@ -455,8 +458,8 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"title": "You're My Best Friend", "title": "You're My Best Friend",
"originalTitle": "You're My Best Friend", "originalTitle": "You're My Best Friend",
"description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.", "description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.",
"disambiguation": null, "disambiguation": "album version",
"releaseInfo": { "originalReleaseDate": "1976-06-18", "originalReleaseYear": 1976, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" }, "releaseInfo": { "originalReleaseDate": "1976-06-18", "originalReleaseYear": 1976, "reReleaseDate": "2011-11-21", "reReleaseYear": 2011, "releaseCountry": "GB", "releaseVersion": "Original" },
"language": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "language": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"tags": [ { "name": "classic" }, { "name": "love" } ], "tags": [ { "name": "classic" }, { "name": "love" } ],
@@ -468,11 +471,11 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"bitDepth": 16, "bitDepth": 16,
"audioCodec": "FLAC", "audioCodec": "FLAC",
"bitrate": 912, "bitrate": 912,
"acoustId": null, "acoustId": "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d",
"replayGainTrackGain": null, "replayGainTrackGain": -7.2,
"replayGainTrackPeak": null, "replayGainTrackPeak": 0.9812,
"replayGainAlbumGain": null, "replayGainAlbumGain": -6.5,
"replayGainAlbumPeak": null "replayGainAlbumPeak": 0.9987
}, },
"trackNumber": 7, "trackNumber": 7,
"discNumber": 1, "discNumber": 1,
@@ -486,12 +489,12 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"languages": [ "languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" } { "languageCode": "en", "languageName": "English", "nativeName": "English" }
], ],
"iswcs": [] "iswcs": ["T-010489707-6"]
}, },
"musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f", "musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f",
"musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null, "updatedOnUtc": "2025-01-20T14:45:00.0000000Z",
"moods": [ "moods": [
{ "name": "happy" }, { "name": "happy" },
{ "name": "warm" } { "name": "warm" }
@@ -524,6 +527,14 @@ 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",
"artwork": [
{
"type": "Cover",
"ordinal": 0,
"path": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg"
}
] ]
} }
``` ```
@@ -553,12 +564,12 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"title": "A Night at the Opera", "title": "A Night at the Opera",
"originalTitle": "A Night at the Opera", "originalTitle": "A Night at the Opera",
"description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.", "description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.",
"disambiguation": null, "disambiguation": "original release",
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-11-21", "originalReleaseDate": "1975-11-21",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
"reReleaseDate": null, "reReleaseDate": "2011-11-21",
"reReleaseYear": null, "reReleaseYear": 2011,
"releaseCountry": "GB", "releaseCountry": "GB",
"releaseVersion": "Remastered" "releaseVersion": "Remastered"
}, },
@@ -597,7 +608,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
"musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null, "updatedOnUtc": "2025-01-20T14:45:00.0000000Z",
"contributors": [ "contributors": [
{ {
"contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b", "contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b",
@@ -622,7 +633,172 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"voteCount": 1234 "voteCount": 1234
} }
], ],
"tracks": [] "tracks": [
{
"id": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f",
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
"metadata": {
"title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"disambiguation": "album version",
"releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": "2011-11-21", "reReleaseYear": 2011, "releaseCountry": "GB", "releaseVersion": "Original" },
"language": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"tags": [ { "name": "classic" }, { "name": "epic" } ],
"genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ],
"isVideo": false,
"durationInSeconds": 354,
"sampleRate": 44100,
"channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"bitrate": 980,
"acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f",
"replayGainTrackGain": -7.5,
"replayGainTrackPeak": 0.9877,
"replayGainAlbumGain": -6.8,
"replayGainAlbumPeak": 0.9999
},
"trackNumber": 1,
"discNumber": 1,
"script": "Latn",
"key": "CMajor",
"bpm": 72,
"work": {
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"title": "Bohemian Rhapsody",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": ["T-010489707-6"]
},
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": "2025-01-20T14:45:00.0000000Z",
"moods": [
{ "name": "dramatic" },
{ "name": "anxious" }
],
"isrcs": [
{ "value": "GBUM71029604" }
],
"contributors": [
{
"contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d",
"role": "Vocals"
},
{
"contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e",
"role": "Guitar"
}
],
"ratings": [
{
"value": 4.5,
"maxValue": 5,
"source": "MusicBrainz",
"voteCount": 2345
},
{
"value": 4.8,
"maxValue": 5,
"source": "LastFm",
"voteCount": 1234
}
]
},
{
"id": "8e1f2a3b-4c5d-4e6f-8a9b-0c1d2e3f4a5b",
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac",
"metadata": {
"title": "You're My Best Friend",
"originalTitle": "You're My Best Friend",
"description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.",
"disambiguation": "album version",
"releaseInfo": { "originalReleaseDate": "1976-06-18", "originalReleaseYear": 1976, "reReleaseDate": "2011-11-21", "reReleaseYear": 2011, "releaseCountry": "GB", "releaseVersion": "Original" },
"language": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"tags": [ { "name": "classic" }, { "name": "love" } ],
"genres": [ { "name": "Rock" }, { "name": "Pop Rock" } ],
"isVideo": false,
"durationInSeconds": 181,
"sampleRate": 44100,
"channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"bitrate": 912,
"acoustId": "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d",
"replayGainTrackGain": -7.2,
"replayGainTrackPeak": 0.9812,
"replayGainAlbumGain": -6.5,
"replayGainAlbumPeak": 0.9987
},
"trackNumber": 7,
"discNumber": 1,
"script": "Latn",
"key": "BMajor",
"bpm": 118,
"work": {
"musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e",
"title": "You're My Best Friend",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": ["T-010489707-6"]
},
"musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f",
"musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": "2025-01-20T14:45:00.0000000Z",
"moods": [
{ "name": "happy" },
{ "name": "warm" }
],
"isrcs": [
{ "value": "GBUM71029609" }
],
"contributors": [
{
"contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d",
"role": "Vocals"
},
{
"contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e",
"role": "Guitar"
}
],
"ratings": [
{
"value": 4.2,
"maxValue": 5,
"source": "MusicBrainz",
"voteCount": 1234
},
{
"value": 4.4,
"maxValue": 5,
"source": "LastFm",
"voteCount": 567
}
]
}
],
"coverPath": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg",
"artwork": [
{
"type": "Cover",
"ordinal": 0,
"path": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg"
}
]
} }
] ]
``` ```
@@ -653,7 +829,10 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
{ {
"id": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "id": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"title": "A Night at the Opera", "title": "A Night at the Opera",
"totalTracks": 12 "totalTracks": 12,
"coverPath": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg",
"releaseYear": 1975,
"releaseTypes": [ "Album" ]
} }
], ],
"currentPage": 1, "currentPage": 1,
@@ -687,12 +866,12 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"title": "A Night at the Opera", "title": "A Night at the Opera",
"originalTitle": "A Night at the Opera", "originalTitle": "A Night at the Opera",
"description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.", "description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.",
"disambiguation": null, "disambiguation": "original release",
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-11-21", "originalReleaseDate": "1975-11-21",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
"reReleaseDate": null, "reReleaseDate": "2011-11-21",
"reReleaseYear": null, "reReleaseYear": 2011,
"releaseCountry": "GB", "releaseCountry": "GB",
"releaseVersion": "Remastered" "releaseVersion": "Remastered"
}, },
@@ -731,7 +910,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
"musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null, "updatedOnUtc": "2025-01-20T14:45:00.0000000Z",
"contributors": [ "contributors": [
{ {
"contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b", "contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b",
@@ -756,7 +935,182 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"voteCount": 1234 "voteCount": 1234
} }
], ],
"tracks": [] "tracks": [
{
"id": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f",
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
"metadata": {
"title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"disambiguation": "album version",
"releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": "2011-11-21", "reReleaseYear": 2011, "releaseCountry": "GB", "releaseVersion": "Original" },
"language": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"tags": [ { "name": "classic" }, { "name": "epic" } ],
"genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ],
"isVideo": false,
"durationInSeconds": 354,
"sampleRate": 44100,
"channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"bitrate": 980,
"acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f",
"replayGainTrackGain": -7.5,
"replayGainTrackPeak": 0.9877,
"replayGainAlbumGain": -6.8,
"replayGainAlbumPeak": 0.9999
},
"trackNumber": 1,
"discNumber": 1,
"script": "Latn",
"key": "CMajor",
"bpm": 72,
"work": {
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"title": "Bohemian Rhapsody",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": ["T-010489707-6"]
},
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": "2025-01-20T14:45:00.0000000Z",
"moods": [
{ "name": "dramatic" },
{ "name": "anxious" }
],
"isrcs": [
{ "value": "GBUM71029604" }
],
"contributors": [
{
"contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d",
"role": "Vocals"
},
{
"contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e",
"role": "Guitar"
}
],
"ratings": [
{
"value": 4.5,
"maxValue": 5,
"source": "MusicBrainz",
"voteCount": 2345
},
{
"value": 4.8,
"maxValue": 5,
"source": "LastFm",
"voteCount": 1234
}
]
},
{
"id": "8e1f2a3b-4c5d-4e6f-8a9b-0c1d2e3f4a5b",
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac",
"metadata": {
"title": "You're My Best Friend",
"originalTitle": "You're My Best Friend",
"description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.",
"disambiguation": "album version",
"releaseInfo": { "originalReleaseDate": "1976-06-18", "originalReleaseYear": 1976, "reReleaseDate": "2011-11-21", "reReleaseYear": 2011, "releaseCountry": "GB", "releaseVersion": "Original" },
"language": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"tags": [ { "name": "classic" }, { "name": "love" } ],
"genres": [ { "name": "Rock" }, { "name": "Pop Rock" } ],
"isVideo": false,
"durationInSeconds": 181,
"sampleRate": 44100,
"channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"bitrate": 912,
"acoustId": "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d",
"replayGainTrackGain": -7.2,
"replayGainTrackPeak": 0.9812,
"replayGainAlbumGain": -6.5,
"replayGainAlbumPeak": 0.9987
},
"trackNumber": 7,
"discNumber": 1,
"script": "Latn",
"key": "BMajor",
"bpm": 118,
"work": {
"musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e",
"title": "You're My Best Friend",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": ["T-010489707-6"]
},
"musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f",
"musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": "2025-01-20T14:45:00.0000000Z",
"moods": [
{ "name": "happy" },
{ "name": "warm" }
],
"isrcs": [
{ "value": "GBUM71029609" }
],
"contributors": [
{
"contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d",
"role": "Vocals"
},
{
"contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e",
"role": "Guitar"
}
],
"ratings": [
{
"value": 4.2,
"maxValue": 5,
"source": "MusicBrainz",
"voteCount": 1234
},
{
"value": 4.4,
"maxValue": 5,
"source": "LastFm",
"voteCount": 567
}
]
}
],
"coverPath": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg",
"artwork": [
{
"type": "Cover",
"ordinal": 0,
"path": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg"
},
{
"type": "Back",
"ordinal": 0,
"path": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/back.jpg"
},
{
"type": "Booklet",
"ordinal": 0,
"path": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/booklet.jpg"
}
]
} }
``` ```
@@ -775,12 +1129,12 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"title": "A Night at the Opera", "title": "A Night at the Opera",
"originalTitle": "A Night at the Opera", "originalTitle": "A Night at the Opera",
"description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.", "description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.",
"disambiguation": null, "disambiguation": "original release",
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-11-21", "originalReleaseDate": "1975-11-21",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
"reReleaseDate": null, "reReleaseDate": "2011-11-21",
"reReleaseYear": null, "reReleaseYear": 2011,
"releaseCountry": "GB", "releaseCountry": "GB",
"releaseVersion": "Remastered" "releaseVersion": "Remastered"
}, },
@@ -854,12 +1208,12 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"title": "A Night at the Opera", "title": "A Night at the Opera",
"originalTitle": "A Night at the Opera", "originalTitle": "A Night at the Opera",
"description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.", "description": "The fourth studio album by the British rock band Queen, released in 1975. It was the most expensive album ever recorded at the time of its release.",
"disambiguation": null, "disambiguation": "original release",
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-11-21", "originalReleaseDate": "1975-11-21",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
"reReleaseDate": null, "reReleaseDate": "2011-11-21",
"reReleaseYear": null, "reReleaseYear": 2011,
"releaseCountry": "GB", "releaseCountry": "GB",
"releaseVersion": "Remastered" "releaseVersion": "Remastered"
}, },
@@ -898,7 +1252,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
"musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null, "updatedOnUtc": "2025-01-20T14:45:00.0000000Z",
"contributors": [ "contributors": [
{ {
"contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b", "contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b",
@@ -923,7 +1277,202 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"voteCount": 1234 "voteCount": 1234
} }
], ],
"tracks": [] "tracks": [
{
"id": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f",
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
"metadata": {
"title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"disambiguation": "album version",
"releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": "2011-11-21", "reReleaseYear": 2011, "releaseCountry": "GB", "releaseVersion": "Original" },
"language": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"tags": [ { "name": "classic" }, { "name": "epic" } ],
"genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ],
"isVideo": false,
"durationInSeconds": 354,
"sampleRate": 44100,
"channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"bitrate": 980,
"acoustId": "f0e1d2c3-b4a5-4c6d-8e7f-9a0b1c2d3e4f",
"replayGainTrackGain": -7.5,
"replayGainTrackPeak": 0.9877,
"replayGainAlbumGain": -6.8,
"replayGainAlbumPeak": 0.9999
},
"trackNumber": 1,
"discNumber": 1,
"script": "Latn",
"key": "CMajor",
"bpm": 72,
"work": {
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"title": "Bohemian Rhapsody",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": ["T-010489707-6"]
},
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": "2025-01-20T14:45:00.0000000Z",
"moods": [
{ "name": "dramatic" },
{ "name": "anxious" }
],
"isrcs": [
{ "value": "GBUM71029604" }
],
"contributors": [
{
"contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d",
"role": "Vocals"
},
{
"contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e",
"role": "Guitar"
}
],
"ratings": [
{
"value": 4.5,
"maxValue": 5,
"source": "MusicBrainz",
"voteCount": 2345
},
{
"value": 4.8,
"maxValue": 5,
"source": "LastFm",
"voteCount": 1234
}
]
},
{
"id": "8e1f2a3b-4c5d-4e6f-8a9b-0c1d2e3f4a5b",
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac",
"metadata": {
"title": "You're My Best Friend",
"originalTitle": "You're My Best Friend",
"description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.",
"disambiguation": "album version",
"releaseInfo": { "originalReleaseDate": "1976-06-18", "originalReleaseYear": 1976, "reReleaseDate": "2011-11-21", "reReleaseYear": 2011, "releaseCountry": "GB", "releaseVersion": "Original" },
"language": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"tags": [ { "name": "classic" }, { "name": "love" } ],
"genres": [ { "name": "Rock" }, { "name": "Pop Rock" } ],
"isVideo": false,
"durationInSeconds": 181,
"sampleRate": 44100,
"channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"bitrate": 912,
"acoustId": "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d",
"replayGainTrackGain": -7.2,
"replayGainTrackPeak": 0.9812,
"replayGainAlbumGain": -6.5,
"replayGainAlbumPeak": 0.9987
},
"trackNumber": 7,
"discNumber": 1,
"script": "Latn",
"key": "BMajor",
"bpm": 118,
"work": {
"musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e",
"title": "You're My Best Friend",
"type": "Song",
"languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" }
],
"iswcs": ["T-010489707-6"]
},
"musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f",
"musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": "2025-01-20T14:45:00.0000000Z",
"moods": [
{ "name": "happy" },
{ "name": "warm" }
],
"isrcs": [
{ "value": "GBUM71029609" }
],
"contributors": [
{
"contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d",
"role": "Vocals"
},
{
"contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e",
"role": "Guitar"
}
],
"ratings": [
{
"value": 4.2,
"maxValue": 5,
"source": "MusicBrainz",
"voteCount": 1234
},
{
"value": 4.4,
"maxValue": 5,
"source": "LastFm",
"voteCount": 567
}
]
}
],
"coverPath": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg",
"artwork": [
{
"type": "Cover",
"ordinal": 0,
"path": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg"
}
]
}
```
### Update Album Cover
Updates the cover image of the album identified by `albumId` with the image uploaded in the multipart form of the request. The album must belong to the artist identified by `artistId` and to the media library identified by `libraryId`, and the uploaded file must be an image.
#### Update Album Cover Request
```js
PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/{albumId}/cover
Content-Type: multipart/form-data; boundary=LuminaBoundary
--LuminaBoundary
Content-Disposition: form-data; name="cover"; filename="cover.jpg"
Content-Type: image/jpeg
< ./cover.jpg
--LuminaBoundary--
```
#### Update Album Cover Response
```js
200 Ok
```
```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"
} }
``` ```
@@ -966,8 +1515,8 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"disambiguation": null, "disambiguation": "album version",
"releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" }, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": "2011-11-21", "reReleaseYear": 2011, "releaseCountry": "GB", "releaseVersion": "Original" },
"language": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "language": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"tags": [ { "name": "classic" }, { "name": "epic" } ], "tags": [ { "name": "classic" }, { "name": "epic" } ],
@@ -997,12 +1546,12 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"languages": [ "languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" } { "languageCode": "en", "languageName": "English", "nativeName": "English" }
], ],
"iswcs": [] "iswcs": ["T-010489707-6"]
}, },
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null, "updatedOnUtc": "2025-01-20T14:45:00.0000000Z",
"moods": [ "moods": [
{ {
"name": "dramatic" "name": "dramatic"
@@ -1071,7 +1620,8 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"id": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", "id": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f",
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"trackNumber": 1, "trackNumber": 1,
"discNumber": 1 "discNumber": 1,
"durationInSeconds": 354
} }
], ],
"currentPage": 1, "currentPage": 1,
File diff suppressed because it is too large. Load diff
@@ -30,12 +30,12 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"disambiguation": null, "disambiguation": "album version",
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-10-31", "originalReleaseDate": "1975-10-31",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
"reReleaseDate": null, "reReleaseDate": "2011-11-21",
"reReleaseYear": null, "reReleaseYear": 2011,
"releaseCountry": "GB", "releaseCountry": "GB",
"releaseVersion": "Original" "releaseVersion": "Original"
}, },
@@ -82,7 +82,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"languages": [ "languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" } { "languageCode": "en", "languageName": "English", "nativeName": "English" }
], ],
"iswcs": [] "iswcs": ["T-010489707-6"]
}, },
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
@@ -130,8 +130,8 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"disambiguation": null, "disambiguation": "album version",
"releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" }, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": "2011-11-21", "reReleaseYear": 2011, "releaseCountry": "GB", "releaseVersion": "Original" },
"language": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "language": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"tags": [ { "name": "classic" }, { "name": "epic" } ], "tags": [ { "name": "classic" }, { "name": "epic" } ],
@@ -161,12 +161,12 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b
"languages": [ "languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" } { "languageCode": "en", "languageName": "English", "nativeName": "English" }
], ],
"iswcs": [] "iswcs": ["T-010489707-6"]
}, },
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null, "updatedOnUtc": "2025-01-20T14:45:00.0000000Z",
"moods": [ "moods": [
{ {
"name": "dramatic" "name": "dramatic"
@@ -232,8 +232,8 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"disambiguation": null, "disambiguation": "album version",
"releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" }, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": "2011-11-21", "reReleaseYear": 2011, "releaseCountry": "GB", "releaseVersion": "Original" },
"language": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "language": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"tags": [ { "name": "classic" }, { "name": "epic" } ], "tags": [ { "name": "classic" }, { "name": "epic" } ],
@@ -263,12 +263,12 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"languages": [ "languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" } { "languageCode": "en", "languageName": "English", "nativeName": "English" }
], ],
"iswcs": [] "iswcs": ["T-010489707-6"]
}, },
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null, "updatedOnUtc": "2025-01-20T14:45:00.0000000Z",
"moods": [ "moods": [
{ {
"name": "dramatic" "name": "dramatic"
@@ -325,12 +325,12 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"disambiguation": null, "disambiguation": "album version",
"releaseInfo": { "releaseInfo": {
"originalReleaseDate": "1975-10-31", "originalReleaseDate": "1975-10-31",
"originalReleaseYear": 1975, "originalReleaseYear": 1975,
"reReleaseDate": null, "reReleaseDate": "2011-11-21",
"reReleaseYear": null, "reReleaseYear": 2011,
"releaseCountry": "GB", "releaseCountry": "GB",
"releaseVersion": "Original" "releaseVersion": "Original"
}, },
@@ -377,7 +377,7 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"languages": [ "languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" } { "languageCode": "en", "languageName": "English", "nativeName": "English" }
], ],
"iswcs": [] "iswcs": ["T-010489707-6"]
}, },
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
@@ -425,8 +425,8 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"title": "Bohemian Rhapsody", "title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody", "originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"disambiguation": null, "disambiguation": "album version",
"releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" }, "releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": "2011-11-21", "reReleaseYear": 2011, "releaseCountry": "GB", "releaseVersion": "Original" },
"language": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "language": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" }, "originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"tags": [ { "name": "classic" }, { "name": "epic" } ], "tags": [ { "name": "classic" }, { "name": "epic" } ],
@@ -456,12 +456,12 @@ PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-
"languages": [ "languages": [
{ "languageCode": "en", "languageName": "English", "nativeName": "English" } { "languageCode": "en", "languageName": "English", "nativeName": "English" }
], ],
"iswcs": [] "iswcs": ["T-010489707-6"]
}, },
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null, "updatedOnUtc": "2025-01-20T14:45:00.0000000Z",
"moods": [ "moods": [
{ {
"name": "dramatic" "name": "dramatic"
@@ -237,7 +237,7 @@ POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books
"metadataProvider": null, "metadataProvider": null,
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null, "updatedOnUtc": null,
"coverPath": null "coverPath": "/media/books/tolkien/the-fellowship-of-the-ring/cover.jpg"
} }
``` ```
@@ -353,7 +353,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId}
"metadataProvider": null, "metadataProvider": null,
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null, "updatedOnUtc": null,
"coverPath": null "coverPath": "/media/books/tolkien/the-fellowship-of-the-ring/cover.jpg"
} }
``` ```
@@ -467,7 +467,7 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books?currentPage=1&pe
"metadataProvider": null, "metadataProvider": null,
"createdOnUtc": "2025-01-01T12:00:00.0000000Z", "createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null, "updatedOnUtc": null,
"coverPath": null "coverPath": "/media/books/tolkien/the-fellowship-of-the-ring/cover.jpg"
} }
], ],
"currentPage": 1, "currentPage": 1,
@@ -0,0 +1,10 @@
PUT {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/{{$guid}}/cover
Authorization: Bearer {{ACCESS_TOKEN}}
Content-Type: multipart/form-data; boundary=LuminaBoundary
--LuminaBoundary
Content-Disposition: form-data; name="cover"; filename="cover.jpg"
Content-Type: image/jpeg
< ./cover.jpg
--LuminaBoundary--
@@ -1,2 +1,2 @@
GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/lite?currentPage=1&perPage=10&searchTerm=queen GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/lite?currentPage=1&perPage=10&searchTerm=queen&filterAlphaKey=q&shouldIgnoreThePrefixForAlphaPicker=true&sortBy=name&sortOrder=Ascending
Authorization: Bearer {{ACCESS_TOKEN}} Authorization: Bearer {{ACCESS_TOKEN}}
@@ -0,0 +1,10 @@
PUT {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{{$guid}}/cover
Authorization: Bearer {{ACCESS_TOKEN}}
Content-Type: multipart/form-data; boundary=LuminaBoundary
--LuminaBoundary
Content-Disposition: form-data; name="cover"; filename="cover.jpg"
Content-Type: image/jpeg
< ./cover.jpg
--LuminaBoundary--
@@ -1,5 +1,7 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using System; using System;
using System.Collections.Generic;
#endregion #endregion
namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums; namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
@@ -23,4 +25,19 @@ public sealed record AlbumLiteRow
/// Gets the number of tracks of the release. /// Gets the number of tracks of the release.
/// </summary> /// </summary>
public int TotalTracks { get; init; } public int TotalTracks { get; init; }
/// <summary>
/// Gets the path of the image representing the album, if available.
/// </summary>
public string? CoverPath { get; init; }
/// <summary>
/// Gets the release year of the album (the re-release year, if available, or the original release year), if known.
/// </summary>
public int? ReleaseYear { get; init; }
/// <summary>
/// Gets the set of types of the release.
/// </summary>
public List<MusicReleaseType>? ReleaseTypes { get; init; }
} }
@@ -18,4 +18,9 @@ public sealed record ArtistLiteRow
/// Gets the name of the artist. /// Gets the name of the artist.
/// </summary> /// </summary>
public required string Name { get; init; } public required string Name { get; init; }
/// <summary>
/// Gets the path of the image representing the artist, if available.
/// </summary>
public string? CoverPath { get; init; }
} }
@@ -28,4 +28,9 @@ public sealed record TrackLiteRow
/// Gets the number of the disc the track belongs to, if applicable. /// Gets the number of the disc the track belongs to, if applicable.
/// </summary> /// </summary>
public int? DiscNumber { get; init; } public int? DiscNumber { get; init; }
/// <summary>
/// Gets the duration of the track in seconds.
/// </summary>
public int DurationInSeconds { get; init; }
} }
@@ -123,4 +123,12 @@ public interface IBookRepository : IRepository<BookEntity>,
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the display names of the authors of the books, keyed by book Id, or an error.</returns> /// <returns>An <see cref="Result{TValue}"/> containing either the display names of the authors of the books, keyed by book Id, or an error.</returns>
Task<Result<IReadOnlyDictionary<Guid, string?>>> GetAuthorsDisplayNamesByBookIdsAsync(IReadOnlyCollection<Guid> bookIds, CancellationToken cancellationToken); Task<Result<IReadOnlyDictionary<Guid, string?>>> GetAuthorsDisplayNamesByBookIdsAsync(IReadOnlyCollection<Guid> bookIds, CancellationToken cancellationToken);
/// <summary>
/// Deletes all the books of the media library identified by <paramref name="libraryId"/>, together with their artwork and their related data.
/// </summary>
/// <param name="libraryId">The Id of the media library whose books are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
} }
@@ -78,4 +78,12 @@ public interface IArtistRepository : IRepository<ArtistEntity>,
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns> /// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Updated>> ResetMetadataStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken); Task<Result<Updated>> ResetMetadataStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Deletes all the artists of the media library identified by <paramref name="libraryId"/>, together with their albums and tracks and their related data.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artists are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
} }
@@ -46,4 +46,23 @@ public interface IMusicArtworkRepository : IRepository<MusicArtworkEntity>,
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns> /// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Updated>> ResetStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken); Task<Result<Updated>> ResetStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Deletes all the pieces of artwork owned by the artists, albums and tracks of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artwork is deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Stores the cover image of the music library item of the provided <paramref name="ownerType"/> identified by <paramref name="ownerId"/>,
/// replacing the file of its existing cover, or adding a new cover artwork when it has none.
/// </summary>
/// <param name="ownerType">The type of the music library item that owns the artwork.</param>
/// <param name="ownerId">The Id of the music library item that owns the artwork.</param>
/// <param name="fileName">The relative file name of the stored cover image.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Updated>> UpsertCoverAsync(MusicArtworkOwnerType ownerType, Guid ownerId, string fileName, CancellationToken cancellationToken);
} }
@@ -32,4 +32,12 @@ public interface IMusicLibraryScanItemMetadataRepository : IRepository<MusicLibr
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns> /// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> DeleteByScanIdAsync(Guid scanId, CancellationToken cancellationToken); Task<Result<Deleted>> DeleteByScanIdAsync(Guid scanId, CancellationToken cancellationToken);
/// <summary>
/// Deletes all the staged music metadata items of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose staged music metadata is deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
} }
@@ -1,5 +1,6 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Telemetry; using Lumina.Application.Common.Telemetry;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
using Lumina.Application.Core.MediaLibrary.Management.Deletion; using Lumina.Application.Core.MediaLibrary.Management.Deletion;
using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Events;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
@@ -44,6 +45,7 @@ public static class ApplicationLayerServices
services.AddScoped<IMediaLibraryItemDeletionStrategy, BooksMediaLibraryItemDeletionStrategy>(); services.AddScoped<IMediaLibraryItemDeletionStrategy, BooksMediaLibraryItemDeletionStrategy>();
services.AddScoped<IMediaLibraryItemDeletionStrategy, MusicMediaLibraryItemDeletionStrategy>(); services.AddScoped<IMediaLibraryItemDeletionStrategy, MusicMediaLibraryItemDeletionStrategy>();
services.AddScoped<IMusicArtworkCleanupService, MusicArtworkCleanupService>();
foreach (var registration in handlerRegistrations) foreach (var registration in handlerRegistrations)
{ {
@@ -157,8 +157,10 @@ public static class AlbumEntityMapping
/// Converts <paramref name="repositoryEntity"/> to <see cref="AlbumResponse"/>. /// Converts <paramref name="repositoryEntity"/> to <see cref="AlbumResponse"/>.
/// </summary> /// </summary>
/// <param name="repositoryEntity">The repository entity to be converted.</param> /// <param name="repositoryEntity">The repository entity to be converted.</param>
/// <param name="coverPath">The optional path of the image representing the album.</param>
/// <param name="artwork">The optional stored artwork of the album, in display order.</param>
/// <returns>The converted response entity.</returns> /// <returns>The converted response entity.</returns>
public static AlbumResponse ToResponse(this AlbumEntity repositoryEntity) public static AlbumResponse ToResponse(this AlbumEntity repositoryEntity, string? coverPath = null, IReadOnlyList<MediaArtworkDto>? artwork = null)
{ {
ReleaseInfoDto releaseInfo = new( ReleaseInfoDto releaseInfo = new(
repositoryEntity.OriginalReleaseDate, repositoryEntity.OriginalReleaseDate,
@@ -220,7 +222,9 @@ public static class AlbumEntityMapping
repositoryEntity.UpdatedOnUtc, repositoryEntity.UpdatedOnUtc,
[.. repositoryEntity.Contributors.Select(contributor => new MediaContributorReferenceDto(contributor.MediaContributorId, contributor.Role))], [.. repositoryEntity.Contributors.Select(contributor => new MediaContributorReferenceDto(contributor.MediaContributorId, contributor.Role))],
[.. repositoryEntity.Ratings.ToResponses()], [.. repositoryEntity.Ratings.ToResponses()],
[.. repositoryEntity.Tracks.Select(track => track.ToResponse())]); [.. repositoryEntity.Tracks.Select(track => track.ToResponse())],
coverPath,
artwork ?? []);
} }
/// <summary> /// <summary>
@@ -24,7 +24,10 @@ public static class AlbumLiteRowMapping
return new AlbumLiteResponse( return new AlbumLiteResponse(
readModel.Id, readModel.Id,
readModel.Title, readModel.Title,
readModel.TotalTracks); readModel.TotalTracks,
readModel.CoverPath,
readModel.ReleaseYear,
readModel.ReleaseTypes);
} }
/// <summary> /// <summary>
@@ -147,8 +147,9 @@ public static class ArtistEntityMapping
/// Converts <paramref name="repositoryEntity"/> to <see cref="ArtistResponse"/>. /// Converts <paramref name="repositoryEntity"/> to <see cref="ArtistResponse"/>.
/// </summary> /// </summary>
/// <param name="repositoryEntity">The repository entity to be converted.</param> /// <param name="repositoryEntity">The repository entity to be converted.</param>
/// <param name="coverPath">The optional path of the image representing the artist.</param>
/// <returns>The converted response entity.</returns> /// <returns>The converted response entity.</returns>
public static ArtistResponse ToResponse(this ArtistEntity repositoryEntity) public static ArtistResponse ToResponse(this ArtistEntity repositoryEntity, string? coverPath = null)
{ {
MusicArtistMetadataDto metadata = new( MusicArtistMetadataDto metadata = new(
repositoryEntity.Name, repositoryEntity.Name,
@@ -178,7 +179,8 @@ public static class ArtistEntityMapping
repositoryEntity.UpdatedOnUtc, repositoryEntity.UpdatedOnUtc,
[.. repositoryEntity.Contributors.Select(contributor => new MediaContributorReferenceDto(contributor.MediaContributorId, contributor.Role))], [.. repositoryEntity.Contributors.Select(contributor => new MediaContributorReferenceDto(contributor.MediaContributorId, contributor.Role))],
[.. repositoryEntity.Ratings.ToResponses()], [.. repositoryEntity.Ratings.ToResponses()],
[.. repositoryEntity.Albums.Select(album => album.ToResponse())]); [.. repositoryEntity.Albums.Select(album => album.ToResponse())],
coverPath);
} }
/// <summary> /// <summary>
@@ -23,7 +23,8 @@ public static class ArtistLiteRowMapping
{ {
return new ArtistLiteResponse( return new ArtistLiteResponse(
readModel.Id, readModel.Id,
readModel.Name); readModel.Name,
readModel.CoverPath);
} }
/// <summary> /// <summary>
@@ -30,6 +30,10 @@ public static class GetArtistsLiteRequestMapping
return new GetArtistsLiteQuery( return new GetArtistsLiteQuery(
libraryId, libraryId,
paginationData, paginationData,
request.SearchTerm); request.SearchTerm,
request.FilterAlphaKey,
request.ShouldIgnoreThePrefixForAlphaPicker,
request.SortBy,
request.SortOrder);
} }
} }
@@ -160,6 +160,7 @@ public static class UpdateArtistCommandMapping
existingTrack, existingTrack,
domainTrack.Path, domainTrack.Path,
domainTrack.Metadata, domainTrack.Metadata,
domainTrack.Disambiguation,
domainTrack.TrackNumber, domainTrack.TrackNumber,
domainTrack.DiscNumber, domainTrack.DiscNumber,
domainTrack.Script, domainTrack.Script,
@@ -94,6 +94,9 @@ public static class AudioMetadataDtoMapping
Optional<int> bpm = Optional<int>.FromNullable(dto.Bpm); Optional<int> bpm = Optional<int>.FromNullable(dto.Bpm);
if (!bpm.HasValue) if (!bpm.HasValue)
bpm = track.Bpm; bpm = track.Bpm;
Optional<string> disambiguation = Optional<string>.FromNullable(dto.Disambiguation);
if (!disambiguation.HasValue)
disambiguation = track.Disambiguation;
Optional<MusicBrainzId> musicBrainzRecordingId = Optional<MusicBrainzId>.None(); Optional<MusicBrainzId> musicBrainzRecordingId = Optional<MusicBrainzId>.None();
if (dto.MusicBrainzRecordingId is not null) if (dto.MusicBrainzRecordingId is not null)
musicBrainzRecordingId = MusicBrainzId.Create(dto.MusicBrainzRecordingId.Value); musicBrainzRecordingId = MusicBrainzId.Create(dto.MusicBrainzRecordingId.Value);
@@ -110,6 +113,7 @@ public static class AudioMetadataDtoMapping
track, track,
track.Path, track.Path,
metadataResult.Value, metadataResult.Value,
disambiguation,
track.TrackNumber, track.TrackNumber,
track.DiscNumber, track.DiscNumber,
script, script,
@@ -187,21 +191,37 @@ public static class AudioMetadataDtoMapping
if (dto.OriginalLanguage is not null && dto.OriginalLanguage.LanguageCode is not null && dto.OriginalLanguage.LanguageName is not null) if (dto.OriginalLanguage is not null && dto.OriginalLanguage.LanguageCode is not null && dto.OriginalLanguage.LanguageName is not null)
originalLanguage = LanguageInfo.Create(dto.OriginalLanguage.LanguageCode, dto.OriginalLanguage.LanguageName, Optional<string>.FromNullable(dto.OriginalLanguage.NativeName)); originalLanguage = LanguageInfo.Create(dto.OriginalLanguage.LanguageCode, dto.OriginalLanguage.LanguageName, Optional<string>.FromNullable(dto.OriginalLanguage.NativeName));
Optional<string> originalTitle = Optional<string>.FromNullable(dto.OriginalTitle);
if (!originalTitle.HasValue)
originalTitle = track.Metadata.OriginalTitle;
Optional<string> description = Optional<string>.FromNullable(dto.Description);
if (!description.HasValue)
description = track.Metadata.Description;
Optional<int> bitDepth = Optional<int>.FromNullable(dto.BitDepth);
if (!bitDepth.HasValue)
bitDepth = track.Metadata.BitDepth;
Optional<string> audioCodec = Optional<string>.FromNullable(dto.AudioCodec);
if (!audioCodec.HasValue)
audioCodec = track.Metadata.AudioCodec;
Optional<int> bitrate = Optional<int>.FromNullable(dto.Bitrate);
if (!bitrate.HasValue)
bitrate = track.Metadata.Bitrate;
return AudioMetadata.Create( return AudioMetadata.Create(
string.IsNullOrWhiteSpace(dto.Title) ? track.Metadata.Title : dto.Title, string.IsNullOrWhiteSpace(dto.Title) ? track.Metadata.Title : dto.Title,
Optional<string>.FromNullable(dto.OriginalTitle).HasValue ? Optional<string>.FromNullable(dto.OriginalTitle) : track.Metadata.OriginalTitle, originalTitle,
dto.DurationInSeconds is > 0 ? dto.DurationInSeconds.Value : track.Metadata.DurationInSeconds, dto.DurationInSeconds is > 0 ? dto.DurationInSeconds.Value : track.Metadata.DurationInSeconds,
dto.SampleRate is > 0 ? dto.SampleRate.Value : track.Metadata.SampleRate, dto.SampleRate is > 0 ? dto.SampleRate.Value : track.Metadata.SampleRate,
dto.Channels is > 0 ? dto.Channels.Value : track.Metadata.Channels, dto.Channels is > 0 ? dto.Channels.Value : track.Metadata.Channels,
releaseInfoResult.Value, releaseInfoResult.Value,
Optional<string>.FromNullable(dto.Description).HasValue ? Optional<string>.FromNullable(dto.Description) : track.Metadata.Description, description,
genres, genres,
tags, tags,
language, language,
originalLanguage, originalLanguage,
Optional<int>.FromNullable(dto.BitDepth).HasValue ? Optional<int>.FromNullable(dto.BitDepth) : track.Metadata.BitDepth, bitDepth,
Optional<string>.FromNullable(dto.AudioCodec).HasValue ? Optional<string>.FromNullable(dto.AudioCodec) : track.Metadata.AudioCodec, audioCodec,
Optional<int>.FromNullable(dto.Bitrate).HasValue ? Optional<int>.FromNullable(dto.Bitrate) : track.Metadata.Bitrate, bitrate,
track.Metadata.AcoustId, track.Metadata.AcoustId,
track.Metadata.ReplayGainTrackGain, track.Metadata.ReplayGainTrackGain,
track.Metadata.ReplayGainTrackPeak, track.Metadata.ReplayGainTrackPeak,
@@ -25,7 +25,8 @@ public static class TrackLiteRowMapping
readModel.Id, readModel.Id,
readModel.Title, readModel.Title,
readModel.TrackNumber, readModel.TrackNumber,
readModel.DiscNumber); readModel.DiscNumber,
readModel.DurationInSeconds);
} }
/// <summary> /// <summary>
@@ -87,6 +87,7 @@ public static class UpdateTrackCommandMapping
track, track,
command.Path!, command.Path!,
metadataResult.Value, metadataResult.Value,
Optional<string>.FromNullable(metadata.Disambiguation),
command.TrackNumber!.Value, command.TrackNumber!.Value,
Optional<int>.FromNullable(command.DiscNumber), Optional<int>.FromNullable(command.DiscNumber),
Optional<string>.FromNullable(command.Script), Optional<string>.FromNullable(command.Script),
@@ -8,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; 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.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
@@ -28,6 +29,7 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.
public class DeleteAlbumCommandHandler : ICommandHandler<DeleteAlbumCommand, Result<Deleted>> public class DeleteAlbumCommandHandler : ICommandHandler<DeleteAlbumCommand, Result<Deleted>>
{ {
private readonly IUnitOfWork _unitOfWork; private readonly IUnitOfWork _unitOfWork;
private readonly IMusicArtworkCleanupService _musicArtworkCleanupService;
private readonly IAuthorizationService _authorizationService; private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService; private readonly ICurrentUserService _currentUserService;
private readonly IValidator<DeleteAlbumCommand> _validator; private readonly IValidator<DeleteAlbumCommand> _validator;
@@ -36,12 +38,14 @@ public class DeleteAlbumCommandHandler : ICommandHandler<DeleteAlbumCommand, Res
/// Initializes a new instance of the <see cref="DeleteAlbumCommandHandler"/> class. /// Initializes a new instance of the <see cref="DeleteAlbumCommandHandler"/> class.
/// </summary> /// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param> /// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="musicArtworkCleanupService">Injected service for removing the artwork of a music library item and of its children.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param> /// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param> /// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param> /// <param name="validator">Injected validator for application validation rules.</param>
public DeleteAlbumCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<DeleteAlbumCommand> validator) public DeleteAlbumCommandHandler(IUnitOfWork unitOfWork, IMusicArtworkCleanupService musicArtworkCleanupService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<DeleteAlbumCommand> validator)
{ {
_unitOfWork = unitOfWork; _unitOfWork = unitOfWork;
_musicArtworkCleanupService = musicArtworkCleanupService;
_authorizationService = authorizationService; _authorizationService = authorizationService;
_currentUserService = currentUserService; _currentUserService = currentUserService;
_validator = validator; _validator = validator;
@@ -115,6 +119,12 @@ public class DeleteAlbumCommandHandler : ICommandHandler<DeleteAlbumCommand, Res
if (removeAlbumResult.IsFailure) if (removeAlbumResult.IsFailure)
return removeAlbumResult.Errors; 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<Deleted> deleteArtworkResult = await _musicArtworkCleanupService.DeleteAlbumArtworkAsync(albumId, cancellationToken).ConfigureAwait(false);
if (deleteArtworkResult.IsFailure)
return deleteArtworkResult.Errors;
Result<Updated> updateResult = await _unitOfWork.ArtistRepository Result<Updated> updateResult = await _unitOfWork.ArtistRepository
.UpdateAsync(artistResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); .UpdateAsync(artistResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure) if (updateResult.IsFailure)
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
using System.IO;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
/// <summary>
/// Command for updating the cover image of an existing album.
/// </summary>
/// <param name="LibraryId">The unique identifier of the media library the album belongs to, taken from the route.</param>
/// <param name="ArtistId">The unique identifier of the artist the album belongs to, taken from the route.</param>
/// <param name="AlbumId">The unique identifier of the album whose cover image is updated, taken from the route.</param>
/// <param name="Cover">The stream of the uploaded cover image file.</param>
/// <param name="FileName">The name of the uploaded cover image file.</param>
[DebuggerDisplay("AlbumId: {AlbumId} FileName: {FileName}")]
public record UpdateAlbumCoverCommand(
string? LibraryId,
string? ArtistId,
string? AlbumId,
Stream? Cover,
string? FileName
) : ICommand;
@@ -0,0 +1,198 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
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;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
/// <summary>
/// Handler for the command to update the cover image of an existing album.
/// </summary>
public class UpdateAlbumCoverCommandHandler : ICommandHandler<UpdateAlbumCoverCommand, Result<UpdateAlbumCoverResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IMusicArtworkService _musicArtworkService;
private readonly IPathService _pathService;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<UpdateAlbumCoverCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateAlbumCoverCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="musicArtworkService">Injected service for storing the artwork of a music library item.</param>
/// <param name="pathService">Injected service for handling file system paths.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public UpdateAlbumCoverCommandHandler(IUnitOfWork unitOfWork, IMusicArtworkService musicArtworkService, IPathService pathService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<UpdateAlbumCoverCommand> validator)
{
_unitOfWork = unitOfWork;
_musicArtworkService = musicArtworkService;
_pathService = pathService;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the command to update the cover image of an existing album.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the response carrying the relative path of the stored cover image, or an error message.
/// </returns>
public async Task<Result<UpdateAlbumCoverResponse>> HandleAsync(UpdateAlbumCoverCommand command, CancellationToken cancellationToken)
{
List<Error> 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!);
Result<AlbumEntity?> getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(albumId, shouldTrackEntities: false, cancellationToken: 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 library and the artist named by the route, so that an album can never be edited through
// another library's or artist'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 update the albums of all libraries; for everyone else, only the albums of the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(existingAlbum.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
// The artwork is stored under the library and artist segments, so their names are resolved to keep the location consistent with the scanned artwork.
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(existingAlbum.LibraryId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound;
string libraryName = getLibraryResult.Value.Title;
Result<ArtistEntity?> getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(existingAlbum.ArtistId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getArtistResult.IsFailure)
return getArtistResult.Errors;
string artistName = getArtistResult.Value?.Name ?? string.Empty;
// The artwork of the album is stored under the directory of its release type, mirroring the structure of the scanned files, so that a
// re-uploaded cover replaces the cover stored for the album at its standardized location instead of writing a second copy elsewhere.
Result<IReadOnlyList<MusicArtworkEntity>> getArtworkResult = await _unitOfWork.MusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, cancellationToken).ConfigureAwait(false);
if (getArtworkResult.IsFailure)
return getArtworkResult.Errors;
string? existingCoverPath = getArtworkResult.Value
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
.Select(artwork => artwork.FileName)
.FirstOrDefault();
string? releaseTypeName = ExtractReleaseTypeDirectoryName(existingCoverPath, artistName)
?? (existingAlbum.ReleaseTypes.Count > 0 ? existingAlbum.ReleaseTypes[0].ReleaseType.ToString() : null);
Result<string> storeArtworkResult = await _musicArtworkService.SaveAlbumArtworkAsync(
existingAlbum.LibraryId,
existingAlbum.Id,
libraryName,
artistName,
existingAlbum.Title,
command.Cover!,
command.FileName!,
releaseTypeName,
cancellationToken).ConfigureAwait(false);
if (storeArtworkResult.IsFailure)
return storeArtworkResult.Errors;
// The stored cover of the album is replaced as a whole: when the new cover is stored under a different name than the previous one
// (for example a png replacing a jpg), the previous file is removed, so that no orphaned artwork is left on disk without a reference.
if (!string.IsNullOrWhiteSpace(existingCoverPath) && existingCoverPath != storeArtworkResult.Value)
{
Result<Deleted> deleteResult = _musicArtworkService.DeleteStoredArtwork(existingCoverPath);
if (deleteResult.IsFailure)
return deleteResult.Errors;
}
// Map the newly stored cover image onto the artwork of the album, replacing the existing cover or adding a new one.
Result<Updated> upsertResult = await _unitOfWork.MusicArtworkRepository.UpsertCoverAsync(
MusicArtworkOwnerType.Album, albumId, storeArtworkResult.Value, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure)
return upsertResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return new UpdateAlbumCoverResponse(storeArtworkResult.Value);
}
/// <summary>
/// Resolves the name of the release type directory the artwork of an album is stored under, from the relative path of its existing cover.
/// </summary>
/// <param name="coverRelativePath">The relative path of the existing cover image of the album, or <see langword="null"/> when the album has no cover.</param>
/// <param name="artistName">The name of the artist of the album.</param>
/// <returns>The name of the on-disk release type directory, or <see langword="null"/> when the album does not use one.</returns>
private string? ExtractReleaseTypeDirectoryName(string? coverRelativePath, string artistName)
{
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.
string[] segments = coverRelativePath.Split(_pathService.PathSeparator, StringSplitOptions.RemoveEmptyEntries);
if (segments.Length < 3)
return null;
string candidate = segments[^3];
if (IsArtistDirectory(candidate, artistName))
return null;
return Enum.TryParse(candidate, ignoreCase: true, out MusicReleaseType releaseType) && Enum.IsDefined(releaseType) ? candidate : null;
}
/// <summary>
/// Checks whether the provided path segment is the artwork directory of the artist of the album.
/// </summary>
/// <param name="pathSegment">The path segment to be checked.</param>
/// <param name="artistName">The name of the artist of the album.</param>
/// <returns><see langword="true"/> when the segment is the artwork directory of the artist, <see langword="false"/> otherwise.</returns>
private bool IsArtistDirectory(string pathSegment, string artistName)
{
if (string.IsNullOrWhiteSpace(artistName))
return false;
Result<PathSegment> artistSegmentResult = _pathService.SanitizeSegment(artistName);
return artistSegmentResult.IsSuccess
&& string.Equals(pathSegment, artistSegmentResult.Value.Name, StringComparison.OrdinalIgnoreCase);
}
}
@@ -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.Albums.Commands.UpdateAlbumCover;
/// <summary>
/// Validates the needed validation rules for <see cref="UpdateAlbumCoverCommand"/>.
/// </summary>
public class UpdateAlbumCoverCommandValidator : AbstractValidator<UpdateAlbumCoverCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateAlbumCoverCommandValidator"/> class.
/// </summary>
public UpdateAlbumCoverCommandValidator()
{
// Validates the identifier of the media library the album belongs to, 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 album whose cover image is updated, 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 uploaded cover image.
RuleFor(command => command.Cover)
.NotNull()
.WithError(Errors.Music.CoverCannotBeNull);
RuleFor(command => command.FileName)
.NotEmpty()
.When(command => command.Cover is not null)
.WithError(Errors.FileSystemManagement.FileNameCannotBeEmpty);
}
}
@@ -8,11 +8,15 @@ using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwn
using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors; using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
@@ -88,6 +92,21 @@ public class GetAlbumQueryHandler : IQueryHandler<GetAlbumQuery, Result<AlbumRes
if (!canAccessLibrary) if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized; return ApplicationErrors.Authorization.NotAuthorized;
return existingAlbum.ToResponse(); // The artwork of an album is stored in the MusicArtwork table, not on the album row, so it is loaded to expose the cover
// and every other stored piece of artwork.
Result<IReadOnlyList<MusicArtworkEntity>> getArtworkResult = await _unitOfWork.MusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, cancellationToken).ConfigureAwait(false);
if (getArtworkResult.IsFailure)
return getArtworkResult.Errors;
string? coverPath = getArtworkResult.Value
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
.Select(artwork => artwork.FileName)
.FirstOrDefault();
// Only the artwork whose file has already been stored can be presented, so the ones that are still pending resolution are left out.
List<MediaArtworkDto> artwork = [.. getArtworkResult.Value
.Where(storedArtwork => !string.IsNullOrWhiteSpace(storedArtwork.FileName))
.Select(storedArtwork => new MediaArtworkDto(storedArtwork.ArtworkType, storedArtwork.Ordinal, storedArtwork.FileName!))];
return existingAlbum.ToResponse(coverPath, artwork);
} }
} }
@@ -7,6 +7,7 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.Primitives;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -24,6 +25,7 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists
public class DeleteArtistCommandHandler : ICommandHandler<DeleteArtistCommand, Result<Deleted>> public class DeleteArtistCommandHandler : ICommandHandler<DeleteArtistCommand, Result<Deleted>>
{ {
private readonly IUnitOfWork _unitOfWork; private readonly IUnitOfWork _unitOfWork;
private readonly IMusicArtworkCleanupService _musicArtworkCleanupService;
private readonly IAuthorizationService _authorizationService; private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService; private readonly ICurrentUserService _currentUserService;
private readonly IValidator<DeleteArtistCommand> _validator; private readonly IValidator<DeleteArtistCommand> _validator;
@@ -32,12 +34,14 @@ public class DeleteArtistCommandHandler : ICommandHandler<DeleteArtistCommand, R
/// Initializes a new instance of the <see cref="DeleteArtistCommandHandler"/> class. /// Initializes a new instance of the <see cref="DeleteArtistCommandHandler"/> class.
/// </summary> /// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param> /// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="musicArtworkCleanupService">Injected service for removing the artwork of a music library item and of its children.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param> /// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param> /// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param> /// <param name="validator">Injected validator for application validation rules.</param>
public DeleteArtistCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<DeleteArtistCommand> validator) public DeleteArtistCommandHandler(IUnitOfWork unitOfWork, IMusicArtworkCleanupService musicArtworkCleanupService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<DeleteArtistCommand> validator)
{ {
_unitOfWork = unitOfWork; _unitOfWork = unitOfWork;
_musicArtworkCleanupService = musicArtworkCleanupService;
_authorizationService = authorizationService; _authorizationService = authorizationService;
_currentUserService = currentUserService; _currentUserService = currentUserService;
_validator = validator; _validator = validator;
@@ -92,6 +96,12 @@ public class DeleteArtistCommandHandler : ICommandHandler<DeleteArtistCommand, R
if (getLibraryResult.Value is null) if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound; return DomainErrors.Library.LibraryNotFound;
// The artwork of the artist and of its albums and tracks does not cascade from the artist row, because the artwork table is shared by all
// the music library item types, so it is removed first, while the artist and its children are still present.
Result<Deleted> deleteArtworkResult = await _musicArtworkCleanupService.DeleteArtistArtworkAsync(artistId, cancellationToken).ConfigureAwait(false);
if (deleteArtworkResult.IsFailure)
return deleteArtworkResult.Errors;
Result<Deleted> deleteArtistResult = await _unitOfWork.ArtistRepository.DeleteByIdAsync(artistId, cancellationToken).ConfigureAwait(false); Result<Deleted> deleteArtistResult = await _unitOfWork.ArtistRepository.DeleteByIdAsync(artistId, cancellationToken).ConfigureAwait(false);
if (deleteArtistResult.IsFailure) if (deleteArtistResult.IsFailure)
return deleteArtistResult.Errors; return deleteArtistResult.Errors;
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
using System.IO;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover;
/// <summary>
/// Command for updating the cover image of an existing artist.
/// </summary>
/// <param name="LibraryId">The unique identifier of the media library this artist belongs to, taken from the route.</param>
/// <param name="ArtistId">The unique identifier of the artist whose cover image is updated, taken from the route.</param>
/// <param name="Cover">The stream of the uploaded cover image file.</param>
/// <param name="FileName">The name of the uploaded cover image file.</param>
[DebuggerDisplay("ArtistId: {ArtistId} FileName: {FileName}")]
public record UpdateArtistCoverCommand(
string? LibraryId,
string? ArtistId,
Stream? Cover,
string? FileName
) : ICommand;
@@ -0,0 +1,144 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
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;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover;
/// <summary>
/// Handler for the command to update the cover image of an existing artist.
/// </summary>
public class UpdateArtistCoverCommandHandler : ICommandHandler<UpdateArtistCoverCommand, Result<UpdateArtistCoverResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IMusicArtworkService _musicArtworkService;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<UpdateArtistCoverCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateArtistCoverCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="musicArtworkService">Injected service for storing the artwork of a music library item.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public UpdateArtistCoverCommandHandler(IUnitOfWork unitOfWork, IMusicArtworkService musicArtworkService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<UpdateArtistCoverCommand> validator)
{
_unitOfWork = unitOfWork;
_musicArtworkService = musicArtworkService;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the command to update the cover image of an existing artist.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the response carrying the relative path of the stored cover image, or an error message.
/// </returns>
public async Task<Result<UpdateArtistCoverResponse>> HandleAsync(UpdateArtistCoverCommand command, CancellationToken cancellationToken)
{
List<Error> 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<ArtistEntity?> getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(artistId, shouldTrackEntities: false, cancellationToken: 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 edited 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 update the artists of all libraries; for everyone else, only the artists of the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(existingArtist.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
// The artwork is stored under the library and artist segments, so their names are resolved to keep the location consistent with the scanned artwork.
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(existingArtist.LibraryId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound;
string libraryName = getLibraryResult.Value.Title;
// The existing cover of the artist is looked up, so that the previous file can be replaced as a whole instead of being left orphaned on disk.
Result<IReadOnlyList<MusicArtworkEntity>> getArtworkResult = await _unitOfWork.MusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, cancellationToken).ConfigureAwait(false);
if (getArtworkResult.IsFailure)
return getArtworkResult.Errors;
string? existingCoverPath = getArtworkResult.Value
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
.Select(artwork => artwork.FileName)
.FirstOrDefault();
Result<string> storeArtworkResult = await _musicArtworkService.SaveArtistArtworkAsync(
existingArtist.LibraryId,
libraryName,
existingArtist.Name,
command.Cover!,
command.FileName!,
cancellationToken).ConfigureAwait(false);
if (storeArtworkResult.IsFailure)
return storeArtworkResult.Errors;
// The stored cover of the artist is replaced as a whole: when the new cover is stored under a different name than the previous one
// (for example a png replacing a jpg), the previous file is removed, so that no orphaned artwork is left on disk without a reference.
if (!string.IsNullOrWhiteSpace(existingCoverPath) && existingCoverPath != storeArtworkResult.Value)
{
Result<Deleted> deleteResult = _musicArtworkService.DeleteStoredArtwork(existingCoverPath);
if (deleteResult.IsFailure)
return deleteResult.Errors;
}
// Map the newly stored cover image onto the artwork of the artist, replacing the existing cover or adding a new one.
Result<Updated> upsertResult = await _unitOfWork.MusicArtworkRepository.UpsertCoverAsync(
MusicArtworkOwnerType.Artist, artistId, storeArtworkResult.Value, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure)
return upsertResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return new UpdateArtistCoverResponse(storeArtworkResult.Value);
}
}
@@ -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.Artists.Commands.UpdateArtistCover;
/// <summary>
/// Validates the needed validation rules for <see cref="UpdateArtistCoverCommand"/>.
/// </summary>
public class UpdateArtistCoverCommandValidator : AbstractValidator<UpdateArtistCoverCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateArtistCoverCommandValidator"/> class.
/// </summary>
public UpdateArtistCoverCommandValidator()
{
// Validates the identifier of the media library the artist belongs to, 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 whose cover image is updated, 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 uploaded cover image.
RuleFor(command => command.Cover)
.NotNull()
.WithError(Errors.Music.CoverCannotBeNull);
RuleFor(command => command.FileName)
.NotEmpty()
.When(command => command.Cover is not null)
.WithError(Errors.FileSystemManagement.FileNameCannotBeEmpty);
}
}
@@ -11,8 +11,11 @@ using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.A
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors; using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
@@ -87,6 +90,15 @@ public class GetArtistQueryHandler : IQueryHandler<GetArtistQuery, Result<Artist
if (!canAccessLibrary) if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized; return ApplicationErrors.Authorization.NotAuthorized;
return existingArtist.ToResponse(); // The artwork of the artist is stored separately from the artist, so it is loaded to expose the cover of the artist in the response.
Result<IReadOnlyList<MusicArtworkEntity>> getArtworkResult = await _unitOfWork.MusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, cancellationToken).ConfigureAwait(false);
if (getArtworkResult.IsFailure)
return getArtworkResult.Errors;
string? coverPath = getArtworkResult.Value
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
.Select(artwork => artwork.FileName)
.FirstOrDefault();
return existingArtist.ToResponse(coverPath);
} }
} }
@@ -1,6 +1,7 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS; using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.DTO.Pagination;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using System.Diagnostics; using System.Diagnostics;
#endregion #endregion
@@ -12,9 +13,17 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists
/// <param name="LibraryId">The unique identifier of the media library whose artists are retrieved, taken from the route.</param> /// <param name="LibraryId">The unique identifier of the media library whose artists are retrieved, taken from the route.</param>
/// <param name="PaginationData">The object containing the requested pagination data.</param> /// <param name="PaginationData">The object containing the requested pagination data.</param>
/// <param name="SearchTerm">The search term used to filter the artists by name.</param> /// <param name="SearchTerm">The search term used to filter the artists by name.</param>
/// <param name="FilterAlphaKey">The alpha key used to filter the artists by the first character of their name.</param>
/// <param name="ShouldIgnoreThePrefixForAlphaPicker">Whether the leading "The " prefix of a name should be ignored when computing the alpha key, or not.</param>
/// <param name="SortBy">The name of the field by which to sort the results.</param>
/// <param name="SortOrder">The direction in which to sort the results.</param>
[DebuggerDisplay("LibraryId: {LibraryId}")] [DebuggerDisplay("LibraryId: {LibraryId}")]
public record GetArtistsLiteQuery( public record GetArtistsLiteQuery(
string? LibraryId, string? LibraryId,
PaginationDataDto? PaginationData, PaginationDataDto? PaginationData,
string? SearchTerm string? SearchTerm,
string? FilterAlphaKey,
bool ShouldIgnoreThePrefixForAlphaPicker,
string? SortBy,
SortOrder? SortOrder
) : IQuery; ) : IQuery;
@@ -78,12 +78,16 @@ public class GetArtistsLiteQueryHandler : IQueryHandler<GetArtistsLiteQuery, Res
LibraryFilterDto filter = new() LibraryFilterDto filter = new()
{ {
LibraryId = libraryId, LibraryId = libraryId,
SearchTerm = query.SearchTerm SearchTerm = query.SearchTerm,
FilterAlphaKey = query.FilterAlphaKey,
ShouldIgnoreThePrefixForAlphaPicker = query.ShouldIgnoreThePrefixForAlphaPicker
}; };
Result<PaginatedResultDto<ArtistLiteRow>> getArtistsResult = await _unitOfWork.ArtistRepository.GetAllLiteAsync( Result<PaginatedResultDto<ArtistLiteRow>> getArtistsResult = await _unitOfWork.ArtistRepository.GetAllLiteAsync(
query.PaginationData, query.PaginationData,
filterModel: filter, query.SortBy,
query.SortOrder,
filter,
cancellationToken: cancellationToken).ConfigureAwait(false); cancellationToken: cancellationToken).ConfigureAwait(false);
return getArtistsResult.Match(value => Result.From(value.ToResponses()), errors => errors); return getArtistsResult.Match(value => Result.From(value.ToResponses()), errors => errors);
} }
@@ -1,4 +1,5 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities; using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Errors;
@@ -26,5 +27,14 @@ public class GetArtistsLiteQueryValidator : AbstractValidator<GetArtistsLiteQuer
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
.When(query => query.LibraryId is not null && query.LibraryId.Length > 0) .When(query => query.LibraryId is not null && query.LibraryId.Length > 0)
.WithError(Errors.Library.LibraryIdCannotBeEmpty); .WithError(Errors.Library.LibraryIdCannotBeEmpty);
// The alpha key must be exactly one of the three picker bucket kinds, so that the filter specification can
// derive the key of a name unambiguously: no filter, a number bucket, a symbol bucket, or a single ASCII letter.
RuleFor(query => query.FilterAlphaKey)
.Must(alphaKey => alphaKey is null
|| alphaKey == LibraryItemAlphaKeys.NUMBER
|| alphaKey == LibraryItemAlphaKeys.SYMBOL
|| (alphaKey.Length == 1 && char.IsAsciiLetter(alphaKey[0])))
.WithError(Errors.Library.InvalidFilterAlphaKey);
} }
} }
@@ -0,0 +1,38 @@
#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;
/// <summary>
/// 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.
/// </summary>
public interface IMusicArtworkCleanupService
{
/// <summary>
/// Removes the artwork records and the stored artwork files of the artist identified by <paramref name="artistId"/>, together with the artwork of its albums and tracks.
/// </summary>
/// <param name="artistId">The Id of the artist whose artwork is removed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> DeleteArtistArtworkAsync(Guid artistId, CancellationToken cancellationToken);
/// <summary>
/// Removes the artwork records and the stored artwork files of the album identified by <paramref name="albumId"/>, together with the artwork of its tracks.
/// </summary>
/// <param name="albumId">The Id of the album whose artwork is removed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> DeleteAlbumArtworkAsync(Guid albumId, CancellationToken cancellationToken);
/// <summary>
/// Removes the artwork records and the stored artwork files of the track identified by <paramref name="trackId"/>.
/// </summary>
/// <param name="trackId">The Id of the track whose artwork is removed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> DeleteTrackArtworkAsync(Guid trackId, CancellationToken cancellationToken);
}
@@ -2,6 +2,7 @@
using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.Common;
using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.Primitives;
using System; using System;
using System.IO;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
#endregion #endregion
@@ -22,10 +23,25 @@ public interface IMusicArtworkService
/// <param name="artistName">The name of the artist of the album.</param> /// <param name="artistName">The name of the artist of the album.</param>
/// <param name="albumTitle">The title of the album.</param> /// <param name="albumTitle">The title of the album.</param>
/// <param name="artwork">The artwork to store.</param> /// <param name="artwork">The artwork to store.</param>
/// <param name="releaseTypeName">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 <see langword="null"/>, no release type segment is added.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <param name="releaseTypeName">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.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns> /// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
Task<Result<string>> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, ArtworkDto artwork, CancellationToken cancellationToken, string? releaseTypeName = null); Task<Result<string>> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, ArtworkDto artwork, string? releaseTypeName, CancellationToken cancellationToken);
/// <summary>
/// Stores the uploaded <paramref name="artwork"/> of the album into the internal media directory, and returns the relative path of the stored artwork.
/// </summary>
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
/// <param name="albumId">The Id of the album.</param>
/// <param name="libraryName">The name of the media library the album belongs to.</param>
/// <param name="artistName">The name of the artist of the album.</param>
/// <param name="albumTitle">The title of the album.</param>
/// <param name="artwork">The stream of the uploaded artwork to store.</param>
/// <param name="fileName">The name of the uploaded artwork file.</param>
/// <param name="releaseTypeName">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 <see langword="null"/>, no release type segment is added.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
Task<Result<string>> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, Stream artwork, string fileName, string? releaseTypeName, CancellationToken cancellationToken);
/// <summary> /// <summary>
/// Deletes the stored artwork of the album from the internal media directory. /// Deletes the stored artwork of the album from the internal media directory.
@@ -50,6 +66,18 @@ public interface IMusicArtworkService
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns> /// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
Task<Result<string>> SaveArtistArtworkAsync(Guid libraryId, string libraryName, string artistName, ArtworkDto artwork, CancellationToken cancellationToken); Task<Result<string>> SaveArtistArtworkAsync(Guid libraryId, string libraryName, string artistName, ArtworkDto artwork, CancellationToken cancellationToken);
/// <summary>
/// Stores the uploaded <paramref name="artwork"/> of the artist into the internal media directory, and returns the relative path of the stored artwork.
/// </summary>
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <param name="libraryName">The name of the media library the artist belongs to.</param>
/// <param name="artistName">The name of the artist.</param>
/// <param name="artwork">The stream of the uploaded artwork to store.</param>
/// <param name="fileName">The name of the uploaded artwork file.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
Task<Result<string>> SaveArtistArtworkAsync(Guid libraryId, string libraryName, string artistName, Stream artwork, string fileName, CancellationToken cancellationToken);
/// <summary> /// <summary>
/// Deletes the stored artwork of the artist from the internal media directory. /// Deletes the stored artwork of the artist from the internal media directory.
/// </summary> /// </summary>
@@ -58,4 +86,11 @@ public interface IMusicArtworkService
/// <param name="artistName">The name of the artist.</param> /// <param name="artistName">The name of the artist.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns> /// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Result<Deleted> DeleteArtistArtwork(Guid libraryId, string libraryName, string artistName); Result<Deleted> DeleteArtistArtwork(Guid libraryId, string libraryName, string artistName);
/// <summary>
/// Deletes the stored artwork file at <paramref name="artworkRelativePath"/> from the internal media directory, when it still exists.
/// </summary>
/// <param name="artworkRelativePath">The relative path of the stored artwork file.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Result<Deleted> DeleteStoredArtwork(string artworkRelativePath);
} }
@@ -0,0 +1,119 @@
#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;
/// <summary>
/// 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.
/// </summary>
internal sealed class MusicArtworkCleanupService : IMusicArtworkCleanupService
{
private readonly IUnitOfWork _unitOfWork;
private readonly IMusicArtworkService _musicArtworkService;
/// <summary>
/// Initializes a new instance of the <see cref="MusicArtworkCleanupService"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="musicArtworkService">Injected service for removing the stored artwork files of a music library item.</param>
public MusicArtworkCleanupService(IUnitOfWork unitOfWork, IMusicArtworkService musicArtworkService)
{
_unitOfWork = unitOfWork;
_musicArtworkService = musicArtworkService;
}
/// <summary>
/// Removes the artwork records and the stored artwork files of the artist identified by <paramref name="artistId"/>, together with the artwork of its albums and tracks.
/// </summary>
/// <param name="artistId">The Id of the artist whose artwork is removed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> 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<IReadOnlyList<AlbumEntity>> getAlbumsResult = await _unitOfWork.AlbumRepository.GetByArtistIdAsync(artistId, cancellationToken).ConfigureAwait(false);
if (getAlbumsResult.IsFailure)
return getAlbumsResult.Errors;
foreach (AlbumEntity album in getAlbumsResult.Value)
{
Result<Deleted> deleteAlbumArtworkResult = await DeleteAlbumArtworkAsync(album.Id, cancellationToken).ConfigureAwait(false);
if (deleteAlbumArtworkResult.IsFailure)
return deleteAlbumArtworkResult.Errors;
}
return await DeleteOwnerArtworkAsync(MusicArtworkOwnerType.Artist, artistId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Removes the artwork records and the stored artwork files of the album identified by <paramref name="albumId"/>, together with the artwork of its tracks.
/// </summary>
/// <param name="albumId">The Id of the album whose artwork is removed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> 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<IReadOnlyList<TrackEntity>> getTracksResult = await _unitOfWork.TrackRepository.GetByAlbumIdAsync(albumId, cancellationToken).ConfigureAwait(false);
if (getTracksResult.IsFailure)
return getTracksResult.Errors;
foreach (TrackEntity track in getTracksResult.Value)
{
Result<Deleted> deleteTrackArtworkResult = await DeleteTrackArtworkAsync(track.Id, cancellationToken).ConfigureAwait(false);
if (deleteTrackArtworkResult.IsFailure)
return deleteTrackArtworkResult.Errors;
}
return await DeleteOwnerArtworkAsync(MusicArtworkOwnerType.Album, albumId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Removes the artwork records and the stored artwork files of the track identified by <paramref name="trackId"/>.
/// </summary>
/// <param name="trackId">The Id of the track whose artwork is removed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public Task<Result<Deleted>> DeleteTrackArtworkAsync(Guid trackId, CancellationToken cancellationToken)
{
return DeleteOwnerArtworkAsync(MusicArtworkOwnerType.Track, trackId, cancellationToken);
}
/// <summary>
/// Removes the artwork records and the stored artwork files of the single music library item identified by <paramref name="ownerType"/> and <paramref name="ownerId"/>.
/// </summary>
/// <param name="ownerType">The type of the music library item whose artwork is removed.</param>
/// <param name="ownerId">The Id of the music library item whose artwork is removed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<Result<Deleted>> DeleteOwnerArtworkAsync(MusicArtworkOwnerType ownerType, Guid ownerId, CancellationToken cancellationToken)
{
Result<IReadOnlyList<MusicArtworkEntity>> 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<Deleted> deleteStoredArtworkResult = _musicArtworkService.DeleteStoredArtwork(artwork.FileName);
if (deleteStoredArtworkResult.IsFailure)
return deleteStoredArtworkResult.Errors;
}
return await _unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(ownerType, ownerId, cancellationToken).ConfigureAwait(false);
}
}
@@ -8,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; 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.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
@@ -28,6 +29,7 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.
public class DeleteTrackCommandHandler : ICommandHandler<DeleteTrackCommand, Result<Deleted>> public class DeleteTrackCommandHandler : ICommandHandler<DeleteTrackCommand, Result<Deleted>>
{ {
private readonly IUnitOfWork _unitOfWork; private readonly IUnitOfWork _unitOfWork;
private readonly IMusicArtworkCleanupService _musicArtworkCleanupService;
private readonly IAuthorizationService _authorizationService; private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService; private readonly ICurrentUserService _currentUserService;
private readonly IValidator<DeleteTrackCommand> _validator; private readonly IValidator<DeleteTrackCommand> _validator;
@@ -36,12 +38,14 @@ public class DeleteTrackCommandHandler : ICommandHandler<DeleteTrackCommand, Res
/// Initializes a new instance of the <see cref="DeleteTrackCommandHandler"/> class. /// Initializes a new instance of the <see cref="DeleteTrackCommandHandler"/> class.
/// </summary> /// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param> /// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="musicArtworkCleanupService">Injected service for removing the artwork of a music library item and of its children.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param> /// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param> /// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param> /// <param name="validator">Injected validator for application validation rules.</param>
public DeleteTrackCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<DeleteTrackCommand> validator) public DeleteTrackCommandHandler(IUnitOfWork unitOfWork, IMusicArtworkCleanupService musicArtworkCleanupService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<DeleteTrackCommand> validator)
{ {
_unitOfWork = unitOfWork; _unitOfWork = unitOfWork;
_musicArtworkCleanupService = musicArtworkCleanupService;
_authorizationService = authorizationService; _authorizationService = authorizationService;
_currentUserService = currentUserService; _currentUserService = currentUserService;
_validator = validator; _validator = validator;
@@ -122,6 +126,12 @@ public class DeleteTrackCommandHandler : ICommandHandler<DeleteTrackCommand, Res
if (removeTrackResult.IsFailure) if (removeTrackResult.IsFailure)
return removeTrackResult.Errors; 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<Deleted> deleteArtworkResult = await _musicArtworkCleanupService.DeleteTrackArtworkAsync(trackId, cancellationToken).ConfigureAwait(false);
if (deleteArtworkResult.IsFailure)
return deleteArtworkResult.Errors;
Result<Updated> updateResult = await _unitOfWork.ArtistRepository.UpdateAsync(artistResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); Result<Updated> updateResult = await _unitOfWork.ArtistRepository.UpdateAsync(artistResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure) if (updateResult.IsFailure)
return updateResult.Errors; return updateResult.Errors;
@@ -1,7 +1,8 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
@@ -20,6 +21,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Events;
/// </summary> /// </summary>
public class LibraryDeletedDomainEventHandler : IDomainEventHandler<LibraryDeletedDomainEvent> public class LibraryDeletedDomainEventHandler : IDomainEventHandler<LibraryDeletedDomainEvent>
{ {
private readonly IUnitOfWork _unitOfWork;
private readonly IEnvironmentContext _environmentContext; private readonly IEnvironmentContext _environmentContext;
private readonly IPathService _pathService; private readonly IPathService _pathService;
private readonly MediaSettingsDto _mediaSettingsModel; private readonly MediaSettingsDto _mediaSettingsModel;
@@ -27,11 +29,13 @@ public class LibraryDeletedDomainEventHandler : IDomainEventHandler<LibraryDelet
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="LibraryDeletedDomainEventHandler"/> class. /// Initializes a new instance of the <see cref="LibraryDeletedDomainEventHandler"/> class.
/// </summary> /// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="environmentContext">Injected facade service for environment contextual services.</param> /// <param name="environmentContext">Injected facade service for environment contextual services.</param>
/// <param name="pathService">Injected service for handling file system paths.</param> /// <param name="pathService">Injected service for handling file system paths.</param>
/// <param name="mediaSettingsModelOptions">Injected service for retrieving <see cref="MediaSettingsDto"/>.</param> /// <param name="mediaSettingsModelOptions">Injected service for retrieving <see cref="MediaSettingsDto"/>.</param>
public LibraryDeletedDomainEventHandler(IEnvironmentContext environmentContext, IPathService pathService, IOptions<MediaSettingsDto> mediaSettingsModelOptions) public LibraryDeletedDomainEventHandler(IUnitOfWork unitOfWork, IEnvironmentContext environmentContext, IPathService pathService, IOptions<MediaSettingsDto> mediaSettingsModelOptions)
{ {
_unitOfWork = unitOfWork;
_environmentContext = environmentContext; _environmentContext = environmentContext;
_pathService = pathService; _pathService = pathService;
_mediaSettingsModel = mediaSettingsModelOptions.Value; _mediaSettingsModel = mediaSettingsModelOptions.Value;
@@ -42,47 +46,80 @@ public class LibraryDeletedDomainEventHandler : IDomainEventHandler<LibraryDelet
/// </summary> /// </summary>
/// <param name="domainEvent">The domain event to be handled.</param> /// <param name="domainEvent">The domain event to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public ValueTask HandleAsync(LibraryDeletedDomainEvent domainEvent, CancellationToken cancellationToken) public async ValueTask HandleAsync(LibraryDeletedDomainEvent domainEvent, CancellationToken cancellationToken)
{ {
// delete the media library directory in the internal location for media library files Guid libraryId = domainEvent.Library.Id.Value;
Result<string> libraryPathResult = GetLibraryPath(domainEvent.Library.Id.Value);
if (libraryPathResult.IsFailure)
throw new EventualConsistencyException(libraryPathResult.FirstError, libraryPathResult.Errors);
Result<FileSystemPathId> newLibraryPathIdResult = FileSystemPathId.Create(libraryPathResult.Value); // The media items of the library and their artwork do not cascade from the library row, because they reference it by a plain id,
if (newLibraryPathIdResult.IsFailure) // so they are removed first, otherwise they would be orphaned in the database. The artwork is removed before its owners, so that
throw new EventualConsistencyException(newLibraryPathIdResult.FirstError, newLibraryPathIdResult.Errors); // its owners are still present when the artwork is looked up.
Result<Deleted> deleteMusicArtworkResult = await _unitOfWork.MusicArtworkRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (deleteMusicArtworkResult.IsFailure)
throw new EventualConsistencyException(deleteMusicArtworkResult.FirstError, deleteMusicArtworkResult.Errors);
Result<Deleted> deleteLibraryDirectoryResult = _environmentContext.DirectoryProviderService.DeleteDirectory(newLibraryPathIdResult.Value); // Deleting the artists removes their albums, tracks and their related data, through the cascading foreign keys.
if (deleteLibraryDirectoryResult.IsFailure) Result<Deleted> deleteArtistsResult = await _unitOfWork.ArtistRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
throw new EventualConsistencyException(deleteLibraryDirectoryResult.FirstError, deleteLibraryDirectoryResult.Errors); if (deleteArtistsResult.IsFailure)
throw new EventualConsistencyException(deleteArtistsResult.FirstError, deleteArtistsResult.Errors);
return ValueTask.CompletedTask;
// Deleting the books removes their artwork and their related data, through the cascading foreign keys.
Result<Deleted> deleteBooksResult = await _unitOfWork.BookRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (deleteBooksResult.IsFailure)
throw new EventualConsistencyException(deleteBooksResult.FirstError, deleteBooksResult.Errors);
// The staged music metadata of the library does not cascade from the library row either, so it is removed as well.
Result<Deleted> deleteStagedMusicMetadataResult = await _unitOfWork.MusicLibraryScanItemMetadataRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (deleteStagedMusicMetadataResult.IsFailure)
throw new EventualConsistencyException(deleteStagedMusicMetadataResult.FirstError, deleteStagedMusicMetadataResult.Errors);
// The cover image of the library is stored under the libraries directory, under a directory named after the library id,
// while the artwork of the media items of the library is stored under the per-media-type directories, under directories
// named after the library, so all of them must be removed when the library is deleted. All the media item files of a library
// live inside these directories, so removing them removes the library's stored media without touching the user's own files.
DeleteLibraryDirectory(_mediaSettingsModel.LibrariesDirectory, libraryId.ToString());
Result<PathSegment> librarySegmentResult = _pathService.SanitizeSegment($"{domainEvent.Library.Title}-{libraryId}");
if (librarySegmentResult.IsFailure)
throw new EventualConsistencyException(librarySegmentResult.FirstError, librarySegmentResult.Errors);
DeleteLibraryDirectory(_mediaSettingsModel.BooksDirectory, librarySegmentResult.Value.Name);
DeleteLibraryDirectory(_mediaSettingsModel.MusicDirectory, librarySegmentResult.Value.Name);
} }
/// <summary> /// <summary>
/// Gets the file system path of a media library identified by <paramref name="libraryId"/>. /// Deletes the directory of a media library from the internal media location of the provided media type.
/// </summary> /// </summary>
/// <param name="libraryId">The id of the media library for which to regtrieve the file system path.</param> /// <param name="mediaTypeDirectory">The name of the media type subdirectory the library directory is stored under.</param>
/// <returns> /// <param name="libraryDirectoryName">The name of the directory of the media library.</param>
/// An <see cref="Result{TValue}"/> containing either the file system path of the media library, or an error message. private void DeleteLibraryDirectory(string mediaTypeDirectory, string libraryDirectoryName)
/// </returns>
private Result<string> GetLibraryPath(Guid libraryId)
{ {
// root directory for media // Root directory for media.
Result<string> rootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettingsModel.RootDirectory); Result<string> rootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettingsModel.RootDirectory);
if (rootPathResult.IsFailure) if (rootPathResult.IsFailure)
return rootPathResult.Errors; throw new EventualConsistencyException(rootPathResult.FirstError, rootPathResult.Errors);
// libraries directory // Media type directory.
Result<string> librariesPathResult = _pathService.CombinePath(rootPathResult.Value, _mediaSettingsModel.LibrariesDirectory); Result<string> mediaTypePathResult = _pathService.CombinePath(rootPathResult.Value, mediaTypeDirectory);
if (librariesPathResult.IsFailure) if (mediaTypePathResult.IsFailure)
return librariesPathResult.Errors; throw new EventualConsistencyException(mediaTypePathResult.FirstError, mediaTypePathResult.Errors);
// this new particular library' directory // This particular library's directory.
Result<string> libraryPathResult = _pathService.CombinePath(librariesPathResult.Value, libraryId.ToString()); Result<string> libraryPathResult = _pathService.CombinePath(mediaTypePathResult.Value, libraryDirectoryName);
if (libraryPathResult.IsFailure) if (libraryPathResult.IsFailure)
return libraryPathResult.Errors; throw new EventualConsistencyException(libraryPathResult.FirstError, libraryPathResult.Errors);
return libraryPathResult.Value;
Result<FileSystemPathId> libraryPathIdResult = FileSystemPathId.Create(libraryPathResult.Value);
if (libraryPathIdResult.IsFailure)
throw new EventualConsistencyException(libraryPathIdResult.FirstError, libraryPathIdResult.Errors);
// The directory only exists when the library actually stored something under this media type, so a missing directory is not an error.
Result<bool> directoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(libraryPathIdResult.Value);
if (directoryExistsResult.IsFailure)
throw new EventualConsistencyException(directoryExistsResult.FirstError, directoryExistsResult.Errors);
if (!directoryExistsResult.Value)
return;
Result<Deleted> deleteLibraryDirectoryResult = _environmentContext.DirectoryProviderService.DeleteDirectory(libraryPathIdResult.Value);
if (deleteLibraryDirectoryResult.IsFailure)
throw new EventualConsistencyException(deleteLibraryDirectoryResult.FirstError, deleteLibraryDirectoryResult.Errors);
} }
} }
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.DTO.Common;
/// <summary>
/// Data transfer object for a stored piece of artwork of a media item.
/// </summary>
/// <param name="Type">The type of the artwork, like the cover or the back of the media item.</param>
/// <param name="Ordinal">The ordinal of the artwork within its type, so that multiple artworks of the same type can be ordered.</param>
/// <param name="Path">The relative path of the stored artwork file.</param>
[DebuggerDisplay("Type: {Type}, Ordinal: {Ordinal}, Path: {Path}")]
public sealed record MediaArtworkDto(
ArtworkType Type,
int Ordinal,
string Path
);
@@ -1,4 +1,5 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using System.Diagnostics; using System.Diagnostics;
#endregion #endregion
@@ -10,9 +11,21 @@ namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artis
/// <param name="CurrentPage">The page of results to retrieve. Optional.</param> /// <param name="CurrentPage">The page of results to retrieve. Optional.</param>
/// <param name="PerPage">The maximum number of artists to retrieve per page. Optional.</param> /// <param name="PerPage">The maximum number of artists to retrieve per page. Optional.</param>
/// <param name="SearchTerm">The search term used to filter the artists by name. Optional.</param> /// <param name="SearchTerm">The search term used to filter the artists by name. Optional.</param>
/// <param name="FilterAlphaKey">
/// The alpha key used to filter the results by the first character of their name, for the alpha picker. Optional.
/// Can be <see langword="null"/> to disable alpha filtering, a single ASCII letter (case-insensitive) to filter by that letter,
/// "#" to filter by names whose first character is a digit, or "*" to filter by names whose first character is neither a letter nor a digit.
/// </param>
/// <param name="ShouldIgnoreThePrefixForAlphaPicker">Whether the leading "The " prefix of a name should be ignored when computing the alpha key, or not. Optional.</param>
/// <param name="SortBy">The name of the field by which to sort the results. Optional.</param>
/// <param name="SortOrder">The direction in which to sort the results. Optional.</param>
[DebuggerDisplay("SearchTerm: {SearchTerm}")] [DebuggerDisplay("SearchTerm: {SearchTerm}")]
public record GetArtistsLiteRequest( public record GetArtistsLiteRequest(
int? CurrentPage, int? CurrentPage,
int? PerPage, int? PerPage,
string? SearchTerm string? SearchTerm,
string? FilterAlphaKey,
bool ShouldIgnoreThePrefixForAlphaPicker,
string? SortBy,
SortOrder? SortOrder
); );
@@ -1,5 +1,7 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using System; using System;
using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
#endregion #endregion
@@ -11,9 +13,15 @@ namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albu
/// <param name="Id">The Id of the album.</param> /// <param name="Id">The Id of the album.</param>
/// <param name="Title">The title of the album.</param> /// <param name="Title">The title of the album.</param>
/// <param name="TotalTracks">The number of tracks of the release.</param> /// <param name="TotalTracks">The number of tracks of the release.</param>
/// <param name="CoverPath">The path of the image representing the album, if available.</param>
/// <param name="ReleaseYear">The release year of the album (the re-release year, if available, or the original release year), if known.</param>
/// <param name="ReleaseTypes">The set of types of the release.</param>
[DebuggerDisplay("Title: {Title}")] [DebuggerDisplay("Title: {Title}")]
public record AlbumLiteResponse( public record AlbumLiteResponse(
Guid Id, Guid Id,
string Title, string Title,
int TotalTracks int TotalTracks,
string? CoverPath,
int? ReleaseYear,
List<MusicReleaseType>? ReleaseTypes
); );
@@ -1,4 +1,5 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
@@ -32,6 +33,8 @@ namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albu
/// <param name="Contributors">The list of references to the media contributors that performed on the album, each with the role they played.</param> /// <param name="Contributors">The list of references to the media contributors that performed on the album, each with the role they played.</param>
/// <param name="Ratings">The list of ratings for this album.</param> /// <param name="Ratings">The list of ratings for this album.</param>
/// <param name="Tracks">The list of tracks of the album.</param> /// <param name="Tracks">The list of tracks of the album.</param>
/// <param name="CoverPath">The path of the image representing the album, if available.</param>
/// <param name="Artwork">The stored artwork of the album, in display order, so that all of its pieces can be presented, not just the cover.</param>
[DebuggerDisplay("Title: {Metadata.Title}")] [DebuggerDisplay("Title: {Metadata.Title}")]
public record AlbumResponse( public record AlbumResponse(
Guid Id, Guid Id,
@@ -51,5 +54,7 @@ public record AlbumResponse(
DateTime? UpdatedOnUtc, DateTime? UpdatedOnUtc,
List<MediaContributorReferenceDto>? Contributors, List<MediaContributorReferenceDto>? Contributors,
List<AudioRatingDto>? Ratings, List<AudioRatingDto>? Ratings,
List<TrackResponse>? Tracks List<TrackResponse>? Tracks,
string? CoverPath,
IReadOnlyList<MediaArtworkDto> Artwork
); );
@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
/// <summary>
/// Represents a response of an update album cover operation.
/// </summary>
/// <param name="CoverPath">The relative path of the stored cover image.</param>
[DebuggerDisplay("CoverPath: {CoverPath}")]
public record UpdateAlbumCoverResponse(
string CoverPath
);
@@ -10,8 +10,10 @@ namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Arti
/// </summary> /// </summary>
/// <param name="Id">The Id of the artist.</param> /// <param name="Id">The Id of the artist.</param>
/// <param name="Name">The name of the artist.</param> /// <param name="Name">The name of the artist.</param>
/// <param name="CoverPath">The path of the image representing the artist, if available.</param>
[DebuggerDisplay("Name: {Name}")] [DebuggerDisplay("Name: {Name}")]
public record ArtistLiteResponse( public record ArtistLiteResponse(
Guid Id, Guid Id,
string Name string Name,
string? CoverPath
); );
@@ -25,6 +25,7 @@ namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Arti
/// <param name="Contributors">The list of references to the media contributors that make up the artist, each with the role they played.</param> /// <param name="Contributors">The list of references to the media contributors that make up the artist, each with the role they played.</param>
/// <param name="Ratings">The list of ratings for this artist.</param> /// <param name="Ratings">The list of ratings for this artist.</param>
/// <param name="Albums">The list of albums of the artist, each with its own list of tracks.</param> /// <param name="Albums">The list of albums of the artist, each with its own list of tracks.</param>
/// <param name="CoverPath">The path of the image representing the artist, if available.</param>
[DebuggerDisplay("Name: {Metadata.Name}")] [DebuggerDisplay("Name: {Metadata.Name}")]
public record ArtistResponse( public record ArtistResponse(
Guid Id, Guid Id,
@@ -38,5 +39,6 @@ public record ArtistResponse(
DateTime? UpdatedOnUtc, DateTime? UpdatedOnUtc,
List<MediaContributorReferenceDto>? Contributors, List<MediaContributorReferenceDto>? Contributors,
List<AudioRatingDto>? Ratings, List<AudioRatingDto>? Ratings,
List<AlbumResponse>? Albums List<AlbumResponse>? Albums,
string? CoverPath
); );
@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
/// <summary>
/// Represents a response of an update artist cover operation.
/// </summary>
/// <param name="CoverPath">The relative path of the stored cover image.</param>
[DebuggerDisplay("CoverPath: {CoverPath}")]
public record UpdateArtistCoverResponse(
string CoverPath
);
@@ -12,10 +12,12 @@ namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Trac
/// <param name="Title">The title of the track.</param> /// <param name="Title">The title of the track.</param>
/// <param name="TrackNumber">The number of the track on its disc.</param> /// <param name="TrackNumber">The number of the track on its disc.</param>
/// <param name="DiscNumber">The number of the disc the track belongs to, if applicable.</param> /// <param name="DiscNumber">The number of the disc the track belongs to, if applicable.</param>
/// <param name="DurationInSeconds">The duration of the track in seconds.</param>
[DebuggerDisplay("Title: {Title}")] [DebuggerDisplay("Title: {Title}")]
public record TrackLiteResponse( public record TrackLiteResponse(
Guid Id, Guid Id,
string Title, string Title,
int TrackNumber, int TrackNumber,
int? DiscNumber int? DiscNumber,
int DurationInSeconds
); );
@@ -462,6 +462,21 @@ internal sealed class BookRepository : IBookRepository
return Result.Updated; return Result.Updated;
} }
/// <summary>
/// Deletes all the books of the media library identified by <paramref name="libraryId"/>, together with their artwork and their related data.
/// </summary>
/// <param name="libraryId">The Id of the media library whose books are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken)
{
// The artwork and the related data of the books are removed by the database, through the cascading foreign keys.
await _luminaDbContext.Books
.Where(book => book.LibraryId == libraryId)
.ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false);
return Result.Deleted;
}
/// <summary> /// <summary>
/// Gets the display names of the author of the books identified by the provided <paramref name="bookIds"/>, /// Gets the display names of the author of the books identified by the provided <paramref name="bookIds"/>,
/// keyed by the Id of the book, or <see langword="null"/> when a book has no author. /// keyed by the Id of the book, or <see langword="null"/> when a book has no author.
@@ -42,7 +42,7 @@ internal sealed class BookAlphaFilterSpecification : FilterSpecification<BookEnt
/// <returns>An expression tree that can be used to evaluate whether a <see cref="BookEntity"/> satisfies the specification criteria.</returns> /// <returns>An expression tree that can be used to evaluate whether a <see cref="BookEntity"/> satisfies the specification criteria.</returns>
public override Expression<Func<BookEntity, bool>> ToExpression() public override Expression<Func<BookEntity, bool>> ToExpression()
{ {
// when no alpha key was requested, every book matches // When no alpha key was requested, every book matches.
if (_filterAlphaKey is null) if (_filterAlphaKey is null)
return book => true; return book => true;
@@ -55,7 +55,7 @@ internal sealed class BookAlphaFilterSpecification : FilterSpecification<BookEnt
if (_filterAlphaKey == LibraryItemAlphaKeys.SYMBOL) if (_filterAlphaKey == LibraryItemAlphaKeys.SYMBOL)
return BuildSymbolPredicate(book, effectiveTitle); return BuildSymbolPredicate(book, effectiveTitle);
// the alpha key is a single ASCII letter // The alpha key is a single ASCII letter.
string globPattern = char.ToLowerInvariant(_filterAlphaKey[0]) + "*"; string globPattern = char.ToLowerInvariant(_filterAlphaKey[0]) + "*";
return BuildGlobPredicate(book, effectiveTitle, globPattern); return BuildGlobPredicate(book, effectiveTitle, globPattern);
} }
@@ -70,7 +70,7 @@ internal sealed class BookAlphaFilterSpecification : FilterSpecification<BookEnt
{ {
Expression titleProperty = Expression.Property(book, nameof(BookEntity.Title)); Expression titleProperty = Expression.Property(book, nameof(BookEntity.Title));
// the raw title: the title, unless it is null or empty, in which case the original title (or an empty string) is used // The raw title is the title, unless it is null or empty, in which case the original title (or an empty string) is used.
BinaryExpression isTitleMissing = Expression.OrElse( BinaryExpression isTitleMissing = Expression.OrElse(
Expression.Equal(titleProperty, Expression.Constant(null, typeof(string))), Expression.Equal(titleProperty, Expression.Constant(null, typeof(string))),
Expression.Equal(titleProperty, Expression.Constant(string.Empty))); Expression.Equal(titleProperty, Expression.Constant(string.Empty)));
@@ -80,7 +80,7 @@ internal sealed class BookAlphaFilterSpecification : FilterSpecification<BookEnt
MethodCallExpression lowerTitle = Expression.Call(rawTitle, s_toLowerMethod); MethodCallExpression lowerTitle = Expression.Call(rawTitle, s_toLowerMethod);
// when ignoring the "The " prefix, strip a leading "the " from the lowercased title // When ignoring the "The " prefix, a leading "the " is stripped from the lowercased title.
Expression effectiveTitle = lowerTitle; Expression effectiveTitle = lowerTitle;
if (_shouldIgnoreThePrefixForAlphaPicker) if (_shouldIgnoreThePrefixForAlphaPicker)
{ {
@@ -284,7 +284,15 @@ internal sealed class AlbumRepository : IAlbumRepository
{ {
Id = album.Id, Id = album.Id,
Title = album.Title, Title = album.Title,
TotalTracks = album.TotalTracks TotalTracks = album.TotalTracks,
// The release year and the release types are exposed so that the clients can group and order the releases of an artist.
ReleaseYear = album.ReReleaseYear ?? album.OriginalReleaseYear,
ReleaseTypes = album.ReleaseTypes.Select(releaseType => releaseType.ReleaseType).ToList(),
// The cover of the album is the cover artwork stored for it, if any, and it is exposed so that the clients can display it without loading the whole album.
CoverPath = _luminaDbContext.MusicArtwork
.Where(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == album.Id && artwork.ArtworkType == ArtworkType.Cover)
.Select(artwork => artwork.FileName)
.FirstOrDefault()
}); });
if (paginationData is null) if (paginationData is null)
@@ -18,6 +18,8 @@ using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
#endregion #endregion
@@ -29,6 +31,10 @@ namespace Lumina.DataAccess.Core.Repositories.MusicLibrary;
/// </summary> /// </summary>
internal sealed class ArtistRepository : IArtistRepository internal sealed class ArtistRepository : IArtistRepository
{ {
private static readonly MethodInfo s_toLowerMethod = typeof(string).GetMethod(nameof(string.ToLower), Type.EmptyTypes)!;
private static readonly MethodInfo s_startsWithMethod = typeof(string).GetMethod(nameof(string.StartsWith), [typeof(string)])!;
private static readonly MethodInfo s_substringMethod = typeof(string).GetMethod(nameof(string.Substring), [typeof(int)])!;
private readonly LuminaDbContext _luminaDbContext; private readonly LuminaDbContext _luminaDbContext;
private readonly IAlbumRepository _albumRepository; private readonly IAlbumRepository _albumRepository;
private readonly ITrackRepository _trackRepository; private readonly ITrackRepository _trackRepository;
@@ -488,7 +494,7 @@ internal sealed class ArtistRepository : IArtistRepository
if (filterSpecification is not null) if (filterSpecification is not null)
artistsQuery = artistsQuery.Where(filterSpecification.ToExpression()); artistsQuery = artistsQuery.Where(filterSpecification.ToExpression());
IQueryable<ArtistEntity> orderedArtistsQuery = ApplySorting(artistsQuery, sortBy, sortOrder ?? SortOrder.Ascending); IQueryable<ArtistEntity> orderedArtistsQuery = ApplySorting(artistsQuery, sortBy, sortOrder ?? SortOrder.Ascending, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker);
// If no pagination was requested, return all the artists of the library. // If no pagination was requested, return all the artists of the library.
if (paginationData is null) if (paginationData is null)
@@ -559,11 +565,16 @@ internal sealed class ArtistRepository : IArtistRepository
if (filterSpecification is not null) if (filterSpecification is not null)
artistsQuery = artistsQuery.Where(filterSpecification.ToExpression()); artistsQuery = artistsQuery.Where(filterSpecification.ToExpression());
IQueryable<ArtistLiteRow> liteRowsQuery = ApplySorting(artistsQuery, sortBy, sortOrder ?? SortOrder.Ascending) IQueryable<ArtistLiteRow> liteRowsQuery = ApplySorting(artistsQuery, sortBy, sortOrder ?? SortOrder.Ascending, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker)
.Select(artist => new ArtistLiteRow .Select(artist => new ArtistLiteRow
{ {
Id = artist.Id, Id = artist.Id,
Name = artist.Name Name = artist.Name,
// The cover of the artist is the cover artwork stored for it, if any, and it is exposed so that the clients can display it without loading the whole artist.
CoverPath = _luminaDbContext.MusicArtwork
.Where(artwork => artwork.OwnerType == MusicArtworkOwnerType.Artist && artwork.OwnerId == artist.Id && artwork.ArtworkType == ArtworkType.Cover)
.Select(artwork => artwork.FileName)
.FirstOrDefault()
}); });
// If no pagination was requested, return all the artists of the library. // If no pagination was requested, return all the artists of the library.
@@ -607,11 +618,22 @@ internal sealed class ArtistRepository : IArtistRepository
/// <returns>A filter specification that can be used to query artists matching the provided criteria.</returns> /// <returns>A filter specification that can be used to query artists matching the provided criteria.</returns>
private static FilterSpecification<ArtistEntity>? BuildFilterSpecification(LibraryFilterDto libraryFilter) private static FilterSpecification<ArtistEntity>? BuildFilterSpecification(LibraryFilterDto libraryFilter)
{ {
FilterSpecification<ArtistEntity>? filterSpecification = null;
// Include the search term filter, if provided. // Include the search term filter, if provided.
if (!string.IsNullOrWhiteSpace(libraryFilter.SearchTerm)) if (!string.IsNullOrWhiteSpace(libraryFilter.SearchTerm))
return new ArtistSearchSpecification(libraryFilter.SearchTerm); filterSpecification = new ArtistSearchSpecification(libraryFilter.SearchTerm);
return null; // Include the alpha key filter, if provided.
if (libraryFilter.FilterAlphaKey is not null)
{
ArtistAlphaFilterSpecification alphaFilterSpecification = new(libraryFilter.FilterAlphaKey, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker);
filterSpecification = filterSpecification is null
? alphaFilterSpecification
: filterSpecification.And(alphaFilterSpecification);
}
return filterSpecification;
} }
/// <summary> /// <summary>
@@ -620,8 +642,8 @@ internal sealed class ArtistRepository : IArtistRepository
/// <param name="artistsQuery">The query to sort.</param> /// <param name="artistsQuery">The query to sort.</param>
/// <param name="sortBy">The field to sort by (case-insensitive).</param> /// <param name="sortBy">The field to sort by (case-insensitive).</param>
/// <param name="sortOrder">The direction of the sorting.</param> /// <param name="sortOrder">The direction of the sorting.</param>
/// <returns>An ordered artists query.</returns> /// <param name="shouldIgnoreThePrefixForAlphaPicker">Whether a leading "the " prefix of a name is ignored when deriving the name sort key, or not.</param>
private static IOrderedQueryable<ArtistEntity> ApplySorting(IQueryable<ArtistEntity> artistsQuery, string? sortBy, SortOrder sortOrder) private static IOrderedQueryable<ArtistEntity> ApplySorting(IQueryable<ArtistEntity> artistsQuery, string? sortBy, SortOrder sortOrder, bool shouldIgnoreThePrefixForAlphaPicker)
{ {
return sortBy?.ToLowerInvariant() switch return sortBy?.ToLowerInvariant() switch
{ {
@@ -638,11 +660,41 @@ internal sealed class ArtistRepository : IArtistRepository
? artistsQuery.OrderByDescending(artist => artist.UpdatedOnUtc).ThenBy(artist => artist.Id) ? artistsQuery.OrderByDescending(artist => artist.UpdatedOnUtc).ThenBy(artist => artist.Id)
: artistsQuery.OrderBy(artist => artist.UpdatedOnUtc).ThenBy(artist => artist.Id), : artistsQuery.OrderBy(artist => artist.UpdatedOnUtc).ThenBy(artist => artist.Id),
_ => sortOrder == SortOrder.Descending _ => sortOrder == SortOrder.Descending
? artistsQuery.OrderByDescending(artist => artist.Name).ThenBy(artist => artist.Id) ? artistsQuery.OrderByDescending(BuildNameSortKey(shouldIgnoreThePrefixForAlphaPicker)).ThenBy(artist => artist.Id)
: artistsQuery.OrderBy(artist => artist.Name).ThenBy(artist => artist.Id), : artistsQuery.OrderBy(BuildNameSortKey(shouldIgnoreThePrefixForAlphaPicker)).ThenBy(artist => artist.Id),
}; };
} }
/// <summary>
/// Builds the expression that derives the name sort key of an artist, matching the effective name used by the alpha filter:
/// the name lowercased, falling back to an empty string when the name is <see langword="null"/>, and optionally
/// stripped of a leading "the " prefix.
/// </summary>
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Whether a leading "the " prefix of a name is ignored when deriving the name sort key, or not.</param>
/// <returns>An expression that evaluates to the name sort key of an artist.</returns>
private static Expression<Func<ArtistEntity, string>> BuildNameSortKey(bool shouldIgnoreThePrefixForAlphaPicker)
{
ParameterExpression artist = Expression.Parameter(typeof(ArtistEntity), "artist");
Expression nameProperty = Expression.Property(artist, nameof(ArtistEntity.Name));
// The raw name: the name, unless it is null, in which case an empty string is used.
Expression rawName = Expression.Coalesce(nameProperty, Expression.Constant(string.Empty));
MethodCallExpression lowerName = Expression.Call(rawName, s_toLowerMethod);
// When ignoring the "The " prefix, strip a leading "the " from the lowercased name.
Expression effectiveName = lowerName;
if (shouldIgnoreThePrefixForAlphaPicker)
{
MethodCallExpression startsWithThe = Expression.Call(lowerName, s_startsWithMethod, Expression.Constant("the "));
MethodCallExpression strippedName = Expression.Call(lowerName, s_substringMethod, Expression.Constant(4));
effectiveName = Expression.Condition(startsWithThe, strippedName, lowerName);
}
return Expression.Lambda<Func<ArtistEntity, string>>(effectiveName, artist);
}
/// <summary> /// <summary>
/// Gets the artist of the library identified by <paramref name="libraryId"/> that has the provided <paramref name="name"/>. /// Gets the artist of the library identified by <paramref name="libraryId"/> that has the provided <paramref name="name"/>.
/// </summary> /// </summary>
@@ -793,4 +845,19 @@ internal sealed class ArtistRepository : IArtistRepository
.ExecuteUpdateAsync(setters => setters.SetProperty(artist => artist.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false); .ExecuteUpdateAsync(setters => setters.SetProperty(artist => artist.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false);
return Result.Updated; return Result.Updated;
} }
/// <summary>
/// Deletes all the artists of the media library identified by <paramref name="libraryId"/>, together with their albums and tracks and their related data.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artists are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken)
{
// The albums, tracks and the related data of the artists are removed by the database, through the cascading foreign keys.
await _luminaDbContext.Artists
.Where(artist => artist.LibraryId == libraryId)
.ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false);
return Result.Deleted;
}
} }
@@ -85,25 +85,84 @@ internal sealed class MusicArtworkRepository : IMusicArtworkRepository
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns> /// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Updated>> ResetStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken) public async Task<Result<Updated>> ResetStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken)
{ {
// The artwork table is shared by all the music library item types, so the owners of the artwork of this library are collected per type. // The artwork table is shared by all the music library item types, so the owner of a piece of artwork is matched by its type against the
List<Guid> artistIds = await _luminaDbContext.Artists // corresponding table, and the database resolves the membership of the owner in the library by a correlated subquery. Collecting the ids
.Where(artist => artist.LibraryId == libraryId) // of every artist, album and track of the library in memory first would make the cost of the operation grow with the size of the library.
.Select(artist => artist.Id)
.ToListAsync(cancellationToken).ConfigureAwait(false);
List<Guid> albumIds = await _luminaDbContext.Albums
.Where(album => album.LibraryId == libraryId)
.Select(album => album.Id)
.ToListAsync(cancellationToken).ConfigureAwait(false);
List<Guid> trackIds = await _luminaDbContext.Tracks
.Where(track => track.LibraryId == libraryId)
.Select(track => track.Id)
.ToListAsync(cancellationToken).ConfigureAwait(false);
await _luminaDbContext.MusicArtwork await _luminaDbContext.MusicArtwork
.Where(musicArtwork => (musicArtwork.OwnerType == MusicArtworkOwnerType.Artist && artistIds.Contains(musicArtwork.OwnerId)) .Where(musicArtwork => (musicArtwork.OwnerType == MusicArtworkOwnerType.Artist
|| (musicArtwork.OwnerType == MusicArtworkOwnerType.Album && albumIds.Contains(musicArtwork.OwnerId)) && _luminaDbContext.Artists.Any(artist => artist.Id == musicArtwork.OwnerId && artist.LibraryId == libraryId))
|| (musicArtwork.OwnerType == MusicArtworkOwnerType.Track && trackIds.Contains(musicArtwork.OwnerId))) || (musicArtwork.OwnerType == MusicArtworkOwnerType.Album
&& _luminaDbContext.Albums.Any(album => album.Id == musicArtwork.OwnerId && album.LibraryId == libraryId))
|| (musicArtwork.OwnerType == MusicArtworkOwnerType.Track
&& _luminaDbContext.Tracks.Any(track => track.Id == musicArtwork.OwnerId && track.LibraryId == libraryId)))
.ExecuteUpdateAsync(setters => setters.SetProperty(musicArtwork => musicArtwork.Status, ArtworkStatus.Pending), cancellationToken).ConfigureAwait(false); .ExecuteUpdateAsync(setters => setters.SetProperty(musicArtwork => musicArtwork.Status, ArtworkStatus.Pending), cancellationToken).ConfigureAwait(false);
return Result.Updated; return Result.Updated;
} }
/// <summary>
/// Deletes all the pieces of artwork owned by the artists, albums and tracks of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artwork is deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken)
{
// The artwork table is shared by all the music library item types, so the owner of a piece of artwork is matched by its type against the
// corresponding table, and the database resolves the membership of the owner in the library by a correlated subquery. Collecting the ids
// of every artist, album and track of the library in memory first would make the cost of the operation grow with the size of the library.
await _luminaDbContext.MusicArtwork
.Where(musicArtwork => (musicArtwork.OwnerType == MusicArtworkOwnerType.Artist
&& _luminaDbContext.Artists.Any(artist => artist.Id == musicArtwork.OwnerId && artist.LibraryId == libraryId))
|| (musicArtwork.OwnerType == MusicArtworkOwnerType.Album
&& _luminaDbContext.Albums.Any(album => album.Id == musicArtwork.OwnerId && album.LibraryId == libraryId))
|| (musicArtwork.OwnerType == MusicArtworkOwnerType.Track
&& _luminaDbContext.Tracks.Any(track => track.Id == musicArtwork.OwnerId && track.LibraryId == libraryId)))
.ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false);
return Result.Deleted;
}
/// <summary>
/// Stores the cover image of the music library item of the provided <paramref name="ownerType"/> identified by <paramref name="ownerId"/>.
/// </summary>
/// <param name="ownerType">The type of the music library item that owns the artwork.</param>
/// <param name="ownerId">The Id of the music library item that owns the artwork.</param>
/// <param name="fileName">The relative file name of the stored cover image.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Updated>> UpsertCoverAsync(MusicArtworkOwnerType ownerType, Guid ownerId, string fileName, CancellationToken cancellationToken)
{
// The existing cover is matched the same way the callers that resolve it do, by owner and artwork type only, so that a cover stored
// with an ordinal other than zero is replaced in place instead of a second cover row being inserted next to it.
MusicArtworkEntity? existingCover = await _luminaDbContext.MusicArtwork
.FirstOrDefaultAsync(musicArtwork => musicArtwork.OwnerType == ownerType
&& musicArtwork.OwnerId == ownerId
&& musicArtwork.ArtworkType == ArtworkType.Cover, cancellationToken).ConfigureAwait(false);
DateTime now = DateTime.UtcNow;
if (existingCover is null)
{
_luminaDbContext.MusicArtwork.Add(new MusicArtworkEntity
{
Id = Guid.NewGuid(),
OwnerType = ownerType,
OwnerId = ownerId,
ArtworkType = ArtworkType.Cover,
Ordinal = 0,
FileName = fileName,
Status = ArtworkStatus.Enriched,
CreatedOnUtc = now,
CreatedBy = Guid.Empty,
// The audit columns are owned by the auditing interceptor, which stamps only the rows that actually changed, so they are never mapped here.
UpdatedOnUtc = null,
UpdatedBy = null
});
}
else
{
existingCover.FileName = fileName;
existingCover.Status = ArtworkStatus.Enriched;
existingCover.LastUpdateUtc = now;
}
return Result.Updated;
}
} }
@@ -71,4 +71,18 @@ internal sealed class MusicLibraryScanItemMetadataRepository : IMusicLibraryScan
.ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false); .ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false);
return Result.Deleted; return Result.Deleted;
} }
/// <summary>
/// Deletes all the staged music metadata items of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose staged music metadata is deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken)
{
await _luminaDbContext.MusicLibraryScanItemMetadata
.Where(musicMetadata => musicMetadata.LibraryId == libraryId)
.ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false);
return Result.Deleted;
}
} }
@@ -0,0 +1,127 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.Specifications;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq.Expressions;
using System.Reflection;
#endregion
namespace Lumina.DataAccess.Core.Repositories.MusicLibrary.Specifications;
/// <summary>
/// Represents a filter specification for filtering artists by the alpha key of their name, for the alpha picker.
/// The alpha key is the first character of the name, lowercased, and optionally computed after ignoring a leading "The " prefix.
/// </summary>
internal sealed class ArtistAlphaFilterSpecification : FilterSpecification<ArtistEntity>
{
private static readonly MethodInfo s_toLowerMethod = typeof(string).GetMethod(nameof(string.ToLower), Type.EmptyTypes)!;
private static readonly MethodInfo s_startsWithMethod = typeof(string).GetMethod(nameof(string.StartsWith), [typeof(string)])!;
private static readonly MethodInfo s_substringMethod = typeof(string).GetMethod(nameof(string.Substring), [typeof(int)])!;
private static readonly MethodInfo s_globMethod = typeof(SqliteDbFunctionsExtensions)
.GetMethod(nameof(SqliteDbFunctionsExtensions.Glob), [typeof(DbFunctions), typeof(string), typeof(string)])!;
private readonly string? _filterAlphaKey;
private readonly bool _shouldIgnoreThePrefixForAlphaPicker;
/// <summary>
/// Initializes a new instance of the <see cref="ArtistAlphaFilterSpecification"/> class.
/// </summary>
/// <param name="filterAlphaKey">The alpha key to filter by. A single ASCII letter, <see cref="LibraryItemAlphaKeys.NUMBER"/>, or <see cref="LibraryItemAlphaKeys.SYMBOL"/>.</param>
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Whether the leading "The " prefix of a name should be ignored when computing the alpha key, or not.</param>
public ArtistAlphaFilterSpecification(string? filterAlphaKey, bool shouldIgnoreThePrefixForAlphaPicker)
{
_filterAlphaKey = filterAlphaKey;
_shouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker;
}
/// <summary>
/// Creates a LINQ expression that represents the predicate defined by the current specification.
/// </summary>
/// <returns>An expression tree that can be used to evaluate whether an <see cref="ArtistEntity"/> satisfies the specification criteria.</returns>
public override Expression<Func<ArtistEntity, bool>> ToExpression()
{
// When no alpha key was requested, every artist matches.
if (_filterAlphaKey is null)
return artist => true;
ParameterExpression artist = Expression.Parameter(typeof(ArtistEntity), "artist");
Expression effectiveName = BuildEffectiveName(artist);
if (_filterAlphaKey == LibraryItemAlphaKeys.NUMBER)
return BuildGlobPredicate(artist, effectiveName, "[0-9]*");
if (_filterAlphaKey == LibraryItemAlphaKeys.SYMBOL)
return BuildSymbolPredicate(artist, effectiveName);
// The alpha key is a single ASCII letter.
string globPattern = char.ToLowerInvariant(_filterAlphaKey[0]) + "*";
return BuildGlobPredicate(artist, effectiveName, globPattern);
}
/// <summary>
/// Builds the expression representing the lowercased name used to derive the alpha key, falling back to an empty string
/// when the name is <see langword="null"/> or empty, and optionally stripped of a leading "the " prefix.
/// </summary>
/// <param name="artist">The parameter representing the artist entity.</param>
/// <returns>The expression of the effective name.</returns>
private Expression BuildEffectiveName(ParameterExpression artist)
{
Expression nameProperty = Expression.Property(artist, nameof(ArtistEntity.Name));
// The raw name is the name, unless it is null, in which case an empty string is used.
Expression rawName = Expression.Coalesce(nameProperty, Expression.Constant(string.Empty));
MethodCallExpression lowerName = Expression.Call(rawName, s_toLowerMethod);
// When ignoring the "The " prefix, a leading "the " is stripped from the lowercased name.
Expression effectiveName = lowerName;
if (_shouldIgnoreThePrefixForAlphaPicker)
{
MethodCallExpression startsWithThe = Expression.Call(lowerName, s_startsWithMethod, Expression.Constant("the "));
MethodCallExpression strippedName = Expression.Call(lowerName, s_substringMethod, Expression.Constant(4));
effectiveName = Expression.Condition(startsWithThe, strippedName, lowerName);
}
return effectiveName;
}
/// <summary>
/// Builds a predicate that is satisfied when the effective name starts with a glob pattern.
/// </summary>
/// <param name="artist">The parameter representing the artist entity.</param>
/// <param name="effectiveName">The expression of the effective name.</param>
/// <param name="globPattern">The glob pattern the effective name must match.</param>
/// <returns>The built predicate.</returns>
private static Expression<Func<ArtistEntity, bool>> BuildGlobPredicate(ParameterExpression artist, Expression effectiveName, string globPattern)
{
MethodCallExpression glob = BuildGlobCall(effectiveName, globPattern);
return Expression.Lambda<Func<ArtistEntity, bool>>(glob, artist);
}
/// <summary>
/// Builds a predicate that is satisfied when the first character of the effective name is neither a letter nor a digit.
/// </summary>
/// <param name="artist">The parameter representing the artist entity.</param>
/// <param name="effectiveName">The expression of the effective name.</param>
/// <returns>The built predicate.</returns>
private static Expression<Func<ArtistEntity, bool>> BuildSymbolPredicate(ParameterExpression artist, Expression effectiveName)
{
Expression notLetter = Expression.Not(BuildGlobCall(effectiveName, "[a-z]*"));
Expression notDigit = Expression.Not(BuildGlobCall(effectiveName, "[0-9]*"));
return Expression.Lambda<Func<ArtistEntity, bool>>(Expression.AndAlso(notLetter, notDigit), artist);
}
/// <summary>
/// Builds the call to <see cref="SqliteDbFunctionsExtensions.Glob"/> for the effective name and the provided glob pattern.
/// </summary>
/// <param name="effectiveName">The expression of the effective name.</param>
/// <param name="globPattern">The glob pattern the effective name must match.</param>
/// <returns>The built method call.</returns>
private static MethodCallExpression BuildGlobCall(Expression effectiveName, string globPattern)
{
Expression functions = Expression.Property(null, typeof(EF), nameof(EF.Functions));
return Expression.Call(s_globMethod, functions, effectiveName, Expression.Constant(globPattern));
}
}
@@ -242,7 +242,7 @@ internal sealed class TrackRepository : ITrackRepository
.Include(track => track.Contributors) .Include(track => track.Contributors)
.AsSplitQuery() .AsSplitQuery()
.Where(track => track.AlbumId == albumId) .Where(track => track.AlbumId == albumId)
.OrderBy(track => track.DiscNumber) .OrderBy(track => track.DiscNumber ?? 1) // some releases don't have a disc number, assume 1
.ThenBy(track => track.TrackNumber) .ThenBy(track => track.TrackNumber)
.ThenBy(track => track.Id) .ThenBy(track => track.Id)
.ToListAsync(cancellationToken).ConfigureAwait(false); .ToListAsync(cancellationToken).ConfigureAwait(false);
@@ -262,7 +262,7 @@ internal sealed class TrackRepository : ITrackRepository
IQueryable<TrackLiteRow> liteRowsQuery = _luminaDbContext.Tracks IQueryable<TrackLiteRow> liteRowsQuery = _luminaDbContext.Tracks
.AsNoTracking() .AsNoTracking()
.Where(track => track.AlbumId == albumId) .Where(track => track.AlbumId == albumId)
.OrderBy(track => track.DiscNumber) .OrderBy(track => track.DiscNumber ?? 1) // some releases don't have a disc number, assume 1
.ThenBy(track => track.TrackNumber) .ThenBy(track => track.TrackNumber)
.ThenBy(track => track.Id) .ThenBy(track => track.Id)
.Select(track => new TrackLiteRow .Select(track => new TrackLiteRow
@@ -270,7 +270,8 @@ internal sealed class TrackRepository : ITrackRepository
Id = track.Id, Id = track.Id,
Title = track.Title, Title = track.Title,
TrackNumber = track.TrackNumber, TrackNumber = track.TrackNumber,
DiscNumber = track.DiscNumber DiscNumber = track.DiscNumber,
DurationInSeconds = track.DurationInSeconds
}); });
if (paginationData is null) if (paginationData is null)
@@ -65,5 +65,6 @@ public static partial class Errors
public static Error IsniValueCannotBeEmpty => Error.Validation(description: nameof(IsniValueCannotBeEmpty)); public static Error IsniValueCannotBeEmpty => Error.Validation(description: nameof(IsniValueCannotBeEmpty));
public static Error IsniValueMustBeMaximum20CharactersLong => Error.Validation(description: nameof(IsniValueMustBeMaximum20CharactersLong)); public static Error IsniValueMustBeMaximum20CharactersLong => Error.Validation(description: nameof(IsniValueMustBeMaximum20CharactersLong));
public static Error WorkTitleCannotBeEmpty => Error.Validation(description: nameof(WorkTitleCannotBeEmpty)); public static Error WorkTitleCannotBeEmpty => Error.Validation(description: nameof(WorkTitleCannotBeEmpty));
public static Error CoverCannotBeNull => Error.Validation(description: nameof(CoverCannotBeNull));
} }
} }
@@ -644,6 +644,7 @@ public sealed class Artist : AggregateRoot<ArtistId>
/// <param name="track">The track to update.</param> /// <param name="track">The track to update.</param>
/// <param name="path">The file system path of the track.</param> /// <param name="path">The file system path of the track.</param>
/// <param name="metadata">The audio metadata of the track.</param> /// <param name="metadata">The audio metadata of the track.</param>
/// <param name="disambiguation">The optional disambiguation comment of the track.</param>
/// <param name="trackNumber">The number of the track on its disc.</param> /// <param name="trackNumber">The number of the track on its disc.</param>
/// <param name="discNumber">The optional number of the disc the track belongs to.</param> /// <param name="discNumber">The optional number of the disc the track belongs to.</param>
/// <param name="script">The optional script used by the language of the track.</param> /// <param name="script">The optional script used by the language of the track.</param>
@@ -663,6 +664,7 @@ public sealed class Artist : AggregateRoot<ArtistId>
Track track, Track track,
string path, string path,
AudioMetadata metadata, AudioMetadata metadata,
Optional<string> disambiguation,
int trackNumber, int trackNumber,
Optional<int> discNumber, Optional<int> discNumber,
Optional<string> script, Optional<string> script,
@@ -686,6 +688,7 @@ public sealed class Artist : AggregateRoot<ArtistId>
track.UpdateDetails( track.UpdateDetails(
path, path,
metadata, metadata,
disambiguation,
trackNumber, trackNumber,
discNumber, discNumber,
script, script,
@@ -347,6 +347,7 @@ public sealed class Track : Entity<TrackId>
/// </summary> /// </summary>
/// <param name="path">The file system path of the track.</param> /// <param name="path">The file system path of the track.</param>
/// <param name="metadata">The audio metadata of the track.</param> /// <param name="metadata">The audio metadata of the track.</param>
/// <param name="disambiguation">The optional disambiguation comment of the track.</param>
/// <param name="trackNumber">The number of the track on its disc.</param> /// <param name="trackNumber">The number of the track on its disc.</param>
/// <param name="discNumber">The optional number of the disc the track belongs to.</param> /// <param name="discNumber">The optional number of the disc the track belongs to.</param>
/// <param name="script">The optional script used by the language of the track.</param> /// <param name="script">The optional script used by the language of the track.</param>
@@ -360,6 +361,7 @@ public sealed class Track : Entity<TrackId>
internal Result<Updated> UpdateDetails( internal Result<Updated> UpdateDetails(
string path, string path,
AudioMetadata metadata, AudioMetadata metadata,
Optional<string> disambiguation,
int trackNumber, int trackNumber,
Optional<int> discNumber, Optional<int> discNumber,
Optional<string> script, Optional<string> script,
@@ -372,6 +374,7 @@ public sealed class Track : Entity<TrackId>
{ {
Path = path; Path = path;
Metadata = metadata; Metadata = metadata;
Disambiguation = disambiguation;
TrackNumber = trackNumber; TrackNumber = trackNumber;
DiscNumber = discNumber; DiscNumber = discNumber;
Script = script; Script = script;
@@ -58,10 +58,10 @@ internal sealed class MusicArtworkService : IMusicArtworkService
/// <param name="artistName">The name of the artist of the album.</param> /// <param name="artistName">The name of the artist of the album.</param>
/// <param name="albumTitle">The title of the album.</param> /// <param name="albumTitle">The title of the album.</param>
/// <param name="artwork">The artwork to store.</param> /// <param name="artwork">The artwork to store.</param>
/// <param name="releaseTypeName">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 <see langword="null"/>, no release type segment is added.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <param name="releaseTypeName">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.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns> /// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
public async Task<Result<string>> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, ArtworkDto artwork, CancellationToken cancellationToken, string? releaseTypeName = null) public async Task<Result<string>> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, ArtworkDto artwork, string? releaseTypeName, CancellationToken cancellationToken)
{ {
Result<string> artworkDirectoryPathResult = BuildAlbumArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle, releaseTypeName); Result<string> artworkDirectoryPathResult = BuildAlbumArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle, releaseTypeName);
if (artworkDirectoryPathResult.IsFailure) if (artworkDirectoryPathResult.IsFailure)
@@ -86,6 +86,106 @@ internal sealed class MusicArtworkService : IMusicArtworkService
return await SaveArtworkAsync(artworkDirectoryPathResult.Value, artwork, cancellationToken).ConfigureAwait(false); return await SaveArtworkAsync(artworkDirectoryPathResult.Value, artwork, cancellationToken).ConfigureAwait(false);
} }
/// <summary>
/// Stores the uploaded <paramref name="artwork"/> of the album into the internal media directory, and returns the relative path of the stored artwork.
/// </summary>
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
/// <param name="albumId">The Id of the album.</param>
/// <param name="libraryName">The name of the media library the album belongs to.</param>
/// <param name="artistName">The name of the artist of the album.</param>
/// <param name="albumTitle">The title of the album.</param>
/// <param name="artwork">The stream of the uploaded artwork to store.</param>
/// <param name="fileName">The name of the uploaded artwork file.</param>
/// <param name="releaseTypeName">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 <see langword="null"/>, no release type segment is added.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
public async Task<Result<string>> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, Stream artwork, string fileName, string? releaseTypeName, CancellationToken cancellationToken)
{
// The uploaded bytes are persisted to a temporary file first, so that the storage pipeline can treat the upload like any other local artwork source and clean it up afterwards.
string temporaryPath = BuildTemporaryUploadPath(fileName);
try
{
await WriteUploadedArtworkAsync(artwork, temporaryPath, cancellationToken).ConfigureAwait(false);
return await SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, new ArtworkDto(ArtworkType.Cover, 0, temporaryPath, null, IsTemporary: true), releaseTypeName, cancellationToken).ConfigureAwait(false);
}
finally
{
DeleteTemporaryFile(temporaryPath);
}
}
/// <summary>
/// Stores the uploaded <paramref name="artwork"/> of the artist into the internal media directory, and returns the relative path of the stored artwork.
/// </summary>
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <param name="libraryName">The name of the media library the artist belongs to.</param>
/// <param name="artistName">The name of the artist.</param>
/// <param name="artwork">The stream of the uploaded artwork to store.</param>
/// <param name="fileName">The name of the uploaded artwork file.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
public async Task<Result<string>> SaveArtistArtworkAsync(Guid libraryId, string libraryName, string artistName, Stream artwork, string fileName, CancellationToken cancellationToken)
{
// The uploaded bytes are persisted to a temporary file first, so that the storage pipeline can treat the upload like any other local artwork source and clean it up afterwards.
string temporaryPath = BuildTemporaryUploadPath(fileName);
try
{
await WriteUploadedArtworkAsync(artwork, temporaryPath, cancellationToken).ConfigureAwait(false);
return await SaveArtistArtworkAsync(libraryId, libraryName, artistName, new ArtworkDto(ArtworkType.Cover, 0, temporaryPath, null, IsTemporary: true), cancellationToken).ConfigureAwait(false);
}
finally
{
DeleteTemporaryFile(temporaryPath);
}
}
/// <summary>
/// Builds the path of the temporary file an uploaded artwork is buffered into, keeping the extension of the uploaded file so that its content can be probed by name.
/// </summary>
/// <param name="fileName">The name of the uploaded artwork file.</param>
/// <returns>The file system path of the temporary file.</returns>
private static string BuildTemporaryUploadPath(string fileName)
{
string extension = Path.GetExtension(fileName);
if (string.IsNullOrWhiteSpace(extension))
extension = ".img";
return Path.Combine(Path.GetTempPath(), $"lumina-upload-{Guid.NewGuid():N}{extension}");
}
/// <summary>
/// Copies the uploaded <paramref name="artwork"/> stream into the temporary file at <paramref name="temporaryPath"/>.
/// </summary>
/// <param name="artwork">The stream of the uploaded artwork.</param>
/// <param name="temporaryPath">The file system path of the temporary file.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private static async Task WriteUploadedArtworkAsync(Stream artwork, string temporaryPath, CancellationToken cancellationToken)
{
await using FileStream fileStream = new(temporaryPath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 81920, useAsync: true);
await artwork.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes the temporary file at <paramref name="temporaryPath"/>, ignoring the failures that must not mask the result of the operation.
/// </summary>
/// <param name="temporaryPath">The file system path of the temporary file.</param>
private static void DeleteTemporaryFile(string temporaryPath)
{
if (!File.Exists(temporaryPath))
return;
try
{
File.Delete(temporaryPath);
}
catch (IOException)
{
// A failed cleanup of the temporary file must not mask the result of the operation.
}
catch (UnauthorizedAccessException)
{
// A failed cleanup of the temporary file must not mask the result of the operation.
}
}
/// <summary> /// <summary>
/// Resolves the local source of the <paramref name="artwork"/>, stores it into <paramref name="artworkDirectoryPath"/>, and cleans up the temporary download of a remote artwork. /// Resolves the local source of the <paramref name="artwork"/>, stores it into <paramref name="artworkDirectoryPath"/>, and cleans up the temporary download of a remote artwork.
/// </summary> /// </summary>
@@ -159,6 +259,32 @@ internal sealed class MusicArtworkService : IMusicArtworkService
return DeleteArtworkInDirectory(artworkDirectoryPathResult.Value); return DeleteArtworkInDirectory(artworkDirectoryPathResult.Value);
} }
/// <summary>
/// Deletes the stored artwork file at <paramref name="artworkRelativePath"/> from the internal media directory, when it still exists.
/// </summary>
/// <param name="artworkRelativePath">The relative path of the stored artwork file.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public Result<Deleted> DeleteStoredArtwork(string artworkRelativePath)
{
if (string.IsNullOrWhiteSpace(artworkRelativePath))
return Result.Deleted;
// The stored path is relative to the application's base directory, so it is rooted back to the absolute path of the file to delete.
string absolutePath = Path.Combine(AppContext.BaseDirectory, artworkRelativePath.TrimStart(_pathService.PathSeparator));
Result<FileSystemPathId> filePathIdResult = FileSystemPathId.Create(absolutePath);
if (filePathIdResult.IsFailure)
return filePathIdResult.Errors;
Result<bool> fileExistsResult = _environmentContext.FileProviderService.FileExists(filePathIdResult.Value);
if (fileExistsResult.IsFailure)
return fileExistsResult.Errors;
if (!fileExistsResult.Value)
return Result.Deleted;
_environmentContext.FileProviderService.DeleteFile(filePathIdResult.Value);
return Result.Deleted;
}
/// <summary> /// <summary>
/// Deletes the files directly contained in <paramref name="artworkDirectoryPath"/>, leaving the subdirectories, such as the album directories of an artist, untouched. /// Deletes the files directly contained in <paramref name="artworkDirectoryPath"/>, leaving the subdirectories, such as the album directories of an artist, untouched.
/// </summary> /// </summary>
@@ -52,12 +52,14 @@ internal sealed class MusicLibraryPathStructure
/// <summary> /// <summary>
/// Gets the name of the on-disk release type directory of the track stored at <paramref name="trackPath"/>, when the structure of the library /// Gets the name of the on-disk release type directory of the track stored at <paramref name="trackPath"/>, when the structure of the library
/// uses one. The directory is the parent of the album directory, and it is only used when its name is a known release type, so that the artist /// uses one. The directory is the parent of the album directory, and it is only used when its name is a known release type and it is not the
/// directory of a flat library is not mistaken for a release type. /// directory of <paramref name="artistName"/>, because the parent of the album directory of a library that has no release type directory is
/// the artist directory, which must not be mistaken for a release type.
/// </summary> /// </summary>
/// <param name="trackPath">The file system path of the track whose release type directory is retrieved.</param> /// <param name="trackPath">The file system path of the track whose release type directory is retrieved.</param>
/// <param name="artistName">The name of the artist of the track, or <see langword="null"/> when it is not known.</param>
/// <returns>The name of the on-disk release type directory, or <see langword="null"/> when the library does not use one.</returns> /// <returns>The name of the on-disk release type directory, or <see langword="null"/> when the library does not use one.</returns>
public string? GetReleaseTypeDirectoryName(string trackPath) public string? GetReleaseTypeDirectoryName(string trackPath, string? artistName = null)
{ {
string albumDirectory = GetAlbumDirectory(trackPath); string albumDirectory = GetAlbumDirectory(trackPath);
string? releaseTypeDirectory = GetParentDirectoryPath(albumDirectory); string? releaseTypeDirectory = GetParentDirectoryPath(albumDirectory);
@@ -65,7 +67,16 @@ internal sealed class MusicLibraryPathStructure
return null; return null;
string releaseTypeName = GetLastSegment(releaseTypeDirectory); string releaseTypeName = GetLastSegment(releaseTypeDirectory);
return Enum.TryParse(releaseTypeName, ignoreCase: true, out MusicReleaseType _) ? releaseTypeName : null; // A numeric directory name parses to an enumeration member that is not defined, so it is rejected explicitly, together with any other
// name that is not a known release type.
if (!Enum.TryParse(releaseTypeName, ignoreCase: true, out MusicReleaseType releaseType) || !Enum.IsDefined(releaseType))
return null;
// The artist directory of a library that has no release type directory is the parent of the album directory, so it is not a release type.
if (!string.IsNullOrWhiteSpace(artistName) && string.Equals(releaseTypeName, artistName, StringComparison.OrdinalIgnoreCase))
return null;
return releaseTypeName;
} }
/// <summary> /// <summary>
@@ -370,7 +370,7 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
// The release type directory groups the artwork of the releases of the artist that share a title, so the album, the single and the live release of the same songs do not collide. // The release type directory groups the artwork of the releases of the artist that share a title, so the album, the single and the live release of the same songs do not collide.
// It is read from the file system, because the structure on disk is the source of truth of the release type of an album. // It is read from the file system, because the structure on disk is the source of truth of the release type of an album.
string? releaseTypeName = _musicLibraryPathStructure.GetReleaseTypeDirectoryName(firstTrackPath); string? releaseTypeName = _musicLibraryPathStructure.GetReleaseTypeDirectoryName(firstTrackPath, albumEntity.Artist?.Name);
return await EnrichArtworkAsync( return await EnrichArtworkAsync(
artworkLookup, artworkLookup,
@@ -381,7 +381,7 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
musicArtworkService, musicArtworkService,
fileHashService, fileHashService,
() => musicArtworkService!.DeleteAlbumArtwork(albumEntity.LibraryId, albumEntity.Id, libraryName, artistName, albumEntity.Title, releaseTypeName), () => musicArtworkService!.DeleteAlbumArtwork(albumEntity.LibraryId, albumEntity.Id, libraryName, artistName, albumEntity.Title, releaseTypeName),
(artwork, token) => musicArtworkService!.SaveAlbumArtworkAsync(albumEntity.LibraryId, albumEntity.Id, libraryName, artistName, albumEntity.Title, artwork, token, releaseTypeName), (artwork, token) => musicArtworkService!.SaveAlbumArtworkAsync(albumEntity.LibraryId, albumEntity.Id, libraryName, artistName, albumEntity.Title, artwork, releaseTypeName, token),
shouldAggregateArtworkWhenMissing, shouldAggregateArtworkWhenMissing,
unitOfWork, unitOfWork,
cancellationToken).ConfigureAwait(false); cancellationToken).ConfigureAwait(false);
@@ -53,9 +53,17 @@ internal static class ThemeSynchronizer
ThemeEntity? existingTheme = themes.Where(theme => theme.ThemeId == manifestResult.Value.Id).FirstOrDefault(); ThemeEntity? existingTheme = themes.Where(theme => theme.ThemeId == manifestResult.Value.Id).FirstOrDefault();
// A theme that was soft deleted by the user must not be reinstalled automatically; an installed bundled theme // A theme that was soft deleted by the user must not be reinstalled automatically, and a theme installed from
// whose files are present is already in sync, so only a bundled theme whose files went missing gets its files reinstalled. // another source (like an uploaded pack) is never replaced by a bundled archive.
if (existingTheme is not null && (existingTheme.IsDeleted || existingTheme.InstallSource != ThemeInstallSource.Bundled || themeService.HasThemePack(existingTheme.ThemeId))) if (existingTheme is not null && (existingTheme.IsDeleted || existingTheme.InstallSource != ThemeInstallSource.Bundled))
continue;
// A bundled theme that is already installed is reinstalled when its files went missing, or when the shipped
// archive carries a new version, so that content updates of the bundled themes reach the installed packs.
bool isBundledThemeOutOfDate = existingTheme is not null
&& (!themeService.HasThemePack(existingTheme.ThemeId)
|| !string.Equals(existingTheme.Version, manifestResult.Value.Version, StringComparison.Ordinal));
if (existingTheme is not null && !isBundledThemeOutOfDate)
continue; continue;
// Installing a bundled theme at startup is best effort: a file system failure here must never crash the host, because the default // Installing a bundled theme at startup is best effort: a file system failure here must never crash the host, because the default
@@ -70,9 +78,20 @@ internal static class ThemeSynchronizer
continue; continue;
} }
// A known theme only gets its missing files reinstalled, so no new row is inserted. // A known theme is refreshed in place, so its row is updated with the shipped version instead of a new row being inserted.
if (existingTheme is not null) if (existingTheme is not null)
{
if (!string.Equals(existingTheme.Version, manifestResult.Value.Version, StringComparison.Ordinal))
{
existingTheme.Version = manifestResult.Value.Version;
existingTheme.UpdatedOnUtc = DateTime.UtcNow;
existingTheme.UpdatedBy = default;
Result<Updated> updateResult = await unitOfWork.ThemeRepository.UpdateAsync(existingTheme, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure)
logger.LogWarning("Failed to update the version of theme '{ThemeId}': {Error}", existingTheme.ThemeId, updateResult.FirstError.Description);
}
continue; continue;
}
ThemeEntity themeEntity = new() ThemeEntity themeEntity = new()
{ {
@@ -107,7 +126,7 @@ internal static class ThemeSynchronizer
} }
await CleanUpMissingThemePacksAsync(themeService, unitOfWork, themes, logger, cancellationToken).ConfigureAwait(false); await CleanUpMissingThemePacksAsync(themeService, unitOfWork, themes, logger, cancellationToken).ConfigureAwait(false);
await EnsureCurrentThemeExistsAsync(themeService, unitOfWork, themes, cancellationToken).ConfigureAwait(false); await EnsureCurrentThemeExistsAsync(themeService, unitOfWork, themes, logger, cancellationToken).ConfigureAwait(false);
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure) if (saveChangesResult.IsFailure)
@@ -189,8 +208,9 @@ internal static class ThemeSynchronizer
/// <param name="themeService">Injected service for the server-side storage and serving of theme packs.</param> /// <param name="themeService">Injected service for the server-side storage and serving of theme packs.</param>
/// <param name="unitOfWork">The unit of work for interacting with the theme repository.</param> /// <param name="unitOfWork">The unit of work for interacting with the theme repository.</param>
/// <param name="themes">The installed themes read from the storage medium.</param> /// <param name="themes">The installed themes read from the storage medium.</param>
/// <param name="logger">Injected logger used for logging.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private static async Task EnsureCurrentThemeExistsAsync(IThemeService themeService, IUnitOfWork unitOfWork, IReadOnlyList<ThemeEntity> themes, CancellationToken cancellationToken) private static async Task EnsureCurrentThemeExistsAsync(IThemeService themeService, IUnitOfWork unitOfWork, IReadOnlyList<ThemeEntity> themes, ILogger logger, CancellationToken cancellationToken)
{ {
if (themes.Any(theme => !theme.IsDeleted && theme.IsCurrent == true)) if (themes.Any(theme => !theme.IsDeleted && theme.IsCurrent == true))
return; return;
@@ -209,6 +229,8 @@ internal static class ThemeSynchronizer
defaultTheme.IsCurrent = true; defaultTheme.IsCurrent = true;
defaultTheme.UpdatedOnUtc = DateTime.UtcNow; defaultTheme.UpdatedOnUtc = DateTime.UtcNow;
defaultTheme.UpdatedBy = default; defaultTheme.UpdatedBy = default;
await unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken).ConfigureAwait(false); Result<Updated> updateResult = await unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure)
logger.LogWarning("Failed to activate theme '{ThemeId}': {Error}", defaultTheme.ThemeId, updateResult.FirstError.Description);
} }
} }
@@ -15,6 +15,7 @@ public static partial class ApiRoutes
public const string ADD_ALBUM = "/libraries/{libraryId}/artists/{artistId}/albums"; public const string ADD_ALBUM = "/libraries/{libraryId}/artists/{artistId}/albums";
public const string GET_ALBUM_BY_ID = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}"; public const string GET_ALBUM_BY_ID = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}";
public const string UPDATE_ALBUM = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}"; public const string UPDATE_ALBUM = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}";
public const string UPDATE_ALBUM_COVER = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover";
public const string DELETE_ALBUM = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}"; public const string DELETE_ALBUM = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}";
public const string GET_ALBUM_TRACKS = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks"; public const string GET_ALBUM_TRACKS = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks";
public const string GET_ALBUM_TRACKS_LITE = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite"; public const string GET_ALBUM_TRACKS_LITE = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite";
@@ -15,6 +15,7 @@ public static partial class ApiRoutes
public const string GET_ARTISTS_LITE = "/libraries/{libraryId}/artists/lite"; public const string GET_ARTISTS_LITE = "/libraries/{libraryId}/artists/lite";
public const string ADD_ARTIST = "/libraries/{libraryId}/artists"; public const string ADD_ARTIST = "/libraries/{libraryId}/artists";
public const string UPDATE_ARTIST = "/libraries/{libraryId}/artists/{artistId}"; public const string UPDATE_ARTIST = "/libraries/{libraryId}/artists/{artistId}";
public const string UPDATE_ARTIST_COVER = "/libraries/{libraryId}/artists/{artistId}/cover";
public const string DELETE_ARTIST = "/libraries/{libraryId}/artists/{artistId}"; public const string DELETE_ARTIST = "/libraries/{libraryId}/artists/{artistId}";
} }
} }
@@ -11,6 +11,7 @@ using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common; using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
@@ -372,6 +373,8 @@ public class AddAlbumEndpointSummary : Summary<AddAlbumEndpoint, AddAlbumRequest
ResponseParam<AlbumResponse>(r => r.Metadata!.Genres, "The list of genres associated with the album."); ResponseParam<AlbumResponse>(r => r.Metadata!.Genres, "The list of genres associated with the album.");
ResponseParam<AlbumResponse>(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the album."); ResponseParam<AlbumResponse>(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the album.");
ResponseParam<AlbumResponse>(r => r.Tracks, "The list of tracks of the album."); ResponseParam<AlbumResponse>(r => r.Tracks, "The list of tracks of the album.");
ResponseParam<AlbumResponse>(r => r.CoverPath, "The path of the image representing the album, if available.");
ResponseParam<AlbumResponse>(r => r.Artwork, "The stored artwork of the album, in display order, if applicable.");
Response(201, "The newly created album is returned.", Response(201, "The newly created album is returned.",
example: new AlbumResponse( example: new AlbumResponse(
@@ -636,8 +639,9 @@ public class AddAlbumEndpointSummary : Summary<AddAlbumEndpoint, AddAlbumRequest
CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc), CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc),
UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc) UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc)
) )
] ],
) CoverPath: "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg",
Artwork: [new MediaArtworkDto(ArtworkType.Cover, 0, "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg")])
); );
Response(401, "Authentication required.", "application/problem+json", Response(401, "Authentication required.", "application/problem+json",
@@ -8,6 +8,7 @@ using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common; using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
@@ -64,6 +65,8 @@ public class GetAlbumEndpointSummary : Summary<GetAlbumEndpoint, EmptyRequest>
ResponseParam<AlbumResponse>(r => r.Metadata!.Genres, "The list of genres associated with the album."); ResponseParam<AlbumResponse>(r => r.Metadata!.Genres, "The list of genres associated with the album.");
ResponseParam<AlbumResponse>(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the album."); ResponseParam<AlbumResponse>(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the album.");
ResponseParam<AlbumResponse>(r => r.Tracks, "The list of tracks of the album."); ResponseParam<AlbumResponse>(r => r.Tracks, "The list of tracks of the album.");
ResponseParam<AlbumResponse>(r => r.CoverPath, "The path of the image representing the album, if available.");
ResponseParam<AlbumResponse>(r => r.Artwork, "The stored artwork of the album, in display order, if applicable.");
Response(200, "The requested album is returned.", Response(200, "The requested album is returned.",
example: new AlbumResponse( example: new AlbumResponse(
@@ -142,8 +145,200 @@ public class GetAlbumEndpointSummary : Summary<GetAlbumEndpoint, EmptyRequest>
], ],
CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc), CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc),
UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc), UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc),
Tracks: [] Tracks:
) [
new(
Id: Guid.NewGuid(),
AlbumId: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
Metadata: new(
Title: "Bohemian Rhapsody",
OriginalTitle: "Bohemian Rhapsody",
Description: "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
Disambiguation: "album version",
ReleaseInfo: new(
OriginalReleaseDate: new DateOnly(1975, 10, 31),
OriginalReleaseYear: 1975,
ReReleaseDate: new DateOnly(2011, 11, 21),
ReReleaseYear: 2011,
ReleaseCountry: ReleaseCountry.GB,
ReleaseVersion: "Original"
),
Language: new(
LanguageCode: "en",
LanguageName: "English",
NativeName: "English"
),
OriginalLanguage: new(
LanguageCode: "en",
LanguageName: "English",
NativeName: "English"
),
Tags: [
new(Name: "classic"),
new(Name: "epic")
],
Genres: [
new(Name: "Rock"),
new(Name: "Progressive Rock")
],
DurationInSeconds: 354,
SampleRate: 44100,
Channels: 2,
BitDepth: 16,
AudioCodec: "FLAC",
Bitrate: 980,
IsVideo: false
),
Script: "Latn",
Key: MusicKey.CMajor,
Bpm: 72,
Work: new MusicWorkDto(
MusicBrainzWorkId: Guid.NewGuid(),
Title: "Bohemian Rhapsody",
Type: "Song",
Languages: [new LanguageInfoDto(LanguageCode: "en", LanguageName: "English", NativeName: "English")],
Iswcs: ["T-010489707-6"]
),
Isrcs: [
new(Value: "GBUM71029604")
],
Moods: [
new(Name: "dramatic"),
new(Name: "anxious")
],
MusicBrainzRecordingId: Guid.NewGuid(),
MusicBrainzTrackId: Guid.NewGuid(),
Contributors: [
new MediaContributorReferenceDto(
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Vocals
),
new MediaContributorReferenceDto(
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Guitar
)
],
Ratings: [
new(
Value: 4.5M,
MaxValue: 5,
Source: AudioRatingSource.MusicBrainz,
VoteCount: 2345
),
new(
Value: 4.8M,
MaxValue: 5,
Source: AudioRatingSource.LastFm,
VoteCount: 1234
)
],
TrackNumber: 1,
DiscNumber: 1,
CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc),
UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc)
),
new(
Id: Guid.NewGuid(),
AlbumId: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac",
Metadata: new(
Title: "You're My Best Friend",
OriginalTitle: "You're My Best Friend",
Description: "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.",
Disambiguation: "album version",
ReleaseInfo: new(
OriginalReleaseDate: new DateOnly(1976, 6, 18),
OriginalReleaseYear: 1976,
ReReleaseDate: new DateOnly(2011, 11, 21),
ReReleaseYear: 2011,
ReleaseCountry: ReleaseCountry.GB,
ReleaseVersion: "Original"
),
Language: new(
LanguageCode: "en",
LanguageName: "English",
NativeName: "English"
),
OriginalLanguage: new(
LanguageCode: "en",
LanguageName: "English",
NativeName: "English"
),
Tags: [
new(Name: "classic"),
new(Name: "love")
],
Genres: [
new(Name: "Rock"),
new(Name: "Pop Rock")
],
DurationInSeconds: 181,
SampleRate: 44100,
Channels: 2,
BitDepth: 16,
AudioCodec: "FLAC",
Bitrate: 912,
IsVideo: false
),
Script: "Latn",
Key: MusicKey.BMajor,
Bpm: 118,
Work: new MusicWorkDto(
MusicBrainzWorkId: Guid.NewGuid(),
Title: "You're My Best Friend",
Type: "Song",
Languages: [new LanguageInfoDto(LanguageCode: "en", LanguageName: "English", NativeName: "English")],
Iswcs: ["T-010489707-6"]
),
Isrcs: [
new(Value: "GBUM71029609")
],
Moods: [
new(Name: "happy"),
new(Name: "warm")
],
MusicBrainzRecordingId: Guid.NewGuid(),
MusicBrainzTrackId: Guid.NewGuid(),
Contributors: [
new MediaContributorReferenceDto(
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Vocals
),
new MediaContributorReferenceDto(
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Guitar
)
],
Ratings: [
new(
Value: 4.2M,
MaxValue: 5,
Source: AudioRatingSource.MusicBrainz,
VoteCount: 1234
),
new(
Value: 4.4M,
MaxValue: 5,
Source: AudioRatingSource.LastFm,
VoteCount: 567
)
],
TrackNumber: 7,
DiscNumber: 1,
CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc),
UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc)
)
],
CoverPath: "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg",
Artwork:
[
new MediaArtworkDto(ArtworkType.Cover, 0, "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg"),
new MediaArtworkDto(ArtworkType.Back, 0, "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/back.jpg"),
new MediaArtworkDto(ArtworkType.Booklet, 0, "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/booklet.jpg")
])
); );
Response(401, "Authentication required.", "application/problem+json", Response(401, "Authentication required.", "application/problem+json",
@@ -36,6 +36,7 @@ public class GetAlbumTracksLiteEndpointSummary : Summary<GetAlbumTracksLiteEndpo
ResponseParam<TrackLiteResponse>(r => r.Title, "The title of the track."); ResponseParam<TrackLiteResponse>(r => r.Title, "The title of the track.");
ResponseParam<TrackLiteResponse>(r => r.TrackNumber, "The number of the track on its disc."); ResponseParam<TrackLiteResponse>(r => r.TrackNumber, "The number of the track on its disc.");
ResponseParam<TrackLiteResponse>(r => r.DiscNumber, "The number of the disc the track belongs to, if applicable."); ResponseParam<TrackLiteResponse>(r => r.DiscNumber, "The number of the disc the track belongs to, if applicable.");
ResponseParam<TrackLiteResponse>(r => r.DurationInSeconds, "The duration of the track in seconds.");
Response(200, "The paginated list of the lightweight read models of the tracks of the album is returned.", Response(200, "The paginated list of the lightweight read models of the tracks of the album is returned.",
example: new PaginatedResponse<TrackLiteResponse> example: new PaginatedResponse<TrackLiteResponse>
@@ -46,13 +47,15 @@ public class GetAlbumTracksLiteEndpointSummary : Summary<GetAlbumTracksLiteEndpo
Id: Guid.NewGuid(), Id: Guid.NewGuid(),
Title: "Bohemian Rhapsody", Title: "Bohemian Rhapsody",
TrackNumber: 1, TrackNumber: 1,
DiscNumber: 1 DiscNumber: 1,
DurationInSeconds: 354
), ),
new TrackLiteResponse( new TrackLiteResponse(
Id: Guid.NewGuid(), Id: Guid.NewGuid(),
Title: "You're My Best Friend", Title: "You're My Best Friend",
TrackNumber: 2, TrackNumber: 2,
DiscNumber: 1 DiscNumber: 1,
DurationInSeconds: 174
) )
], ],
CurrentPage = 1, CurrentPage = 1,
@@ -9,6 +9,7 @@ using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common; using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
@@ -176,6 +177,8 @@ public class UpdateAlbumEndpointSummary : Summary<UpdateAlbumEndpoint, UpdateAlb
ResponseParam<AlbumResponse>(r => r.Metadata!.Genres, "The list of genres associated with the album."); ResponseParam<AlbumResponse>(r => r.Metadata!.Genres, "The list of genres associated with the album.");
ResponseParam<AlbumResponse>(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the album."); ResponseParam<AlbumResponse>(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the album.");
ResponseParam<AlbumResponse>(r => r.Tracks, "The list of tracks of the album."); ResponseParam<AlbumResponse>(r => r.Tracks, "The list of tracks of the album.");
ResponseParam<AlbumResponse>(r => r.CoverPath, "The path of the image representing the album, if available.");
ResponseParam<AlbumResponse>(r => r.Artwork, "The stored artwork of the album, in display order, if applicable.");
Response(200, "The updated album is returned.", Response(200, "The updated album is returned.",
example: new AlbumResponse( example: new AlbumResponse(
@@ -254,8 +257,195 @@ public class UpdateAlbumEndpointSummary : Summary<UpdateAlbumEndpoint, UpdateAlb
], ],
CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc), CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc),
UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc), UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc),
Tracks: [] Tracks:
) [
new(
Id: Guid.NewGuid(),
AlbumId: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
Metadata: new(
Title: "Bohemian Rhapsody",
OriginalTitle: "Bohemian Rhapsody",
Description: "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
Disambiguation: "album version",
ReleaseInfo: new(
OriginalReleaseDate: new DateOnly(1975, 10, 31),
OriginalReleaseYear: 1975,
ReReleaseDate: new DateOnly(2011, 11, 21),
ReReleaseYear: 2011,
ReleaseCountry: ReleaseCountry.GB,
ReleaseVersion: "Original"
),
Language: new(
LanguageCode: "en",
LanguageName: "English",
NativeName: "English"
),
OriginalLanguage: new(
LanguageCode: "en",
LanguageName: "English",
NativeName: "English"
),
Tags: [
new(Name: "classic"),
new(Name: "epic")
],
Genres: [
new(Name: "Rock"),
new(Name: "Progressive Rock")
],
DurationInSeconds: 354,
SampleRate: 44100,
Channels: 2,
BitDepth: 16,
AudioCodec: "FLAC",
Bitrate: 980,
IsVideo: false
),
Script: "Latn",
Key: MusicKey.CMajor,
Bpm: 72,
Work: new MusicWorkDto(
MusicBrainzWorkId: Guid.NewGuid(),
Title: "Bohemian Rhapsody",
Type: "Song",
Languages: [new LanguageInfoDto(LanguageCode: "en", LanguageName: "English", NativeName: "English")],
Iswcs: ["T-010489707-6"]
),
Isrcs: [
new(Value: "GBUM71029604")
],
Moods: [
new(Name: "dramatic"),
new(Name: "anxious")
],
MusicBrainzRecordingId: Guid.NewGuid(),
MusicBrainzTrackId: Guid.NewGuid(),
Contributors: [
new MediaContributorReferenceDto(
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Vocals
),
new MediaContributorReferenceDto(
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Guitar
)
],
Ratings: [
new(
Value: 4.5M,
MaxValue: 5,
Source: AudioRatingSource.MusicBrainz,
VoteCount: 2345
),
new(
Value: 4.8M,
MaxValue: 5,
Source: AudioRatingSource.LastFm,
VoteCount: 1234
)
],
TrackNumber: 1,
DiscNumber: 1,
CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc),
UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc)
),
new(
Id: Guid.NewGuid(),
AlbumId: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac",
Metadata: new(
Title: "You're My Best Friend",
OriginalTitle: "You're My Best Friend",
Description: "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.",
Disambiguation: "album version",
ReleaseInfo: new(
OriginalReleaseDate: new DateOnly(1976, 6, 18),
OriginalReleaseYear: 1976,
ReReleaseDate: new DateOnly(2011, 11, 21),
ReReleaseYear: 2011,
ReleaseCountry: ReleaseCountry.GB,
ReleaseVersion: "Original"
),
Language: new(
LanguageCode: "en",
LanguageName: "English",
NativeName: "English"
),
OriginalLanguage: new(
LanguageCode: "en",
LanguageName: "English",
NativeName: "English"
),
Tags: [
new(Name: "classic"),
new(Name: "love")
],
Genres: [
new(Name: "Rock"),
new(Name: "Pop Rock")
],
DurationInSeconds: 181,
SampleRate: 44100,
Channels: 2,
BitDepth: 16,
AudioCodec: "FLAC",
Bitrate: 912,
IsVideo: false
),
Script: "Latn",
Key: MusicKey.BMajor,
Bpm: 118,
Work: new MusicWorkDto(
MusicBrainzWorkId: Guid.NewGuid(),
Title: "You're My Best Friend",
Type: "Song",
Languages: [new LanguageInfoDto(LanguageCode: "en", LanguageName: "English", NativeName: "English")],
Iswcs: ["T-010489707-6"]
),
Isrcs: [
new(Value: "GBUM71029609")
],
Moods: [
new(Name: "happy"),
new(Name: "warm")
],
MusicBrainzRecordingId: Guid.NewGuid(),
MusicBrainzTrackId: Guid.NewGuid(),
Contributors: [
new MediaContributorReferenceDto(
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Vocals
),
new MediaContributorReferenceDto(
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Guitar
)
],
Ratings: [
new(
Value: 4.2M,
MaxValue: 5,
Source: AudioRatingSource.MusicBrainz,
VoteCount: 1234
),
new(
Value: 4.4M,
MaxValue: 5,
Source: AudioRatingSource.LastFm,
VoteCount: 567
)
],
TrackNumber: 7,
DiscNumber: 1,
CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc),
UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc)
)
],
CoverPath: "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg",
Artwork: [new MediaArtworkDto(ArtworkType.Cover, 0, "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg")])
); );
Response(401, "Authentication required.", "application/problem+json", Response(401, "Authentication required.", "application/problem+json",
@@ -0,0 +1,82 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
/// <summary>
/// API endpoint for the <c>/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover</c> route.
/// </summary>
public class UpdateAlbumCoverEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
{
private readonly ICommandHandler<UpdateAlbumCoverCommand, Result<UpdateAlbumCoverResponse>> _updateAlbumCoverCommandHandler;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateAlbumCoverEndpoint"/> class.
/// </summary>
/// <param name="updateAlbumCoverCommandHandler">Injected service for handling update album cover commands.</param>
public UpdateAlbumCoverEndpoint(ICommandHandler<UpdateAlbumCoverCommand, Result<UpdateAlbumCoverResponse>> updateAlbumCoverCommandHandler)
{
_updateAlbumCoverCommandHandler = updateAlbumCoverCommandHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(FastEndpoints.Http.PUT);
Routes(ApiRoutes.Albums.UPDATE_ALBUM_COVER);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Updates the cover image of the album with the image uploaded in the multipart form of the request.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
{
// Take the identifiers from the route.
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString();
string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString();
IFormFile? cover = null;
if (HttpContext.Request.HasFormContentType)
{
try
{
// The cover is the first file of the multipart form; a multipart body without any file cannot be parsed as a form,
// so a malformed upload is treated as a missing cover, which the command validator reports.
cover = HttpContext.Request.Form.Files.Count > 0 ? HttpContext.Request.Form.Files[0] : null;
}
catch (InvalidDataException)
{
cover = null;
}
}
// The cover stream must stay open while the handler stores the image, and is disposed as soon as the handler returns.
UpdateAlbumCoverCommand command = new(libraryId, artistId, albumId, cover?.OpenReadStream(), cover?.FileName);
try
{
Result<UpdateAlbumCoverResponse> result = await _updateAlbumCoverCommandHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
finally
{
command.Cover?.Dispose();
}
}
}
@@ -0,0 +1,108 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
/// <summary>
/// Class used for providing a textual description for the <see cref="UpdateAlbumCoverEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateAlbumCoverEndpointSummary : Summary<UpdateAlbumCoverEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateAlbumCoverEndpointSummary"/> class.
/// </summary>
public UpdateAlbumCoverEndpointSummary()
{
Summary = "Updates the cover image of an album.";
Description = "Updates the cover image of the album identified by the route, with the image uploaded in the multipart form of the request.";
Response(200, "The relative path of the stored cover image is returned.",
example: new UpdateAlbumCoverResponse(
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"
)
);
Response(401, "Authentication required.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "Authentication failed",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover"
}
}
);
Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Unauthorized",
status = 403,
detail = "NotAuthorized",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
Response(404, "The request failed because the album or its media library does not exist.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "AlbumNotFound",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "LibraryNotFound",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
}
);
Response(422, "The request did not pass validation checks, either on the request itself or while storing the uploaded cover image.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"LibraryIdCannotBeEmpty",
"ArtistIdCannotBeEmpty",
"AlbumIdCannotBeEmpty",
"CoverCannotBeNull",
"FileNameCannotBeEmpty",
"FileTooLarge",
"CoverFileMustBeAnImage"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -13,6 +13,7 @@ using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common; using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
@@ -454,6 +455,8 @@ public class AddArtistEndpointSummary : Summary<AddArtistEndpoint, AddArtistRequ
ResponseParam<ArtistResponse>(r => r.Albums![0].Contributors, "The list of references to the media contributors that performed on the album, each with the role they played."); ResponseParam<ArtistResponse>(r => r.Albums![0].Contributors, "The list of references to the media contributors that performed on the album, each with the role they played.");
ResponseParam<ArtistResponse>(r => r.Albums![0].Ratings, "The list of ratings for the album."); ResponseParam<ArtistResponse>(r => r.Albums![0].Ratings, "The list of ratings for the album.");
ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks, "The list of tracks of the album."); ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks, "The list of tracks of the album.");
ResponseParam<ArtistResponse>(r => r.Albums![0].CoverPath, "The path of the image representing the album, if available.");
ResponseParam<ArtistResponse>(r => r.Albums![0].Artwork, "The stored artwork of the album, in display order, if applicable.");
ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks![0].Id, "The Id of the track."); ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks![0].Id, "The Id of the track.");
ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks![0].AlbumId, "The Id of the album the track belongs to."); ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks![0].AlbumId, "The Id of the album the track belongs to.");
ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks![0].LibraryId, "The Id of the media library this track belongs to."); ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks![0].LibraryId, "The Id of the media library this track belongs to.");
@@ -502,6 +505,7 @@ public class AddArtistEndpointSummary : Summary<AddArtistEndpoint, AddArtistRequ
ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks![0].Ratings, "The list of ratings for the track."); ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks![0].Ratings, "The list of ratings for the track.");
ResponseParam<ArtistResponse>(r => r.CreatedOnUtc, "The date and time when the artist was created."); ResponseParam<ArtistResponse>(r => r.CreatedOnUtc, "The date and time when the artist was created.");
ResponseParam<ArtistResponse>(r => r.UpdatedOnUtc, "The date and time when the artist was last updated, if applicable."); ResponseParam<ArtistResponse>(r => r.UpdatedOnUtc, "The date and time when the artist was last updated, if applicable.");
ResponseParam<ArtistResponse>(r => r.CoverPath, "The path of the image representing the artist, if available.");
Response(201, "The new artist is returned.", Response(201, "The new artist is returned.",
example: new ArtistResponse( example: new ArtistResponse(
@@ -820,9 +824,12 @@ public class AddArtistEndpointSummary : Summary<AddArtistEndpoint, AddArtistRequ
CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc), CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc),
UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc) UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc)
) )
] ],
CoverPath: "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg",
Artwork: [new MediaArtworkDto(ArtworkType.Cover, 0, "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg")]
) )
], ],
CoverPath: "/media/music/Queen-3b3a19f3/cover.jpg",
CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc), CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc),
UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc) UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc)
) )
@@ -8,6 +8,7 @@ using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common; using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
@@ -38,6 +39,7 @@ public class GetArtistEndpointSummary : Summary<GetArtistEndpoint, EmptyRequest>
ResponseParam<ArtistResponse>(r => r.Albums, "The list of albums of the artist, each with its own list of tracks."); ResponseParam<ArtistResponse>(r => r.Albums, "The list of albums of the artist, each with its own list of tracks.");
ResponseParam<ArtistResponse>(r => r.CreatedOnUtc, "The date and time when the artist was created."); ResponseParam<ArtistResponse>(r => r.CreatedOnUtc, "The date and time when the artist was created.");
ResponseParam<ArtistResponse>(r => r.UpdatedOnUtc, "The date and time when the artist was last updated, if applicable."); ResponseParam<ArtistResponse>(r => r.UpdatedOnUtc, "The date and time when the artist was last updated, if applicable.");
ResponseParam<ArtistResponse>(r => r.CoverPath, "The path of the image representing the artist, if available.");
Response(200, "The requested artist is returned.", Response(200, "The requested artist is returned.",
example: new ArtistResponse( example: new ArtistResponse(
@@ -161,9 +163,12 @@ public class GetArtistEndpointSummary : Summary<GetArtistEndpoint, EmptyRequest>
CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc), CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc),
UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc) UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc)
) )
] ],
CoverPath: "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg",
Artwork: [new MediaArtworkDto(ArtworkType.Cover, 0, "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg")]
) )
] ],
CoverPath: "/media/music/Queen-3b3a19f3/cover.jpg"
) )
); );
@@ -8,6 +8,7 @@ using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common; using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
@@ -64,6 +65,8 @@ public class GetArtistAlbumsEndpointSummary : Summary<GetArtistAlbumsEndpoint, E
ResponseParam<AlbumResponse>(r => r.Metadata!.Genres, "The list of genres associated with the album."); ResponseParam<AlbumResponse>(r => r.Metadata!.Genres, "The list of genres associated with the album.");
ResponseParam<AlbumResponse>(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the album."); ResponseParam<AlbumResponse>(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the album.");
ResponseParam<AlbumResponse>(r => r.Tracks, "The list of tracks of the album."); ResponseParam<AlbumResponse>(r => r.Tracks, "The list of tracks of the album.");
ResponseParam<AlbumResponse>(r => r.CoverPath, "The path of the image representing the album, if available.");
ResponseParam<AlbumResponse>(r => r.Artwork, "The stored artwork of the album, in display order, if applicable.");
Response(200, "The list of albums of the artist is returned.", Response(200, "The list of albums of the artist is returned.",
example: new AlbumResponse[] example: new AlbumResponse[]
@@ -144,7 +147,103 @@ public class GetArtistAlbumsEndpointSummary : Summary<GetArtistAlbumsEndpoint, E
], ],
CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc), CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc),
UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc), UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc),
Tracks: [] Tracks:
[
new(
Id: Guid.NewGuid(),
AlbumId: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
Metadata: new(
Title: "Bohemian Rhapsody",
OriginalTitle: "Bohemian Rhapsody",
Description: "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
Disambiguation: "album version",
ReleaseInfo: new(
OriginalReleaseDate: new DateOnly(1975, 10, 31),
OriginalReleaseYear: 1975,
ReReleaseDate: new DateOnly(2011, 11, 21),
ReReleaseYear: 2011,
ReleaseCountry: ReleaseCountry.GB,
ReleaseVersion: "Original"
),
Language: new(
LanguageCode: "en",
LanguageName: "English",
NativeName: "English"
),
OriginalLanguage: new(
LanguageCode: "en",
LanguageName: "English",
NativeName: "English"
),
Tags: [
new(Name: "classic"),
new(Name: "epic")
],
Genres: [
new(Name: "Rock"),
new(Name: "Progressive Rock")
],
DurationInSeconds: 354,
SampleRate: 44100,
Channels: 2,
BitDepth: 16,
AudioCodec: "FLAC",
Bitrate: 980,
IsVideo: false
),
Script: "Latn",
Key: MusicKey.CMajor,
Bpm: 72,
Work: new MusicWorkDto(
MusicBrainzWorkId: Guid.NewGuid(),
Title: "Bohemian Rhapsody",
Type: "Song",
Languages: [new LanguageInfoDto(LanguageCode: "en", LanguageName: "English", NativeName: "English")],
Iswcs: ["T-010489707-6"]
),
Isrcs: [
new(Value: "GBUM71029604")
],
Moods: [
new(Name: "dramatic"),
new(Name: "anxious")
],
MusicBrainzRecordingId: Guid.NewGuid(),
MusicBrainzTrackId: Guid.NewGuid(),
Contributors: [
new MediaContributorReferenceDto(
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Vocals
),
new MediaContributorReferenceDto(
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Guitar
)
],
Ratings: [
new(
Value: 4.5M,
MaxValue: 5,
Source: AudioRatingSource.MusicBrainz,
VoteCount: 2345
),
new(
Value: 4.8M,
MaxValue: 5,
Source: AudioRatingSource.LastFm,
VoteCount: 1234
)
],
TrackNumber: 1,
DiscNumber: 1,
CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc),
UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc)
)
],
CoverPath: "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg",
Artwork: [new MediaArtworkDto(ArtworkType.Cover, 0, "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg")]
), ),
new AlbumResponse( new AlbumResponse(
Id: Guid.NewGuid(), Id: Guid.NewGuid(),
@@ -222,7 +321,97 @@ public class GetArtistAlbumsEndpointSummary : Summary<GetArtistAlbumsEndpoint, E
], ],
CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc), CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc),
UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc), UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc),
Tracks: [] Tracks:
[
new(
Id: Guid.NewGuid(),
AlbumId: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/music/queen/the-works/01-radio-ga-ga.flac",
Metadata: new(
Title: "Radio Ga Ga",
OriginalTitle: "Radio Ga Ga",
Description: "A song by the British rock band Queen, written by Roger Taylor and released on the album The Works in 1984.",
Disambiguation: "album version",
ReleaseInfo: new(
OriginalReleaseDate: new DateOnly(1984, 1, 23),
OriginalReleaseYear: 1984,
ReReleaseDate: new DateOnly(2011, 11, 21),
ReReleaseYear: 2011,
ReleaseCountry: ReleaseCountry.GB,
ReleaseVersion: "Remastered"
),
Language: new(
LanguageCode: "en",
LanguageName: "English",
NativeName: "English"
),
OriginalLanguage: new(
LanguageCode: "en",
LanguageName: "English",
NativeName: "English"
),
Tags: [
new(Name: "classic"),
new(Name: "synth-pop")
],
Genres: [
new(Name: "Rock"),
new(Name: "Synth-pop")
],
DurationInSeconds: 349,
SampleRate: 44100,
Channels: 2,
BitDepth: 16,
AudioCodec: "FLAC",
Bitrate: 920,
IsVideo: false
),
Script: "Latn",
Key: MusicKey.FMajor,
Bpm: 112,
Work: new MusicWorkDto(
MusicBrainzWorkId: Guid.NewGuid(),
Title: "Radio Ga Ga",
Type: "Song",
Languages: [new LanguageInfoDto(LanguageCode: "en", LanguageName: "English", NativeName: "English")],
Iswcs: ["T-010489707-6"]
),
Isrcs: [
new(Value: "GBUM71029610")
],
Moods: [
new(Name: "dramatic"),
new(Name: "uplifting")
],
MusicBrainzRecordingId: Guid.NewGuid(),
MusicBrainzTrackId: Guid.NewGuid(),
Contributors: [
new MediaContributorReferenceDto(
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Vocals
),
new MediaContributorReferenceDto(
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Guitar
)
],
Ratings: [
new(
Value: 4.6M,
MaxValue: 5,
Source: AudioRatingSource.MusicBrainz,
VoteCount: 2100
)
],
TrackNumber: 1,
DiscNumber: 1,
CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc),
UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc)
)
],
CoverPath: "/media/music/Queen-3b3a19f3/The Works-6d7e8f9a/cover.jpg",
Artwork: [new MediaArtworkDto(ArtworkType.Cover, 0, "/media/music/Queen-3b3a19f3/The Works-6d7e8f9a/cover.jpg")]
) )
} }
); );
@@ -3,6 +3,7 @@ using FastEndpoints;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Contracts.Responses.Common; using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
@@ -35,6 +36,9 @@ public class GetArtistAlbumsLiteEndpointSummary : Summary<GetArtistAlbumsLiteEnd
ResponseParam<AlbumLiteResponse>(r => r.Id, "The Id of the album."); ResponseParam<AlbumLiteResponse>(r => r.Id, "The Id of the album.");
ResponseParam<AlbumLiteResponse>(r => r.Title, "The title of the album."); ResponseParam<AlbumLiteResponse>(r => r.Title, "The title of the album.");
ResponseParam<AlbumLiteResponse>(r => r.TotalTracks, "The number of tracks of the release."); ResponseParam<AlbumLiteResponse>(r => r.TotalTracks, "The number of tracks of the release.");
ResponseParam<AlbumLiteResponse>(r => r.CoverPath, "The path of the image representing the album, if available.");
ResponseParam<AlbumLiteResponse>(r => r.ReleaseYear, "The release year of the album (the re-release year, if available, or the original release year), if known.");
ResponseParam<AlbumLiteResponse>(r => r.ReleaseTypes, "The set of types of the release.");
Response(200, "The paginated list of the lightweight read models of the albums of the artist is returned.", Response(200, "The paginated list of the lightweight read models of the albums of the artist is returned.",
example: new PaginatedResponse<AlbumLiteResponse> example: new PaginatedResponse<AlbumLiteResponse>
@@ -44,12 +48,18 @@ public class GetArtistAlbumsLiteEndpointSummary : Summary<GetArtistAlbumsLiteEnd
new AlbumLiteResponse( new AlbumLiteResponse(
Id: Guid.NewGuid(), Id: Guid.NewGuid(),
Title: "A Night at the Opera", Title: "A Night at the Opera",
TotalTracks: 12 TotalTracks: 12,
CoverPath: "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg",
ReleaseYear: 1975,
ReleaseTypes: [MusicReleaseType.Album]
), ),
new AlbumLiteResponse( new AlbumLiteResponse(
Id: Guid.NewGuid(), Id: Guid.NewGuid(),
Title: "The Works", Title: "The Works",
TotalTracks: 9 TotalTracks: 9,
CoverPath: "/media/music/Queen-3b3a19f3/The Works-6d7e8f9a/cover.jpg",
ReleaseYear: 1984,
ReleaseTypes: [MusicReleaseType.Album]
) )
], ],
CurrentPage = 1, CurrentPage = 1,
@@ -10,6 +10,7 @@ using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common; using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
@@ -50,6 +51,7 @@ public class GetArtistsEndpointSummary : Summary<GetArtistsEndpoint, GetArtistsR
ResponseParam<ArtistResponse>(r => r.Albums, "The list of albums of the artist, each with its own list of tracks."); ResponseParam<ArtistResponse>(r => r.Albums, "The list of albums of the artist, each with its own list of tracks.");
ResponseParam<ArtistResponse>(r => r.CreatedOnUtc, "The date and time when the artist was created."); ResponseParam<ArtistResponse>(r => r.CreatedOnUtc, "The date and time when the artist was created.");
ResponseParam<ArtistResponse>(r => r.UpdatedOnUtc, "The date and time when the artist was last updated, if applicable."); ResponseParam<ArtistResponse>(r => r.UpdatedOnUtc, "The date and time when the artist was last updated, if applicable.");
ResponseParam<ArtistResponse>(r => r.CoverPath, "The path of the image representing the artist, if available.");
Response(200, "The paginated list of the artists of the media library is returned.", Response(200, "The paginated list of the artists of the media library is returned.",
example: new PaginatedResponse<ArtistResponse> example: new PaginatedResponse<ArtistResponse>
@@ -173,9 +175,12 @@ public class GetArtistsEndpointSummary : Summary<GetArtistsEndpoint, GetArtistsR
CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc), CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc),
UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc) UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc)
) )
] ],
CoverPath: "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg",
Artwork: [new MediaArtworkDto(ArtworkType.Cover, 0, "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg")]
) )
] ],
CoverPath: "/media/music/Queen-3b3a19f3/cover.jpg"
), ),
new ArtistResponse( new ArtistResponse(
Id: Guid.NewGuid(), Id: Guid.NewGuid(),
@@ -294,9 +299,12 @@ public class GetArtistsEndpointSummary : Summary<GetArtistsEndpoint, GetArtistsR
CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc), CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc),
UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc) UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc)
) )
] ],
CoverPath: "/media/music/David Bowie-2b0e5f5a/Heroes-4a5b6c7d/cover.jpg",
Artwork: [new MediaArtworkDto(ArtworkType.Cover, 0, "/media/music/David Bowie-2b0e5f5a/Heroes-4a5b6c7d/cover.jpg")]
) )
] ],
CoverPath: "/media/music/David Bowie-2b0e5f5a/cover.jpg"
) )
], ],
CurrentPage = 1, CurrentPage = 1,
@@ -3,6 +3,7 @@ using FastEndpoints;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Contracts.Responses.Common; using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
@@ -27,15 +28,24 @@ public class GetArtistsLiteEndpointSummary : Summary<GetArtistsLiteEndpoint, Get
ExampleRequest = new GetArtistsLiteRequest( ExampleRequest = new GetArtistsLiteRequest(
CurrentPage: 1, CurrentPage: 1,
PerPage: 48, PerPage: 48,
SearchTerm: "queen" SearchTerm: "queen",
FilterAlphaKey: "q",
ShouldIgnoreThePrefixForAlphaPicker: true,
SortBy: "name",
SortOrder: SortOrder.Ascending
); );
RequestParam(r => r.CurrentPage, "The page of results to retrieve. Optional."); RequestParam(r => r.CurrentPage, "The page of results to retrieve. Optional.");
RequestParam(r => r.PerPage, "The maximum number of artists to retrieve per page. Optional."); RequestParam(r => r.PerPage, "The maximum number of artists to retrieve per page. Optional.");
RequestParam(r => r.SearchTerm, "The search term used to filter the artists by name. Optional."); RequestParam(r => r.SearchTerm, "The search term used to filter the artists by name. Optional.");
RequestParam(r => r.FilterAlphaKey, "The alpha key used to filter the artists by the first character of their name, for the alpha picker. Optional.");
RequestParam(r => r.ShouldIgnoreThePrefixForAlphaPicker, "Whether the leading \"The \" prefix of a name is ignored when computing the alpha key, or not. Optional.");
RequestParam(r => r.SortBy, "The name of the field by which to sort the results. Optional.");
RequestParam(r => r.SortOrder, "The direction in which to sort the results. Optional.");
ResponseParam<ArtistLiteResponse>(r => r.Id, "The Id of the artist."); ResponseParam<ArtistLiteResponse>(r => r.Id, "The Id of the artist.");
ResponseParam<ArtistLiteResponse>(r => r.Name, "The name of the artist."); ResponseParam<ArtistLiteResponse>(r => r.Name, "The name of the artist.");
ResponseParam<ArtistLiteResponse>(r => r.CoverPath, "The path of the image representing the artist, if available.");
Response(200, "The paginated list of the lightweight read models of the artists is returned.", Response(200, "The paginated list of the lightweight read models of the artists is returned.",
example: new PaginatedResponse<ArtistLiteResponse> example: new PaginatedResponse<ArtistLiteResponse>
@@ -44,11 +54,13 @@ public class GetArtistsLiteEndpointSummary : Summary<GetArtistsLiteEndpoint, Get
[ [
new ArtistLiteResponse( new ArtistLiteResponse(
Id: Guid.NewGuid(), Id: Guid.NewGuid(),
Name: "Queen" Name: "Queen",
CoverPath: "/media/music/Queen-3b3a19f3/cover.jpg"
), ),
new ArtistLiteResponse( new ArtistLiteResponse(
Id: Guid.NewGuid(), Id: Guid.NewGuid(),
Name: "David Bowie" Name: "David Bowie",
CoverPath: "/media/music/David Bowie-2b0e5f5a/cover.jpg"
) )
], ],
CurrentPage = 1, CurrentPage = 1,
@@ -113,7 +125,8 @@ public class GetArtistsLiteEndpointSummary : Summary<GetArtistsLiteEndpoint, Get
{ {
"General.Validation", new[] "General.Validation", new[]
{ {
"LibraryIdCannotBeEmpty" "LibraryIdCannotBeEmpty",
"InvalidFilterAlphaKey"
} }
} }
}, },
@@ -11,6 +11,7 @@ using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common; using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
@@ -453,6 +454,8 @@ public class UpdateArtistEndpointSummary : Summary<UpdateArtistEndpoint, UpdateA
ResponseParam<ArtistResponse>(r => r.Albums![0].Contributors, "The list of references to the media contributors that performed on the album, each with the role they played."); ResponseParam<ArtistResponse>(r => r.Albums![0].Contributors, "The list of references to the media contributors that performed on the album, each with the role they played.");
ResponseParam<ArtistResponse>(r => r.Albums![0].Ratings, "The list of ratings for the album."); ResponseParam<ArtistResponse>(r => r.Albums![0].Ratings, "The list of ratings for the album.");
ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks, "The list of tracks of the album."); ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks, "The list of tracks of the album.");
ResponseParam<ArtistResponse>(r => r.Albums![0].CoverPath, "The path of the image representing the album, if available.");
ResponseParam<ArtistResponse>(r => r.Albums![0].Artwork, "The stored artwork of the album, in display order, if applicable.");
ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks![0].Id, "The Id of the track."); ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks![0].Id, "The Id of the track.");
ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks![0].AlbumId, "The Id of the album the track belongs to."); ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks![0].AlbumId, "The Id of the album the track belongs to.");
ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks![0].LibraryId, "The Id of the media library this track belongs to."); ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks![0].LibraryId, "The Id of the media library this track belongs to.");
@@ -501,6 +504,7 @@ public class UpdateArtistEndpointSummary : Summary<UpdateArtistEndpoint, UpdateA
ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks![0].Ratings, "The list of ratings for the track."); ResponseParam<ArtistResponse>(r => r.Albums![0].Tracks![0].Ratings, "The list of ratings for the track.");
ResponseParam<ArtistResponse>(r => r.CreatedOnUtc, "The date and time when the artist was created."); ResponseParam<ArtistResponse>(r => r.CreatedOnUtc, "The date and time when the artist was created.");
ResponseParam<ArtistResponse>(r => r.UpdatedOnUtc, "The date and time when the artist was last updated, if applicable."); ResponseParam<ArtistResponse>(r => r.UpdatedOnUtc, "The date and time when the artist was last updated, if applicable.");
ResponseParam<ArtistResponse>(r => r.CoverPath, "The path of the image representing the artist, if available.");
Guid artistId = Guid.NewGuid(); Guid artistId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid(); Guid libraryId = Guid.NewGuid();
@@ -817,9 +821,12 @@ public class UpdateArtistEndpointSummary : Summary<UpdateArtistEndpoint, UpdateA
CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc), CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc),
UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc) UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc)
) )
] ],
CoverPath: "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg",
Artwork: [new MediaArtworkDto(ArtworkType.Cover, 0, "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg")]
) )
], ],
CoverPath: "/media/music/Queen-3b3a19f3/cover.jpg",
CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc), CreatedOnUtc: new DateTime(2025, 1, 15, 10, 30, 0, DateTimeKind.Utc),
UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc) UpdatedOnUtc: new DateTime(2025, 1, 20, 14, 45, 0, DateTimeKind.Utc)
) )
@@ -0,0 +1,81 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
/// <summary>
/// API endpoint for the <c>/libraries/{libraryId}/artists/{artistId}/cover</c> route.
/// </summary>
public class UpdateArtistCoverEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
{
private readonly ICommandHandler<UpdateArtistCoverCommand, Result<UpdateArtistCoverResponse>> _updateArtistCoverCommandHandler;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateArtistCoverEndpoint"/> class.
/// </summary>
/// <param name="updateArtistCoverCommandHandler">Injected service for handling update artist cover commands.</param>
public UpdateArtistCoverEndpoint(ICommandHandler<UpdateArtistCoverCommand, Result<UpdateArtistCoverResponse>> updateArtistCoverCommandHandler)
{
_updateArtistCoverCommandHandler = updateArtistCoverCommandHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(FastEndpoints.Http.PUT);
Routes(ApiRoutes.Artists.UPDATE_ARTIST_COVER);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Updates the cover image of the artist with the image uploaded in the multipart form of the request.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
{
// Take the identifiers from the route.
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString();
IFormFile? cover = null;
if (HttpContext.Request.HasFormContentType)
{
try
{
// The cover is the first file of the multipart form; a multipart body without any file cannot be parsed as a form,
// so a malformed upload is treated as a missing cover, which the command validator reports.
cover = HttpContext.Request.Form.Files.Count > 0 ? HttpContext.Request.Form.Files[0] : null;
}
catch (InvalidDataException)
{
cover = null;
}
}
// The cover stream must stay open while the handler stores the image, and is disposed as soon as the handler returns.
UpdateArtistCoverCommand command = new(libraryId, artistId, cover?.OpenReadStream(), cover?.FileName);
try
{
Result<UpdateArtistCoverResponse> result = await _updateArtistCoverCommandHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
finally
{
command.Cover?.Dispose();
}
}
}
@@ -0,0 +1,107 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
/// <summary>
/// Class used for providing a textual description for the <see cref="UpdateArtistCoverEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateArtistCoverEndpointSummary : Summary<UpdateArtistCoverEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateArtistCoverEndpointSummary"/> class.
/// </summary>
public UpdateArtistCoverEndpointSummary()
{
Summary = "Updates the cover image of an artist.";
Description = "Updates the cover image of the artist identified by the route, with the image uploaded in the multipart form of the request.";
Response(200, "The relative path of the stored cover image is returned.",
example: new UpdateArtistCoverResponse(
CoverPath: "/media/music/music-3f2504e0-4f89-41d3-9a0c-0305e82c3301/Queen-2b0e5f5a-0b3f-4b7e-8f4a-8c9e3d2f5a6b/cover.jpg"
)
);
Response(401, "Authentication required.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "Authentication failed",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover"
}
}
);
Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Unauthorized",
status = 403,
detail = "NotAuthorized",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
Response(404, "The request failed because the artist or its media library does not exist.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "ArtistNotFound",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "LibraryNotFound",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
}
);
Response(422, "The request did not pass validation checks, either on the request itself or while storing the uploaded cover image.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"LibraryIdCannotBeEmpty",
"ArtistIdCannotBeEmpty",
"CoverCannotBeNull",
"FileNameCannotBeEmpty",
"FileTooLarge",
"CoverFileMustBeAnImage"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -308,7 +308,7 @@ public class AddBookEndpointSummary : Summary<AddBookEndpoint, AddBookRequest>
MetadataProvider: default, MetadataProvider: default,
CreatedOnUtc: DateTime.UtcNow, CreatedOnUtc: DateTime.UtcNow,
UpdatedOnUtc: default, UpdatedOnUtc: default,
CoverPath: null CoverPath: "/media/books/tolkien/the-fellowship-of-the-ring/cover.jpg"
) )
); );
@@ -147,7 +147,7 @@ public class GetBooksEndpointSummary : Summary<GetBooksEndpoint, GetBooksRequest
MetadataProvider: default, MetadataProvider: default,
CreatedOnUtc: DateTime.UtcNow, CreatedOnUtc: DateTime.UtcNow,
UpdatedOnUtc: default, UpdatedOnUtc: default,
CoverPath: null CoverPath: "/media/books/tolkien/the-fellowship-of-the-ring/cover.jpg"
), ),
new( new(
Id: Guid.NewGuid(), Id: Guid.NewGuid(),
@@ -240,7 +240,7 @@ public class GetBooksEndpointSummary : Summary<GetBooksEndpoint, GetBooksRequest
MetadataProvider: default, MetadataProvider: default,
CreatedOnUtc: DateTime.UtcNow, CreatedOnUtc: DateTime.UtcNow,
UpdatedOnUtc: default, UpdatedOnUtc: default,
CoverPath: null CoverPath: "/media/books/tolkien/the-two-towers/cover.jpg"
) )
], ],
CurrentPage = 1, CurrentPage = 1,
@@ -57,13 +57,13 @@ public class GetBooksLiteEndpointSummary : Summary<GetBooksLiteEndpoint, GetBook
Id: Guid.NewGuid(), Id: Guid.NewGuid(),
Title: "The Fellowship of the Ring", Title: "The Fellowship of the Ring",
ReleaseYear: 1954, ReleaseYear: 1954,
CoverPath: null CoverPath: "/media/books/tolkien/the-fellowship-of-the-ring/cover.jpg"
), ),
new( new(
Id: Guid.NewGuid(), Id: Guid.NewGuid(),
Title: "The Two Towers", Title: "The Two Towers",
ReleaseYear: 1954, ReleaseYear: 1954,
CoverPath: null CoverPath: "/media/books/tolkien/the-two-towers/cover.jpg"
) )
], ],
CurrentPage = 1, CurrentPage = 1,
@@ -68,7 +68,6 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Lumina.Contracts\Lumina.Contracts.csproj" /> <ProjectReference Include="..\Lumina.Contracts\Lumina.Contracts.csproj" />
<ProjectReference Include="..\Lumina.Application\Lumina.Application.csproj" /> <ProjectReference Include="..\Lumina.Application\Lumina.Application.csproj" />
<ProjectReference Include="..\Lumina.Contracts\Lumina.Contracts.csproj" />
<ProjectReference Include="..\Lumina.Infrastructure\Lumina.Infrastructure.csproj" /> <ProjectReference Include="..\Lumina.Infrastructure\Lumina.Infrastructure.csproj" />
<ProjectReference Include="..\Lumina.DataAccess\Lumina.DataAccess.csproj" /> <ProjectReference Include="..\Lumina.DataAccess\Lumina.DataAccess.csproj" />
</ItemGroup> </ItemGroup>
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.Enums.AudioLibrary;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary;
/// <summary>
/// Data transfer object for the rating of an audio media element.
/// </summary>
[DebuggerDisplay("Value: {Value}, MaxValue: {MaxValue}")]
public class AudioRatingDto : RatingDto
{
/// <summary>
/// Gets or sets the source of the audio rating (e.g., a specific website or platform).
/// </summary>
public AudioRatingSource? Source { get; set; }
}
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
/// <summary>
/// Data transfer object for an ISRC (International Standard Recording Code) of a track.
/// </summary>
[DebuggerDisplay("Value: {Value}")]
public class IsrcDto
{
/// <summary>
/// Gets or sets the value of the ISRC.
/// </summary>
public string? Value { get; set; }
}
@@ -0,0 +1,118 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.MediaContributors;
using Lumina.Presentation.Web.Common.Enums.AudioLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
/// <summary>
/// Data transfer object carrying the full details of an album, as stored in the media library.
/// </summary>
[DebuggerDisplay("Title: {Metadata?.Title}")]
public class MusicAlbumDto
{
/// <summary>
/// Gets or sets the Id of the album.
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// Gets or sets the Id of the artist the album belongs to.
/// </summary>
public Guid ArtistId { get; set; }
/// <summary>
/// Gets or sets the Id of the media library this album belongs to.
/// </summary>
public Guid LibraryId { get; set; }
/// <summary>
/// Gets or sets the path of the image representing the album, if available.
/// </summary>
public string? CoverPath { get; set; }
/// <summary>
/// Gets or sets the stored artwork of the album, in display order, so that all of its pieces can be presented, not just the cover.
/// </summary>
public List<MediaArtworkDto>? Artwork { get; set; }
/// <summary>
/// Gets or sets the album metadata of the album.
/// </summary>
public MusicAlbumMetadataDto? Metadata { get; set; }
/// <summary>
/// Gets or sets the physical or digital medium of the album, if applicable.
/// </summary>
public MusicMediaFormat? MediaFormat { get; set; }
/// <summary>
/// Gets or sets the outermost physical packaging of the album, if applicable.
/// </summary>
public MusicReleasePackaging? Packaging { get; set; }
/// <summary>
/// Gets or sets the barcode of the album, if applicable.
/// </summary>
public string? Barcode { get; set; }
/// <summary>
/// Gets or sets the catalog numbers of the album, if applicable.
/// </summary>
public List<string>? CatalogNumbers { get; set; }
/// <summary>
/// Gets or sets the name of the label that issued the album, if applicable.
/// </summary>
public string? Label { get; set; }
/// <summary>
/// Gets or sets the ASIN (Amazon Standard Identification Number) of the album, if applicable.
/// </summary>
public string? ASIN { get; set; }
/// <summary>
/// Gets or sets the MusicBrainz identifier of the release, if applicable.
/// </summary>
public Guid? MusicBrainzReleaseId { get; set; }
/// <summary>
/// Gets or sets the MusicBrainz identifier of the release group, if applicable.
/// </summary>
public Guid? MusicBrainzReleaseGroupId { get; set; }
/// <summary>
/// Gets or sets the MusicBrainz identifier of the release artist, if applicable.
/// </summary>
public Guid? MusicBrainzReleaseArtistId { get; set; }
/// <summary>
/// Gets or sets the date and time when the album was created.
/// </summary>
public DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the optional date and time when the album was updated.
/// </summary>
public DateTime? UpdatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the list of references to the media contributors that performed on the album, each with the role they played.
/// </summary>
public List<MediaContributorReferenceDto>? Contributors { get; set; }
/// <summary>
/// Gets or sets the list of ratings for this album.
/// </summary>
public List<AudioRatingDto>? Ratings { get; set; }
/// <summary>
/// Gets or sets the list of tracks of the album.
/// </summary>
public List<MusicTrackDto>? Tracks { get; set; }
}
@@ -0,0 +1,45 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.AudioLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
/// <summary>
/// Data transfer object for a lightweight album element, containing only the properties needed by the client for card-style navigation.
/// </summary>
[DebuggerDisplay("Title: {Title}")]
public class MusicAlbumLiteDto
{
/// <summary>
/// Gets or sets the Id of the album.
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// Gets or sets the title of the album.
/// </summary>
public string Title { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the number of tracks of the release.
/// </summary>
public int TotalTracks { get; set; }
/// <summary>
/// Gets or sets the path of the image representing the album, if available.
/// </summary>
public string? CoverPath { get; set; }
/// <summary>
/// Gets or sets the release year of the album (the re-release year, if available, or the original release year), if known.
/// </summary>
public int? ReleaseYear { get; set; }
/// <summary>
/// Gets or sets the set of types of the release.
/// </summary>
public List<MusicReleaseType>? ReleaseTypes { get; set; }
}
@@ -0,0 +1,90 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.Enums.AudioLibrary;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
/// <summary>
/// Data transfer object for the metadata of an album.
/// </summary>
[DebuggerDisplay("Title: {Title}")]
public class MusicAlbumMetadataDto
{
/// <summary>
/// Gets or sets the title of the album.
/// </summary>
public string? Title { get; set; }
/// <summary>
/// Gets or sets the original title of the album, if different from the current title.
/// </summary>
public string? OriginalTitle { get; set; }
/// <summary>
/// Gets or sets a brief description or summary of the album.
/// </summary>
public string? Description { get; set; }
/// <summary>
/// Gets or sets the disambiguation comment of the album, used to distinguish albums with the same title.
/// </summary>
public string? Disambiguation { get; set; }
/// <summary>
/// Gets or sets the release information, including release date and other relevant details.
/// </summary>
public ReleaseInfoDto? ReleaseInfo { get; set; }
/// <summary>
/// Gets or sets the language of the album.
/// </summary>
public LanguageInfoDto? Language { get; set; }
/// <summary>
/// Gets or sets the original language of the album, if it has been translated.
/// </summary>
public LanguageInfoDto? OriginalLanguage { get; set; }
/// <summary>
/// Gets or sets the list of tags that further describe or categorize the album.
/// </summary>
public List<TagDto>? Tags { get; set; }
/// <summary>
/// Gets or sets the list of genres associated with the album.
/// </summary>
public List<GenreDto>? Genres { get; set; }
/// <summary>
/// Gets or sets the script used by the language of the release of the album.
/// </summary>
public string? Script { get; set; }
/// <summary>
/// Gets or sets the set of types of the release.
/// </summary>
public List<MusicReleaseType>? ReleaseTypes { get; set; }
/// <summary>
/// Gets or sets the status of the release.
/// </summary>
public MusicReleaseStatus? ReleaseStatus { get; set; }
/// <summary>
/// Gets or sets the number of discs of the release.
/// </summary>
public int? TotalDiscs { get; set; }
/// <summary>
/// Gets or sets the number of tracks of the release.
/// </summary>
public int? TotalTracks { get; set; }
/// <summary>
/// Gets or sets the title of the specific release (edition) the album files match, if different from the release group title.
/// </summary>
public string? ReleaseTitle { get; set; }
}
@@ -0,0 +1,43 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
/// <summary>
/// Data transfer object for a MusicBrainz area, the geographic area a music artist is associated with.
/// </summary>
[DebuggerDisplay("Name: {Name}")]
public class MusicAreaDto
{
/// <summary>
/// Gets or sets the MusicBrainz identifier of the area.
/// </summary>
public Guid? MusicBrainzAreaId { get; set; }
/// <summary>
/// Gets or sets the name of the area.
/// </summary>
public string? Name { get; set; }
/// <summary>
/// Gets or sets the sort name of the area, if applicable.
/// </summary>
public string? SortName { get; set; }
/// <summary>
/// Gets or sets the disambiguation comment of the area, if applicable.
/// </summary>
public string? Disambiguation { get; set; }
/// <summary>
/// Gets or sets the MusicBrainz type of the area, if applicable.
/// </summary>
public string? Type { get; set; }
/// <summary>
/// Gets or sets the ISO 3166 code of the area, if applicable.
/// </summary>
public string? Iso3166Code { get; set; }
}
@@ -0,0 +1,53 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
/// <summary>
/// Data transfer object for an alternative name of a music artist.
/// </summary>
[DebuggerDisplay("Name: {Name}")]
public class MusicArtistAliasDto
{
/// <summary>
/// Gets or sets the name of the alias.
/// </summary>
public string? Name { get; set; }
/// <summary>
/// Gets or sets the sort name of the alias, if applicable.
/// </summary>
public string? SortName { get; set; }
/// <summary>
/// Gets or sets the type of the alias, if applicable.
/// </summary>
public string? Type { get; set; }
/// <summary>
/// Gets or sets the locale the alias is used in, if applicable.
/// </summary>
public string? Locale { get; set; }
/// <summary>
/// Gets or sets whether this is the primary alias of the artist.
/// </summary>
public bool IsPrimary { get; set; }
/// <summary>
/// Gets or sets the date the alias began being used, if applicable.
/// </summary>
public DateOnly? BeginDate { get; set; }
/// <summary>
/// Gets or sets the date the alias stopped being used, if applicable.
/// </summary>
public DateOnly? EndDate { get; set; }
/// <summary>
/// Gets or sets whether the alias is no longer used.
/// </summary>
public bool IsEnded { get; set; }
}
@@ -0,0 +1,81 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
using Lumina.Presentation.Web.Common.DTO.MediaContributors;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
/// <summary>
/// Data transfer object carrying the full details of a music artist, as stored in the media library.
/// </summary>
[DebuggerDisplay("Name: {Metadata?.Name}")]
public class MusicArtistDto
{
/// <summary>
/// Gets or sets the Id of the artist.
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// Gets or sets the Id of the media library this artist belongs to.
/// </summary>
public Guid LibraryId { get; set; }
/// <summary>
/// Gets or sets the path of the image representing the artist, if available.
/// </summary>
public string? CoverPath { get; set; }
/// <summary>
/// Gets or sets the metadata of the artist.
/// </summary>
public MusicArtistMetadataDto? Metadata { get; set; }
/// <summary>
/// Gets or sets the website of the artist, if applicable.
/// </summary>
public string? Website { get; set; }
/// <summary>
/// Gets or sets the MusicBrainz identifier of the artist, if applicable.
/// </summary>
public Guid? MusicBrainzArtistId { get; set; }
/// <summary>
/// Gets or sets the list of IPI (Interested Party Information) codes of the artist.
/// </summary>
public List<string>? Ipis { get; set; }
/// <summary>
/// Gets or sets the list of ISNI (International Standard Name Identifier) codes of the artist.
/// </summary>
public List<string>? Isnis { get; set; }
/// <summary>
/// Gets or sets the date and time when the artist was created.
/// </summary>
public DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the optional date and time when the artist was updated.
/// </summary>
public DateTime? UpdatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the list of references to the media contributors that make up the artist, each with the role they played.
/// </summary>
public List<MediaContributorReferenceDto>? Contributors { get; set; }
/// <summary>
/// Gets or sets the list of ratings for this artist.
/// </summary>
public List<AudioRatingDto>? Ratings { get; set; }
/// <summary>
/// Gets or sets the list of albums of the artist, each with its own list of tracks.
/// </summary>
public List<MusicAlbumDto>? Albums { get; set; }
}
@@ -0,0 +1,28 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
/// <summary>
/// Data transfer object for a lightweight music artist element, containing only the properties needed by the client for card-style navigation.
/// </summary>
[DebuggerDisplay("Name: {Name}")]
public class MusicArtistLiteDto
{
/// <summary>
/// Gets or sets the Id of the artist.
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// Gets or sets the name of the artist.
/// </summary>
public string Name { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the path of the image representing the artist, if available.
/// </summary>
public string? CoverPath { get; set; }
}
Loaded 100 of 469 files, more files were not shown because too many files have changed in this diff. Show more